Preprocessor, const, static, and enum
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
What runs before the compiler
- Before the compiler sees your code, the preprocessor handles every line that starts with
#. - It pastes in headers, replaces macros, and removes comments — a simple text step.
- You have used it already:
#include <stdio.h>is a preprocessor command.
#include and #define
#include <stdio.h>pastes the contents of a header so you can use its functions.#define PI 3.14159makesPIa macro: the preprocessor replaces everyPIwith that text.- Macros have no type and no semicolon — they are pure text replacement.
const vs #define
const double pi = 3.14159;is a real variable that cannot be changed. It has a type, so the compiler checks it.#define PI 3.14159is just text replacement, done before compiling.- Modern C usually prefers
constfor values, but#defineis still common for constants and flags.
static and enum
- A
staticvariable inside a function keeps its value between calls — it is set up once, not reset every time the function runs. - An
enumgives names to a set of relatedintvalues:enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES };(hereHEARTSis0). - Both make code clearer:
staticfor memory that persists,enumfor named choices.
#include <stdio.h>
#define GREETING "Hello"
enum Color { RED, GREEN, BLUE };
int main(void) {
printf("%s\n", GREETING); // Hello
enum Color c = GREEN;
printf("%d\n", c); // 1
return 0;
}
Now you try
- Use the given
#defineandenumin the starters. - A
staticlocal variable remembers its value across calls. Do not write amain— the checker provides one.
The enum Suit { HEARTS, DIAMONDS, CLUBS, SPADES } is given. Complete const char *suit_name(enum Suit s) so it returns the name ("Hearts", "Diamonds", "Clubs", "Spades") using a switch. Do not write a main.
Click Run to see the output here.
A macro #define PI 3.14159265358979 is given. Complete double circle_area(double r) so it returns the area of a circle, PI * r * r, using the macro. Do not write a main.
Click Run to see the output here.
Complete int next_id(void) using a static local counter, so the first call returns 1, the next 2, then 3, and so on. Do not write a main.
Click Run to see the output here.