Wednesday, November 18, 2026
HomeC ProgrammingDeclaration, Values, change, Flags and Errors

Declaration, Values, change, Flags and Errors


An enum in C provides names to integer constants, and that’s virtually all it does. The compiler will fortunately retailer 42 in a variable whose enum solely defines 0, 1 and a pair of, and it by no means checks. GCC, Clang and MSVC don’t even agree on which integer kind an enum is. Used effectively, enums nonetheless make C code far simpler to learn and provides the compiler sufficient info to warn you when a change misses a case.

This information covers declaring enums and controlling their values, an actual order-status instance, change statements that warn about lacking circumstances, changing enums to strings, bit flags, the X-macro method, the brand new C23 syntax for selecting an enum’s dimension, and the errors that trigger actual bugs. A brief part on the finish exhibits how C++ adjustments enums with enum class. Each program was compiled and examined with GCC, Clang and MSVC.

What Is an Enum in C?

An enum (enumeration) in C is a user-defined kind manufactured from a set of named integer constants, referred to as enumerators. You write enum adopted by an non-compulsory tag and an inventory of names in braces:

enum traffic_light { RED, AMBER, GREEN };

enum traffic_light mild = GREEN;

Three info clarify most of how enums behave:

  • The constants are plain int values. RED is 0, AMBER is 1 and GREEN is 2, they usually can be utilized anyplace an int fixed can, together with case labels and array sizes.
  • An enum variable is an integer. Its precise integer kind is chosen by the compiler, and C doesn’t limit it to the listed values.
  • The names are world to their scope. Two enums in the identical scope can not each outline RED.

Use an enum at any time when a variable holds one in every of a hard and fast set of decisions: an order’s standing, a log degree, a day of the week, the state of a machine, or an error code.

Declaring an Enum and Setting Its Values

By default the primary fixed is 0 and each after it’s another than the earlier one. You can provide any fixed an express worth, and the counting continues from there:

/* fundamentals: declaring enums, the values the compiler assigns, express
   values, aliases, and looping over a contiguous enum. */
#embrace <stdio.h>

/* Values begin at 0 and go up by one. */
enum weekday { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

/* Express values, as in HTTP standing codes. A continuing with out "=" is one
   greater than the fixed earlier than it. */
enum http_status {
    HTTP_OK = 200,
    HTTP_CREATED,                 /* 201 */
    HTTP_NOT_FOUND = 404,
    HTTP_SERVER_ERROR = 500,
};

/* Two names might share a worth: right here the final actual degree doubles because the
   variety of ranges, so the enum can dimension an array. */
enum fan_speed { FAN_OFF, FAN_LOW, FAN_MEDIUM, FAN_HIGH, FAN_SPEED_COUNT, FAN_MAX = FAN_HIGH };

int essential(void)
{
    enum weekday at present = WEDNESDAY;
    printf("WEDNESDAY = %d, SUNDAY = %dn", (int)at present, SUNDAY);
    printf("weekend? %sn", at present >= SATURDAY ? "sure" : "no");

    printf("HTTP_OK = %d, HTTP_CREATED = %d, HTTP_NOT_FOUND = %dn", HTTP_OK, HTTP_CREATED, HTTP_NOT_FOUND);

    static const char *const fan_names[FAN_SPEED_COUNT] = {"off", "low", "medium", "excessive"};
    for (enum fan_speed s = FAN_OFF; s < FAN_SPEED_COUNT; s++)
        printf("fan %d: %spercentsn", (int)s, fan_names[s], s == FAN_MAX ? " (max)" : "");

    printf("sizeof(enum weekday) = %zu, sizeof(int) = %zun", sizeof(enum weekday), sizeof(int));
    return 0;
}

Output:

WEDNESDAY = 2, SUNDAY = 6
weekend? no
HTTP_OK = 200, HTTP_CREATED = 201, HTTP_NOT_FOUND = 404
fan 0: off
fan 1: low
fan 2: medium
fan 3: excessive (max)
sizeof(enum weekday) = 4, sizeof(int) = 4

What this exhibits:

