How to define an enumerated type (enum) in C?

It’s worth pointing out that you don’t need a typedef. You can just do it like the following

enum strategy { RANDOM, IMMEDIATE, SEARCH };
enum strategy my_strategy = IMMEDIATE;

It’s a style question whether you prefer typedef. Without it, if you want to refer to the enumeration type, you need to use enum strategy. With it, you can just say strategy.

Both ways have their pro and cons. The one is more wordy, but keeps type identifiers into the tag-namespace where they won’t conflict with ordinary identifiers (think of struct stat and the stat function: these don’t conflict either), and where you immediately see that it’s a type. The other is shorter, but brings type identifiers into the ordinary namespace.

Leave a Comment