Lecture 18
Lecture 18
Lecture – 18
Preprocessor directory: The source code for C program can include various
instructions to the compiler. A preprocessor directive performs macro substitution
conditional compilation and inclusion of named files.
The C preprocessor as defined by the ANSI C standard contains the following directives :
#if, #elif, #else, #ifdef, #ifndef, #endif, #include, #define, #undef, #line, #error, #pragma.
#define: The #define directive is used to define an identifier and a character sequence that is
encountered in the source file. The identifier is called a macro name, and the replacement
process is called macro substitution. The general form of the directive is:
Example 1:
#define MAX 100
#define one 1
#define two one+one
#define three two+one
#define str “hellow”
The #define has another powerful feature. The macro name can have arguments.
Example 2:
#define MIN(a,b) ((a)<(b))?a : b
Minimum 10
void main(void)
{
int x = 10, y = 20 ; printf(“Minimum %d\n”, MIN(x,y));
}
1/3
Example 3:
#define SUM_A(x, y) \
({ \
double answer; \
if ((x) == 0 || (y) == 0) \
answer = 0; \
else \
answer = x+y; \
(answer); \
})
…………………………………………………………………………………………………………….
…………………………………………………………………………………………………………….
…………………………………………………………………………………………………………….
2/3
Conditional compilation: Syntax of conditional compilation is given below:
#if expression
statement
#endif
Example 4:
#define MAX 12
#define SERIAL 5
void main(void)
{
int flag = 0 ;
#if MAX>10
flag = 1;
198
#if SERIAL
int port = 198;
#else
int port = 200;
#endif
#else
char a[100]=”hellow”;
#endif
if(flag)
printf(“%d”,port);
else
printf(“%s”,a);
}
Example 5:
#define TED
TED is defined
void main(void)
{
#ifdef TED
printf(“TED is defined\n”);
#else
printf(“TED is not defined\n”);
#endif
}
3/3