Shorter Names with typedef

Writing struct every time is tiring. typedef gives a type a new, shorter name:

#include <stdio.h>

typedef struct {
    int width;
    int height;
} Rectangle;

int main() {
    Rectangle r;
    r.width = 5;
    r.height = 3;
    printf("Area: %d\n", r.width * r.height);
    return 0;
}

Output

Area: 15

Now Rectangle is a type name, just like int. Most C programmers use typedef with their structs.

typedef for any type

typedef works for other types too. It can make your code say what a value means:

#include <stdio.h>

typedef int Money;

int main() {
    Money price = 250;
    Money paid = 300;
    printf("Change: %d\n", paid - price);
    return 0;
}

Output

Change: 50

Structs inside structs

A field can itself be a struct:

#include <stdio.h>

typedef struct {
    int day;
    int month;
    int year;
} Date;

typedef struct {
    char title[40];
    Date when;
} Event;

int main() {
    Event e;
    sprintf(e.title, "Science Fair");
    e.when.day = 14;
    e.when.month = 3;
    e.when.year = 2026;
    printf("%s: %02d/%02d/%d\n", e.title, e.when.day, e.when.month, e.when.year);
    return 0;
}

Output

Science Fair: 14/03/2026

Tip: Read e.when.day from left to right: "in e, go to when, then to day".

HOME LABS COMMUNITY DASHBOARD