C/C++ Arena

Step 2 of 7

Structs in functions

A struct is a value, like an int. You can pass it to a function, return it from one, and assign one struct to another with =, which copies every member.

#include <stdio.h>

struct Rect {
    double w;
    double h;
};

double area(struct Rect r) {
    return r.w * r.h;
}

struct Rect scaled(struct Rect r, double k) {
    r.w *= k;
    r.h *= k;
    return r;
}

int main(void) {
    struct Rect a = {2.0, 3.0};
    struct Rect b = scaled(a, 2.0);
    printf("%.1f %.1f\n", area(a), area(b));
    return 0;
}
6.0 24.0

Copies again

Passing a struct copies it, just like an int. scaled changes its own copy r and returns it; a in main is untouched. That's often exactly what you want for small structs like points or rectangles: functions that take values and return new values are easy to reason about.

For large structs, copying every member on every call costs time, and a function that needs to modify the caller's struct can't do it through a copy. Both problems are solved with pointers, which is the next step.

Guarding a division

A ratio like kills per death needs care when the bottom is 0: dividing an int by zero is undefined behavior and usually crashes, and dividing a double by zero gives infinity (or "not a number" for 0.0 / 0.0). Check for the special case first and return the fallback the task asks for. Remember to convert to double before dividing, or the fraction is lost.

Your turn: write double kd(struct Player p) that returns kills divided by deaths as a double. If deaths is 0, return the kills.

Previous: Define a struct Next: Pointers to structs and ->