One of my university colleagues, who has started programming this year, sometimes writes if statements like this:
if(something) doA();
else
if(something2) doC();
else doD();
He is conviced that the second if-else
pair is treated as a single entity, and that it is in fact nested under the first else
.
I'm, however, sure that his code is equivalent to:
if(something) doA();
else if(something2) doC();
else doD();
This shows that the second else is not actually nested, but on the same level as the first if. I told him he needs to use curly braces to achieve what he wants to.
"But my code works as intended!"
And indeed, it worked as intended. Turns out the behavior of the code was the same, even if the else
was not nested.
Surprisingly, I have found myself unable to write a clear and concise example that shows 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 is the incorrect-looking version always equivalent to the one with curly braces, in terms of behavior?