-->

The Preprocessor

The Preprocessor 
One of the most important features of 'C' language is to offer preprocessor directives. The preprocessor directives are always initialized at the beginning of the program. It begins with the symbol # (hash). 
It can be placed anywhere, but quite often it is declared at the beginning, before the main () function or any particular function. 

The #define DIRECTIVE 
The #include DIRECTIVE 
The #ifndef DIRECTIVE 
The #error DIRECTIVE 
The #line DIRECTIVE 
The #pragma DIRECTIVE

The #define Preprocessor Directive 
The syntax of # define directive is as follows. 
# define identifier <substitute text> 
OR
 # define identifier (argument 1... argument N) substitute text 
Example # deifne PI 3.14 
The statement defines macro templates. During preprocessing, the preprocessor replaces every occurrence of PI (identifier) with 3.14 (substitute value). Here, PI is a macro template and 3.14 is its macro expansion. 
The macro templates are generally declared with capital letters for quick identification. One can also define macros with small letters. 
The macro templates and its expansions, must be separated with at least one blank space. It is not necessary to provide space between # and define. It is optional to the programmer. 

Use the identifier for 3.1413 as PI and write a program to find the area of circle using it. 
# include <stdio.h> 
# include <conio.h> 
# define PI 3.14 
void main ()
float r, area; 
printf ("\n Enter radius of circle in cms."); 
scanf ("%f", &r); 
area=PI*r*r; 
printf ("Area of a circle = %.2f cm2", area); 
getche ();
}

OUTPUT: 
Enter radius of circle in cms. : 7 
Area of a Circle = 153.86 cm2 
Explanation: In the above program PI replaces 3.14 during the pre-processing (before compilation). In the program, instead of writing the value of PI as 3.14, we define directly the value PI as 3.14. Th term PI is replaced by 3.14 and used for calculating the area of a circle. 
# undef identifier 
It is useful when we do not want to allow the use of macros in any portion of the program. 

Write a program to undefine a macro.
 # include <stdio.h> 
# include <conio.h> 
# define wait getche (); 
void main () 
int k; 
# undef wait getche (); 
clrscr ();
for (k=1; k<=5; k++) 
printf ("%d\t",k); 
wait; 

Explanation: In the above program, wait is defined in place of getche(). In the program, # undef directive undefines the same macro. Hence, the compiler flags an error message "undefined symbol 'wait' in function main." 

Related Posts

Subscribe Our Newsletter