[clang] Don't treat the default switch path as unreachable when all enumerators are covered (PR #123166)
Jeremy Rifkin via cfe-commits
cfe-commits at lists.llvm.org
Thu Jan 16 10:37:44 PST 2025
jeremy-rifkin wrote:
Hi Erich, thanks for taking a look.
My preference here would be to explicitly mark the default path as unreachable as such if the intent of the code is that the code path should be unreachable, similar to how one might write:
```cpp
bool is_prime(int num) {
if(num < 0) {
std::unreachable();
}
}
```
For such a function, the input `num` would never be negative under normal operation similar to how an enum might be assumed to never take on abnormal values under normal operation.
On one hand I can see an argument for treating enums as special, however, from a safety standpoint I think it’s much better to not make any assumptions about valid enum values.
Even setting flag enums and such aside, assuming enums can't take on abnormal values seems a very fickle assumption to bake into the compiler. Especially when C enums are involved, e.g. there is no warning on the following:
```cpp
enum E { a, b };
int foo(E e) {
switch(e) {
case E::a:
return 20;
case E::b:
return 30;
}
}
```
I don't know of any existing annotation that could be used to indicate the intent of an enum to clang. While on one hand I can see value in annotating a flag enum is such, e.g., my preference would be to not annotate enums about intended use and rather annotate the uses about relevant assumptions (i.e. marking paths unreachable explicitly). Sometimes enums are used in ways they aren’t intended and it would be impossible to predict that at the point of declaration (whether this is good practice or not is a different question). I'd also prefer to follow existing good practice (warn about a potentially non-returning path) here rather than rely on adoption of a new practice (annotations about enum use).
https://github.com/llvm/llvm-project/pull/123166
More information about the cfe-commits
mailing list