#if statement : Conditional Compilation Directives (C Preprocessor)

#if statement : Conditional Compilation Directives (C Preprocessor)

What #if statement do ?

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

Syntax :

#if Expression
    Statement 1
    Statement 2
    .
    .
    Statement n
#endif

Explanation : #if Statement

  1. Expression allows only constant expression
  2. Result of the Expression is TRUE , then Block of Statement between #if and #endif is followed
  3. Result of the Expression is FALSE , then Block of Statement between #if and #endif is skipped
  4. Result of the Expression is Non-Zero , then Block of Statement between #if and #endif is followed
  5. Result of the Expression is Zero , then Block of Statement between #if and #endif is skipped
  6. #endif is the end of #if statement

Live Example 1 :

#include<stdio.h>
#define NUM 10
void main()
{
#if((NUM%2)==0)
      printf("\nNumber is Even");
#endif
}

Output :

Number is Even

Live Example 2 :

#include<stdio.h>
#define NUM 11
void main()
{
#if((NUM%2)==0)
      printf("\nNumber is Even");
#else
      printf("\nNumber is Odd");
#endif
}

Output :

Number is Odd

What is Constant Expression ?

Expression whose result is Constant Number is called Constant Expression

Example : Constant Expression

  1. 10 + 20
  2. 10 / 2 + 4
  3. (56 + 4 * 2 )

Example : Non Constant Expression

  1. x + 20
  2. 10 / y + 4
  3. (56 + y * 2 )

Note : Expression which contain Variable is non Constant Expression

Illustration :

#include<stdio.h>
void main()
{
int num=10;
#if((num%2)==0)
      printf("\nNumber is Even");
#else
      printf("\nNumber is Odd");
#endif
}

Output :

Compile Error 
/* As Variable is included in constant Expression */