C/C++ Arena

Step 1 of 7

Define a struct

Real data comes in groups. A player has a name, kills and deaths; a point has an x and a y. Keeping them in separate variables means passing three arguments everywhere and hoping they stay in sync. A struct bundles related variables into one new type.

#include <stdio.h>

struct Book {
    const char *title;
    int year;
    double price;
};

int main(void) {
    struct Book b = {"The C Programming Language", 1978, 45.0};
    printf("%s (%d)\n", b.title, b.year);
    b.price = b.price * 0.8;
    printf("sale price %.2f\n", b.price);
    return 0;
}
The C Programming Language (1978)
sale price 36.00

The parts

In memory

A struct's members are stored together, in declaration order, as one block. The compiler may add a few bytes of padding between members so each is aligned for fast access, which is why sizeof(struct Book) can be larger than the sum of its members.

Your turn: complete the struct and print the weapon's name and damage.

Next: Structs in functions