#ifndef preprocessor directive in C language

#ifndef works exactly as the opposite of #ifdef. The #ifndef preprocessor directive checks whether the macro is defined in #define preprocessor. If not, then the compiler will execute code under #ifndef otherwise the code of #else will be executed by default if any.

Here we will see the syntax of #ifndef preprocessor directive and C program using this directive. At first let’s see the syntax of #ifndef preprocessor directive first.

syntax :

// syntax of #ifndef preprocessor directive

#ifndef MACRO
  // code to execute if the macro is not defined
  
#else
  // code to execute if the macro is defined
  
#endif
  // other code to execute

C program using #ifndef preprocessor directive

Now, we will see a C program which will help you to learn about #ifndef preprocessor. The program bellow will execute the code under #else preprocessor because we have defined the AGE in #define preprocessor directive.

// C program using #ifndef preprocessor directive

#include <stdio.h>
#include <conio.h>
#define AGE

int main(){
  int age = 0;
  
  #ifndef AGE
  printf("Age is not defined here.\n");
  
  #else
  printf("Enter your age : ");
  scanf("%d", &age);
  printf("\nYou are %d years old now.\n", age);
  
  #endif
  printf("Program is finished.\n");
  
  return 0;
}

Output of program :

ifndef-preprocessor-directive-in-c-c-has-ifndef-preprocessor

But if we comment out the #define preprocessor directive then we will see that the code under #ifndef preprocessor will be executed. Let’s see this in the program bellow;

#include <stdio.h>
#include <conio.h>
// #define AGE   // comment out #define

int main(){
  int age = 0;

  #ifndef AGE     // This code will execute now
  printf("Age is not defined here.\n");

  #else      // this code will not be executed
  printf("Enter your age : ");
  scanf("%d", &age);
  printf("\nYou are %d years old now.\n", age);

  #endif
  printf("Program is finished.\n");

  return 0;
}

Program output :

Age is not defined here.
Program is finished.