One downside to non-braced conditionals is that a semicolon accidentally placed after the conditional will cause the block to always run, e.g.:
if (null != foo);
bar();
This is valid code in C and Java, and bar() will always run in this case.
Having seen people waste hours on such a semicolon, I always use braces, even in one-liners, because I never know when someone is going to break it out into multiple lines later:
I was going to say that a compiler should issue a warning for this, as you'd almost never want a semicolon right after an if condition, but to my surprise Eclipse doesn't seem to flag it.
It does however indent the line after the semicolon to the same level as the if, which is at least a red flag that something is up, if you are used to how the auto-indenting normally works.
Absolutely, indentation helps catch this when writing.
When I've seen this happen, it wasn't because of a semicolon added when the code was written. It was someone accidentally adding a semicolon to a line later, without realizing it. Unless they then went to the next line and hit the "fix indentation" key, they didn't catch it.
Both clang and gcc warn on "if(1);", clang by default, gcc with -Wextra. clang also warns on "while(1);" - I think this is somewhat obnoxious, since it can be useful, and would prefer if it only warned if the semicolon was followed by an opening brace, but YMMV.
I personally have never put a semicolon after a condition and being mainly a C# developer I have written a lot of them. Is this really something that happens more than once or twice in a lifetime?
Yes, but such mistake, once made, is very hard to notice (because you never do this, you don't look for it), so it may well lead to a fatal disaster. Hence 'once in a lifetime'.
As someone who programs in Go a lot these days, that line (I assume you meant the first curly to be { and not }) looks less obviously wrong than it would have in the past when I did more C/C++ programming.
Because I've gotten used to Go's support for short assignment in an if, the semi doesn't look completely out of place there (though the construction here is not valid Go either).
I know, let's start a language war thread: "That's why I use Python." ;)
More seriously, after more than 10 years of writing C, C++ and Java, I've never run into this problem. I still wrap mine out of habit (to prevent this dreaded occurrence), but I think good testing would obviate any need for this.
Having seen people waste hours on such a semicolon, I always use braces, even in one-liners, because I never know when someone is going to break it out into multiple lines later: