C/C++ Arena

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

Your turn: define TEAM_SIZE as 5 so the program prints 10 players.

Next: Macro pitfalls