basics · intermediate · ~15 min
Construct and return anonymous struct instances using C99 compound literals.
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.
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);
vec3_add: returns a Vec3 containing (a.x + b.x, a.y + b.y, a.z + b.z) using a compound literal (Vec3){ ... }.vec3_scale: returns a Vec3 containing (v.x * factor, v.y * factor, v.z * factor) using a compound literal.vec3_dot: returns integer scalar a.x * b.x + a.y * b.y + a.z * b.z.vec3_equals: returns 1 if all three coordinates match, 0 otherwise.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
Vec3 structures passed by value and scalar integer multipliers.
Returns Vec3 structs by value or integer dot product / equality.
Must construct returned vectors using compound literal syntax (Vec3){...}.
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;
}
Forgetting (Vec3) cast before the curly brace initializer; arithmetic sign errors.
Zero factor scales to {0, 0, 0}; negative coordinates; orthogonal vectors have 0 dot product.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.