C Preprocessor and Macros
The preprocessor runs before the compiler. It handles the lines that start with #. It copies header files, replaces macros and removes code which is not needed.
Common directives
| Directive | Work |
|---|---|
#include | Adds the content of a file |
#define | Defines a macro (a name for a value or code) |
#undef | Removes a macro |
#ifdef / #ifndef | Compiles code only if a macro is defined / not defined |
#if, #else, #endif | Conditional compilation |
#include
#include <stdio.h> // standard header (system folder)
#include "myfile.h" // your own header (current folder)
Macro with arguments
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main(void) {
printf("%d\n", SQUARE(5));
printf("%d\n", MAX(8, 3));
return 0;
}
Output:
Output of the above program is
25
8
Always put brackets around each argument and around the whole macro. Without them the result can be wrong. For example, #define SQUARE(x) x * x gives 11 for SQUARE(2 + 3) instead of 25.
Conditional compilation
#include <stdio.h>
#define DEBUG
int main(void) {
#ifdef DEBUG
printf("Debug mode is on\n");
#endif
printf("Program running\n");
return 0;
}
Output:
Output of the above program is
Debug mode is on
Program running
If you remove the line #define DEBUG, the debug message is not even compiled. This is used to keep one code for different systems.
Header guard
In your own header files, a guard stops the file from being included two times.
#ifndef MYHEADER_H
#define MYHEADER_H
// declarations here
#endif
Note:
A macro is only a text replace. If the argument has side effects, like SQUARE(i++), it runs two times. Use a function when you need safety.
Next: C File Handling.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |