#ifdef statement : Conditional Compilation Directives (C Preprocessor)

#ifdef 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
  • Block is Called as Conditional Group

Syntax :

#ifdef MACRONAME 
    Statement_block;
#endif

Explanation :

  1. If the MACRONAME specified after #ifdef is defined previously in #define then statement_block is followed otherwise it is skipped
  2. We say that the conditional succeeds if MACRO is defined, fails if it is not.

Live Example 1 :

#include<stdio.h>
#define NUM 10
void main()
{
// Define another macro if MACRO NUM is defined
#ifdef NUM
      #define MAX 20 
#endif
printf("MAX number is : %d",MAX);
}

Output :

MAX Number is 20

Live Example 2 :

#include<stdio.h>
void main()
{
#ifdef MAX 
    #define MIN 90
#else
    #define MIN 100
#endif
printf("MIN number : %d",MIN);
}

Output :

MIN number : 100

Rules :

  1. The MACRONAME inside of a conditional can include preprocessing directives.
  2. They are executed only if the conditional succeeds.
  3. You can nest conditional groups inside other conditional groups, but they must be completely nested.
  4. You cannot start a conditional group in one file and end it in another.

Live Example 3

#include<stdio.h>
int main(){
#ifdef __DATE__
         printf("%s",__DATE__);
    #else
         printf("__DATE__ is not defined");
    #endif
return 0;
}

Output :

Current Date is Printed
  • __DATE__ is global identifier defined in <stdio.h> header file.
  • When we include <stdio.h> header file , at the same time __DATE__ gets included in C Program.