<Previous Lesson

Visual Programming

Next Lesson>

Lesson#4

Structures and Unions

User Defined or Custom Data types .....................................................................2
1. Structures...................................................................................................2
Declaring struct variables ..............................................................................2
Initializing Structures.............................................................................................4
Accessing the fields of a structure .................................................................5
Operations on structures ...............................................................................6
2. Unions........................................................................................................6
Using a Union ................................................................................................6
Example.........................................................................................................6
3. Enumeration...............................................................................................7
Advantages and Disadvantages of Enumerations .........................................7
4. Typedef ......................................................................................................7
Advantages of typedef ...................................................................................8
What's the difference between these two declarations? ................................8
Summary...........................................................................................................8
Tips ...................................................................................................................8
Structures and Unions 2

User Defined or Custom Data types

In addition to the simple data types (int, char, double, ...) there are composite data types
which combine more than one data element. The Custom data types include:
1. Structures
2. Unions
3. Enumerations
4. Typedefs
Arrays are used to store many data elements of the same type. An element is accessed by
subscript, eg, a[i]. Similarly, structures (also called records) group elements which don't
need to all be the same type. They are accessed using the "." operator, eg, r.name.

1. Structures

“A structure is a collection of variables under a single name. These variables can be of
different types, and each has a name that is used to select it from the structure”
Let's take an example:
struct Person {
char name[20];
float height;
int age;
};
This defines a new type, Person. The order of the fields is generally not important. Don't
forget the semicolon after the right brace. The convention is to capitalize the first letter in
any new type name.

Declaring struct variables

The new struct type can now be used to declare variables. For example,

Person abc;

Structures are syntactically defined with the word struct. So struct is another keyword
that cannot be used as variable name. Followed by the name of the structure. The data,
contained in the structure, is defined in the curly braces. All the variables that we have
been using can be part of structure. For example:
struct Person{
char name[20];
Structures and Unions 3
float height;
int age;
};
Here we have declared a structure, ‘person’ containing different elements. The name
member element of this structure is declared as char array. For the address, we have
declared an array of hundred characters. To store the height, we defined it as float
variable type. The variables which are part of structure are called data members i.e. name,
height and age are data members of person. Now this is a new data type which can be
written as:
person p1, p2;
Here p1 and p2 are variables of type person l language and their extensibility. Moreover,
it means that we can create new data types depending upon the requirements.
Structures may also be defined at the time of declaration in the following manner:
struct person{
char name[20];
float height
int age;
}p1, p2;
We can give the variable names after the closing curly brace of structure declaration.
These variables are in a comma-separated list.
Structures can also contain pointers which also fall under the category of data type. So we
can have a pointer to something as a part of a structure. We can’t have the same structure
within itself but can have other structures. Let’s say we have a structure of an address. It
contains streetAddress like 34 muslim town, city like sukhar, rawalpindi, etc and country
like Pakistan. It can be written in C language as:
struct address{
char streetAddress[100];
char city[50];
char country[50];
}
Now the structure address can be a part of person structure. We can rewrite person
structure as under:
struct person{
char name[20];
address personAdd;
float height;
int age;
Structures and Unions 4
};
Here personAdd is a variable of type Address and a part of person structure. So we can
have pointers and other structures in a structure. We can also have pointers to a structure
in a structure. We know that pointer hold the memory address of the variable. If we have
a pointer to an array, it will contain the memory address of the first element of the array.
Similarly, the pointer to the structure points to the starting point where the data of the
structure is stored.
The pointers to structure can be defined in the following manner i.e.
person *pPtr;
Here pptr is a pointer to a data type of structure person. Briefly speaking, we have
defined a new data type. Using structures we can declare:
Simple variables of new structure
Pointers to structure
Arrays of structure

Initializing Structures

We have so far learnt how to define a structure and declare its variables. Let’s see how
can we put the values in its data members. The following example can help us understand
the phenomenon further.
struct person{
char name[64];
int age;
float height;
};
person p1, p2, p3;
Once the structure is defined, the variables of that structure type can be declared.
Initialization may take place at the time of declaration i.e.
person p1 = {“Ali”, 19, 5.5 };
In the above statement, we have declared a variable p1 of data type person structure and
initialize its data member. The values of data members of p1 are comma separated in
curly braces. “Ali” will be assigned to name, 19 to age and 5.5 to height. So far we have
not touched these data members directly.
To access the data members of structure, dot operator (.) is used. Therefore while
manipulating name of p1, we will say p1.name. This is a way of referring to a data
member of a structure. This may be written as:
p1.age = 20;
p1.height = 6.2;
Structures and Unions 5
Similarly, to get the output of data members on the screen, we use dot operator. To
display the name of p1 we can write it as:
cout << “The name of p1 = “ << p1.name;
Other data members can be displayed on the screen in the same fashion.
Remember the difference between the access mechanism of structure while using the
simple variable and pointer.
While accessing through a simple variable, use dot operator i.e. p1.name
While accessing through the pointer to structure, use arrow operator i.e. pPtr-
>name;

