C++ struct, short for C++ Structure, is an user-defined data type available in C++. It allows a user to combine data items of (possibly) different data types under a single name.
C++ structs are different from arrays because arrays only hold data of similar data-types; C++ struct, on the other hand, can store data of multiple data-types.
Each element in the structure is called a member.
A structure is defined with the struct
keyword. A structure is a possible collection of primary data types and other structures.
structure_name
holds the name we want to give to our structure.data_type variable
is the C++ variables of different data types like int
, char
, float
, etc.struct structure_name{//data_type variable 1//data_type variable 2//data_type variable 3...};
The code below initializes the structure of Employee
. It has three member variables:
name
: An array of char
type.age
: A variable of int
type.salary
**: A variable of float
type.struct Employee{char name[50];int age;float salary;};
Structures can be assigned values when they are initialized.
struct Employee{char name[50];int age;float salary;};int main() {struct Employee e1 = {"John", 32, 4200};//accessing the values in the variableprintf("Name: %s\n", e1.name);printf("Age : %d\n", e1.age);printf("Salary : %f\n", e1.salary);}
struct Employee{string name;int age;float salary;};int main() {struct Employee e1;e1.name = "Albert";e1.age = 32;e1.salary = 4200;//accessing the values in the variablecout<< "Name: " << e1.name <<endl;cout<< "Age : " << e1.age <<endl;cout<< "Salary : " << e1.salary <<endl;}
Variables in a structure are accessed by:
struct Employee{int age;float salary;};int main() {struct Employee e1 = {32, 4200};//accessing the values in the variablecout<< "Age : " << e1.age << endl;cout<< "Salary : " << e1.salary << endl;}