C++ Programming

C++ Structure, C++ enum data type and union with programming examples

C++ STRUCTURES

C++ Structure is composed of data items(members) that are not of the same type. So a C++ structure is a structure data type with a fixed number of components (not necessarily of the same type) that are accessed by name, not subscript.

The syntax for defining a c++ structure is:

struct structure_name

{

type member1;

type member2;

………..

………….

 type member_n;

};

Where struct is a reserved word; structure_name is any valid identifier name that identifies the structure. The structure_name is optional in many cases, but it is recommended to always use it. The member1, member2…..member_n are the individual member declarations. The member’s name must be unique within a structure, however, the same name may be used for the variable names outside of the c++ structure, but avoid it.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

struct student

{

int Rno;

char name[15];

float percentage;

};

A structure is first defined and then variables of structure type are declared. A variable of a structure type is declared to access data in the members of the c++ structure.


EXAMPLE

Declare a c++ structure with the address as tag and having two members name of character type and age of integer type.

struct address

{

char name (15);

int age;

};

The c++ structure member name is of character type with 15 characters length (including the null character) and age is of integer type.

C++ Structure Variables

A structure is a collection of data items or elements. It is defined to declare its variables. These are called structure variables. A variable of structure type represents the members of its structure.

When a structure type variable is declared, a space is reserved in computer memory to hold all members of the structure. The memory occupied by a structure variable is equal to the sum of the memory occupied by each member of the structure, A structure can be defined prior to or inside the main() function. In is defined inside the main() function then the structure variables can be declared only inside the main function. If it is defined prior to the main() function, its variables can be defined anywhere in the program.

To declare a structure variable, the structure is first defined, e.g.

struct address

{

char city [15];

 int pcode;

};

address tag, age;

In the above example, city and pcode are the members of the structure address. The variable tag and age are declared as structure variables. The structure address has two members: city and pcode. The variable city occupies 15 bytes and pcode occupies 2 bytes. Thus each variable of this structure will occupy 17 bytes space in memory, i.e. 15 bytes for the city and 2 bytes for pcode.



Accessing Members of a c++ Structure

The dot operator (.) is used to access the members of a structure. To access a member of a specific c++ structure, the structure variable name, the dot operator and then the member of the structure is written. The syntax to access a member of a structure is:

Struct_variable.struct_element

Where:

struct_variable

It specifics the name of the structure variable. A period or full-stop specifics the dot operator.

struct_element

It specifies the actual element of the structure whose value is to be accessed.

Example how to Accessing the members of a structure in C/C++:

#include <iostream>
using namespace std;
struct address
    {
        char city[15];
        int pcode;   
    };

int main()
{
    address addr;
    cout<<"Enter city :";
    cin>>addr.city;
    cout<<"Enter Postal code :";
    cin>>addr.pcode;
    cout<<"Output from structure"<<endl;
    cout<<"city :"<<addr.city<<endl;
    cout<<"Postal code :"<<addr.pcode<<endl;

    return 0;
}

Program output:

Enter city :New York
Enter Postal code : 10005
Output from structure
City : New York
Postal code : 10005


Initialization of C++ Structure Variables

The values into a structure variable can be assigned when it is declared. It is called initialization of the structure variable. To initialize a structure variable data is assigned to the members of the structure. To assign data to the members of the structure, the data items arc written in the same order in which these have been defined in the structure. The type of the data must also correspond to the type of the member of the structure. For example, in the C++ structure “address”, member city is of character type and is the first member. The value that is to be assigned to it must be of character type and is written first. Similarly, the second member is pcode. The value that is to be assigned to it must be of integer type and is written second.

struct address

{

Char city[15];

Int pcode;

};

Address tag={“new York ”, 10005};

Array Type Members of C++ Structure

The members of the structure may be of different types. These can also be simple variables or array variables.

For example, in the following structure. the member “sub” is an array of int type. It has four elements. The member “name” is of string type and a string is also an array.

 struct rec

