Enums in C

Our enum type ServerState is implemented using an enum in C.

#include <stdio.h>
#include <stdlib.h>

typedef enum {
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
} ServerState;

const char* stateName[] = {
    [StateIdle] = "idle",
    [StateConnected] = "connected",
    [StateError] = "error",
    [StateRetrying] = "retrying"
};

const char* serverStateToString(ServerState ss) {
    return stateName[ss];
}

ServerState transition(ServerState s) {
    switch (s) {
        case StateIdle:
            return StateConnected;
        case StateConnected:
        case StateRetrying:
            // Suppose we check some predicates here to
            // determine the next state…
            return StateIdle;
        case StateError:
            return StateError;
        default:
            fprintf(stderr, "unknown state: %s\n", serverStateToString(s));
            exit(1);
    }
}

int main() {
    ServerState ns = transition(StateIdle);
    printf("%s\n", serverStateToString(ns));

    ServerState ns2 = transition(ns);
    printf("%s\n", serverStateToString(ns2));

    return 0;
}

In C, we use an enum to define our ServerState type. This provides a way to create a set of named constants, which is similar to the enumerated type concept.

We create an array stateName to map each enum value to its string representation. This is analogous to the map used in the original example.

The serverStateToString function serves the same purpose as the String() method in the original code, converting a ServerState to its string representation.

The transition function remains largely the same, but we use C’s switch statement syntax.

In the main function, we demonstrate the usage of our enum and the transition function. Note that in C, we don’t need to worry about type mismatch between int and ServerState as we would in a more strongly-typed language.

To compile and run this program:

$ gcc -o enums enums.c
$ ./enums
connected
idle

This example demonstrates how to implement and use enum-like structures in C, providing a way to work with a fixed set of named values.