[clang] Don't treat the default switch path as unreachable when all enumerators are covered (PR #123166)

via cfe-commits cfe-commits at lists.llvm.org
Thu Jan 16 15:47:56 PST 2025


Sirraide wrote:

> While it isn't technically 'unreachable', it IS by intent of the code. Is there perhaps some sort of annotation on the struct we have that we could skip this assumption on instead? Something that says "this enum might have values not in the enumerator list"?

Hmm, I can think of two options here.
1. Assume every enum is complete by default, and add a `[[clang::incomplete_enum]]` attribute (which you can then put on an enum declaration similarly to `[[nodiscard]]` on class declarations) or something like that to announce your intent to create values outside the declared enumerator range.
2. The opposite, i.e. assume every enum is incomplete by default, and add a `[[clang::complete_enum]]` attribute.

I do think it makes sense to require users to write
```c++
int foo(Enum e) {
    switch (e) {
        case Enum::A: return 1;
        // ...
    }

   std::unreachable();
}
```
by default. 

At least that’s what I personally have been doing for a long time. Also, GCC, MSVC, and EDG all warn on this by default, which imo is an indication that this is considered a serious enough accidental error that we should do the same—and as someone who once spent far too much time debugging a program that was accidentally falling off the end of a function, I’d argue that it doesn’t happen often, but when it happens, it’s *really* hard to spot (and I at least would find myself thinking that ‘the compiler should really have warned about that’).

https://github.com/llvm/llvm-project/pull/123166


More information about the cfe-commits mailing list