Example 1 — Add and scale vectors
One function returns a new struct; another modifies in place.
#include <stdio.h>
struct Vec { int x, y; };
static struct Vec add(struct Vec a, struct Vec b) {
struct Vec r = {a.x + b.x, a.y + b.y};
return r;
}
static void scale(struct Vec *v, int k) {
v->x *= k;
v->y *= k;
}
int main(void) {
struct Vec a = {1, 2}, b = {3, 4};
struct Vec s = add(a, b);
printf("sum = (%d, %d)\n", s.x, s.y);
scale(&s, 2);
printf("scaled = (%d, %d)\n", s.x, s.y);
return 0;
} How It Works
addworks on copies and returns a newstruct Vec.scalereceives&s, so it changessdirectly.- 1+3 = 4, 2+4 = 6, then both double.
