C #define & Macros
In this page:
Object-like Macros
#define PI 3.14159 is the classic example -- every occurrence of PI in your code is textually replaced with 3.14159 before compilation, giving you a single place to update the value if it ever needs to change.
Example: Object-like Macros
#include <stdio.h>
#define PI 3.14159
int main() {
printf("%.5f", PI);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Function-like Macros
#define SQUARE(x) ((x) * (x)) looks like a function call at the point of use, but the preprocessor literally substitutes the text of the argument into the macro body wherever x appears, with no actual function call overhead at runtime.
Example: Function-like Macros
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
printf("%d", SQUARE(5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Macros with Multiple Arguments
#define MAX(a, b) ((a) > (b) ? (a) : (b)) demonstrates a two-argument macro -- each parameter name in the macro body gets replaced by the corresponding argument's literal text when the macro is used.
Example: Macros with Multiple Arguments
#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main() {
printf("%d", MAX(3, 7));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Why Parentheses are Critical
Without them, SQUARE(x) defined as x * x would expand SQUARE(1+2) into 1+2 * 1+2, which evaluates incorrectly due to operator precedence -- wrapping every parameter and the whole expression in parentheses avoids this entire class of bugs.
Example: Why Parentheses are Critical
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
printf("%d", SQUARE(1 + 2));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Undefining Macros with #undef
This is useful when a macro should only be active for part of your file, or when you want to redefine it to a different value for a different section of code without triggering a 'macro redefined' warning.
Example: Undefining Macros with #undef
#include <stdio.h>
#define VALUE 10
int main() {
printf("%d ", VALUE);
#undef VALUE
#define VALUE 20
printf("%d", VALUE);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: