Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
struct
structure

What is a C++ struct?

Educative Answers Team

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.

Syntax

A structure is defined with the struct keyword. A structure is a possible collection of primary data types and other structures.

  • The 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
    ...
};

Code

Defining a structure

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;
};

Initializing a structure

Structures can be assigned values when they are initialized.

Before initialization:

struct Employee
{
  char name[50];
  int age;
  float salary;
};

int main() {
  struct Employee e1 = {"John", 32, 4200};

  //accessing the values in the variable
  printf("Name: %s\n", e1.name);
  printf("Age : %d\n", e1.age);
  printf("Salary : %f\n", e1.salary);
}

After initialization:

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 variable
  cout<< "Name: " << e1.name <<endl;
  cout<< "Age : " << e1.age <<endl;
  cout<< "Salary : " << e1.salary <<endl;
}

Accessing a Structure

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 variable
  cout<< "Age : " << e1.age << endl;
  cout<< "Salary : " << e1.salary << endl;
}

RELATED TAGS

c++
struct
structure
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring