Object-like macros in C
A define is textual substitution, done before the compiler sees your code.
#define MAX_STARS 3
#define GREETING "welcome"
#define BUFFER_SIZE (256 * 4)
int stars_available(void) {
int buffer[8];
(void) buffer;
return MAX_STARS;
}
size_t greeting_length(void) {
return sizeof GREETING - 1;
}
int buffer_bytes(void) {
return BUFFER_SIZE;
}
How it works
- There is no type and no scope, only replacement.
- An
enumorconstis usually the better constant. - Undefining and redefining is legal, which is part of the danger.
Keywords and builtins used here
buffer_bytesgreeting_lengthintreturnsize_tsizeofstars_availablevoid
The run, in numbers
- Lines
- 17
- Characters to type
- 265
- Tokens
- 50
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 32 seconds.
Step 1 of 4 in Macros, step 1 of 12 in Preprocessor & headers.