Sunday, January 10, 2016

Enumeration Types

Enumeration types are used to hold a value that belongs to a particular set. Keyword 'enum' is used to define enumeration types. Each element in the enumeration type is assigned with a consecutive integer constant starting with 0 by default.
Syntax for declaring enum is given below
enum type_name{value_1, value_2, value_3,...}
Each of the values in the value set (ie; value_1, value_2 etc) are integer constants. By default, they start with 0 and increments by 1. You can override this values your self. Let's take a look at it with the help of an example.
  1. #include <stdio.h>
  2. enum day_of_week{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
  3. int main(){
  4. enum day_of_week today;
  5. //Assigns enum value sunday to the variable today.
  6. today = sunday;
  7. printf("%d", today);
  8. return 0;
  9. }
  10.  
  11. Output:
  12. 0
In the above program enum type "day_of_week" consists of 7 values; Sunday to Saturday. Each of them is internally assigned with an integer constant starting with 0 by default. 'Sunday' gets 0, 'Monday' gets 1 and so on. Here the 'printf' statement will output the value 0, because we've assigned enum value 'Sunday' to the variable 'today' of type 'day_of_week'.

If you want to use different integer values for the enumeration constants instead of the default values, you can assign it during the declaration as given below.
  1. #include <stdio.h>
  2. enum day_of_week{ sunday=4, monday, tuesday, wednesday=10, thursday, friday, saturday};
  3. int main(){
  4. enum day_of_week today;
  5. //Assigns enum value sunday to the variable today.
  6. today = monday;
  7. printf("%d", today);
  8. return 0;
  9. }
  10.  
  11. Output:
  12. 5
In the above program, we've assigned integer constant 4 to enum constant 'Sunday'. Now the value sequence will start with this assigned value. ie; Monday will get value 5, Tuesday will get value 6 and so on. Again we've overriden the default value for Wednesday (which would have been 7) to 10. This causes the value sequence to reset the values starting from Wednesday. So Thursday will get value 11, Friday will get value 12 and so on. Values assigned to the enumeration constants or the name of the constants it self shouldn't repeat in an enumeration.
What advantage you see by using enum over integer constants directly? 
You can see that enum improves the code readability and maintainability. If you directly use value 0, 1.. etc to represent days of a week, somebody else looking at the code might get confused. enum is a basic tool used in software programming to avoid such magic numbers.

No comments: