Search code examples
cenumsc11stdatomic

Can I apply the C11 `_Atomic` keyword to enum types?


If I have a type

enum foo {
    FOO,
    BAR,
    BAZ,
};

can I then declare an atomic version of that type like

_Atomic(enum foo);

or do I have to use e.g. atomic_int and cast the result of atomic_load()?

The following program compiles without warnings:

    #include <stdatomic.h>
    #include <stdio.h>

    enum foo {FOO, BAR, BAZ};

    int main(void) {
        _Atomic(enum foo) foo_a;
        atomic_store(&foo_a, BAR);
        enum foo val = atomic_load(&foo_a);
        printf("%u\n", val);
        return 0;
    }

but so does:

    #include <stdatomic.h>
    #include <stdio.h>

    enum foo {FOO, BAR, BAZ};

    int main(void) {
        enum foo foo; // <---- non atomic
        atomic_store(&foo, BAR);
        enum foo val = atomic_load(&foo);
        printf("%u\n", val);
        return 0;
    }

Solution

  • Yes, all data types can be atomic, and there is no need to use the atomic generic functions for these. All operations with such an object is then atomic.

    For your second example it is weird that you compiler does not issue a warning. Using a non-atomic for an atomic operation is a constraint violation, so the compiler should give you a diagnostic.