AnyCompiler

Enums and typedef

enum Day { MONDAY, TUESDAY, WEDNESDAY } declares three named constants that are really just ints underneath, numbered automatically starting from 0 — MONDAY is 0, TUESDAY is 1, WEDNESDAY is 2. It's C's lightweight alternative to a long list of #define constants.

typedef

typedef gives an existing type a new name. It's most useful with structs: without it, every declaration needs the struct keyword (struct Point p;) — typedef struct { ... } Point; lets you write just Point p; instead, which is the convention most real C codebases use.

#include <stdio.h>

enum Day { MONDAY, TUESDAY, WEDNESDAY };

typedef struct {
    int x;
    int y;
} Point;

int main() {
    enum Day today = TUESDAY;
    printf("%d\n", today);
    Point p = {1, 2};
    printf("%d %d\n", p.x, p.y);
    return 0;
}
Output
1
1 2

Next: const and static — marking something unmodifiable, and the real compiler error you get from trying anyway.

Practice exercise

Define enum Day { MONDAY, TUESDAY, WEDNESDAY }. Set a variable today to WEDNESDAY and print it as an int.