Structure, Typedef & Enumerated Data Type: Module - 3
Structure, Typedef & Enumerated Data Type: Module - 3
Programming in C++
17
In the previous lesson you have learnt that array is a collection of values of
same data type. Sometimes it is required to store information, which can be
of same or different types. For this purpose, structure statement is used in C++
programming language. In this lesson you will learn three important statements
structure, typedef and enumerated data type of C++ programming language.
OBJECTIVES
After reading this lesson, you will be able to:
z define variable, initialize and access members of the structure;
z explain the concept of nested structure;
z explain typedef statement in a program;
z define enum statement and use it.
17.1 STRUCTURE
A structure is a collection of simple variables which can be of same or different
types. It is a user defined datatype which allows you to combine different data
types to store a particular type of record. The data items in a structure are called
the members of the structure. Consider the following example:
Example 1
# include < iostream.h >
struct student
{ char name [20]; int marks;
};
As the structure is nested inside another, you must apply the dot operator twice
to access the structure members:
The inner braces are required just to separate the values, although it is ignored
by the compiler.
17.2 TYPEDEF
It is used to define a new name for an existing data type. It provides an alternative
name for standard data type. It is used for self documenting the code by allowing
descriptive names (for better understanding) for the standard data type.
Example 3
jan = 0, feb = 1, mar = 2, apr = 3, may = 4
The ordering can be altered by using an equal sign and value.
enum months { jan = 1, feb, mar, apr, may };
Here jan = 1, feb = 2, mar = 3, apr = 4, may = 5
The value of the next element in the list is previous value plus one.
Enum color { red, green = 5, blue };
The value of blue will be 6 An enum variable takes
For example: only one value out of
the possible values.
# include < iostream.h >
enum months { jan, feb, mar, apr, may };
void main ( )
{
months m1, m2;
m1 = jan;
m2 = apr;
int diff = m2 - m1;
cout << “Months between” << diff << “\n”;
if (m1 > m2) cout << “m2 comes before m1”;
}
The output of the above program is
TERMINAL EXERCISE
1. What is a structure? Write a structure specification in C++ for the record
given below:
Code: A string of 5 characters (including null)
17.1
1 is a collection of simple variables which can be of same or different types.
2 new data type
3. structure variable. member
4. (a) 100
(b) The structures are equal