Conditional compilation
Macro | Meaning |
(i) |
If the given condition is true then the statements (A) will be compiled and executed otherwise statements (B) will be compiled and executed |
(ii) |
If the specified macro is defined then the set of statements (A) are compiled otherwise not. |
(iii) |
If the specified macro is defined then the set of statements (A) are compiled otherwise set of statements (B) are compiled |
(iv) |
If the specified macro is not defined then the set of statements (A) are compiled otherwise not. |
(v) |
If the specified macro is not defined then the set of statements (A) are compiled otherwise set of statements (B) are compiled |
(vi) |
On execution of this statement the specified macro is undefined. |
Examples:1
#if (expression)
statements (A)
#else
statements (B)
#endif
#include<stdio.h> #include<conio.h> #define a 10 void main() { //clrscr(); #if(a>1) printf("Hello"); #else printf("Hi"); #endif getch(); }
/* Output */ Hello
#include<stdio.h> #include<conio.h> #define a 10 void main() { //clrscr(); #if(a>100) printf("Hello"); #else printf("Hi"); #endif getch(); }
/* Output */ Hi
Example:2
#ifdef macroname
statements
#endif
#include<stdio.h> //#include<conio.h> #define a 10 void main() { int i; //clrscr(); printf("hello\n"); #ifdef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); return(0); }
/* Output */ hello 1 3 5 7 9 hi
Example:3
#ifdef macroname
statements
#else
statements
#endif
#include<stdio.h> //#include<conio.h> #define a 10 int main() { int i; //clrscr(); printf("hello\n"); #ifdef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #else for(i=2;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); return(0); }
/* Output */ hello 1 3 5 7 9 hi
Example:4
#ifndef macroname
statements
#endif
#include<stdio.h> //#include<conio.h> #define a 10 int main() { int i; //clrscr(); printf("hello\n"); #ifndef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); return(0); }
/* Output */ hello hi
Example:5
#ifndef macroname
statements
#else
statements
#endif
#include<stdio.h> #include<conio.h> #define a 10 int main() { int i; //clrscr(); printf("hello\n"); #ifndef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #else for(i=2;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); return(0); }
/* Output */ hello 2 4 6 8 10 hi
Example:6
#undef macroname
#include<stdio.h> //#include<conio.h> #define a 10 int main() { int i; //clrscr(); printf("hello\n"); #ifdef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #else for(i=2;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); #undef a printf("hello\n"); #ifdef a for(i=1;i<=10;i=i+2) { printf("%d\n",i); } #else for(i=2;i<=10;i=i+2) { printf("%d\n",i); } #endif printf("hi\n"); return(0); }
/* Output */ hello 1 3 5 7 9 hi hello 2 4 6 8 10 hi