Nearby lessons
64 of 72C - enum
An enumeration or enum gives meaningful names to a group of integer constants. It makes program values easier to understand, such as days, colours, or order status.
1. What Is an enum?
An enum lets us give meaningful names to related integer constants. This is easier to understand than remembering what each number means.
In simple words: Instead of writing a number like 1 for green, we can use a name such as GREEN.
2. Default Values in enum
If you do not assign values, C starts with 0 for the first name and increases each following value by one.
3. Assign Your Own Values
You can assign specific integer values to enum names. If the next name has no value, it normally gets one more than the previous enumerator.
4. Use enum with switch
Using an enum with switch makes each case easy to understand because we can use meaningful names instead of numbers.
5. enum vs #define
Both enum and #define can be used to give names to values. An enum groups related integer constants together and can automatically assign the values.
- Use
enumfor related options such as days, menu choices, and statuses. - Use
#definewhen you need a preprocessor replacement, such as a simple symbolic constant.
Common Mistakes
- Remember that the first enum value is 0 by default, not 1.
- Use the exact enum constant names defined in your program.
- Do not assume C automatically rejects every integer value that is not listed in the enum.
- Do not forget the semicolon after the enum definition.
- The enum keyword defines an enumeration.
- By default, the first enum value is 0 and each next value increases by 1.
- You can assign your own values to enum constants.
- enum works well with switch statements.
- C does not automatically restrict an enum variable to only the listed values.