NIOS Computer Science: Chapter 12 – Structure, Typedef & Enumerated Data Type Part 3

Download PDF of This Page (Size: 426K)

Figure shows enumerated data type

Figure Shows Enumerated Data Type

Figure shows enumerated data type

Typedef

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. (for beltes understanding) for the standard data type.

The general format is:

typedef existing data type new data type;

For example:

typedef float real;

Now, in a program one can use data type real instead of float.

Therefore, the following statement is valid:

real amount;

Enumerated Data Type

It has the following features:

Image of Enumerated Data Type Features

Image of Enumerated Data Type Features

Image of Enumerated Data Type 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.

For example:

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.

For example:

# 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 Months between 3 because the member of the enumerated series is stored as integer constant in the memory.