The importance of c enumeration (typedef enum) [duplicate]

  1. It’s definitely not “too technical”.

  2. “typedef” and “enum” are two completely different things.

  3. The basic reason to have “enums” is to avoid “magic numbers”:

    Let’s say you have three “states”: STOP, CAUTION and GO. How do you represent them in your program?

    One way is to use the string literals “STOP”, “CAUTION” and “GO”. But that has a lot of problems – including the fact that you can’t use them in a C “switch/case” block.

    Another way is to Map” them to the integer values “0”, “1” and “2”. This has a lot of benefits. But seeing “STOP” in your code is a lot more meaningful than seeing a “0”. Using “0” in your code like that is an example of a “magic number”. Magic numbers are Bad: you want to use a “meaningful name” instead.

Before enums were introduced in the language, C programmers used macros:

   #define STOP 0
   #define CAUTION 1
   #define GO 2

A better, cleaner approach in modern C/C++ is to use an enum instead:

enum traffic_light_states {
  STOP,
  CAUTION,
  GO
}; 

Using a “typedef” just simplifies declaring a variable of this type:

typedef enum {
  STOP,
  CAUTION,
  GO
} traffic_light_states_t ; 

Leave a Comment

tech