Exhaustive matching for C enums

I like Rust. I like how it forces you to do exhaustive matching in match statements (well, as long as you don’t use a catch-all like _ => {}), so when I add a new enum type, the compiler helplfully reminds me to handle it.

I don’t get to work in Rust nearly as much as I’d like; I usually find myself swimming in the C, instead.

Thankfully, modern compilers like GCC and Clang have a lot of warnings you can enable to help you avoid mistakes. For example, you can get the same kind of exhaustive matching for switch statements that you can get in Rust’s match statements, provided that you don’t add a default case.

Adding the -Werror=switch and -Werror=return-type will handle this for you.

enum my_enum {
  MY_ENUM_foo,
  MY_ENUM_bar,
};

static char const *my_enum_as_string(enum my_enum value) {
  switch (value) {
    case MY_ENUM_foo: return "foo";
    case MY_ENUM_bar: return "bar";
    // no default
  }

  // no return
}

If, in the switch statement above, I forgot to handle either MY_ENUM_foo or MY_ENUM_bar, I’d have gotten a compiler error.

Tags: