Structures
beginnerWhat you'll learn
- Group related fields into one named type.
- Initialize and access struct members.
- Pass a struct to a function as a single value.
A structure (struct) groups related variables under one name.
Start With a Problem
To store one student you need a name, an age, and a gpa. As separate variables they are easy to mix up, and you cannot pass 'a student' to a function as one value.
Group the fields of one thing into a single type:
Now a student is a single named value you can pass around. The rest of this note shows how to declare, initialize, and use structs.
Declaring a Structure
Using Structures
Printing Structures
Array of Structures
Structures vs Separate Variables
Common mistakes: forgetting the semicolon after the closing brace of a struct definition is a compile error, and a default-constructed struct leaves members with garbage values (Student s; leaves age indeterminate). Aggregate initialization follows member order, so listing values out of order silently assigns the wrong fields.
Key takeaway: Structures group related data under one name — classes add functions and access control on top.
Try it: Create a Book struct with title, author, and pages. Make an array of 3 books and print each one.