0

The question:

How can I get the compiler to warn me when I haven't included a branch for every possible value of a type? This is especially relevant when I am coding with a type that may gain values later (std::variant or an enum).


Example:

Here is the code I am playing with (in an attempt to make this work):

enum MyEnum {
    ECHAD
    ,SHTAYIM
    // ,SHALOSH
};

int main() {
    MyEnum x = ECHAD;
    switch (x) {
        case ECHAD:
            std::cout << "One" << std::endl;
            break;
        case SHTAYIM:
            std::cout << "Two" << std::endl;
            break;
        default:
            static_assert(false, "You haven't handled every possible value of MyEnum");
    }
}

And here is a godbolt with the following code: https://godbolt.org/z/Kn76q8naq

In my mental model, this should compile. Because every possible value of MyEnum has been accounted for. So the default branch need not get compiled. That is, until SHALOSH gets added to the enum. THEN the compiler should jump in and point this out to me.


More explanation

exhaustiveness checking serves as a kind of refactoring tool. Whenever you expand the possibilities in a type, the compiler will point you to the places where you forgot to handle the new cases you just created

For a fuller explanation please see this blog post: https://blog.janestreet.com/what-do-haskellers-have-against-exhaustiveness/ and the talk linked within it.

glennsl
  • 28,186
  • 12
  • 57
  • 75
Ari Sweedler
  • 807
  • 7
  • 25
  • 2
    Use compiler warning flags: `-Wall`, `-Wextra` and for treating warnings as errors `-Werror`: https://godbolt.org/z/Wz13e8arW – Yksisarvinen Mar 21 '22 at 22:01
  • 1
    Realted/duplicate: [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) – Yksisarvinen Mar 21 '22 at 22:02
  • 1
    Hello @Yksisarvinen. If you add as an answer: "Use [`-Werror=switch`](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options)", I will accept it. – Ari Sweedler Mar 21 '22 at 22:05
  • *"So the `default` branch need not get compiled."* All branches should be valid. There is `if constexpr` which allows to discard (dependant) not selected branch which is an exception. – Jarod42 Mar 22 '22 at 09:28
  • @Jarod42 If you’re switching on the value of a book and you have a `true` and a `false` branch, then the `default` branch need not be compiled. This is different than a known-at-compile-time constexpr. – Ari Sweedler Mar 22 '22 at 15:42
  • as a side note, there is a library for the efficient ML-style pattern-matrching in C++, https://github.com/solodon4/Mach7 – ivg Mar 22 '22 at 18:38

0 Answers0