Structs
8 min · C
Group related values under named fields — C's way to bundle data.
Enemy 1 of 5
Bundling data with struct
So far every variable has held one kind of value on its own. A struct lets you bundle several related fields together under one type, even if the fields have different types themselves. struct Player { char name[20]; int score; }; declares a new type named struct Player that always carries both a name and a score together.
Once you have a struct Player p, you reach its fields with dot notation: p.name, p.score. This is the same dot syntax you may have already seen with method calls like .length() — in both cases, the dot means "look inside this value for the named piece."
Structs are C's version of what other languages call a class (without methods) or a record — grouping fields that belong together (a player's name and score, a point's x and y) is such a universal need that essentially every language has some equivalent, whether it's a struct, a class, or an object literal.
Loading editor...