  • Default values begin at 0. WEDNESDAY is 2 and SUNDAY is 6, so comparisons corresponding to at present >= SATURDAY work on the order of declaration.
  • Express values could also be something that matches. HTTP_CREATED has no worth of its personal, so it’s HTTP_OK + 1, which is 201.
  • Two names might share a worth. FAN_MAX is an alias for FAN_HIGH.
  • A remaining COUNT fixed is the variety of values earlier than it, so long as they begin at 0 with no gaps. It sizes the fan_names desk and ends the loop. Maintain it final, or it stops being the rely.

An enum’s dimension is normally 4 bytes, the identical as int, however the usual doesn’t promise this, because the part on what kind an enum is exhibits.

A Actual-World Instance: Order Standing

A web-based store tracks each order by a collection of phases. That could be a pure enum, and it exhibits the selections that matter in actual code: which numbers to make use of, how you can title every worth, how you can learn one from textual content, and which adjustments are allowed.

#ifndef ORDER_H
#outline ORDER_H

#embrace <stdbool.h>

/* The phases of an internet order. The numbers are written to the database,
   so each is mounted explicitly and by no means reused: including a stage means
   including a brand new quantity on the finish, not renumbering. Zero is unnoticed on
   goal, so a standing that was by no means set (a zeroed struct) is invalid. */
typedef enum order_status {
    ORDER_PENDING   = 1,
    ORDER_PAID      = 2,
    ORDER_SHIPPED   = 3,
    ORDER_DELIVERED = 4,
    ORDER_CANCELLED = 5,
} order_status;

/* True if v is without doubt one of the values above. Verify this earlier than changing a
   quantity from a file, the community or the consumer into an order_status. */
bool order_status_valid(int v);

/* "pending", "paid", ...; "invalid" for some other worth. */
const char *order_status_name(order_status s);

/* Parses a reputation corresponding to "shipped". Returns false for anything. */
bool order_status_parse(const char *textual content, order_status *out);

/* The enterprise guidelines: which stage might observe which. */
bool order_can_move(order_status from, order_status to);

#endif
#embrace "order.h"

#embrace <string.h>

bool order_status_valid(int v)
{
    return v >= ORDER_PENDING && v <= ORDER_CANCELLED;
}

/* A change with no default: if a brand new standing is added and never dealt with
   right here, GCC and Clang warn (-Wswitch, a part of -Wall). */
const char *order_status_name(order_status s)
{
    change (s) {
    case ORDER_PENDING:   return "pending";
    case ORDER_PAID:      return "paid";
    case ORDER_SHIPPED:   return "shipped";
    case ORDER_DELIVERED: return "delivered";
    case ORDER_CANCELLED: return "cancelled";
    }
    return "invalid";
}

bool order_status_parse(const char *textual content, order_status *out)
{
    for (int v = ORDER_PENDING; v <= ORDER_CANCELLED; v++) {
        if (strcmp(textual content, order_status_name((order_status)v)) == 0) {
            *out = (order_status)v;
            return true;
        }
    }
    return false;
}

bool order_can_move(order_status from, order_status to)
{
    change (from)  to == ORDER_CANCELLED;
    case ORDER_PAID:      return to == ORDER_SHIPPED 
    return false;
}
enum order_status: the allowed adjustments Every field is one enumerator and the quantity saved for it. Arrows are the strikes order_can_move() permits. rejected after transport ORDER_PENDING = 1 ORDER_PAID = 2 ORDER_SHIPPED = 3 ORDER_DELIVERED = 4 ORDER_CANCELLED = 5 0 will not be used: a zeroed standing is invalid. Values are written to the database, so they’re express and by no means change. New phases get new numbers: 6, 7, …

Determine 1: The order-status enum as a state machine. The numbers are the values saved for every enumerator; the arrows are the adjustments order_can_move() permits, and the dashed arrow is one it rejects.

Three selections on this code keep away from bugs which might be straightforward to put in writing:

  • The values are express and begin at 1. The numbers find yourself in a database. Writing them out makes clear that they need to by no means change, and leaving out 0 means a standing that was by no means set (in a zeroed struct, say) is detected as invalid as an alternative of passing for “pending”.
  • order_status_name() makes use of a change with no default. If somebody provides ORDER_REFUNDED and forgets this operate, GCC and Clang warn. The return "invalid"; after the change handles values outdoors the enum.
  • Textual content is transformed to an enum in a single place. order_status_parse() accepts solely the precise names, and order_can_move() encodes the enterprise guidelines: a shipped order might be delivered however now not cancelled.

order_demo applies a file of standing updates to some orders, the way in which an order service processes occasions:

# order standing
1001 paid
1002 paid
1001 shipped
1002 cancelled
1003 paid
1001 cancelled
1003 refunded
1001 delivered
1004 shipped

Output:

order 1001: pending -> paid
order 1002: pending -> paid
order 1001: paid -> shipped
order 1002: paid -> cancelled
order 1003: pending -> paid
order 1001: shipped -> cancelled not allowed
order 1003: "refunded" will not be a standing, ignored
order 1001: shipped -> delivered
order 1004: pending -> shipped not allowed

Remaining standing (saved as numbers):
  order 1001  delivered = 4
  order 1002  cancelled = 5
  order 1003  paid      = 2
  order 1004  pending   = 1
3 updates rejected

The rejected strains are the fascinating ones. Order 1001 can’t be cancelled after it has shipped, “refunded” will not be a standing in any respect, and order 1004 can not ship earlier than it has been paid. The ultimate desk exhibits the numbers that will be saved, which is why these numbers are mounted within the header.

Utilizing an Enum in a change Assertion

A change over an enum reads higher than a sequence of if-else statements, and it provides the compiler an opportunity to assist. When a change on an enum worth has no default and doesn’t deal with each fixed, GCC and Clang warn. The warning is -Wswitch, and it’s a part of -Wall.

pitfalls/missing_case.c exhibits what occurs when a brand new fixed is added to an enum and one change will not be up to date:

enum standing { PENDING, PAID, SHIPPED, DELIVERED, REFUNDED };

static int delivery_days(enum standing s)
{
    change (s) {
    case PENDING:   return 5;
    case PAID:      return 4;
    case SHIPPED:   return 2;
    case DELIVERED: return 0;
    }
    return -1;          /* reached just for REFUNDED */
}

GCC stories it at compile time:

warning: enumeration worth 'REFUNDED' not dealt with in change [-Wswitch]

If the warning is ignored, this system runs and quietly returns the fallback worth:

Output:

standing 0: 5 days
standing 1: 4 days
standing 2: 2 days
standing 3: 0 days
standing 4: -1 days

Two habits make this warning give you the results you want:

