Conditional Compilation

Conditional Compilation directives are a type of directive that helps to compile a specific portion of the program or to skip the compilation of some specific part of the program based on some conditions. This can be done with the help of the two preprocessing commands ‘ifdef‘ and ‘endif


 #ifdef

The #ifdef  preprocessor directive checks if macro is defined by #define. If yes, it executes the code.

Syntax:

#ifdef MACRO  
//code  

#endif

Example 

Program 1:
#include<stdio.h>
#include<conio.h>
#define PI 3.14
int main()
{
float r;
printf("Enter the radius of circle:");
scanf("%f",&r);
 /* Area of circle*/
 printf("Area of circle is %f \n ",(PI * r * r));
/*Circumference of circle*/
 printf("Circumference of circle is %f \n ",( 2 * PI * r ));
getch();
return 0;
}

Program 2
#include<stdio.h>
#include<conio.h>
#define PI 3.14
#define AREA
int main()
{
float r;
printf("Enter the radius of circle:");
scanf("%f",&r);
#ifdef AREA
 /* Area of circle*/
 printf("Area of circle is %f \n ",(PI * r * r));
#endif 
 /*Circumference of circle*/
 printf("Circumference of circle is %f \n ",( 2 * PI * r ));
getch();
return 0;
}
Program 3
#include<stdio.h>
#include<conio.h>
#define PI 3.14
//#define AREA
int main()
{
float r;
printf("Enter the radius of circle:");
scanf("%f",&r);
#ifdef AREA
 /* Area of circle*/
 printf("Area of circle is %f \n ",(PI * r * r));
 #else
 /*Circumference of circle*/
 printf("Circumference of circle is %f \n ",( 2 * PI * r ));
#endif 
getch();
return 0;
}


#if

The #if  preprocessor directive evaluates the expression or condition. If condition is true, it executes the code.

Syntax:

#if expression  
//code  

#endif  

Example
#include <stdio.h>    
#include <conio.h>    
#define NUMBER 1  
int main() {  
  
#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();
return 0;  
}  
Output
2 Value of number is : 1

#undef

To undefine a macro means to cancel its definition. This is done with the #undef directive.

Syntax:

# undef token
#include <stdio.h>    
#include <conio.h>    
#define NUMBER 1 
#undef NUMBER 
int main() {  
  
#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();
return 0;  
}  
Output
Compile Time Error: 'NUMBER' undeclared



#ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.

Syntax:

#ifndef MACRO  
//code  
#endif  

Example
#include <stdio.h>    
#include <conio.h>
#define PI 3.14
int main()
{
	#ifndef PI
	printf("Value of PI is not  defined");
    #else
    printf("Value of PI is defined");
    #endif
	getch();
	return 0;
}
Output
Value of PI is defined






 

No comments:

Post a Comment