I'm almost certain this has been asked before, but I can't find it being answered anywhere.
When can I omit curly braces in C? I've seen brace-less return
statements before, such as
if (condition)
return 5;
But this doesn't always seem to work for all statements, i.e. when declaring a method.
edit:
Are the rules for brace omission the same as in Java?
You mainly need curly braces when you want to combine multiple statements or expressions into one, e.g.:
So if you put the above under
if
orelse
the whole thing in the braces will be executed as a whole, whereas if you omit the braces, only the first one (x = 1;
in this case) will be used as part ofif
orelse
.You also typically use them with
switch()
:You typically need them with the
do-while
statement:You need them with C89 compilers when you want to define and use a temporary variable in the middle of the code:
You use them to begin and end the body of a function, a structure/union definition, an enumeration definition, initialization of a structure/union/array, e.g.:
You may omit them sometimes in initializations, e.g.:
Anytime there is a block with more than one line (counting lines as a single statement with a ; )
Examples:
Everything after the ; in the above lines does not count as 'inside' the block as if there were { }.
If in doubt, use braces. They don't "cost" any extra [unless you absolutely use them incorrectly].
A fairly basic rule is "if you have more than one semicolon at the same indentation, you should have braces". It's not entirely that simple, but as a "one sentence with no ifs, buts or other complications" it will have to do.
And yes, Java being based on C-syntax has the same fundamental rules - there are possibly some weirdness where Java is different from C or C++, but that's unusual/strange things, not something you'd normally hit when writing typical code [I haven't done much java, so I can't say I've found any of them, but I'm pretty sure there are SOME differences - they are different languages, after all].