Using #ifdef preprocessor directive in C

#ifdef preprocessor directive is used to check that whether the macro is defined in #define preprocessor. If yes, then the compiler will execute code under #ifdef otherwise the code of #else will be executed by default.

In this C tutorial we will learn about #ifdef and see program with it. Before getting started let’s see the syntax of #ifdef preprocessor directive.

Syntax :

// syntx of #ifdef preprocessor directive

#ifdef MACRO  
  // code to execute
  
#else
  // code to execute
  
#endif  

C program with #ifdef preprocessor directive

Consider the following C program to understand #ifdef preprocessor.

// C program using #ifdef preprocessor directive

#include <stdio.h>
#define WINDOWS 1

int main(){

   #ifdef WINDOWS
   printf("WINDOWS is defined here.\n");

   #else
   printf("WINDOWS is not defined here.\n");

   #endif
   printf("\nRest of the program here.\n");

   return 0;
}

The output will be as like as following;

WINDOWS is defined here.

Rest of the program here.

But if we comment out #define preprocessor in the above program then the output will be changed. See bellow;

#include <stdio.h>
// #define WINDOWS 1  // comment out #define preprocessor

int main(){

   #ifdef WINDOWS
   printf("WINDOWS is defined here.\n");

   #else
   printf("WINDOWS is not defined here.\n");

   #endif
   printf("\nRest of the program here.\n");

   return 0;
}

Output :

ifdef-preprocessor-directive-in-c-c-has-ifdef-preprocessor-program