Website For Developers

Structures in C++



Syntax of structure declaration

struct myStructure {
// structure members
int numbr;
string name;
};


// Keep in Mind, Structure declaration is end with semicolon.

Syntax of defining structure variable

myStructure myVariable;
// myStructure is the structure name and myVariable is the structure variable name.

Syntax to access structure members

myVariable.numbr;
myVariable.name;
//myVariable is the structure variable name and numbr, name are structure members.


Example of structures in C++

#include<iostream>
#include<conio.h>
using namespace std;
//structure declaration
struct myStructure {
  int id;
  string name;
};

int main() {
  // defining structure variable
  myStructure myVariable;
  cout<<"Enter ID: ";
  cin>>myVariable.id; //access structure member id
  cout<<"Enter Name: ";
  cin>>myVariable.name; //access structure member name
  getch();
  return0;
}

Output

Enter ID: 73
Enter Name: Walton



Example of structures in C++

#include<iostream>
#include<conio.h>
using namespace std;
struct student {
  int id;
  string name;
  int age;
};

int main() {
  student s1,s2;
  // getting first student data
  cout<<"Enter first student ID: ";
  cin>>s1.id;
  cout<<"Enter first student name: ";
  cin>>s1.name;
  cout<<"Enter first student age: ";
  cin>>s1.age;

  // getting second student data
  cout<<endl<<"Enter second student ID ";
  cin>>s2.id;
  cout<<"Enter second student name: ";
  cin>>s2.name;
  cout<<"Enter second age: ";
  cin>>s2.age;
  if(s1.age < s2.age) {
    cout<<"First student is small. ";
  }
  else if(s2.age < s1.age) {
    cout<<endl<<"Second student is small. ";
  }
  else {
    cout<<endl<<"Both the students have the same age. ";
  }
  getch();
  return 0;
}

Output

Enter first student ID: 21
Enter first student name: Adam
Enter first student age: 8
Enter second student ID: 22
Enter second student name: Ali
Enter second student age: 13
First student is small.