'How can identify the one statement inside if without braces?
normally without braces we define one statement so
I want to ask
if ( n > 0 )
if ( m > 0 )
printf("Condition satisfied.");
is this one statement or
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
so I ask from above two codes which is right code? and give out put for this code
if(a > b)
if(b > c)
s1;
else s2;
s2 will be executed if
Solution 1:[1]
In a case like this:
if ( n > 0 )
if ( m > 0 )
printf(" Condition satisfied.");
else
printf(" condition not satisfied. ");
The else pairs with the innermost if. So the above is the same as:
if ( n > 0 ) {
if ( m > 0 ) {
printf(" Condition satisfied.");
} else {
printf(" condition not satisfied. ");
}
}
Such cases can be potentially confusing, so unless you can put the entire statement cleanly on one line, always use braces to be clear what goes where.
Solution 2:[2]
This C Tutorial explains “Dangling else” in C. It explains the association of single else statement in a nested if statement. In nested if statements, when a single “else clause” occurs, the situation happens to be dangling else! For example:
if (condition)
if (condition)
if (condition)
else
printf("dangling else!\n"); /* dangling else, as to which if statement, else clause associates */
1. In such situations, else clause belongs to the closest if statement which is incomplete that is the innermost if statement! 2. However, we can make else clause belong to desired if statement by enclosing all if statements in block outer to which if statement to associate the else clause. For example:
if (condition) {
if (condition)
if (condition)
} else
printf("else associates with the outermost if statement!\n");
Solution 3:[3]
When you write something like
if(n > 0)
if(m > 0)
printf("Condition satisfied.\n");
else
printf("Condition not satisfied.\n");
then, yes, you've got the "dangling else" problem. It can be hard to figure out which if the else goes with. By using explicit braces, you can definitively associate the else with the correct if.
But, in this case, it's not correct to associate the else with either of the ifs! In this case, I believe you'd want to write it like this:
if(n > 0 && m > 0)
printf("Condition satisfied.\n");
else printf("Condition not satisfied.\n");
Now, not only is it smaller and easier to read, not only is there no dangling else problem, but you'll always get a correct result, with one or the other message printed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbush |
| Solution 2 | |
| Solution 3 | Steve Summit |
