C++ Structure, Typedef and Enumerated Data Type


A structure is a collection of simple variables which can be of same or different types. The data items in a structure are called the members of the structure.

Consider the following example:

#include <iostream.h>
struct student
char name[20];
int marks;
void main()
student S1, S3;
cin >> S1.name >> S1.marks;
cout << S1.name << S1.marks;
student S2 = {“ANKIT”, 32};
cout << S2.name << S2.marks;
S3 = S2;
cout << S3.name << S3.marks;

Variable of the structure

S1 and S2 are called variable of the structure student. They are given enough space in memory to hold the members of the structure (22 bytes each for above program).

Accessing of data members

The accessing of data members is done by using the following format: structure_variable.member_name

Initialization of structure variable

Initialization is done at the time of declaration of a variable. For example:

Student S2 = {“ANKITA”, 32};

Structure variable in Assignment Statements

The statement

S3 = S2;

assigns the value of each member of S2 to the corresponding member of S3. Since a large structure can have many members, such an assignment statement requires the compiler to do a considerable amount of work.

One structure variable can be assigned to another only when they are of the same structure type, otherwise compiler will give an error.


It is used to define new data type 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.

The general format is: typedef existing_datatype new_datatype;

For example:

typedef float real;

Now, in a program you can use datatype real instead of float. Therefore, the following statement is valid:

real amount;

Enumerated Data Type

It has the following features:

  • It is user defined.
  • It works if you know in advance a finite list of values that a data type can take.
  • The list cannot be input by the user or output on the screen.

For example:

enum months{jan, feb, mar, apr, may};

enum days{sun, mon, tue, wed, thu};

enum toys{cycle, bicycle, scooter};

The enum specifier defines the set of all names that will be permissible values of the type called members which are stored internally as integer constant. The first name was given the integer value 0, the second value 1 and so on. The value of the next element in the list is previous value plus one.