[dev] [style] variable declaration locations and varriable length arrays vs malloc

From: Evan Gates <evan.gates_AT_gmail.com>
Date: Mon, 2 Mar 2015 15:31:47 -0800

This came up recently in talks about style in sbase due to my
misunderstanding of "Do not mix declarations and code" and subsequent
addition of the line "All variable declarations at top of block" in
the style guide.

It was my understanding that "Do not mix declarations and code" meant
stick to ANSI C declarations. ANSI C allows declarations of variables
only at the top of blocks, but allows them in any block so they aren't
relegated to the top of the function. It was pointed out to me that
"Do not mix declarations and code" is stricter and means that all
variables must be declared at the top of the function.

Declaring variables at the top of a block, as opposed to top of the
function has a few uses, but the most useful (in my limited
experience) is combining it with C99's variable length arrays to
create buffers without calls to malloc/free. For example:

while ((d = readdir(dp))) {
    char buf[strlen(path) + strlen(d->d_name) + 1];


while ((d = readdir(dp))) {
    buf = emalloc(strlen(path) + strlen(d->d_name) + 1];

Received on Tue Mar 03 2015 - 00:31:47 CET

This archive was generated by hypermail 2.3.0 : Tue Mar 03 2015 - 00:36:07 CET