C Language | Preprocessing | Macro Constants - #define, #undef
Use #define to assign a name to a token sequence. This is useful for meaningful constants and reusable expressions.
Expanding Token Sequences
A #define directive creates a macro. Before compilation, the preprocessor replaces each macro name with its token sequence.
#define identifier token-sequence
The replacement may contain any valid token sequence.
#define MAIN int main() { return 0; }
MAIN
Macros are often used for named constants such as option values and error codes.
Code 1
#include <stdio.h>
#define KITTY "Kitty on your lap"
#define BUFFER 0xFF
int main() {
char str[BUFFER] = KITTY;
printf("%s\n" , str);
return 0;
}
Macros do not have local scope. Use #undef to remove a definition when it is no longer needed.
#undef Directive
#undef identifier
Code 2
#include <stdio.h>
int main() {
#define PI 3.14159265358979323846
printf("%f\n" , PI); /* OK */
#undef PI
/* printf("%f\n" , PI); error */
return 0;
}
After #undef PI, the name PI is no longer defined. Removing temporary macro definitions can prevent naming conflicts.