I am a computer science student, and some time ago our professor explained us that in C language we can remove curly braces when there's only one statement like:
if (a)
do b
but we can't do something like this:
if(a)
do b
do c
because that would be doing more than one statement.
But it also told us that there's an exception about removing curly braces, something we can't do even if it's only one statement. I did a lot of search but the only thing I found is that I can't do that in a do-while loop, but we are talking about if statements, any help?
Edit: we were also talking about nested if statements, maybe it's about that?
Well if there is only one statement to execute after if condition then using curly braces or not doesn't make it different. Without curly braces only first statement consider in scope so statement after if condition will get executed even if there is no curly braces. But it is Highly Recommended to use curly braces.
The remaining lines (below the first statement) will not consider as a if part. Then it wont work anymore. So i think in some cases it does matter. If there's a single statement inside an if-then, the {} curly braces can be omitted.
As @rajesh says, braces are optional when the body is a single statement. Having said that, leaving the braces in even for single statement cases is recommended by some coding styles because you (or the programmer who comes after you) are less likely to make errors when you change the code later. if ("pie"== "pie") System.out.println ("Hurrah!");
With brackets, this danger isn't present. If there is only one statement after if then braces are not mandatory. Now if you have a block of code which needs to fall under the if condition, then you need to use braces. My two cents. Writing two lines after an if statement without curly braces is a mistake I have never seen made.
You professor is probably talking about a situation like this:
if (a)
if (b)
printf("a and b\n");
else // this goes with the inner "if"
printf("not a\n");
Contrary to what the indentation suggests, the else
is not associated with the outer if
statement but with the inner if
statement. In this case you need to add curly braces to the body of the outer if
for the else
to be associated properly:
if (a) {
if (b)
printf("a and b\n");
}
else
printf("not a\n");
It's best to always use braces for the bodies of conditional and looping constructs to prevent this kind of ambiguity and the bugs that go with them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With