Arrays of structures

Let’s discuss the arrays of structure. The declaration is similar as used to deal with the
simple variables. The declaration of array of hundred students is as follows:
students[100];
In the above statement, s is an array of type student structure. The size of the array is
hundred and the index will be from 0 to 99. If we have to access the name of first student,
the first element of the array will be as under:
s[0].name;
Here s is the array so the index belongs to s. Therefore the first student is s[0], the 2nd
student is s[1] and so on. To access the data members of the structure, the dot operator is
used. Remember that the array index is used with the array name and not with the data
member of the structure.

Accessing the fields of a structure

The fields of a structure are accessed by using the "." operator followed by the name of
the field.

abc.name = “Name”;
abc.height = 5.5;
abc.age = 23;

Structures and Unions
6

Operations on structures

A struct variable can be assigned to/from, passed as a parameter, returned by function,
used as an element in an array. You may not compare structs, but must compare
individual fields. The arithmetic operators also don't work with structs. And the I/O
operators >> and << do not work for structs; you must read/write the fields individually.

2. Unions

A union is a user-defined data or class type that, at any given time, contains only one
object from its list of members (although that object can be an array or a class type).

Using a Union

A C++ union is a limited form of the class type. It can contain access specifiers (public,
protected, private), member data, and member functions, including constructors and
destructors. It cannot contain virtual functions or static data members. It cannot be used
as a base class, nor can it have base classes. Default access of members in a union is
public.
A C union type can contain only data members.
In C, you must use the union keyword to declare a union variable. In C++, the union
keyword is unnecessary:
union DATATYPE var2; // C declaration of a union variable
DATATYPE var3; // C++ declaration of a union variable
A variable of a union type can hold one value of any type declared in the union. Use the
member-selection operator (
.) to access a member of a union:
var1.i = 6; // Use variable as integer
var2.d = 5.327; // Use variable as double
You can declare and initialize a union in the same statement by assigning an expression
enclosed in curly braces. The expression is evaluated and assigned to the first field of the
union.

Example

// using_a_union.cpp

#include <stdio.h>
union NumericType
{
int iValue;

Structures and Unions
7

long lValue;
double dValue;
};
int main()
{
union NumericType Values = { 10 }; // iValue = 10
printf("%d\n", Values.iValue);
Values.dValue = 3.1416;
printf("%f\n", Values.dValue);
}
Output

10
3.141600

3. Enumeration

C++ uses the enum statement to assign sequential integer values to names and provide a
type name for declaration.

enum TrafficLightColor {RED, YELLOW, GREEN};
. . .
int y;
TrafficLightColor x;
. . .
y = 1;
x = YELLOW;

The enum declaration creates a new integer type. By convention the first letter of an
enum type should be in uppercase. The list of values follows, where the first name is
assigned zero, the second 1, etc.

Advantages and Disadvantages of Enumerations

Some advantages of enumerations are that the numeric values are automatically assigned,
that a debugger may be able to display the symbolic values when enumeration variables
are examined, and that they obey block scope. (A compiler may also generate nonfatal
warnings when enumerations and integers are indiscriminately mixed, since doing so can
still be considered bad style even though it is not strictly illegal.) A disadvantage is that
the programmer has little control over those nonfatal warnings; some programmers also
resent not having control over the sizes of enumeration variables.

4. Typedef

Typedef is creating a synonym "new_name" for "data_type"
Structures and Unions 8
Its syntax is: typedef data_type new_name;
Advantages of typedef
Long chain of keyword in declarations can be shortened.
Actual definition of the data type can be changed.
What's the difference between these two declarations?
struct x1 { ... };
typedef struct { ... } x2;
The first form declares a "structure tag"; the second declares a "typedef". The main
difference is that the second declaration is of a slightly more abstract type -- its users
don't necessarily know that it is a structure, and the keyword struct is

Tips

Use structures when you have to deal with heterogeneous data types like different
attributes of an object.
Take extreme care in accessing the members of a structure.
Keep in your mind that just declaring the structure does not occupy any space in
memory unless and until you define a variable of type struct.
While using unions, do remember that at one time only one member is contained
in it.
By default the values assigned to enumeration values starts at zero, but if
required, we can start assigning integer values from any integer.
The use of typedefs makes the code simpler by introducing short names for the
long data type names.

Summary

The custom or user defined data types are those data types which we create by our own
selves according to the requirements or the given situation. The most commonly used
custom data types include structures, unions etc. Unlike arrays, structures can store data
members of different data types. Unions are also a very important custom data type that
at a given time contains only one element from its member list. Enum declarations
creates a new integer type. The integer type is chosen to represent the values of an
enumeration type. Thus, a variable declared as enum is an int. Similarly, typedefs are also
used for making a synonym or provides way to shorten the long chain of keywords in

declarations.

<Previous Lesson

Visual Programming

Next Lesson>

Home

Lesson Plan

Topics

Go to Top

Next Lesson
Previous Lesson
Lesson Plan
Topics
Home
Go to Top