  • Omit default when a change is supposed to cowl each enum worth. A default department tells the compiler you’ve dealt with every thing else, so it stops warning about new constants. Put the fallback after the change as an alternative, as order_status_name() does.
  • Construct with warnings as errors (-Werror, or -Werror=change for simply this one). The take a look at suite for this text builds missing_case.c that means and checks that the construct fails with a message naming REFUNDED.

MSVC doesn’t warn by default. Its equal, warning C4062, is off even at /W4. Flip it on with /w44062, or make it an error with /we4062 because the take a look at suite does.

Changing an Enum to a String

C has no built-in option to print an enum’s title: printf("%d") prints the quantity. There are three widespread methods to get the title.

1. A change. That is what order_status_name() does. It’s the most secure, as a result of -Wswitch catches a lacking title, and it really works for any values, together with gaps and enormous numbers.

2. A lookup desk with designated initializers. Every title is positioned on the index of its fixed, so the order of the strains now not issues:

static const char *const names[] = {
    [ORDER_PENDING] = "pending",
    [ORDER_PAID] = "paid",
    [ORDER_SHIPPED] = "shipped",
    [ORDER_DELIVERED] = "delivered",
    [ORDER_CANCELLED] = "cancelled",
};

That is quick and compact. However indexing it with a worth that’s not a legitimate standing reads outdoors the array, which is mistake #1 beneath.

3. An X-macro. One record generates each the enum and its names, so they can not drift aside. This program makes use of it for log ranges:

/* log_levels: an X-macro retains an enum and its names in a single record, in order that they
   can not drift aside when a degree is added.

   utilization: log_levels [debug|info|warning|error]   (the minimal degree to indicate) */
#embrace <stdio.h>
#embrace <string.h>

#outline LOG_LEVELS(X) 
    X(DEBUG, "debug")  
    X(INFO, "information")    
    X(WARNING, "warning") 
    X(ERROR, "error")

enum log_level {
#outline AS_ENUM(title, textual content) LOG_##title,
    LOG_LEVELS(AS_ENUM)
#undef AS_ENUM
    LOG_LEVEL_COUNT
};

static const char *const log_level_names[] = {
#outline AS_NAME(title, textual content) textual content,
    LOG_LEVELS(AS_NAME)
#undef AS_NAME
};

_Static_assert(sizeof log_level_names / sizeof log_level_names[0] == LOG_LEVEL_COUNT,
               "each log degree wants a reputation");

static void log_message(enum log_level minimal, enum log_level degree, const char *textual content)
{
    if (degree >= minimal)
        printf("[%-7s] %sn", log_level_names[level], textual content);
}

int essential(int argc, char **argv)
{
    enum log_level minimal = LOG_INFO;
    if (argc > 1) {
        int discovered = 0;
        for (int i = 0; i < LOG_LEVEL_COUNT; i++)
            if (strcmp(argv[1], log_level_names[i]) == 0) {
                minimal = (enum log_level)i;
                discovered = 1;
            }
        if (!discovered) {
            fprintf(stderr, "log_levels: unknown degree "%s"n", argv[1]);
            return 2;
        }
    }
    printf("%d ranges; exhibiting %s and aboven", LOG_LEVEL_COUNT, log_level_names[minimum]);
    log_message(minimal, LOG_DEBUG, "cache lookup for key 42");
    log_message(minimal, LOG_INFO, "server began on port 8080");
    log_message(minimal, LOG_WARNING, "disk 91% full");
    log_message(minimal, LOG_ERROR, "cost service unreachable");
    return 0;
}

Output:

4 ranges; exhibiting information and above
[info   ] server began on port 8080
[warning] disk 91% full
[error  ] cost service unreachable

With a better minimal degree, the debug and information messages are filtered out:

Output:

4 ranges; exhibiting warning and above
[warning] disk 91% full
[error  ] cost service unreachable

LOG_LEVELS(X) expands the macro X as soon as per degree. Outlined as AS_ENUM, it produces LOG_DEBUG, LOG_INFO, .... Outlined as AS_NAME, it produces "debug", "information", .... Including a degree is one new line within the record, and the _Static_assert stops the construct if the desk and the enum ever disagree. X-macros look uncommon at first, however they’re widespread in massive C code bases for error codes, opcodes and configuration keys.

Enum Flags: Combining Values with Bitwise Operators

When a variable wants to carry a number of choices without delay (permissions, options, file modes), give every enum fixed its personal bit. Then any mixture matches in a single integer, and the bitwise operators |, & and ~ add, take a look at and take away them:

/* flags: an enum of single bits, mixed right into a set of permissions,
   as in a file-sharing app. Every fixed is one bit, so any mixture
   matches in a single unsigned int. */
#embrace <stdio.h>

enum permission {
    PERM_READ   = 1u << 0,
    PERM_WRITE  = 1u << 1,
    PERM_SHARE  = 1u << 2,
    PERM_DELETE = 1u << 3,
};

/* A mix corresponding to READ | WRITE will not be one of many enum's constants,
   so the set is stored in an unsigned int slightly than an enum permission. */
typedef unsigned int permissions;

static void present(const char *who, permissions p)
{
    printf("%-8s 0xpercentX:", who, p);
    if (p == 0)
        printf(" none");
    if (p & PERM_READ)
        printf(" learn");
    if (p & PERM_WRITE)
        printf(" write");
    if (p & PERM_SHARE)
        printf(" share");
    if (p & PERM_DELETE)
        printf(" delete");
    putchar('n');
}

int essential(void)
 PERM_SHARE;
    printf("viewer can learn and share? %sn", (viewer & wanted) == wanted ? "sure" : "no");
    printf("editor can learn and share? %sn", (editor & wanted) == wanted ? "sure" : "no");
    return 0;

Output:

viewer   0x1: learn
editor   0x3: learn write
proprietor    0xF: learn write share delete
editor+  0x7: learn write share
owner-   0x7: learn write share
viewer can learn and share? no
editor can learn and share? sure
Enum flags: one bit per fixed The low 4 bits of an unsigned int. A set of permissions is the OR of its bits. PERM_DELETE 1u << 3 = 8 PERM_SHARE 1u << 2 = 4 PERM_WRITE 1u << 1 = 2 PERM_READ 1u << 0 = 1 viewer PERM_READ 0 0 0 1 0x1 editor PERM_READ | PERM_WRITE 0 0 1 1 0x3 editor, after |= PERM_SHARE 0 1 1 1 0x7 proprietor all 4 1 1 1 1 0xF

Determine 2: Permission flags from flags.c. Every enumerator is a single bit, so any mixture of permissions matches in a single unsigned int; the hex values match this system’s output.

Issues to note:

