0
0
C++programming~5 mins

Defining structures in C++

Choose your learning style9 modes available
Introduction

Structures help you group related data together in one place. This makes your program easier to understand and use.

When you want to store information about a person, like name, age, and height.
When you need to keep details about a book, such as title, author, and pages.
When you want to organize data about a point in 2D space with x and y coordinates.
When you want to pass multiple related values to a function as one unit.
Syntax
C++
struct StructureName {
    dataType member1;
    dataType member2;
    // more members
};
Use struct keyword to define a structure.
Members inside a structure can be of different data types.
Examples
This defines a structure named Person with two members: name and age.
C++
struct Person {
    string name;
    int age;
};
This defines a Point structure to hold coordinates.
C++
struct Point {
    double x;
    double y;
};
This structure holds information about a book.
C++
struct Book {
    string title;
    string author;
    int pages;
};
Sample Program

This program defines a Person structure, creates a variable p1, sets its members, and prints them.

C++
#include <iostream>
#include <string>
using namespace std;

struct Person {
    string name;
    int age;
};

int main() {
    Person p1;
    p1.name = "Alice";
    p1.age = 30;

    cout << "Name: " << p1.name << "\n";
    cout << "Age: " << p1.age << "\n";
    return 0;
}
OutputSuccess
Important Notes

Remember to end the structure definition with a semicolon ;.

You can create many variables of the structure type to hold different data.

Structures help keep related data organized and easy to manage.

Summary

Structures group related data under one name.

Use struct keyword to define them.

Access members using the dot . operator.