C enumeration type

Introduction to C enumeration types

usetypedefwithenumWe can use keywords to define a type that can have one value or another value.

This is one of the most important usestypedefKey words.

This is the syntax for enumerated types:

typedef enum {
  //...values
} TYPENAME;

By convention, the enumeration types we create are usually uppercase.

This is a simple example:

typedef enum {
  true,
  false
} BOOLEAN;

C comes with aboolTypes of, So this example is not practical, but you can understand it.

Another example is to define working days:

typedef enum {
  monday,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;

This is a simple program that uses this enumerated type:

#include <stdio.h>

typedef enum {
  monday,
  tuesday,
  wednesday,
  thursday,
  friday,
  saturday,
  sunday
} WEEKDAY;

int main(void) { WEEKDAY day = monday;

if (day == monday) { printf(“It’s monday!”); } else { printf(“It’s not monday”); } }

Each item in the enumeration definition is internally paired with an integer. So in this examplemonday is 0, tuesdayIt is 1, and so on.

This means that the condition may haveif (day == 0)insteadif (day == monday), But for us humans, it is easier to reason with names instead of numbers, so this is a very convenient syntax.

Download mine for freeC manual


More clang tutorials: