Using structs
- C++ course
- Beginner
- Lesson 95/116
- 4 min
Learn to declare struct variables and access fields.
Declaring a struct variable
After defining a struct, you can use it like a type. To declare a variable of the struct type, write the type name followed by the variable name.
struct Point { int x; int y; };
Point p;
p.x = 3;
p.y = 4;Here p is a variable of type Point. To access members you use the . operator: p.x and p.y. After assigning values to the members, you can use them in computations or output.
Assigning and using members
You assign values to a struct variable's members with = and read them with .. Members behave like normal variables; they can take part in arithmetic, comparisons and output.
Point p;
p.x = 5;
p.y = 10;
cout << p.x + p.y; // 15Here p.x and p.y are added like two ints. Keeping several members under one struct makes it easier to carry and process related data together; it also improves code readability.
Practice Assign Point members and add them
Declare Point p;. Assign p.x = 5; and p.y = 10;. Print their sum with cout << p.x + p.y << endl;.
Starter code
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
int main() {
// declare the variable, assign members, print their sum
return 0;
}Sample solution
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
int main() {
Point p;
p.x = 5;
p.y = 10;
cout << p.x + p.y << endl;
return 0;
}Expected output
15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you access the x member of p, a Point variable?
- p::x
- p->x
- p[x]
- p.x Correct answer
Explanation: The dot operator is used to access a member.
2 Match each expression with its result
| Term | Meaning |
|---|---|
p.x = 3 |
assigns 3 to x |
p.y |
reads the y member |
Point p |
declares a variable |
3 Fill in the blank: member access
Point p;
p____x = 7;
Point p;
p.x = 7;
Explanation: The dot operator accesses the member.