{

char name [15];

int sub [4];

};

Method to access the elements of an array that is a member of a structure is the same as for other members. The dot operator accesses a specific element of an array of a member. its index value or subscript is used. The variable of a structure type that has an array members member is Initialized in the usual manner. The members of the array are initialized the same sequence in which they are defined in the structure. For example, in the following example, the member “sub” is initialized in the same way as an array variable is initialized.

struct result

}

char name [15];

int sub [4];

int total;

};

Result student= {“khan”, {30,20,48,50},0};

Example how to use Array Type Members of Structures in C/C++ programming:

#include <iostream>

using namespace std;
struct rec
    {
        char s_name[15];
        int sub[4];
        int total;
        
    };

int main()
{
    rec result;
    int i,j, total;
    
    cout<<"Enter student Name: ";
    cin>>result.s_name;
    for(i=0; i<=3; i++)
    {
        
        cout<<"Enter marks of subject: "<< i+1<<"=";
        cin>>result.sub[i];
    }
    result.total= result.sub[0] + result.sub[1] + result.sub[2] + result.sub[3];
    
    cout<<"output"<<endl<<endl;
    cout<<"Name of student: "<<result.s_name<<endl;
    for(i=0; i<=3; i++)
    {
        cout<<"marks of subject"<<i+1<<" : "<<result.sub[i]<<endl;
        
    }
    cout<<"total marks: "<< result.total;

    return 0;
}

Program Output:

Enter marks of subject: 1=50
Enter marks of subject: 2=80
Enter marks of subject: 3=60
Enter marks of subject: 4=40
Student detail marks sheet:

Name of student: Khan
Marks of subject1 : 50
Marks of subject2 : 80
Marks of subject3 : 60
Marks of subject4 : 40
Total marks: 230

Structure Variables as Arrays

A structure variable may also be declared as an array. This is done to manage a large number of records. Each variable of the array represents a complete record. For example, in the following example, the structure variable arts is of the array type. It contains 10 elements. Each element can store one record.

struct result

{

char s_name [15];

int sub [4];

 int total;

}

result arts[10];

There are three members of the above structure. Each member is accessed by one element of the arts array. The indexed variables are used to access these records. The index of first element or record is an arts[0]. Similarly, the last record is arts[9].


Example how to use Structure Variables as Arrays  in C/C++ programming:

#include <iostream>
using namespace std;

struct result
{
    char s_name[15];
    float marks;
    char city[25];
    
};
int main()
{
   result obj[5];
   int i;
   for(i=0; i<=4; i++)
   {
       cout<<"Input Record "<<i+1<<" : ";
       cin>>obj[i].s_name;
       cout<<"Enter marks of student : ";
       cin>>obj[i].marks;
       cout<<"Enter city of student : ";
       cin>>obj[i].city;
       
   }
   cout<<"output Records"<<endl;
   for(i=0; i<= 4; i++)
   {
       cout<<"Record # "<<i+1<<" : "<<obj[i].s_name<<" ";
       cout<<obj[i].marks<<" ";
       cout<<obj[i].city<<" "<<endl;
       
       
   }

    return 0;
}

Program Output:

Input Record 1 : khan
Enter marks of student : 345
Enter city of student : new york
Input Record 2 : john
Enter marks of student : 234
Enter city of student : new york
Input Record 3 :smith 
Enter marks of student : 654
Enter city of student : new york
Input Record 4 :xyz
Enter marks of student : 456
Enter city of student : new york
Input Record 5 :abc
Enter marks of student : 345
Enter city of student : new york
output Records
Record # 1 : khan 345 new york
Record # 2 : john 234 new york 
Record # 3 : smith 654 new york 
Record # 4 : xyz 456 new york 
Record # 5 : abc 345 new york 

Initialization of Array of Structure

Like an array, the data into array of structure variables can also be assigned at the time of its declaration. For example, in the following example, the structure variable “rec” has three elements. The data of fields of each record is enclosed in braces and is separated by commas.

