All lessons

Structs

8 min · C

Group related values under named fields: C's way to bundle data.

C · Structs0/5 cleared

Enemy 1 of 5

Bundling data with struct

A struct bundles related fields, like a name and a score, into one type. This code makes a struct Player and prints its name field with p.name. Press Run to see it.

Why this works

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.

You
Goblin Glitch
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.