  • Every fixed is an influence of two, written as 1u << n so the bit place is seen. PERM_DELETE is bit 3, worth 8.
  • The set is saved in an unsigned int, not an enum permission. PERM_READ | PERM_WRITE is 3, which isn’t one of many enum’s constants. C would permit storing it within the enum variable, however the kind would then promise one thing it doesn’t imply.
  • To examine for a number of flags without delay, examine towards the entire masks. (p & wanted) == wanted is true solely when each bit in wanted is about; p & wanted alone is true when any one in every of them is.

What Sort Is an Enum in C?

Enumeration constants have kind int. The enum kind itself is “suitable with” an integer kind that the compiler chooses (C17 §6.7.2.2), so long as it could actually maintain all of the values. Compilers select in another way. underlying.c asks in two methods: with _Generic, which selects a string primarily based on the kind of its argument, and by storing −1 and studying it again, which exhibits whether or not the kind is signed:

/* underlying: which integer kind the compiler picked for every enum.
   The C normal leaves this to the implementation (C17 6.7.2.2), so
   the output differs between compilers. Enumeration constants
   themselves are at all times int earlier than C23. */
#embrace <stdio.h>

enum shade { RED, GREEN, BLUE };            /* no unfavourable values */
enum temperature { COLD = -10, HOT = 40 };  /* a unfavourable worth */

#outline TYPE_NAME(x) _Generic((x), 
    int: "int", unsigned int: "unsigned int", 
    lengthy: "lengthy", unsigned lengthy: "unsigned lengthy", 
    lengthy lengthy: "lengthy lengthy", unsigned lengthy lengthy: "unsigned lengthy lengthy", 
    char: "char", signed char: "signed char", unsigned char: "unsigned char", 
    quick: "quick", unsigned quick: "unsigned quick", 
    default: "one other kind")

int essential(void)
{
    enum shade c = GREEN;
    enum temperature t = HOT;
    (void)t;    /* _Generic solely appears to be like on the kind; it by no means evaluates t */
    printf("the fixed GREEN has kind   %sn", TYPE_NAME(GREEN));
    printf("enum shade is suitable with %sn", TYPE_NAME(c));
    printf("enum temperature is suitable with %sn", TYPE_NAME(t));
    printf("sizeof(enum shade) = %zun", sizeof c);

    /* A second take a look at that works the identical means on each compiler: retailer -1
       and skim it again. A signed kind retains -1; an unsigned one wraps. */
    enum shade probe = (enum shade)-1;
    lengthy lengthy again = probe;
    printf("(enum shade)-1 reads again as %lld: %sn", again, again < 0 ? "signed" : "unsigned");
    return 0;
}
Query GCC 13.3 Clang 18 MSVC
Sort of the fixed GREEN int int int
_Generic says enum shade is suitable with unsigned int unsigned int no integer kind (default)
_Generic says enum temperature is suitable with int int no integer kind (default)
sizeof(enum shade) 4 4 4
(enum shade)-1 reads again as 4294967295 (unsigned) 4294967295 (unsigned) -1 (signed)

