I totally agree, the "bare" if/for/while block is a real curse and should never have been allowed. I decided a while ago to always put in braces in C-style languages even for single statements. If nothing else, it just looks better. The code looks more "balanced", i think, an "if" without curly braces looks like it's toppling over or something.
I suspect this is the reason the Golang designers made braces mandatory even for one-statement if clauses.
Is the above code example, though legal, considered bad practice?
if (foo)
bar; baz;
Is the above code example, though legal, considered bad practice?Yes, misleading indentation like this is bad practice for anyone who believes that there is such a thing as "bad practice" exists. For clarity to those who do not know C, the problem is that "baz" is executed unconditionally, even though the formatting misleadingly implies that it depends on "foo".
Unfortunately (in my opinion) there is not consensus on whether the following is bad practice:
if (foo)
bar;
My belief is that this formatting should be avoided, to avoid the case where someone not familiar with the rules of C (or not thinking about them) edits it to add a manually indented "baz" on the next line: if (foo)
bar;
baz;
Personally, I'm fine with a single line without braces: if (foo) bar;
But I believe that as soon as the body is moved to another line, braces should be required: if (foo) {
bar;
}
This belief is common, but not universally shared. Some go farther and say that braces should always be required (there is a good argument for this). Others say that a two line if statement without braces is just fine (I think they are wrong).Thanks for your informative answer.
Even if it is done correctly with a comma after the 'bar' instead of a semicolon, I think it is a bad practice to separate statements with commas. But if you think in semicolon all of the time and skip some brackets then you will mostly get similar buggy code as the above.
Of course the fact that everything, including a block, is a single statement is C is one of the things that gave me my first big "whoa" moment when learning to program, and makes me glad that C was the first "real" language I learned (after Basic). K&R C is far more elegant than people give it credit for, probably because modern, real-world C is full of all sorts of weird stuff (and often egregious preprocessor abuse - yes, I'm looking at you PHP), or people learn C++ first and assume it's all the same.