this post was submitted on 24 Jun 2025
7 points (88.9% liked)

C++

2040 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 2 years ago
MODERATORS
7
safe enum (programming.dev)
submitted 6 days ago* (last edited 6 days ago) by [email protected] to c/[email protected]
 

for anyone who doesn't know, this "-Werror=switch-enum" compiler option make the compiler throw an error if all of the enum values aren't explicitly handled in a "switch" statement


enum class colors {
        blue,
        red,
        purple,
}

void func(colors c)
{
        switch(c)
        {
                case colors::blue:
                        // do something
                        break;
                case colors::red:
                        // do something
                        break;
                default:
                        // do something
                        break;
        }
}


int main()
{
        func(colors::blue);
}

this code doesn't compile on clang and gcc with the option "-Werror=switch-enum" because the "colors::purple" isn't explicitly handled. be aware that it doesn't throw a compiler error for "if" statements if one of the values isn't handled

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here