Procecessor Directive : #ifdef

The #ifdef is a conditional compilation directive, which allow programmers to include certain portion of the code depending upon the output of constant expression. It simply checks if the macro is defined by #define or not. If yes then it executes the given statements otherwise #else code is executed, if present. The syntax is:
Syntax :
#ifdef MACRONAME
  // Statement to execute
#endif
Or
#ifdef MACRONAME
  // Statement to execute
#else
  // Statement to execute
#endif
Example 1 :
#include <stdio.h>

#define NUM1 20

#ifdef NUM1
  #define NUM2 40
#else
  #define NUM1 20
  #define NUM2 40
#endif

int main() {
  printf("%d : %d\n", NUM1, NUM2);
  return 0;
}
Output :

20 : 40

At the above example if the NUM1 is defined the preprocessor statement only defines the NUM2 directive else it will define both NUM1 and NUM2.

Example 2 :
#include <stdio.h>

#define PI 3.14

int main() {

#ifdef PI
  printf("%.2f\n", PI);
#else
  float pi;
  printf("Enter the value of PI : ");
  scanf("%.2f", &pi);
  printf("%.2f\n", pi);
#endif

  return 0;

}
Output :

3.14

At above example if the macro directive PI is defined then it will print the value, otherwise asks the user for the value of PI.
#include <stdio.h>

int main() {

#ifdef PI
  printf("%.2f\n", PI);
#else
  float pi;
  printf("Enter the value of PI : ");
  scanf("%f", &pi);
  printf("%.2f\n", pi);
#endif

  return 0;
}
Output :

Enter the value of PI : 3.14
3.14


Next : C Language Tutorials List