struct marks

{

char code [10];

char name [15];

float marks;

}

marks rec [3]= {

{ “GS”, “ABC”, 45.9},

{ “Math”, “XYZ”, 45.9},

{“Eng”, “khan”, 55.8}

};


Example how to initialize an Array of Structure in C/C++ programming:

#include <iostream>

using namespace std;

struct marks 
{
char code [10]; 
char name [15]; 
float marks; 
};

int main()
{
   marks rec [3]= {
{ "GS", "ABC", 45.9}, 
{ "Math", "XYZ", 45.9},
{"Eng", "khan", 55.8}
};

int i;
for(i=0; i<=2; i++)
{
    cout<<"subject code :"<<rec[i].code<<"\t"<<"Name :"<<rec[i].name<<"\t"<<"marks :"<<rec[i].marks<<endl;
    
}


    return 0;
}

Program output:

subject code :GS  Name :ABC   marks :45.9
subject code :Math  Name :XYZ   marks :45.9
subject code :Eng   Name :khan  marks :55.8

Difference between Array and structure:

  • The array is the collection of the related data elements of the same type of element whereas structure is the collection of the different data types.
  • The array is derived datatype whereas structure is programming defining one.

Nested Structure

When members of a structure are defined as structure type, these are called nested structures.

struct info

{

char s name [15];

char f name [15];

char city [15];

int age;

};

 struct p_data

{

info sl;

info s2;

float x;

}

 p_data rec;

In the above example, info structure is defined with four members. The structure p_data is defined after the info and it contains three members, two are of structure type and one of float type. The members sl and s2 within the structure are the nested structures. The structure variable “rec“ is of nested structure type. It is like a structure of array. The structures can be nested to any degree.


Initialization of Nested Structures

The structure variable that contains members of structure type is initialized as the structure of array is initialized.

For example, the above structure variable “rec“ may be initialized as:

p_data rec = {

{“ABC”, “XYZ “, uk”, 20}

{“Khan”, “ali”, “usa”, 30}, 6.9};

Example how to initialize Nested Structure in C/C++ programming:

#include <iostream>
using namespace std;

struct info
{
char s_name[15];
char f_name[15];
char city[15];
int age;
};
struct p_data
{
info s1; 
info s2; 
float x;
};

int main()
{
   p_data rec = {
    {"Fawad khan", "Jamshaid Khan ", "uk", 25} ,
    {"Khan", "ali", "usa", 30}, 6.9};


cout<<"1st record "<<endl;
cout<<"Name : "<<rec.s1.s_name<<endl;
cout<<"S / O : "<<rec.s1.f_name<<endl;
cout<<"Address : "<<rec.s1.city<<endl;
cout<<"Age : "<<rec.s1.age<<endl<<endl;
cout<<"2nd record "<<endl;
cout<<"Name : "<<rec.s2.s_name<<endl;
cout<<"S / O : "<<rec.s2.f_name<<endl;
cout<<"Address : "<<rec.s2.city<<endl;
cout<<"Age : "<<rec.s2.age<<endl;


    return 0;
}

Program output:

1st record 
Name : Fawad khan
S / O : Jamshaid Khan 
Address : uk
Age : 25

2nd record 
Name : Khan
S / O : ali
Address : usa
Age : 30

Accessing Members of Nested Structures

The members of nested structures are accessed in the same way as the members of simple structures are accessed. However, to access members of nested structures, more than one dot operators are used.

For example:

rec.81.age = 22;

In the above statement “rec” is the name of the structure variable, sl is member of structure p_data and age is the member of structure info.

Example how to Accessing Members of  Nested Structure in C/C++ programming:

#include <iostream>
using namespace std;

struct rec
{
char s_name[15], f_name[15],city[15];
int age;
};
struct group
{
rec s1,s2; 
float x;
};

