Structured Data
In C/C++ the struct, short for structure, is a composite type whose value is made up of a number of fields. Each field stores a value of a certain type. A value of the struct’s type stores data for each field described in the structure.
In your code, structs can be used to model data associated with the things, the entities, associated with your program. For example, a financial application can have structs to organise the data for account
, customer
, and transaction
types. A murder mystery game may have player
, clue
, and scene
types, whereas a space invaders game would have player
, alien
, and bullet
types. Each of these can be modelled in code using structured data.
Structs - Why, When, and How
Structs are your go-to tool for modelling the things (entities) within your digital reality. You can now put together all the data related to that entity in the one type. Then, when you want one of these entities in your code, you use your type. This can be in a local variable, or in parameters. Anywhere you have data can now be used to work with your entities.
Each struct should model an identifiable entity in your digital reality. These are one of your key building blocks, allowing you to clearly show the things associated with your program. As you think about the program, these entities should clearly relate to the program. For example, in a banking system you would expect to see accounts, and transactions. These are clearly entities associated with this domain.
As you build up these structs, think about the data associated with the entity. This can be simple data like the numbers and text, but can also be other structures or enumerations. For example, a bank account would have a name (text) and a number. A customer struct may then have an account as one of its fields.
Globally declaring structs has some great additional benefits. As you grow your program by building it iteratively, you can add additional fields to your structs. This will add the additional fields throughout your program - everywhere you have a variable of that type will now have these additional details. This is such a cool feature, so watch out for this as you start working with structs in your code.
In C/C++
Example
The following code shows an example of a struct in C/C++. The person
struct contains a name
, and an integer called age
. Remember that the type declaration is creating a new type. After declaring the struct, you can now create variables of the person_struct type.