C/C++ Arena

Step 6 of 7

typedef

Writing struct Player every time gets tiresome. typedef creates a new name (an alias) for an existing type:

typedef unsigned long long u64;   // u64 now means unsigned long long

It's most often used with structs, so the type can be named with one word:

#include <stdio.h>

typedef struct {
    int r, g, b;
} Color;

Color mix(Color a, Color b) {
    Color out = {(a.r + b.r) / 2, (a.g + b.g) / 2, (a.b + b.b) / 2};
    return out;
}

int main(void) {
    Color red = {255, 0, 0};
    Color blue = {0, 0, 255};
    Color purple = mix(red, blue);
    printf("%d %d %d\n", purple.r, purple.g, purple.b);
    return 0;
}
127 0 127

Reading it

typedef struct { ... } Color; defines an unnamed struct and names it Color in one go. After that, Color works like int or double: in declarations, parameters and return types.

Notice int r, g, b;: several members of the same type can share one declaration.

Returning a new struct

mix builds a new Color from its inputs and returns it, leaving the inputs unchanged. Small value types like colors, points and vectors are usually written this way, and it's exactly how math-style code works in C and C++. You'll see this style again with operator overloading in C++, where a + b can be defined for your own types.

Style

Some C codebases (the Linux kernel, for example) avoid typedefs for structs, preferring the explicit struct x. Others use them everywhere. Follow the style of the code you're working in.

Your turn: complete the typedef and write Vec2 add(Vec2 a, Vec2 b) returning the component-wise sum.

Previous: enum Next: Unions and tagged unions