#if statement : Conditional Compilation Directives (C Preprocessor)
Contents
#if statement : Conditional Compilation Directives (C Preprocessor)
What #if statement do ?
- These Conditional Compilation Directives allow us to include certain portion of the code depending upon the output of constant expression
Syntax :
#if Expression Statement 1 Statement 2 . . Statement n #endif
Explanation : #if Statement
- Expression allows only constant expression
- Result of the Expression is TRUE , then Block of Statement between #if and #endif is followed
- Result of the Expression is FALSE , then Block of Statement between #if and #endif is skipped
- Result of the Expression is Non-Zero , then Block of Statement between #if and #endif is followed
- Result of the Expression is Zero , then Block of Statement between #if and #endif is skipped
- #endif is the end of #if statement
Live Example 1 :
#include<stdio.h> #define NUM 10 void main() { #if((NUM%2)==0) printf("\nNumber is Even"); #endif }
Output :
Number is Even
Live Example 2 :
#include<stdio.h> #define NUM 11 void main() { #if((NUM%2)==0) printf("\nNumber is Even"); #else printf("\nNumber is Odd"); #endif }
Output :
Number is Odd
What is Constant Expression ?
Expression whose result is Constant Number is called Constant Expression
Example : Constant Expression
- 10 + 20
- 10 / 2 + 4
- (56 + 4 * 2 )
Example : Non Constant Expression
- x + 20
- 10 / y + 4
- (56 + y * 2 )
Note : Expression which contain Variable is non Constant Expression
Illustration :
#include<stdio.h> void main() { int num=10; #if((num%2)==0) printf("\nNumber is Even"); #else printf("\nNumber is Odd"); #endif }
Output :
Compile Error /* As Variable is included in constant Expression */