5.4 Macros
5.4 Macros
The Preprocessor
– Two forms
• #include <filename>
– For standard library header files
– Searches pre-designated directories
• #include “filename”
-an external file containing functions or macro definitions
can be included as a part of program
– Searches in current directory
– Normally used for programmer-defined files
Macro
– Operation specified in #define
– Macro without arguments #define id 5
• Treated like a symbolic constant #define pi 3.14159
– Macro with arguments
• Arguments substituted for replacement text
• Macro expanded
– Performs a text substitution
Multiple arguments:
#define RECTANGLE_AREA( x, y ) (( x ) * ( y ))
// multiline
rectArea = RECTANGLE_AREA( a + 4, b + 7 ); #define PRINT(x,y) if(x>y)\
becomes prirntf(“x>y”);\
rectArea = (( a + 4 ) * ( b + 7 ));
else\
printf(“x<=y”);
Nested macro:
#define M 5
#define N M+1
#define square(x) ((x)*(x))
#define qube(x) (square(x)*(x))
………
To make portable program
……..
#ifdef TEST
……
…….
……
#else
…….
……..
#endif
The statements between the directives #ifdef and #endif will be compiled only if
the macro TEST is defined.