Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 11

PREPROCESSOR DIRECTIVES

2/15/2012

Preprocessor Directives
Our programs are passing through several processors before it is ready for compilation. This preprocessors offers several features which are called preprocessor directives. Each of the preprocessor directives begin with a symbol # Can be placed anywhere in the program but most often placed at the beginning of a program. Preprocessor directives are:
 Macro expansion  File inclusion  Conditional compilation  Miscellaneous directives

2/15/2012

Macro Expansion
Consider an example:
#define UPPER 25 /*Macro definition*/ main( ) { int i ; for ( i = 1 ; i <= UPPER ; i++ ) printf ( "\n %d", i ) ; } During preprocessing replaces every occurrence of UPPER by value 25

2/15/2012

Macro Expansion
Program is examined by the C preprocessor before passing to the compiler. During preprocessing, if it finds any macro definition # define, then it looks for the template in the entire program. Templates replaced by appropriate expansion before passed to the compiler. Use capital letters for macro template
2/15/2012 4

Macro Expansion
Macro templates and macro expansion are separated by blanks or tabs. Space between # and define is optional. Macro definition should not be terminated by semicolon. If the occurrence of any value repeatedly comes in the program, using macro is a clever idea. Because if that value has to be changed someday, it s enough to make change in the macro definition alone.
2/15/2012 5

Macros with arguments


Macros can have arguments.
#define AREA(x) ( 3.14 * x * x ) main( ) { float r1 = 6.25, r2 = 2.5, a ; a = AREA ( r1 ) ; printf ( "\n Area of circle = %f", a ) ; a = AREA ( r2 ) ; printf ( "\n Area of circle = %f", a ) ; }

Not only it expands the macro, but it also substitutes the argument AREA(r1) is expanded as 3.14 * r1 * r1

2/15/2012

Macros versus Functions


In macro, preprocessor replaces the macro template with its expansion but in the case of function calls, control is passed to the function. Macros-Runs faster but program size is large Functions-Runs slower but program size is small
2/15/2012 7

File Inclusion
Used to include file. # include filename Causes the entire contents of the filename to be included. It is used in two cases:
When we have a large program When we use some macros and functions repeatedly in a program.

2/15/2012

File Inclusion
Two ways to write include statement:
#includefilename-looks for the file in the current directory as well as in the path specified with the filename #include<filename>-looks for the file in the specified list of directories only.

2/15/2012

I request Electronics and communication ENGINEERING students to visit my blog for more abhishek1ek.blogspot.com awhengineering.blogspot.com
2/15/2012

10

2/15/2012

11

You might also like