3 ms·
I sorta see where you're coming from, but I can't really see myself avoiding switch entirely in C. I do agree that it's very poorly designed since it makes it v
by simias 6y ago
I sorta see where you're coming from, but I can't really see myself avoiding switch entirely in C. I do agree that it's very poorly designed since it makes it very easy to shoot yourself in the foot. It does make it very nice to write some things, in particular state machines. It can even be less error prone in these situations since compilers will (sometimes) warn if you don't match all possible values of an enum, which is nice if you add a state to your machine and forget to update it everywhere.
Fortunately these days there are compiler warnings to alleviate some of the risks. GCC with -Wextra will warn if you have an unmarked fallthrough in a switch for instance (but not with -Wall).
But beyond that I do agree that if I could go back in time and tell Dennis Ritchie to change some things about the language "make switch break by default and add a fallthrough keyword when you actually want the behaviour" would be very high on the list. I get why he made it that way in the first place (if you implement switch/case in assembly with a jump table you get basically the same behaviour by default and you need additional code to break) but it makes for poor ergonomics in C.