Thursday, 27 April 2017

Enum (Enumerated Type)

An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used.

enum flag { const1, const2, ..., constN };
 
Here, name of the enumeration is flag.

And, const1, const2,...., constN are values of type flag.

By default, const1 is 0, const2  is 1 and so on. You can change default values of enum elements during declaration (if necessary).

// Changing default values of enum
enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3,
};

Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here's how you can create variables of enum type.
enum boolean { false, true };
enum boolean check;
 

Example: Enumeration Type

#include <stdio.h>

 enum week 
{ 
 sunday, monday, tuesday, wednesday, thursday, friday, saturday 
};

 int main()  
{ 
  enum week today; 
  today = wednesday;
  printf("Day %d",today+1); 
  return 0; 
}

Output
Day 4

Why enums are used in C programming?

Enum variable takes only one value out of many possible values. Example to demonstrate it,
#include <stdio.h>

enum suit {
    club = 0,
    diamonds = 10,
    hearts = 20,
    spades = 3
} card;

int main() 
{
        card = club;
 printf("Size of enum variable = %d bytes", sizeof(card)); 
 return 0;
}
Output
Size of enum variable = 4 bytes
It's because the size of an integer is 4 bytes.
This makes enum a good choice to work with flags.

How to use enums for flags?

Let us take an example,
enum designFlags {
 ITALICS = 1,
 BOLD = 2,
 UNDERLINE = 4
} button;
Suppose you are designing a button for Windows application. You can set flags ITALICS, BOLD and UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above pseudocode.
// In binary

ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100 
Since, the integral constants are power of 2, you can combine two or more flags at once without overlapping using bitwise OR | operator. This allows you to choose two or more flags at once. For example,
#include <stdio.h>

enum designFlags {
 BOLD = 1,
 ITALICS = 2,
 UNDERLINE = 4
};

int main() {
 int myDesign = BOLD | UNDERLINE; 

        //    00000001
        //  | 00000100
        //  ___________
        //    00000101

 printf("%d", myDesign);

 return 0;
}
Output
5 

 

No comments:

Post a Comment