Concept
How do enumerated types represent named values in C?
ComputerScienceOne / Using Enumerated Types for Error Codes
"19. Error Handling values it can take are SUNDAY, MONDAY, etc. and we can use these keywords in our program. For example,\n\nDayOfWeek today = MONDAY;\n\nif(today == SUNDAY || today == SATURDAY) {\n\nprintf(\"It is the weekend!\n\n\");\n\n}\n\nNote the modern naming conventions: the type identifier uses upper camel casing while the enumerated values follow an uppercase underscore convention. Though our example does not contain a value with multiple words, if it had, we would have used an underscore to separate them. Furthermore, enumerated type declarations are usually placed in separate header files along with function prototype declarations. Care must be taken when using enumerated types, however. Internally, C simply associates integers with the values. Thus, in our example, SUNDAY is actually 0, MONDAY is 1, and SATURDAY is 6. When we do assignments or equality comparisons, we’re actually just comparing integers. Consequently, a DayOfWeek variable may be assigned values that do not correspond to our enumeration. For example, DayOfWeek today = 1000; is valid code and will not (in general) result in any compiler errors or warnings, even though it is assigning an invalid value to the variable. You should only assign valid values to an enumerated type variable. Proper error checking should also be done. Despite this limitation, using enumerated types in C provides an obvious advantage. Without an enumerated type we’d be forced to use a collection of magic numbers to indicate values. Even for something as simple as the days of the week we’d be constantly trying to remember: which day is Wednesday again? I forget, does our week start with Monday or Sunday? Etc. By using an enumerated type these questions are mostly moot as we can use the more human-readable keywords and eliminate the guess work."
Related Ideas
- How do you declare an enumerated type in C?ComputerScienceOne · Enumerated Types
- Why are enumerated types better than arbitrary integer error codes?ComputerScienceOne · Enumerated Types
- How can a quadratic roots function return error codes?ComputerScienceOne · Error Handling By Design
- How do you declare and use an enumerated type in Java?ComputerScienceOne · More Tricks
- What advantages do enumerated types provide in Java?ComputerScienceOne · More Tricks
- What are POSIX Error Codes?ComputerScienceOne · POSIX Error Codes
- What topics are covered in error handling?ComputerScienceOne · Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . .
- What primitive types does C support?ComputerScienceOne · Declaration & Assignment