Step 1 of 5
#define constants
Before the compiler proper sees your code, a first stage called the preprocessor runs. It handles every line that starts with #. You've been using it since the first lesson: #include <stdio.h> tells the preprocessor to paste in the contents of that header file.
#define creates a macro: a name that the preprocessor replaces with text everywhere it appears.
#include <stdio.h>
#define MAX_HP 100
#define GAME_NAME "Arena"
int main(void) {
int hp = MAX_HP;
printf("%s: %d/%d\n", GAME_NAME, hp - 35, MAX_HP);
return 0;
}
Arena: 65/100
It's text replacement
The preprocessor doesn't understand C. It literally replaces the token MAX_HP with 100 before compiling, as if you had typed 100 yourself. So there's no type, no memory, and no = or ; in the definition. A common mistake is #define MAX_HP 100;: the semicolon becomes part of the replacement and breaks expressions like MAX_HP * 2.
Conventions
- Macro names are written in
UPPER_CASE, so readers know text replacement is happening. - Use them for values used in many places, so changing one line updates them all.
- In modern C,
constvariables andenumconstants are often preferable because they have types and obey scope. But#defineis still everywhere in real C code, including all the standard headers, and it's the only option for some jobs, like conditional compilation (#ifdef DEBUG). One C quirk: unlike in C++, aconst intis not a true compile-time constant in C, so it can't size an array declared outside a function; a#defineor anenumconstant can.
Your turn: define TEAM_SIZE as 5 so the program prints 10 players.