Hello,
is the following:
(Without curly braces)Code:for ( i = 1 ; i < 5 ; i++) if (x == 1) y = 5 * x;
the same as:
(With curly braces)?Code:for ( i = 1 ; i < 5 ; i++) { if (x == 1) y = 5 * x; }
Thank you.
Hello,
is the following:
(Without curly braces)Code:for ( i = 1 ; i < 5 ; i++) if (x == 1) y = 5 * x;
the same as:
(With curly braces)?Code:for ( i = 1 ; i < 5 ; i++) { if (x == 1) y = 5 * x; }
Thank you.
Yes.
The reason is that the if(condition) statement line of code, is not a full line, we write it that way to help us, but the compiler see's it as ONE statement, until it reaches the ending semi-colon.
Did you try compiling it and seeing what happens? That is where I would start if I were you.
Normally I put curly braces around all blocks just for readability and so that I do not have to guess what the code is going to do because of some misplaced or absent curlies.
The code as it is makes no sense though.Code:for ( i = 1 ; i < 5 ; i++) { if (x == 1) { y = 5 * x; } }
Huge agreement with Bubba
...and for another reason...debugging.
If you use a GUI debugger and want to set breakpoints, it's nearly impossible to get them write unless you have a coding style like Bubba's.
Even:
if ( a ) c = d;
Is a problem in this regard, because you can't set a breakpoint on c=d that fires only when "a" is true, and this comes up enough that it's worth the brackets, IMO.
Another reason to use the brackets - expansion.
Today, it's just c=d, then that turns into c=d, g=f, then you need to introduce a function call, and soon you have to add the brackets anyway.
Yes because it's so hard to go back later and add a pair of braces around a statement that doesn't have them.
I also prefer braces, but those were some of the lamest reasons I've ever read.
Quzah.
Hope is the first step on the road to disappointment.
For the original question, the answer, as pointed out, is they are equivalent.
I suggest putting curly braces around everything, too, though.
Suppose you have something like
And later decided to add one more statement to the loop, if you are not careful, you can be misled by the indentation.Code:for ( i = 1 ; i < 5 ; i++) y += i;
That, however, is equivalent toCode:for ( i = 1 ; i < 5 ; i++) y += i; x += i;
The compiler won't necessarily complain because the code can be and often is perfectly legal.Code:for ( i = 1 ; i < 5 ; i++) { y += i; } x += i;
This can lead to some hard to find bugs.
How about I add another one saying that the coding standards at work require I put curlies around everything so I have gotten used to doing it this way? Is that a better reason?I also prefer braces, but those were some of the lamest reasons I've ever read.
Thank you all for your support.