C Enumeration

An enumeration is a user-defined data type. We use the keyword enum for declaring an enumeration. Enumeration holds all the properties of integer so the size of an enumerator is 2 byte. We use enumerator for assigning names to the integral constants which makes the program easy to read and maintain. Here, you can see the syntax of enum in C language.

Syntax:

enum enum_name{ constant1, connstant2, ……, constantN};

Here, name of the enumeration is enum_name. So the enum_name is our own variable

And, constant1constant2,…., constantN are values of the type enum_name.

The value of constant1 is 0 (zero) by default. And, it is incremented by 1 for the sequential identifiers in the list. If we do not initialize the constant value then by default sequence starts from zero and next to generated value should be previous constant value one.

The C language also provides us with the privilege to change the default value of the enumerator. The following example illustrates these changes.

// Illustration of the change in default values of enum
enum  laptop{
    Toshiba = 0,
    Dell = 15,
    hp = 2,
    Lenovo = 13,
};

Example using enumeration in C

Code:

#include<stdio.h>
#include<conio.h>

enum period {science, math, social, health, english};
void main()
{
 enum period current;
 current=health;
 printf("%d period",current+1); 
 getch();
}

In the above example, “enum period” is a user-defined data type and current is an integer type variable. The current variable will initialize health. Here, we have added “current + 1” because enum starts from 0. So adding “1” will lead us to the exact answer. Otherwise, the program will display the value less than the original value. The above code will hence display its output as below.

Output:

4 period
SHARE C Enumeration

You may also like...

Leave a Reply

Your email address will not be published.

Share