int main()
{
    group rec;
    cout<<"Enter Data for First Record"<<endl;
    cout<<"Enter Name :";
    cin>>rec.s1.s_name;
    cout<<"Enter father name :";
    cin>>rec.s1.f_name;
    cout<<"Enter Name of city :";
    cin>>rec.s1.city;
    cout<<"Enter age :";
    cin>>rec.s1.age;
    cout<<"Enter Data for second Record"<<endl;
    cout<<"Enter Name :";
    cin>>rec.s2.s_name;
    cout<<"Enter father name :";
    cin>>rec.s2.f_name;
    cout<<"Enter Name of city :";
    cin>>rec.s2.city;
    cout<<"Enter age :";
    cin>>rec.s2.age;
    cout<<"First Record is :";
    cout<<"Name :"<<rec.s1.s_name<<endl;
    cout<<"Father Name  :"<<rec.s1.f_name<<endl;
    cout<<"city :"<<rec.s1.city<<endl;
    cout<<"Age :"<<rec.s1.age<<endl;
     cout<<"second Record is :";
    cout<<"Name :"<<rec.s2.s_name<<endl;
    cout<<"Father Name  :"<<rec.s2.f_name<<endl;
    cout<<"city :"<<rec.s2.city<<endl;
    cout<<"Age :"<<rec.s2.age<<endl;
    return 0;
}

Program Output:

Enter Data for First Record
Enter Name :fawad khan
Enter father name :jamshaid khan
Enter Name of city :new york
Enter age :25
Enter Data for second Record
Enter Name :Abc
Enter father name :XYZ
Enter Name of city :new york
Enter age :30
First Record is :Name :fawad khan
Father Name  :jamshaid khan
city :new york
Age :25
second Record is :Name Abc
Father Name  :XYX
city :new york
Age :30

Unions and Structures in c++

Unions are special structures, used in advanced programming application. They enable us to store a number of different variables at same space in memory i.e. all variables (members) of union share the same memory location. Union and structure look alike and both syntaxes are almost same, but there is a difference. In structure, different variables are stored at different locations in memory, while in union, different variable are stored at same space in memory. The general syntax for union is

union union_name

{

Type member_1;

Type member_2;

………

………

Type member_n;

 

};

 

For example:

union DMC

{

int RNO;

float percentage;

char pass;

} Result;

As discussed earlier that the union is like a structure but union stores the different variables at the same memory locations. This may be examined with the help of sizeof operator.

The difference between union and struct data type size  in C/C++ programming :

Union data type size:

#include <iostream>

using namespace std;

int main()
{
    union student
    {
        char name[15];
        char gender;
        float percentage;
    }std;
    cout<<"size = "<<sizeof(union student);
    return 0;
}

Program output:

size = 16

struct data type size:  

#include <iostream>

using namespace std;

int main()
{
    struct student
    {
        char name[15];
        char gender;
        float percentage;
    }std;
    cout<<"size = "<<sizeof(struct student);
    return 0;
}

Program output:

size = 20

Like structure, dot operator is used to access union members.

For example:

Result.RNO=100;

Result.percentage=80.9;

Result.pass=P;

Since the variables share the same storage area within the computer’s memory, therefore only one member of a union is active at one time. thus it the responsibility of the programmer to keep track of what type of information is stored at any given time.

Difference between c++ structure and union:

  • The structure is the same as a union but the structure holds many objects at a time.
  • In structure, the member has own memory location. members of the union have the same memory location.

Structures and Function in c++:

You know that function returns only one value, but using call by reference, you can make a function return more than one value at a time. In this method, we pass the addresses, any change in the variables, stored at that addresses, would make change effective anywhere in the program, even in main().


Example write a program which calls by value in c++ structure:

When the value of the structure variable is passed as an argument of calling function is called call by value.

#include <iostream>

using namespace std;
void swap(int x, int y);

