if statement in for loop, brackets needed?

Started by
31 comments, last by Nicholas Kong 11 years, 2 months ago
I tell my students to always use braces, because this is the kind of thing that trips them up.

On the other hand, at least in my eyes, the situation where braces and indentation do not match is too obvious to be dangerous. In code that is otherwise properly indented, I can't miss it. Never saw a coworker make that mistake either. I find omitting the braces from one-liners makes the code easier to read and understand. Compare this:
foo();

if(condition)
{
    bar();
}

xyzzy();
with this:
foo();

if(condition)
    bar();

xyzzy();
With braces, the visual distance of every line with text is almost the same. It's harder to see that the two lines in the middle are logically related to each other. The version without braces has the same visual rhythm as if you were reading the logic aloud: "foo, (pause), if condition then bar, (pause), xyzzy."
Advertisement

Putting the first curly on the same line helps that:

foo();

if(condition){
    bar();
}

xyzzy();

use braces even if it is one statement. you wont think other person reading your code to think less about these little subtle things. it makes it more readable in my opinion

This topic is closed to new replies.

Advertisement