c sharp Logo

Structures (Struct)


A C++ structure (also known as a struct) is a user-defined data type that can be used to group together related data items of different types. Structures are similar to classes, but they do not support inheritance or other object-oriented features.

To declare a structure in C++, you use the struct keyword. For example:

struct Person {

  char name[50];

  int age;

  float salary;

};

 

This declares a structure named Person with three members: name, age, and salary. The name member is a character array of 50 elements, the age member is an integer, and the salary member is a floating-point number.

Once you have declared a structure, you can create variables of that type. For example:

Person person;

 

This creates a variable named person of the Person structure type.

You can then access the members of the structure using the dot operator (.). For example:

person.name = "John Doe";

person.age = 30;

person.salary = 100000.00;

 

This sets the name, age, and salary members of the person structure to the specified values.

You can also use structures in loops and other control flow statements. For example:

Person people[3];

 

for (int i = 0; i < 3; i++) {

  // Get the name, age, and salary from the user.

  std::cin >> people[i].name >> people[i].age >> people[i].salary;

}

 

// Print the names, ages, and salaries of the people.

for (int i = 0; i < 3; i++) {

  std::cout << people[i].name << ", " << people[i].age << ", " << people[i].salary << std::endl;

}

 

This code will create an array of three Person structures and then prompt the user to enter the name, age, and salary for each person. The code will then print the names, ages, and salaries of the people to the console.

Structures are a powerful data type that can be used to organize and manipulate data in a variety of ways. They are efficient and easy to use, and they are a fundamental part of the C++ programming language.