2k views

Consider the following program fragment

  if(a > b)  if(b > c)     s1;  else s2;

s2 will be executed if

1. a <= b
2. b > c
3. b >= c and a <= b
4. a > b and b <= c
| 2k views

Explanation: Given program fragment is without braces, it is equivalent with braces will be like this:
if (a > b)
{
if (b > c) { s1; }
else { s2; }
}

Note: A expression's scope remains until its sub expressions does not complete.

Reference: Executed program on URL: https://ideone.com/GmMM5E

by Active (2.4k points)
selected by
0
similar to dangling else problem ?
+2
Yes in the sense of someone who is new to the language. But dangling-else is a compilation issue- this problem is solved before a language is made. In C/C++ this is solved by always taking the else to the nearest if. So, as a programmer there is no problem of dangling-else and even for a compiler designer there is no problem - its solved when the language was made.
0
@arjun sir how can you say it is like one mention mangilal saswat it could be like this

if(a>b)

if(b>c)

s1;

else s2;

notice there is sno semicolon so it is not dangling else problem

@pC boss

Point here to be noted is that when I write if (a >b) now after this I haven't written any braces so anything written within it would be considered as a single statement hence it is equivalent to if(a>b){ if (b < c) {s1 ;} else {s2 ;}

therefore clearly if s2 has to execute then we must have the condition a>b to be true simultaneously with b<=c , so option D is correct .
by Loyal (6.4k points)
0
there can be one more possibility
if(a>b)

{

if(b>c)

{     s1;

}
}
else
s2;

in this case option a is correct
0
This possibility is not equivalent to given program fragment. Given program assumes 'else' with internal 'if' but you have made 'else' with external 'if'.
+1 vote
 C compiler parses every else statement greedily ie every else statement will match the nearest if statement. Hence the correct representation is  if(a>b) {       if(b>c)           s1;       else           s2; }   Answer is D
by (299 points)
0
If no braces are put then only the next statement after if condition is executed if condition is true. So In this case if a>b then it will go to next command b>c else it will skip b>c follow-up statement (s1). And s2 will be executed. The program behaves in the way akash3052 has demonstrated. So option 'a' is correct.
S2 WILL BE EXECUTED IF D)a>b and b<=c
by Active (2.1k points)

When 1st IF is true and second IF is false then only s2 will be executed
by Loyal (9.9k points)