5 ms·
I did. But not requiring the `if` at all obviates the need for this `switch` abuse. Hence my question about its necessity.
by delinka 10y ago
I did. But not requiring the `if` at all obviates the need for this `switch` abuse. Hence my question about its necessity.
- pdpi 10y agothe ifs allow the code to function correctly even if you forget to update this function with newly-added cases in the enums. The switch statement makes the known-cases behave O(1), while also bypassing unneeded validation.
- akkartik 10y agoThe known cases are O(1) even with an `if` -- all it's doing is a range check. Any performance benefit from this hack is miniscule at best. It may even end up confusing a compiler and making performance worse.
- pdpi 10y agoSure. I'm not arguing it's a good idea. It just serves as (somewhat forced) motivation for showing how to exploit this behaviour with switch labels, which is the real point of the post.
- drivers99 10y agoIf the number of options (CMD5, CMD6, etc) changes, he needs the code to not break if he adds them to the enum but doesn't doesn't extend the switch statement.
- pdpi 10y agoNot quite the same as Rust, but at least both GCC and Clang offer `-Wswitch-enum` which will cause non-exhaustive switches on enums to be raise warnings.
- deleted 10y ago[deleted]