Enumeration in C

In C language Enumeration or enum is a user defined data type. It is mainly used to assign names to integral constants.

Enumerations are defined much like structures; the keyword enum signals the start of an enumeration type. The general form for enumerations is :
 enum enum-type-name { const1, const2... constN } variable_list;

Where enum-type-name is name of the enumeration and const1, const2... are enum values. And variable_list is list of variables of enum type. Also note that both the enum-type-name and variable_list are optional, but at least one of them must be present.

Now lets see an example of enumeration :
enum numbers {
  num1,
  num2,
  num3,
} x;
The above statement create enumeration numbers with enum variable named x. And in enumeration by num1, num2 and num3 are by default assigned to 0, 1, 2 .. so on.

Also note that an enum variable can take only value out of enum vaules.

Now lets see a C example code :
#include <stdio.h>

enum numbers {
  num1,
  num2,
  num3
} x;

int main() {

  x=num1;
  printf("%d\n", x);

  x=num2;
  printf("%d\n", x);

  x=num3;
  printf("%d\n", x);

  return 0;
}
Output :

0
1
2

In the above example if we assign num1 = 100 then the value of num2 = 101 and num3 = 103.

Example :
#include <stdio.h>

enum numbers {
  num1=100,
  num2,
  num3
};

int main() {

  enum numbers x;

  x=num1;
  printf("%d\n", x);

  x=num2;
  • }
printf("%d\n", x); x=num3; printf("%d\n", x); return 0;
Output :

100
101
102

Another example :
#include <stdio.h>

enum numbers {
  num1=100,
  num2=200,
  num3=300
};

int main() {

  enum numbers x;

  x=num1;
  printf("%d\n", x);

  x=num2;
  printf("%d\n", x);

  x=num3;
  printf("%d\n", x);

  return 0;
}
Output :

100
200
300

Next Topic :