basics · intermediate · ~15 min

Compound Literal Vector Math

Construct and return anonymous struct instances using C99 compound literals.

Challenge

C99 compound literals (type){ initializer } create anonymous lvalue objects on the fly, allowing functions to return and operate on temporary geometric vectors without named temporary variables.

Your Task

Given the 3D integer vector definition:

typedef struct {
    int x;
    int y;
    int z;
} Vec3;

Implement vector arithmetic functions:

Vec3 vec3_add(Vec3 a, Vec3 b);
Vec3 vec3_scale(Vec3 v, int factor);
int vec3_dot(Vec3 a, Vec3 b);
int vec3_equals(Vec3 a, Vec3 b);

Rules

  1. vec3_add: returns a Vec3 containing (a.x + b.x, a.y + b.y, a.z + b.z) using a compound literal (Vec3){ ... }.
  2. vec3_scale: returns a Vec3 containing (v.x * factor, v.y * factor, v.z * factor) using a compound literal.
  3. vec3_dot: returns integer scalar a.x * b.x + a.y * b.y + a.z * b.z.
  4. vec3_equals: returns 1 if all three coordinates match, 0 otherwise.

Example

Vec3 a = {1, 2, 3};
Vec3 b = {4, 5, 6};
Vec3 c = vec3_add(a, b); // {5, 7, 9}
vec3_dot(a, b); // 1*4 + 2*5 + 3*6 = 32

Input format

Vec3 structures passed by value and scalar integer multipliers.

Output format

Returns Vec3 structs by value or integer dot product / equality.

Constraints

Must construct returned vectors using compound literal syntax (Vec3){...}.

Starter code

typedef struct {
    int x;
    int y;
    int z;
} Vec3;

Vec3 vec3_add(Vec3 a, Vec3 b) {
    (void)a; (void)b;
    return (Vec3){0, 0, 0};
}
Vec3 vec3_scale(Vec3 v, int factor) {
    (void)v; (void)factor;
    return (Vec3){0, 0, 0};
}
int vec3_dot(Vec3 a, Vec3 b) {
    (void)a; (void)b;
    return 0;
}
int vec3_equals(Vec3 a, Vec3 b) {
    (void)a; (void)b;
    return 0;
}

Common mistakes

Forgetting (Vec3) cast before the curly brace initializer; arithmetic sign errors.

Edge cases to handle

Zero factor scales to {0, 0, 0}; negative coordinates; orthogonal vectors have 0 dot product.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.