C++ Enum | Enumeration - Learn C++ - C++ Tutorial - C++ programming
Learn c++ - c++ tutorial - c++ enum - c++ examples - c++ programs
What is Enumeration in C++
- An enumeration is a user-defined data type that consists of integral constants. To define an enumeration, keyword enum is used.
- Here, the name of the enumeration is season.
- And, spring, summer and winter are values of type season.
- By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if necessary).
learn c++ tutorials - enum in c++ Example
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
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.
- Here, a variable check of type enum boolean is created.
Here is another way to declare same check variable using different syntax.
Example 1: Enumeration Type
Output
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
Example2: Changing Default Value of Enums
Output
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
Why enums are used in C++ programming?
- An enum variable takes only one value out of many possible values.
Example to demonstrate it,
Output
- It's because the size of an integer is 4 bytes.;
- This makes enum a good choice to work with flags.
- You can accomplish the same task using C++ structures. However, working with enums gives you efficiency along with flexibility.
How to use enums for flags?
- Let us take an example,
- 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.
- 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,
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
Output
- When the output is 5, you always know that bold and underline is used.
- Also, you can add flag to your requirements.