C Preprocessor
The preprocessor prepares C code before the compiler reads it. It handles the lines that start with #.
Name a value
LIMIT stands for 100 everywhere below its definition. The output is 100.
#include <stdio.h>
#define LIMIT 100
int main() {
printf("%d\n", LIMIT);
return 0;
}Name a decimal value
PI stands for 3.14159. The output is the distance around a circle of radius 5, which is 31.415900.
#include <stdio.h>
#define PI 3.14159
int main() {
double radius = 5.0;
double around = 2 * PI * radius;
printf("%f\n", around);
return 0;
}A macro with a value
SQUARE(6) swaps in as 6 times 6. The output is 36.
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
printf("%d\n", SQUARE(6));
return 0;
}Example
#include <stdio.h>
#define LENGTH 8
#define WIDTH 3
#define DOUBLE(x) ((x) * 2)
int main() {
int area = LENGTH * WIDTH;
printf("Area: %d\n", area);
printf("Double of 7: %d\n", DOUBLE(7));
return 0;
}Key points
- A line that starts with # is a preprocessor directive.
- The #include line brings in a header file before compiling starts.
- The #define line gives a name to a value.
- #define LIMIT 100 means LIMIT stands for 100 everywhere below it.
- A macro is a #define that acts like a small named shortcut.
- A macro can take a value in brackets, like SQUARE(6).
- The preprocessor swaps the name for its value before compiling.
- Macros do not run like functions.
LENGTH stands for 8 and WIDTH stands for 3, so the area is 24. The DOUBLE macro swaps 7 in as 7 times 2, which is 14.
Note
A #define line has no semicolon at the end.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does #define LIMIT 100 do?