Thursday, September 24, 2009

PREPROCESSORS:

Preprocessor directives or commands begin in a ‘ # ’.


Preprocessor process the code before it passes through compiler.

Advantages of Preprocessors:

Easy to develop

Easy to understand

Preprocessor directives are,

#define  ---  Defines a macro substitution or constants.

#undef  ---- Undefines a macro previously created by #define.

#include ----  Specifies a file to be included.

#endif ---- Specifies the end of #if.

#ifndef ---- Tests whether the macro is not def.

#if ----- Code will compiled only if a specified condition is met.

#else ---- Specifies alternatives when #if condition fails.



Preprocessors can be divided into three categories:



1. Macro Definition and Substitution.

2. File inclusion.

3. Conditional compilation.



1. Macro Definition and substitution:

Macro substitution is a process where an identifier in a program is replaced by a predefined string.

Writing macro definition in capitals is a convention not a rule.

Ex: #define PI 3.14159

#define AREA 12.36 // Macro substitution

#define CUBE(x) (x*x*x) // Macro as an argument



2. File inclusion:

#include with the system header file of that name,which controls console input and output.

This file inclusion also be written using double quotes.

#include “conio.h”

If the filename is enclosed within the angle brackets,the file searched for in the standard compiler include paths.

If the filename is enclosed within the double quotes,the search path is expanded to the current source directory.



3. Condition compilation:

In conditional compilation a piece code can be compiled, when the specified condition is true.

Syntax:

#ifdef name

Program text

#else

Program text

#endif

Example:

#ifdef MAX_LENGTH

#define MAX_LENGTH 100

#endif

char str[MAX_LENGTH];

1 comment: