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

C++ Structure

Description:

C++ Structure- this is a very detail tutorial about structure in c++ and you will also learn different types of structure programming in this tutorial.

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.

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++:

Program output:


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:

Program Output:

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:

Program Output:

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:

Program output:

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:

Program output:

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:

Program Output:



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:

Program output:

struct data type size:  

Program output:

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.

Program output:


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

 Program output:

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:

Output:

 

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:

Program output:

 

Recommended For You

Leave a Reply

%d bloggers like this: