2.3.2 Defining and Accessing Structs
Structs help take the place of some classes by storing related member variables. The main use of a struct is to group similar data together under one variable type.
Basic Format for Structs
Structs are generally defined to store multiple data elements in a single format. Here is the basic syntax for a struct.
There are several things to notice about the definition. First, the definition begins by using the key word struct
. After that, the name of the struct is given. In this course, you will see structs names starting in lowercase letters and using camel case.
After the name is a set of curly brackets and inside of these you will see the different data types and variable names.
One thing to notice is that the struct definition ends with a curly bracket and a semicolon, ;
. The semicolon is critical.
Structs are typically defined at the top of the program and need to be defined before they can be used.
Example: Student struct
Let’s take a look at a specific example. If you wanted to create a student struct that can store the student’s name and their grade, it would look like this:
Notice in this example that it declares two member variables by giving a variable type and a name.
All values and the struct itself are public by default.
Using a Struct
Once created, you can use a struct like you would use another variable. Access for assignment and updates to the member variables is done through a dot access:
Using the student struct from above as an example, here is how you would assign and access a member variable.
Notice in the example that the student is declared and then values are defined without having to instantiate any object. Structs behave like a class in Java, but are much quicker and easier to implement. As a result, you will find that you will use structs often in your programming.
Last updated