Defining a struct with the struct keyword
What you'll learn: How to create your own custom data type to group different variables together under one name.
The Limitation of Basic Types
Up until now, you have used variables to store single pieces of data: an int for a whole number, a char for a letter, or a float for a decimal. However, real-world data is rarely that simple. If you are writing a program for a library, a "Book" isn't just one number; it is a combination of a title, an author, and a page count.
Without structures, you would have to manage three separate variables for every single book. If you had ten books, you would have thirty scattered variables! A struct (short for structure) allows you to bundle these different variables together into a single "package."
Think of it Like a Form
Imagine a paper application form for a gym membership. The form has specific fields: Name, Age, and Membership ID. Even though one field is text and another is a number, they all belong to the same "entity"—the member.
In C, the struct keyword is how you design that blank form. You are telling the compiler, "From now on, I want a new type of data that contains these specific pieces of information."
The Syntax
To define a struct, you use the struct keyword followed by a name (called a tag) and a pair of curly braces. Inside the braces, you list the variables you want to include.
struct Player {
char level_grade;
int health_points;
float stamina;
};
In this example, we have created a new blueprint called struct Player. It hasn't created a player yet; it has simply defined what a player looks like. Note the semicolon at the end of the closing brace—this is required in C to signal the end of the definition.
Why Use This?
By grouping data, your code becomes much more organized. Instead of passing five different variables into a function, you can pass one single struct. It keeps related data "glued" together, making your programs easier to read and much harder to break.
Key takeaway
A struct is a custom data type that acts as a blueprint, allowing you to group variables of different types into a single, organized unit.