C Language | Structure Declarations | Enumerations - enum
An enumeration defines named integer constants. It is useful when a program handles a related set of values.
Named Constants
Declare an enumeration with enum.
enum Message { MSG_YES, MSG_NO };
The first omitted value is 0, and later omitted values increase by one. Explicit values change the sequence.
enum Message { MSG_YES, MSG_NO, MSG_OK = 8, MSG_CANCEL };
Here, MSG_CANCEL is 9.
#include <stdio.h>
enum Message { MSG_OK, MSG_YES = 2, MSG_NO };
int main(void) {
enum Message msg = MSG_NO;
printf("MSG_OK = %d : MSG_YES = %d : MSG_NO = %d\n",
MSG_OK, MSG_YES, msg);
return 0;
}
Enumerators are constants, not structure members. Write MSG_OK, not Message.MSG_OK. C compilers may accept integer values other than the declared enumerators, so validating values remains the programmer’s responsibility.
Enumerations are useful when one function supports several related modes.
enum { MSG_OK, MSG_YESNO };
enum { ID_OK = 1, ID_YES, ID_NO };
A message function can branch on MSG_OK or MSG_YESNO and return the corresponding identifier.