Three issues stand out:

  • GCC and Clang selected an unsigned kind for enum shade, whose values are all non-negative, and int as soon as a unfavourable worth seems. Storing −1 in enum shade reads again as 4294967295.
  • MSVC selected a signed kind. The identical −1 reads again as −1, and the scale is 4 bytes. So the identical enum shade is unsigned on one compiler and signed on one other, and each are appropriate C.
  • MSVC’s _Generic matched the enum to no integer kind in any respect and fell by to default. The usual requires each enum to be suitable with some integer kind, and _Generic selects by compatibility, so this can be a quirk of MSVC’s _Generic, not a 3rd reply. It’s also why this system has the second, moveable take a look at: when a compile-time examine provides a shocking reply, verify it with a runtime one.

In on a regular basis code this hardly ever issues, but it surely does in three locations:

  • Printing. Solid to int earlier than passing an enum to printf("%d"). That’s at all times appropriate, whichever kind the compiler selected.
  • Comparisons with unfavourable numbers. If the enum is unsigned, if (shade < 0) is rarely true, and code that makes use of −1 as a “none” worth should outline it contained in the enum.
  • Binary layouts. Writing a struct containing an enum to a file or a community packet bakes within the compiler’s alternative. GCC’s -fshort-enums possibility even shrinks enums to the smallest kind that matches, which adjustments construction layouts and breaks compatibility with code constructed with out it. Retailer enums in information as fixed-width integers corresponding to uint8_t or int32_t, or use the C23 syntax beneath.

typedef enum and Naming Conventions

Writing enum order_status in all places is verbose, so most C code provides a typedef, as order.h does:

typedef enum order_status { ORDER_PENDING = 1, /* ... */ } order_status;

Now order_status alone is the kind. Preserving the tag (enum order_status) as effectively is beneficial as a result of a tag might be forward-declared and seems in debugger output.

Enumerator names share one namespace with variables, features and typedefs in the identical scope. Two enums can not each outline NONE:

/* Should NOT compile: enumeration constants share one namespace with
   variables and features, so two enums in the identical scope can not each
   have a relentless referred to as NONE. */
enum alignment { NONE, LEFT, RIGHT };
enum border { NONE, THIN, THICK };

int essential(void)
{
    return LEFT;
}
GCC:   error: redeclaration of enumerator 'NONE'
Clang: error: redefinition of enumerator 'NONE'

That’s the reason C enums conventionally prefix each fixed with the kind’s title, as in ORDER_, LOG_ and PERM_. Uppercase names observe the conference for constants. Brief names corresponding to OK, ERROR or NONE additionally collide with macros in system headers; Home windows headers, for instance, outline ERROR.

enum vs #outline vs const int

All three can title a relentless, however they don’t seem to be interchangeable:

Property enum fixed #outline const int
Has a kind the compiler checks int (the enum kind for variables) No, it’s textual content Sure, int
Usable in case labels and array sizes Sure Sure No (C17); sure with C23 constexpr
Teams associated values into one kind Sure No No
-Wswitch warns about lacking values Sure No No
Seen by title in a debugger Sure Often not Sure
Respects block scope Sure No, lively till #undef Sure
Any kind (floating level, strings, 64-bit earlier than C23) No, int solely Sure Sure

The case label row surprises many programmers. In C, in contrast to C++, a const int will not be a relentless expression:

/* Should NOT compile with warnings as errors: a const int will not be an
   integer fixed expression in C, so it can't be a case label.
   (An enumeration fixed can; see src/order.c.) */
static const int MAX_RETRIES = 3;

int give_up(int makes an attempt)
{
    change (makes an attempt) {
    case MAX_RETRIES:
        return 1;
    default:
        return 0;
    }
}

int essential(void)
{
    return give_up(1);
}
GCC:   error: case label doesn't scale back to an integer fixed
Clang: warning: expression will not be an integer fixed expression; folding it to a relentless is a GNU extension

GCC rejects this system. Clang accepts it as an extension and solely warns, so code that builds with Clang can fail on one other compiler. An enum fixed has neither drawback.

Use an enum for a set of associated integer decisions, #outline for values the preprocessor wants (#if, conditional compilation), and const variables for typed values that don’t must be fixed expressions.

C23: Selecting an Enum’s Underlying Sort

C23 helps you to write the integer kind after a colon, as C++ has allowed since C++11. The function comes from WG14 paper N3030:

/* c23_enum: C23 lets an enum title its underlying kind. Constructed solely by
   compilers that assist it (GCC 13+, Clang 18+ with -std=c2x or -std=c23). */
#embrace <stdio.h>

enum status_byte : unsigned char { S_PENDING = 1, S_PAID, S_SHIPPED, S_DELIVERED, S_CANCELLED };
enum status_plain { P_PENDING = 1, P_PAID, P_SHIPPED, P_DELIVERED, P_CANCELLED };

/* Constants might now be wider than int when the kind says so. */
enum file_size : lengthy lengthy { MAX_UPLOAD = 5LL * 1024 * 1024 * 1024 };   /* 5 GiB */

struct shipment_small { enum status_byte standing; unsigned char warehouse; unsigned quick weight_kg; };
struct shipment_plain { enum status_plain standing; unsigned char warehouse; unsigned quick weight_kg; };

int essential(void)
{
    printf("sizeof(enum status_byte)  = %zun", sizeof(enum status_byte));
    printf("sizeof(enum status_plain) = %zun", sizeof(enum status_plain));
    printf("struct with byte enum:  %zu bytesn", sizeof(struct shipment_small));
    printf("struct with plain enum: %zu bytesn", sizeof(struct shipment_plain));
    printf("1,000,000 shipments: %zu vs %zu bytesn",
           1000000 * sizeof(struct shipment_small), 1000000 * sizeof(struct shipment_plain));
    printf("MAX_UPLOAD = %lldn", (lengthy lengthy)MAX_UPLOAD);
    return 0;
}

Output:

sizeof(enum status_byte)  = 1
sizeof(enum status_plain) = 4
struct with byte enum:  4 bytes
struct with plain enum: 8 bytes
1,000,000 shipments: 4000000 vs 8000000 bytes
MAX_UPLOAD = 5368709120

A one-byte standing halves the scale of this cargo file, which issues when there are thousands and thousands of them or when the structure should match a file format byte for byte. A set kind additionally permits constants outdoors the int vary, such because the 5 GiB MAX_UPLOAD. The C23 guidelines additionally permit enums with out a mounted kind to carry values past int, with the compiler selecting a wider kind.

This wants a compiler with C23 assist: GCC 13 or newer and Clang 18 or newer, with -std=c2x or -std=c23. This system was constructed with each. MSVC’s C compiler doesn’t assist it but, so the repository builds this one program solely the place the compiler accepts it.

Widespread Errors with Enums in C

1. Trusting a quantity to be a legitimate enum worth

Values that come from outdoors this system, corresponding to a file, a database, a community packet or consumer enter, are plain integers. C helps you to convert any of them to an enum with out grievance. pitfalls/out_of_range.c reads three statuses, one in every of which (7) was written by a special program and isn’t a legitimate standing:

/* Pitfall: trusting a quantity to be a legitimate enum worth.

   C lets any int be saved in an enum variable. Statuses learn again from a
   file arrive as plain numbers, and one in every of them (7) will not be an order standing,
   as a result of one other program wrote it. Utilizing it to index a desk of names
   reads previous the tip of the desk.

   utilization: pitfall_out_of_range checked     (validates first: secure)
          pitfall_out_of_range unchecked   (indexes instantly: undefined conduct) */
#embrace "order.h"

#embrace <stdio.h>
#embrace <string.h>

static const char *const names[] = {
    [ORDER_PENDING] = "pending",
    [ORDER_PAID] = "paid",
    [ORDER_SHIPPED] = "shipped",
    [ORDER_DELIVERED] = "delivered",
    [ORDER_CANCELLED] = "cancelled",
};

int essential(int argc, char **argv)
{
    int checked = argc > 1 && strcmp(argv[1], "checked") == 0;
    const int from_file[] = {2, 4, 7};

    for (size_t i = 0; i < sizeof from_file / sizeof from_file[0]; i++) {
        int v = from_file[i];
        if (checked && !order_status_valid(v)) {
            printf("file %zu: standing %d will not be legitimate, skippedn", i, v);
            proceed;
        }
        order_status s = (order_status)v;           /* C accepts any worth */
        printf("file %zu: standing %d = %sn", i, v, names[s]);
    }
    return 0;
}

With validation, the unhealthy file is skipped:

Output:

file 0: standing 2 = paid
file 1: standing 4 = delivered
file 2: standing 7 will not be legitimate, skipped

With out it, names[7] reads previous the tip of a five-element desk. That’s undefined conduct: this system would possibly print rubbish, crash, or appear to work. UndefinedBehaviorSanitizer stops it on the unhealthy index:

out_of_range.c:35: runtime error: index 7 out of bounds for kind 'char *[6]'

With AddressSanitizer alone, the identical line is reported as a global-buffer-overflow. The repair is the one order.h supplies: examine each quantity from outdoors with order_status_valid() earlier than changing it. In code that handles untrusted enter, this examine is a safety requirement, not a mode alternative.

2. Including a relentless in the midst of a saved enum

Enum values are numbers, and numbers saved to a file or database outlive the code that wrote them. Inserting a brand new fixed in the midst of an enum with out express values renumbers every thing after it:

/* Pitfall: inserting a brand new fixed in the midst of an enum whose values
   are saved outdoors this system.

   Model 1 of a store saved order statuses to its database as numbers.
   Model 2 added ON_HOLD after PAID, with out express values, so each
   later fixed moved up by one. The outdated data now learn again incorrect. */
#embrace <stdio.h>
#embrace <string.h>

enum status_v1 { V1_PENDING, V1_PAID, V1_SHIPPED, V1_DELIVERED };
static const char *const names_v1[] = {"pending", "paid", "shipped", "delivered"};

enum status_v2 { V2_PENDING, V2_PAID, V2_ON_HOLD, V2_SHIPPED, V2_DELIVERED };
static const char *const names_v2[] = {"pending", "paid", "on maintain", "shipped", "delivered"};

