Jun 28, 2014

C Programming #30: Constant - enum

Following article will deal with yet another type of constant called enum (short for enumeration). Enumeration constant is part of data type called as enumeration data type. Enumeration data type is a user defined data type which consists of integral constant, each integral constant is given a symbolic name which is called as enumeration constant.


Syntax of enum :

enum xyz{CONST1, CONST2, CONST3};

xyz is name of enumeration data type, this data type can take on constant value CONST1, CONST2 and CONST3 and each constant has integral number 0,1,2 assigned to them, respectively.

Consider the following example


#include <stdio.h>
int main()
{
   /* Following is defining the new data type weekday */
   enum week_day {SUN, MON, TUE, WED, THU, FRI, SAT};

   /* Following is declaration two variables of type enum week_day */
   enum week_day day1, day2;

   int x;
   char a;

   day1 = SUN;
   day2 = THU;

   x = day1;
   a = FRI;

   printf("day1 is %d\n", SUN);
   printf("day2 is %d\n", THU);
   printf("value of x is %d\n", x);
   printf("value of a is %d\n", a);

   day1 = 1001;
 
   printf("day1 is %d\n", day1);
   printf("Sizeof day1 is %d\n", sizeof(day1));
 
   return 0;
}

Output of above program is


day1 is 0
day2 is 4
value of x is 0
value of a is 5
day1 is 1001
Sizeof day1 is 4

Explanation
  • enum week_day {SUN, MON, TUE, WED, THU, FRI, SAT};
    • Using above definition we are telling compiler that week_day is new enum data type name.
    • Such data type can have value SUN, MON etc.
    • Internally, compiler assigns number starting from 0, incrementing 1 each time.
    • Hence, SUN will take 0, MON will take 1 and so on.
  • enum week_day day1, day2;
    • This is declaring the variables day1 and day2 to be of type enum week_day.
    • Internally compiler will allocate space for day1 and day2.
    • Since enum can store named integral constants, the sizeof it is same as integer.
  • Enum variable/constant can be assigned to other integral variable/constant and vice versa.
  • Enum variable can be assigned other numbers other than the one provided in the set.


If there are lot of related constants then please use Enumeration constants instead of macro constant.

Can integral constant be given custom number ?
Yes we can assign them in following way

Example

enum type {CONST1 = 10, CONST2, CONST3 = 20, CONST4 = 10};

Following is integral values of constant.
  • CONST1 is 10
  • CONST2 is 11
  • CONST3 is 20
  • CONST4 is 10
Quiz - Not written yet
All Article - C Programming

No comments :

Post a Comment