Home > Enterprise >  How can identify the one statement inside if without braces?
How can identify the one statement inside if without braces?

Time:05-10

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

CodePudding user response:

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.

CodePudding user response:

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");
    
  • Related