Initializing and Accessing Members of a Structure Variable in C++
Understand how to initialize and access members of structure variables in C++. Learn both individual member assignment with dot operators and one-line initialization with initializer lists to manage structured data effectively.
We'll cover the following...
Introduction
We have seen how to define a structure and declare a structure variable in a program. Let’s see how we can store data in the member variables of the structure.
Basic syntax
The basic syntax for storing values in the member of the structure variable is given below:
To access the member of the structure variable, we write the name of the structure variable, followed by a dot operator, which is further followed by the name of the member. To assign a value to the member variable, we use the assignment operator followed by the value and the statement terminator (i.e., semicolon).
Example program
Let’s store values in structure variables s1, s2, and s3.
Explanation
Line No. 14: We are accessing the member name of s1 using the dot operator and then we set it to John.
Similarly, we access the member’s roll_number and marks and set their values.
We repeat the same procedure to set the values for the rest of the structure variables.
Initializing members in one line
You are probably thinking, setting each member of the structure variable is a tedious task. So, is there a way to set all the members of structure variables in one line?
Yes, there is. We can initialize structure variables in one line using the initializer list.
We will assign a comma-separated list of values enclosed in a curly bracket to the structure variable. The first member will be assigned the first value in the curly bracket, the second member will be assigned the second value, and so on.
ℹ️ If the initializer list does not have some member of structure variables, those members are automatically initialized to their default value.
See the program given below!
In the program above, we set the members of s1 and s2 in one line.
Let’s study an array of structures in the upcoming lesson.
Stay tuned!