been looking at this one problem I came across. The question is what does the following snippet return.
int main()
{
int a = 1, b = 2, c = 3, d = 4;
int x = a;
if (a > b)
if (b < c) x = b;
else x = c;
return(x);
}
As I understand this, if statements without a curly brace are allowed and will execute the immediate statement following it. So in the case of the first condition (a > b), if true, then the following line will execute as the statement. And then if the nested if statements' condition (b < c) is also true, then the statement following it will be executed. And the else statement would "belong" to the first if statement. However, putting this into a compiler shows me that the else statement actually belongs to the nested if statement and returns 1.
Could someone explain what I am misunderstanding? Does the else statement, in the case without any curly braces, also belong to the closest if statement?
And yes, I understand this is a poorly written piece of code with the readability out the window. I would not do this in practice but still am curious about the correct way to interpret this program.
I ran the program and saw that it returns 1, which indicates to me that the else statement is actually part of the nested if statement, which contradicts the fact if statements without curly braces execute only the line immediately following it.
Above is a single if-else statement, from the point of view of the outer
if. Indeedelseis specified to belong to the closestifit can.So the outer
ifeither skips this statement, or not. Nothing special is happening hereNote that using curly braces also creates a single compound statement.
ifalways either executes or skips a single statement, even in that case.It's just that a statement can have multiple statements in it.