int essential(void)
{
    const int saved_by_v1[] = {V1_PAID, V1_SHIPPED, V1_DELIVERED};
    printf("%-6s %-10s %-10sn", "worth", "saved as", "learn as");
    for (int i = 0; i < 3; i++) {
        int v = saved_by_v1[i];
        printf("%-6d %-10s %-10spercentsn", v, names_v1[v], names_v2[v],
               strcmp(names_v1[v], names_v2[v]) != 0 ? "  <- incorrect" : "");
    }
    return 0;
}

Output:

worth  saved as   learn as   
1      paid       paid      
2      shipped    on maintain     <- incorrect
3      delivered  shipped     <- incorrect

Information saved as “shipped” now learn again as “on maintain”, and delivered orders seem merely shipped. Nothing fails; the info is simply incorrect. When values are saved or despatched anyplace, give each fixed an express worth, and add new constants on the finish with new numbers.

3. Including a default department to an enum change

A default department silences -Wswitch, so the compiler can now not let you know about constants added later. Use default solely whenever you actually imply “every thing else”, and in any other case deal with invalid values after the change, as proven earlier.

4. Forgetting that enum names are world

Unprefixed names corresponding to NONE, ERROR or RED collide with different enums, with variables, and with macros from headers. Prefix each fixed with its kind’s title.

5. Assuming an enum’s dimension or signedness

Writing sizeof(enum ...) bytes to a file, or evaluating an enum with −1, relies on a alternative the usual leaves to the compiler. GCC and Clang selected an unsigned kind the place MSVC selected a signed one. Use fixed-width integers for storage, or C23’s enum title : kind syntax.

Enums in C++: enum class

C++ retains C’s enums, with one comfort: the enum key phrase is non-compulsory when declaring a variable, so Weekday day; works with out enum or a typedef. C++11 then added enum class, a scoped enumeration that fixes the weaknesses lined above:

  • Scoped names. The constants are written Sign::purple, so two enum lessons can each have purple.
  • No implicit conversions. An enum class worth doesn’t flip into an int except you write static_cast<int>.
  • A selected underlying kind. enum class Sign : std::uint8_t is one byte. C23 borrowed this syntax.
// enum_class: how C++ adjustments enums. A plain enum works as in C (and the
// enum key phrase is non-compulsory when declaring a variable); an enum class provides
// scoped names, no implicit conversion to int, and a selected underlying kind.
#embrace <cstdint>
#embrace <iostream>
#embrace <string_view>
#embrace <type_traits>

enum Weekday { monday, tuesday, wednesday };            // plain, as in C

enum class Sign : std::uint8_t { purple, amber, inexperienced };  // scoped, one byte
enum class Mild : std::uint8_t { off, purple, inexperienced };      // "purple" once more: no conflict

constexpr std::string_view title(Sign s)
{
    change (s) {
    case Sign::purple:   return "purple";
    case Sign::amber: return "amber";
    case Sign::inexperienced: return "inexperienced";
    }
    return "invalid";
}

constexpr Sign subsequent(Sign s)
{
    change (s) {
    case Sign::purple:   return Sign::inexperienced;
    case Sign::inexperienced: return Sign::amber;
    case Sign::amber: return Sign::purple;
    }
    return Sign::purple;
}

int essential()
{
    Weekday day = tuesday;          // no "enum" key phrase wanted in C++
    std::cout << "tuesday = " << day << 'n';

    Sign s = Sign::purple;
    for (int i = 0; i < 4; ++i) {
        std::cout << title(s) << " (" << static_cast<int>(s) << ")n";
        s = subsequent(s);
    }

    static_assert(sizeof(Sign) == 1, "the underlying kind is std::uint8_t");
    static_assert(std::is_same_v<std::underlying_type_t<Sign>, std::uint8_t>);
    std::cout << "sizeof(Sign) = " << sizeof(Sign) << ", sizeof(Weekday) = " << sizeof(Weekday) << 'n';
    std::cout << "Sign::purple = " << static_cast<int>(Sign::purple) << ", Mild::purple = "
              << static_cast<int>(Mild::purple) << ": similar title, two scopes, no clashn";
}

Output:

tuesday = 1
purple (0)
inexperienced (2)
amber (1)
purple (0)
sizeof(Sign) = 1, sizeof(Weekday) = 4
Sign::purple = 0, Mild::purple = 1: similar title, two scopes, no conflict

C++ can also be stricter than C about conversions. The primary line beneath compiles in C (with a plain enum), and each are errors in C++:

Colour c = 1;                 // int to enum: error in C++, even for a plain enum
int n = Sign::inexperienced;       // enum class to int: error; use static_cast<int>
g++:     error: invalid conversion from 'int' to 'Colour' [-fpermissive]
g++:     error: can not convert 'Sign' to 'int' in initialization
clang++: error: can not initialize a variable of kind 'Colour' with an rvalue of kind 'int'

The repository’s assessments examine that each applications fail to compile with GCC, Clang and MSVC.

How the Code Is Examined

