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 task

Complete the typedef and write Vec2 add(Vec2 a, Vec2 b) returning the component-wise sum.

Challenge 2

Write Vec2 scale(Vec2 v, double k), which multiplies both components by k, and double dot(Vec2 a, Vec2 b), which returns a.x * b.x + a.y * b.y.

Challenge 3

Write the typedef for a Rect yourself: a struct with two Vec2 fields, min (the bottom-left corner) and max (the top-right corner). Then write int contains(Rect r, Vec2 p) that returns 1 if the point is inside the rectangle or on its edge.

Previous: enum Next: Unions and tagged unions