One of my university colleagues who started programming this year sometimes writes if such statements look like this:
if(something) doA(); else if(something2) doC(); else doD();
He is convinced that the second pair of if-else considered as a single entity and that it is actually nested under the first else .
I am sure, however, that its code is equivalent:
if(something) doA(); else if(something2) doC(); else doD();
This shows that the second other is not nested, but at the same level as the first if. I told him that he needed to use braces to achieve what he wants.
"But my code works as intended!"
And indeed, he worked as intended. It turns out that the behavior of the code was the same, even if else not nested.
Surprisingly, I found that I could not write a clear and concise example demonstrating different behavior between
if(something) doA(); else if(something2) doC(); else doD();
and
if(something) doA(); else { if(something2) doC(); else doD(); }
Can you help me find an example that will show my colleague the difference between using / not using curly braces?
Or a mis-looking version, always equivalent to the one that has curly braces, in terms of behavior?
c ++ c if-statement nested
Vittorio romeo
source share