#elif statement : Conditional Compilation Directives (C Preprocessor)

#elif statement : Conditional Compilation Directives (C Preprocessor)

What it does ?

  • These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression

Syntax :

#if Expression1
   Statement_block 1;
#elif Expression2
   Statement_block 2;
#elif Expression3
   Statement_block 3;
#else
   Statement_block 4;
#endif

Explanation :

  1. Expression allows only constant expression
  2. #elif directive means “else if”
  3. #elif Establishes an if-else-if chain for multiple compilation options.
  4. Result of the Expression is TRUE , then Block of Statement between #if and fist #elif is compiled , then it jumps to #endif.
  5. Result of the Expression is FALSE , then Corresponding #elif condition is tested , if true the the block followed by that elif is Compiled otherwise it checks for Next condition followed by next elif statement
  6. #endif is the end of #if statement

Live Example 1 :

#include<stdio.h>
#define NUM 10
void main()
{
#if(NUM == 0)
       printf("\nNumber is Zero");
#elif(NUM > 0)
       printf("\nNumber is Positive");
#else
       printf("\nNumber is Negative");
#endif
}

Output :

Number is Positive

Live Example 2 :

#include<stdio.h>
#define MARKS 71
void main()
{
#if(MARKS >= 70)
      printf("\nDistinction");
#elif((MARKS >= 60)&&(MARKS < 70 )
      printf("\nFirst Class");
#elif((MARKS >= 40)&&(MARKS < 60 )
      printf("\nSecond Class");
#else
      printf("\nFail");
#endif
}

Output :

Distinction

What is Constant Expression ?

Expression whose result is Constant Number is called Constant Expression

Example : Constant Expression

  1. 190 + 20
  2. 190 / 52 + 4
  3. (356 + 44 * 2 )

Example : Non Constant Expression

  1. y + 270
  2. 130 / v + 44
  3. (546 + y * 22 )

Note : Expression which contain Variable is non Constant Expression