An enum instance is straightforward to put in writing and straightforward to get subtly incorrect, so the assessments examine greater than the output.

  • Byte-for-byte output. Each program should print precisely the output proven on this article, besides underlying, whose reply is as much as the compiler.
  • Packages that should not compile. 5 applications, together with the title conflict, the const int case label, the 2 C++ conversions and missing_case.c constructed with its warning as an error, should fail to construct with a message that names the issue. A construct that fails for some unrelated cause doesn’t rely as a move.
  • Unit assessments for the order library. These examine that precisely the values 1 to five are legitimate, that each title parses again to its worth, that near-misses corresponding to “Paid” and “paid ” are rejected, and that each one 25 standing adjustments observe the foundations.
  • Deliberate errors. assessments/mutations.py places eight errors into the order library and confirms the unit assessments catch each:
Deliberate mistake Unit-test examine that failed
legitimate vary begins at 0 order_status_valid(v) == (v >= 1 && v <= 5)
legitimate vary misses the final standing order_status_valid(v) == (v >= 1 && v <= 5)
two statuses share a reputation order_status_parse(title, &again) && again == (order_status)v
parse skips the final standing order_status_parse(title, &again) && again == (order_status)v
parse accepts a prefix !order_status_parse("", &s)
shipped orders might be cancelled order_can_move((order_status)from, (order_status)to) == (allowed[from][to] == 1)
an order can skip cost order_can_move((order_status)from, (order_status)to) == (allowed[from][to] == 1)
invalid standing strikes anyplace !order_can_move((order_status)0, ORDER_PAID)

Key Takeaways

  • An enum is a set of named int constants. Values begin at 0 and go up by one except you give them explicitly.
  • C doesn’t examine enum values. Validate each quantity that comes from a file, the community or the consumer earlier than treating it as an enum, particularly earlier than utilizing it as an array index.
  • Omit default in a change that ought to cowl each worth, so -Wswitch warns when a relentless is added. MSVC wants /w44062 to provide the identical warning.
  • Give saved enums express values, and solely ever append. Inserting a relentless within the center silently renumbers saved information.
  • Use one bit per fixed for flags, and preserve combos in an unsigned integer.
  • An enum’s integer kind is as much as the compiler: GCC and Clang made enum shade unsigned, and MSVC made it signed. C23’s enum title : kind fixes it.
  • Prefix enum constants with the kind’s title, as a result of they share one namespace with every thing else in scope.

Conclusion

Enums are one of many least expensive methods to make C code clearer: a change over ORDER_SHIPPED and ORDER_DELIVERED explains itself, the place one over 3 and 4 doesn’t. The catch is {that a} C enum is just a naming system on prime of integers. The compiler won’t cease you from storing an invalid worth, reordering saved numbers, or counting on a dimension it by no means promised. Express values, validation on the boundaries, change statements with out default and warnings was errors cowl almost all of it.

For extra of the language, see the C programming part.

Supply Code and Exams

enums workflow status

All applications on this web page are within the sorts/enums listing of the MYCPLUS C examples repository.

Construct, take a look at and run:

cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
./construct/order_demo information/occasions.txt

What the construct checks.

  • Compilers: GCC and Clang beneath C11 and C17, plus C++17, with -Wall -Wextra -pedantic -Werror, and MSVC beneath /W4 /WX. missing_case.c is the one program allowed to construct with a warning, as a result of the warning is the lesson.
  • Output: each program prints precisely what’s proven right here.
  • Compile failures: the 5 applications that should not compile fail with the anticipated message.
  • Sanitizers and mutations: the assessments run clear beneath AddressSanitizer and UndefinedBehaviorSanitizer, the unchecked lookup is caught, and all eight deliberate errors are caught.

What I Verified

The whole lot within the Ubuntu column was run for this text on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18, CMake 3.28, MinGW-w64 GCC 13). The WSL and Home windows columns come from the run_all.sh and run_all.ps1 scripts within the repository.

Verify Ubuntu 24.04 WSL (Ubuntu) Home windows 11
Builds with warnings as errors: GCC and Clang (C11, C17, C++17) on Linux, MSVC /W4 /WX on Home windows GCC and Clang, C11 and C17: handed GCC 13.3 and Clang 18, C11 and C17: handed MSVC /W4 /WX, C11 and C17: constructed
CTest: unit assessments, byte-for-byte outputs, and 5 applications that should fail to compile 17 of 17 in all 4 configurations 17 of 17 in all 4 configurations 16 of 16 in C11 and in C17 (no C23 program)
C23 enum title : kind program Constructed and checked with GCC 13 and Clang 18 Constructed and checked with GCC and Clang Not constructed (MSVC’s C compiler doesn’t assist it)
AddressSanitizer and UndefinedBehaviorSanitizer, each take a look at 17 of 17, clear 17 of 17, clear Not relevant
The unchecked lookup in out_of_range.c is caught UBSan: index 7 out of bounds UBSan: index 7 out of bounds Not relevant
Valgrind memcheck, each program No errors, no leaks No errors, no leaks Not relevant
8 deliberate errors injected into the order library 8 of 8 caught 8 of 8 caught Not run
Home windows construct cross-compiled with MinGW-w64, warnings as errors Handed (C11 and C17) Not run Not relevant
Underlying kind of enum shade Unsigned: unsigned int (GCC and Clang) unsigned int (GCC and Clang) Signed: (enum shade)-1 reads again as −1. _Generic matched no integer kind

Not lined: macOS, embedded compilers (the place -fshort-enums is typically the default), and C23 on MSVC.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments