Date: agosto 25, 2025
Author: Guillermo Garcia
Categories: Embedded C programming Tags: Embedded C programming
In this article we are going to look at enumerations, which is a type of variable renaming in C and is very common in embedded system programs.
Table of Contents
An enumeration consists of a set of named integer constants (called the «enumeration set,» «enumerator
constants,» «enumerators,» or «members») and is considered a variable type. An enumeration type is
initialized with enum. The elements inside of the enumeration, for all intents and purposes, behave the
same as constants upon compilation of the code.
The enum keyword allows to create a new type that consists of a limited list of elements. Variables of such an enumeration type store one of the values of the enumerations set.
enum days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
creates a new type called enum days. Variables of that type can hold any one of the identifiers Sun till Sat. Internally, these identifiers are represented by integers starting from 0 for Sun until 6 for Sat.
The declaration enumerations:
enum days d1, d2;
creates 2 variables of the type enum days.
Print the days of the week using an enumeration type.
#include <stdio.h>
enum days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
void PrintDay(enum days);
int main(void)
{
enum days d1, d2;
d1 = Mon;
if (d1 == Mon)
printf("First working day of the week\n");
for (d2 = Wed; d2 < Sat; d2++)
PrintDay(d2);
return 0;
}
void PrintDay(enum days d)
{
switch (d)
{
case Mon: printf("Monday\n"); break;
case Tue: printf("Tuesday\n"); break;
case Wed: printf("Wednesday\n"); break;
case Thu: printf("Thursday\n"); break;
case Fri: printf("Friday\n"); break;
case Sat: printf("Saturday\n"); break;
case Sun: printf("Sunday\n"); break;
}
}
Output:
First working day of the week Wednesday Thursday Friday
Note that a switch is used to translate the identifiers Sun till Sat into real weekdays. Remember that a switch statement can only be used if the expression evaluates to an integer number. This is the case since the identifiers are internally stored as integer numbers.
It turns out that enumerated types are treated like integers by the compiler. Underneath they have numbers 0,1,2,… etc. You should never rely on this fact, but it does come in handy for certain applications.
For example, our security_levels enum has the following values:
enum days {Sun, Mon, Tue, Wed, Thu, Fri, Sat} = enum days {0, 1, 2, 3, 4, 5, 6};

Deja una respuesta