C++: Struct Basics
Last updated: 2026-08-26
Arrays can store multiple values of the same type, but what if you need to store a student's name (string), age (integer), score (floating-point)?
That's where structs come in — combining multiple variables of different types into a single unit.
1. What Is a Struct?
(1) 1.1 Structs in Everyday Life
| Real-Life Example | Program Equivalent |
|---|---|
| A business card (name, phone, email) | Struct |
| A book (title, author, price) | Struct |
| A student (name, age, score) | Struct |
Characteristics of Structs:
- Members can have different types
- Contiguous memory (like arrays)
- A precursor to "classes" (you'll learn classes later)
(2) 1.2 Why Do We Need Structs?
Without structs (tedious):
▶ Example 2: Code Example (Difficulty ⭐)
#include <iostream>
#include <string>
int main() {
std::string name1 = "Alice";
int age1 = 20;
double score1 = 92.5;
std::string name2 = "Bob";
int age2 = 21;
double score2 = 88.0;
// ... you'd need to declare 3 × 100 variables!
return 0;
}
Output:
(program output)
With structs (concise):
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student s1 = {"Alice", 20, 92.5};
Student s2 = {"Bob", 21, 88.0};
// ... much cleaner!
return 0;
}
2. Declaring and Defining Structs
(1) 2.1 Declaring a Struct
Syntax:
struct StructName {
memberType1 memberName1;
memberType2 memberName2;
...
};
Example:
#include <iostream>
#include <string>
// Declare a struct
struct Student {
std::string name;
int age;
double score;
}; // ⚠️ Note: the semicolon is required!
int main() {
// ...
return 0;
}
💡 Key Point: A struct declaration ends with a semicolon! This is a common mistake for beginners.
3. Creating and Initializing Struct Variables
(1) 3.1 Creating a Struct Variable
Student s1; // Create a variable s1 of type Student
(2) 3.2 Initializing a Struct Variable
Method 1: Initialize in declaration order
Student s1 = {"Alice", 20, 92.5};
Method 2: Designated member initialization (C++20, recommended)
Student s1 = {.name = "Alice", .age = 20, .score = 92.5};
Method 3: Assign values individually
Student s1;
s1.name = "Alice";
s1.age = 20;
s1.score = 92.5;
💡 Tip: Method 1 or Method 2 is recommended for conciseness.
4. Accessing Struct Members
(1) 4.1 Reading Members
Syntax:
structName.memberName
Example:
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student s1 = {"Alice", 20, 92.5};
std::cout << "Name: " << s1.name << std::endl; // Alice
std::cout << "Age: " << s1.age << std::endl; // 20
std::cout << "Score: " << s1.score << std::endl; // 92.5
return 0;
}
(2) 4.2 Modifying Members
Student s1 = {"Alice", 20, 92.5};
s1.score = 95.0; // Modify the score
std::cout << "New score: " << s1.score << std::endl; // 95.0
5. Passing Structs as Function Parameters
(1) 5.1 Pass by Value (Not Recommended)
void printStudent(Student s) { // ❌ Pass by value: copies the entire struct, expensive
std::cout << "Name: " << s.name << std::endl;
}
(2) 5.2 Pass by Reference (Recommended)
void printStudent(const Student& s) { // ✅ Pass by reference: no copy, and cannot modify
std::cout << "Name: " << s.name << std::endl;
std::cout << "Age: " << s.age << std::endl;
std::cout << "Score: " << s.score << std::endl;
}
💡 Golden Rule: When passing a struct as a parameter, prefer const reference — it avoids copy overhead and prevents accidental modification.
6. Arrays of Structs
Structs can also be organized into arrays!
Example: Student Array (Difficulty ⭐⭐)
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
double score;
};
int main() {
Student students[3] = {
{"Alice", 20, 92.5},
{"Bob", 21, 88.0},
{"Charlie", 19, 95.0}
};
// Iterate over the struct array
for (int i = 0; i < 3; i++) {
std::cout << "========== Student " << i + 1 << " ==========" << std::endl;
std::cout << "Name: " << students[i].name << std::endl;
std::cout << "Age: " << students[i].age << std::endl;
std::cout << "Score: " << students[i].score << std::endl;
std::cout << std::endl;
}
return 0;
}
7. Practice: Student Grade Management (Struct Version)
▶ Example 1: Complete Student Grade Management (Difficulty ⭐⭐⭐)
#include <iostream>
#include <string>
#include <vector> // will learn vector later, using array for now
struct Student {
std::string name;
int age;
double score;
};
// Function declaration
void addStudent(Student students, int& count);
void printStudents(const Student students, int count);
double calculateAverage(const Student students, int count);
int main() {
const int MAX_STUDENTS = 100;
Student students[MAX_STUDENTS];
int count = 0;
int choice;
do {
std::cout << "========== Student Score Management ==========" << std::endl;
std::cout << "1. Add student" << std::endl;
std::cout << "2. Display all students" << std::endl;
std::cout << "3. CalculateAverage" << std::endl;
std::cout << "4. Exit" << std::endl;
std::cout << "Please select (1-4): ";
std::cin >> choice;
if (choice == 1) {
addStudent(students, count);
} else if (choice == 2) {
printStudents(students, count);
} else if (choice == 3) {
if (count == 0) {
std::cout << "No student data!" << std::endl;
} else {
std::cout << "Average: " << calculateAverage(students, count) << std::endl;
}
} else if (choice == 4) {
std::cout << "Goodbye!" << std::endl;
} else {
std::cout << "Error: Please enter 1-4 a number between 1-4!" << std::endl;
}
std::cout << std::endl;
} while (choice != 4);
return 0;
}
// Function definition
void addStudent(Student students, int& count) {
if (count >= 100) {
std::cout << "Maximum number of students reached!" << std::endl;
return;
}
std::cout << "Please enter your name: ";
std::cin.ignore();
std::getline(std::cin, students[count].name);
std::cout << "Please enter your age: ";
std::cin >> students[count].age;
std::cout << "Please enter score: ";
std::cin >> students[count].score;
count++;
std::cout << "Added successfully!" << std::endl;
}
void printStudents(const Student students, int count) {
if (count == 0) {
std::cout << "No student data!" << std::endl;
return;
}
std::cout << "\n========== Student List ==========" << std::endl;
for (int i = 0; i < count; i++) {
std::cout << i + 1 << ". Name: " << students[i].name
<< ",Age: " << students[i].age
<< ",Score: " << students[i].score << std::endl;
}
std::cout << "================================\n\n";
}
double calculateAverage(const Student students, int count) {
if (count == 0) {
return 0.0;
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += students[i].score;
}
return sum / count;
}
Output:
========== Student Score Management ==========
1. Add student
2. Display all students
3. CalculateAverage
4. Exit
Please select (1-4):
No student data!
Average:
Goodbye!
Error: Please enter 1-4 a number between 1-4!
Maximum number of students reached!
Please enter your name:
Please enter your age:
Please enter score:
Added successfully!
No student data!
========== Student List ==========
. Name:
===============================
▶ Example 3: Struct as a Function Return Value (Difficulty ⭐)
#include <iostream>
#include <string>
struct Student {
std::string name;
int age;
double score;
};
// Function that returns a struct
Student createStudent(std::string n, int a, double s) {
Student stu;
stu.name = n;
stu.age = a;
stu.score = s;
return stu;
}
int main() {
Student s1 = createStudent("Zhang San", 20, 92.5);
std::cout << "Name: " << s1.name << std::endl;
std::cout << "Age: " << s1.age << std::endl;
std::cout << "Score: " << s1.score << std::endl;
return 0;
}
Output:
Name:
Age:
Score:
8. Common Mistakes
(1) 8.1 Forgetting the Semicolon
Error Example:
struct Student { // ❌ Forgot the semicolon
std::string name;
int age;
} // ❌ There should be a semicolon here
int main() {
// ...
}
Compiler Error Message:
error: expected ';' after struct definition
(2) 8.2 Accessing a Non-Existent Member
Error Example:
struct Student {
std::string name;
int age;
};
int main() {
Student s1;
s1.score = 92.5; // ❌ Error: Student has no score member
return 0;
}
❓ FAQ
struct has default access of public > - class has default access of privateQ: What's the most important thing about struct basics? A: Understand the core concepts first, then reinforce them through practice examples.
📖 Summary
- Structs combine multiple variables of different types into a single unit
- Declaring a struct:
struct StructName { member list };(note the semicolon!) - Initialization:
StructName variableName = {value1, value2, ...}; - Accessing members:
variableName.memberName - When passing as a parameter, prefer
constreference - Structs can also be organized into arrays
📝 Exercises
-
Basic (Difficulty ⭐): Define a
Bookstruct with three members: title, author, and price. Create twoBookvariables and output them. -
Intermediate (Difficulty ⭐⭐): Define a
Rectanglestruct with two members: width and height. -
Write a function
double calculateArea(const Rectangle& r)to calculate the area -
Write a function
double calculatePerimeter(const Rectangle& r)to calculate the perimeter -
Test in
main -
Challenge (Difficulty ⭐⭐⭐): Define a
Datestruct (year, month, day), and write a function to check whether a date is valid (e.g., 2024-02-29 is valid, 2023-02-29 is invalid).
- Struct: packages different types of data into a single unit
- Member access uses the . operator; pointers use ->
- Initialization: uniform initialization {} or member-by-member assignment
- Structs can be used as function parameters and return values
- Struct arrays manage multiple records
9. 🚀 Next Steps
Now that you've learned structs, let's move on to Phase 4 (Pointers & References) — the most core and challenging part of C++, but mastering it will let you write more efficient code!