Nested if Statements


A nested 'if' is and if that is the target of another ifs are very common in programming. If there is a nested if, then any other statement always indicates the nearest if statement which is in the same block within another block and is not already related to any other. For example,

if(expression1)
{
 if(expression2)
 {
   // body
 }
 if(expression3)
 {
   //body
 }
 else
 {
   //body
 }
}

As noted, the final else is not associated with if(expression2) because it is not in the same block. Rather, the final else is associated with if(expression1). Also, the inner else is associated with if(expression3), which is the nearest if.

The C language guarantees at least 15 levels of nesting. In practice, most compilers allow substantially more. More importantly, Standard C++ suggests that at least 256 levels of nested ifs be allowed in a C++ program. However, nesting outside of a few levels is rarely necessary, and additional nesting can quickly confuse the meaning of the algorithm.

Sample Program

Program
#include <stdio.h>

int main() {
  int a =10,b=12,c=11;
  if(a>b)
  {
   if(a>c)
    printf("a is big");
   else
    printf("c is big");
  }
  else
  {
   if(c>b)
    printf("c is big");
   else
    printf("b is big");
  }
  return 0;
}
nested-if flow diagram

Note

If we start using nested then one of the classic problems is .... other statements are different problems. This happens when any other match is too much available for an if. The answer to this problem is very simple. If the current block does not always match the recent match. In some cases, it is possible that false conditions are not required. In this situation, otherwise the statement may be omitted.