3 ms·
Given the common advice to _always_ include a "default" label in your switches, I had formed the impression that entering a default-less switch with a value tha
by nemetroid 6y ago
Given the common advice to _always_ include a "default" label in your switches, I had formed the impression that entering a default-less switch with a value that doesn't have a matching case would result in undefined behaviour. This is not the case: it will simply do nothing.
- junon 6y agoIn my experience, this dogmatic advice is often counterproductive. If this is a switch that is reasonably defended (internal API, etc.) then leaving off a default in a fixed enumeration type switch (where you want to hit _every_ switch case value possible) is ideal. Most modern processors will warn (or -Werror, as everyone should be using these days) if one of the enum constants is missing, reducing the surface area for logic bugs. If you are really paranoid about out-of-bounds values in a switch statement, then insert an assert() after the statement itself with a negated string literal, e.g. assert(!"invalid switch value"); This is a pretty reasonable approach for code that, again, is reasonably defended against faulty inputs or working with some degree of guarantee. If I'm not mistaken, often times such switch statements are even optimized to jump tables at compile time, too - namely if there are small/few/no gaps in the case values.