#else statement : Conditional Compilation Directives (C Preprocessor)

#else 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 :

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

Explanation :

  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 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 */

Why we get Compile Error ?

  1. Preprocessor directives are executed before Compiler.
  2. All the variables are processed by compiler and Preprocessor symbols are processed by Preprocessor.
  3. We have include variable inside Preprocessor which is incorrect.