#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
if(a > 0)
{
cout << "we are in the first" << endl;
if(b > 3)
{
cout << "we are in the second" << endl;
}
}
else
{
cout << "we are in else" << endl;
}
}
According to the C ISO:
In the second form of if statement (the one including else), if the first substatement is also an if statement then that inner if statement shall contain an else part. In other words, the else is associated with the nearest un-elsed if.
I thought that my code above would print out "we are in else", since the condition of the nearest un-elsed if
, the inner one, resulted in false. What did I miss?
CodePudding user response:
The standard talks here about no block statements. In situation like this:
if (a > 0)
if (b > 3) std::cout << "nested-if\n";
else std::cout << "nested-else\n";
else
is a part of the nested if
. Such things must be unambiguous in standard, but I strongly recommend using block statements (wrapped in {}
) in every situation to prevent confusion.
CodePudding user response:
When they say "nearest" then they refer to the distance to the whole if statement
, not only the if
keyword. The whole if statement is:
if (a>0){
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
It ends at the }
. The }
closes the block of the outer if
and that is the if
which is closes to the else
.
See also here for a little more formal explanation of the if-statement consisting of more than just the if
: https://en.cppreference.com/w/cpp/language/if.
CodePudding user response:
Context. The part you're missing is context.
Every time you open a {} pair you introduce a new context, so the exterior else only "knows" about the first if.
The if inside the new context could have an else of it's own. If you wanted the behavior of the else being pertaining to the last if, you should not have created a new context.
E.g:
if (someVar == true)
if (someOtherVar == true)
cout << "Some text" << endl;
else
cout << "Some other text" << endl;
else
cout << "Another entirely different text" << endl;
CodePudding user response:
Your code -
int a =1;
int b =2;
if (a>0)
{
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
else
{
cout<<"we are in else"<<endl;
}
Logic path -
int a =1;
int b =2;
if (1>0)
{
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
else
{
cout<<"we are in else"<<endl;
}
int a =1;
int b =2;
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
we are in else
is not executed.