int main()
{
    int x=5;
    int y=6;
    swap(x,y);
    cout<<"X = "<<x<<"\t"<<"Y = "<<y<<endl;
    
    return 0;
}

void swap(int x, int y)
{
    int temp;
    temp=x;
    x=y;
    y=temp;
    cout<<"X = "<<x<<"\t"<<"Y = "<<y<<endl;
    return;
}

Program output:

X = 6 Y = 5

X = 5 Y = 6

Example write a program which calls by reference in c++ structure:

When the value of the address structure variable is passed as an argument  of calling function are called call by reference

#include <iostream>

using namespace std;
void swap(int *x, int *y);

int main()
{
    int x=5;
    int y=6;
    swap(&x,&y);
    cout<<"X = "<<x<<"\t"<<"Y = "<<y<<endl;
    
    return 0;
}

void swap(int *x, int *y)
{
    int temp;
    temp= *x;
    *x= *y;
    *y=temp;
    cout<<"X = "<<*x<<"\t"<<"Y = "<<*y<<endl;
    return;
}

 Program output:

X = 6   Y = 5

X = 6   Y = 5

Note:

When a structure element is to be pass to any other function it is essential to declare the structure outside the main function as global.

Pointer to structure:

Pointer to structure means we can assign the address of a structure to the structure type pointer variable. It points to the starting address of a structure.

Syntax :

Struct <name>  *ptr;

For example :

Struct student *ptr

Write a program to illustrate the concept of a pointer to structure:

#include <iostream>
using namespace std;

struct student
{
    int rollno;
    char name[13];
};

int main()
{
    student *ptr, data;

    ptr = &data;
    
    cout << "Enter Student name: ";
    cin >> (*ptr).name;
    cout << "Enter Student RollNo: ";
    cin >> (*ptr).rollno;
 
    cout << "Displaying Student information." << endl;
    cout << "Information = " << " Name is " << (*ptr).name <<" and the rollno is " <<(*ptr).rollno;

    return 0;
}

Output:

Enter Student name: fawad
Enter Student RollNo: 344
Displaying Student information.
Information =  Name is fawad and the rollno is 344

 

Enumerated (enum) Data types:

Like int, float etc, C/C++ has the facility to define your own data type. There are many ways to define user-defined type, enum type is one of them. Enumerations improve the program readability and to make the program easier to understand and use. These are called enum types, because they are enumerated by listing the constants that make up the type. These constants must be legal C/C++ identifiers and are separated by comma and enclosed in braces, it has the following general syntax.

enum typename {member1, member2…..};

where enum is the C/C++ reserved word, typename is any valid identifier’s name and member1, member2….(known as enumerators) are the individual identifiers that define integer constants. For example; the following declaration defines the enumeration type Animals which specifies 5 values:

enum Animals{mouse, cat, dog, cow, elephant};

After the above declaration, the values 0,1,2….. will automatically be assigned to the enumerators i.e. the value 0 will be assigned to identifier mouse, 1 to cat, 2 to dog and so on. You can also explicitly assign value to enum identifier. For example:

enum animals{mouse =1, cat, dog, cow, elephant};

enum animals{mouse =2, cat =5, dog =4, cow =1, elephant =3};

it is important to note that if more than one enum types are defined in a program, then the enumerators for these types must be different. For example, the following declarations are illegal

enum semester1 {EDP,C, math,English};

enum semester2 {electronics,math,java};


Example how to used enumerated (enum) data type in C/C++ programming:

#include <iostream>

using namespace std;

int main()
{
    enum Animals {mouse=1, cat, dog, elephant};
    Animals pets;
    int c;
    cout<<"Enter pet number"; 
    cin>>c;
    switch(c)
    {
        case (mouse):cout<<"Set trap";
        break;
        case (cat): cout<<"pet";
        break;
        case (dog):
        case (elephant):
        cout<<"Run";
        
    }
 

    return 0;
}

Program output:

Enter pet number: 2

pet

Enter pet number: 3

Run

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button