TeachMate
My ProgressJoin Session

Structures

0/5 completed · ~0h 28m

All Topics
C++LearnStructuresSyllabus
1 / 5

Structures

beginner
6 min read

What you'll learn

  • Group related fields into one named type.
  • Initialize and access struct members.
  • Pass a struct to a function as a single value.

A structure (struct) groups related variables under one name.

Start With a Problem

To store one student you need a name, an age, and a gpa. As separate variables they are easy to mix up, and you cannot pass 'a student' to a function as one value.

string name1 = "Alice";
int age1 = 20;
double gpa1 = 3.8;   // ... and the same for every other student

Group the fields of one thing into a single type:

struct Student {
    string name;
    int age;
    double gpa;
};

Student s{"Alice", 20, 3.8};   // one value, three fields

Now a student is a single named value you can pass around. The rest of this note shows how to declare, initialize, and use structs.

Declaring a Structure

struct Student {
    string name;
    int age;
    double gpa;
};

Using Structures

Student s1;
s1.name = "Alice";
s1.age = 20;
s1.gpa = 3.8;

// Or initialize directly
Student s2 = {"Bob", 22, 3.5};

// Or with braces (C++11)
Student s3{"Charlie", 21, 3.9};

Printing Structures

void printStudent(const Student& s) {
    cout << "Name: " << s.name << endl;
    cout << "Age: " << s.age << endl;
    cout << "GPA: " << s.gpa << endl;
}

Array of Structures

Student class_[3] = {
    {"Alice", 20, 3.8},
    {"Bob", 22, 3.5},
    {"Charlie", 21, 3.9}
};

for (int i = 0; i < 3; i++) {
    printStudent(class_[i]);
}

Structures vs Separate Variables

// Bad: separate variables
string name1, name2, name3;
int age1, age2, age3;
double gpa1, gpa2, gpa3;

// Good: array of structures
struct Student { string name; int age; double gpa; };
Student students[3];

Common mistakes: forgetting the semicolon after the closing brace of a struct definition is a compile error, and a default-constructed struct leaves members with garbage values (Student s; leaves age indeterminate). Aggregate initialization follows member order, so listing values out of order silently assigns the wrong fields.

Key takeaway: Structures group related data under one name — classes add functions and access control on top.

Try it: Create a Book struct with title, author, and pages. Make an array of 3 books and print each one.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects