← Back to C Course | Chapter 11: Preprocessor | Lesson 2 of 5

C #define & Macros

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

c
#include <stdio.h>
#define PI 3.14159
int main() {
	printf("%.5f", PI);
	return 0;
}

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

c
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
	printf("%d", SQUARE(5));
	return 0;
}

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

c
#include <stdio.h>
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int main() {
	printf("%d", MAX(3, 7));
	return 0;
}

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

c
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
	printf("%d", SQUARE(1 + 2));
	return 0;
}

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

c
#include <stdio.h>
#define VALUE 10
int main() {
	printf("%d ", VALUE);
	#undef VALUE
	#define VALUE 20
	printf("%d", VALUE);
	return 0;
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.