Enumerations allow defining a user-defined data type consisting of integral constants. An enum defines a set of named constants and optionally assigns them values. By default, the first constant is 0 and subsequent constants are integers incrementing by 1. Enumerated types are useful for working with sets of related flag values that can be logically combined. They provide type safety and efficiency compared to using integer constants directly.
• An enumerationis 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
};
2
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;
• Here, a variable check of type enum boolean is created.
• Here is another way to declare same check variable using
different syntax.
enum boolean
{ false,
true } check;
3
Why enums areused in C
programming?
• Enum variable takes only one value out of many possible
values. Example to demonstrate it, This makes enum a good
choice to work with flags.
5
6.
• It's becausethe size of an integer is 4 bytes.
• This makes enum a good choice to work with
flags.
• You can accomplish the same task
using structures. However, working with
enums gives you efficiency along with
flexibility.
6
7.
How to useenums for flags?
• Suppose you are designing a button for Windows application.
You can set flags ITALICS, BOLD and UNDERLINE to work with
text.
• here is a reason why all the integral constants are power of 2
in above pseudocode.
7
8.
• Since, theintegral 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,
8
9.
• When theoutput is 5, you always know that
bold and underline is used.
• Also, you can add flag to your requirements.
9