C Programming language

Pre processor in C
Previous Home Next

C pre-processor

It is a program that processes our source program before it is passed to the compiler.

Features of pre prcessor

The pre-processor offers several features called pre-processor directives. Each of these pre-processor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed at the beginning of a program, before the first function definition.

We would learn the following pre-processor directives here:

  1. Macro expansion
  2. File inclusion
  3. Conditional Compilation
  4. Miscellaneous directives

Macro expansion

Have a look at the following program:

#define UPPER 25
main( )
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;

In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has already been defined before main( ) through the statement,#define UPPER 25 This statement is called ‘macro definition’ or more commonly, just a ‘macro’. What purpose does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program with 25.

When we compile the program, before the source code passes to the compiler it is examined by the C preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in search of the macro templates; wherever it finds one, it replaces the macro template with the appropriate macro expansion.

In C programming it is customary to use capital letters for macro template. This makes it easy for programmers to pick out all the macro templates when reading through the program.

Note that a macro template and its macro expansion are separated by blanks or tabs. A space between # and define is optional. Remember that a macro definition is never to be terminated by a semicolon.

Previous Home Next