#if in C

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

 
  1. #if expression  
  2. //code  
  3. #endif  

 

Syntax with #else:

 

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

 
  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let’s see a simple example to use #if preprocessor directive.

 
  • #include <stdio.h>  
  • #include <conio.h>  
  • #define NUMBER 0  
  • void main() {  
  • #if (NUMBER==0)  
  • printf(“Value of Number is: %d”,NUMBER);  
  • #endif         
  • getch();  
  • }  

Output:

Value of Number is: 0

Let’s see another example to understand the #if directive clearly.

 
  • #include <stdio.h>    
  • #include <conio.h>    
  • #define NUMBER 1  
  • void main() {  
  • clrscr();  
  • #if (NUMBER==0)  
  • printf(“1 Value of Number is: %d”,NUMBER);  
  • #endif  
  •   
  • #if (NUMBER==1)  
  • printf(“2 Value of Number is: %d”,NUMBER);  
  • #endif  
  • getch();  
  • }  

Output:

2 Value of Number is: 1

 

#else in C

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

 
  • #if expression  
  • //if code  
  • #else  
  • //else code  
  • #endif  

Syntax with #elif:

 
  • #if expression  
  • //if code  
  • #elif expression  
  • //elif code  
  • #else  
  • //else code  
  • #endif  

#else in C example

Let’s see a simple example to use #else preprocessor directive.

 
  • #include <stdio.h>  
  • #include <conio.h>  
  • #define NUMBER 1  
  • void main() {  
  • #if NUMBER==0  
  • printf(“Value of Number is: %d”,NUMBER);  
  • #else  
  • print(“Value of Number is non-zero”);  
  • #endif         
  • getch();  
  • }  

Output:

Value of Number is non-zero