Lesson 25 of 31
Preprocessor Macros
Preprocessor Macros
The C preprocessor runs before compilation, performing text substitution. Lines starting with # are preprocessor directives.
Simple Constants
#define creates named constants -- the preprocessor replaces every occurrence with the value:
#define PI 3
#define MAX_SIZE 100
int arr[MAX_SIZE];
Standing orders: defined before the mission begins, automatically applied everywhere they're referenced. That's a
#define.
Macros with Parameters
Macros can take arguments, acting like inline functions:
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
printf("%d\n", SQUARE(5)); // 25
printf("%d\n", MAX(10, 20)); // 20
Why the Extra Parentheses?
Without parentheses, macros can produce unexpected results due to operator precedence:
#define BAD_SQUARE(x) x * x
printf("%d\n", BAD_SQUARE(2 + 3));
// Expands to: 2 + 3 * 2 + 3 = 11 (not 25!)
#define GOOD_SQUARE(x) ((x) * (x))
printf("%d\n", GOOD_SQUARE(2 + 3));
// Expands to: ((2 + 3) * (2 + 3)) = 25
Conditional Compilation
#define DEBUG 1
#if DEBUG
printf("Debug mode\n");
#endif
Your Task
Define the following macros:
ABS(x)-- absolute value of xCLAMP(x, lo, hi)-- clamp x between lo and hi
Print ABS(-5), ABS(3), CLAMP(15, 0, 10), and CLAMP(-3, 0, 10).
TCC compiler loading...
Loading...
Click "Run" to execute your code.