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:

  1. Members can have different types
  2. Contiguous memory (like arrays)
  3. 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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
(program output)

With structs (concise):

CPP
#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:

TEXT 📖 Display only
struct StructName {
 memberType1 memberName1;
 memberType2 memberName2;
 ...
};

Example:

CPP
#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

CPP
Student s1; // Create a variable s1 of type Student

(2) 3.2 Initializing a Struct Variable

Method 1: Initialize in declaration order

TEXT 📖 Display only
Student s1 = {"Alice", 20, 92.5};

Method 2: Designated member initialization (C++20, recommended)

CPP
Student s1 = {.name = "Alice", .age = 20, .score = 92.5};

Method 3: Assign values individually

TEXT 📖 Display only
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:

TEXT 📖 Display only
structName.memberName

Example:

CPP
#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

TEXT 📖 Display only
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

CPP
void printStudent(Student s) { // ❌ Pass by value: copies the entire struct, expensive
 std::cout << "Name: " << s.name << std::endl;
}
TEXT 📖 Display only
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 ⭐⭐)

CPP
#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 ⭐⭐⭐)

TEXT 📖 Display only
#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:

TEXT 📖 Display only
========== 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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Name: 
Age: 
Score: 
💡 Tip: Structs can be used as function return values for creating and initializing struct objects.


8. Common Mistakes

(1) 8.1 Forgetting the Semicolon

Error Example:

TEXT 📖 Display only
struct Student { // ❌ Forgot the semicolon
 std::string name;
 int age;
 } // ❌ There should be a semicolon here

int main() {
 // ...
}

Compiler Error Message:

TEXT 📖 Display only
error: expected ';' after struct definition

(2) 8.2 Accessing a Non-Existent Member

Error Example:

CPP
struct Student {
 std::string name;
 int age;
};

int main() {
 Student s1;
 s1.score = 92.5; // ❌ Error: Student has no score member
 return 0;
}

❓ FAQ

Q What's the difference between a struct and a class?
A We'll cover classes in detail later, but briefly: > - struct has default access of public > - class has default access of private

Q: What's the most important thing about struct basics? A: Understand the core concepts first, then reinforce them through practice examples.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Define a Book struct with three members: title, author, and price. Create two Book variables and output them.

  2. Intermediate (Difficulty ⭐⭐): Define a Rectangle struct with two members: width and height.

  3. Write a function double calculateArea(const Rectangle& r) to calculate the area

  4. Write a function double calculatePerimeter(const Rectangle& r) to calculate the perimeter

  5. Test in main

  6. Challenge (Difficulty ⭐⭐⭐): Define a Date struct (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).


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!

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