Friday, December 21, 2007

Top Ten, 8 of 10

When we last left our hero, we were looking at ten ways to get screwed by the "C" programming language. Today's entry is Easily changed block scope.

if ( ... )
foo();
else
bar();

When adding a line of code to either the if or the else clause, one needs to add braces. If you add to the else clause this way:

if ( ... )
foo();
else
i++;
bar();

the i++ statement is in the else, but bar() gets called no matter what. One needs to add braces.

if ( ... ) {
foo();
} else {
i++;
bar();
}

OK, so the braces aren't needed for the if clause here. But since this is the way that the language works, and since braces can be placed anywhere, and since braces do not slow down the compiled code, or add anything to the code size, why not put them everywhere? It reduces the chance of error, increases consistency, and makes editing easier.

There are C programmers who skip braces for one-line if statements:

if (...) doit();
if (...) doit2();

but not

if (...) { doit(); }
if (...) { doit2(); }

despite C's terse block structure. I'm not one of them. I don't use one line if statements.

No comments: