12 ms·
The new switch expression is to the old switch statement what the ?: operator is to the if/else statement. Sometimes you want to provide one of two different v
by doodpants 8y ago
The new switch expression is to the old switch statement what the ?: operator is to the if/else statement.
Sometimes you want to provide one of two different values based on a condition. If you use if/else, then each statement body has to contain either an assignment (if the value is to be used later in the same function), or a return (if the value is to be immediately returned from the enclosing function). It is often more clear and concise to use a ?: expression at the site where the value is to be used.
Now consider the case where you need to choose among three or more different values. You can use chained if/else statements, which have the same drawback of needing to contain either assignments or returns. Or you can use chained ?: expressions, but there's really no good way to format this in a way that remains clean and easy to understand.
The new switch expression provides a cleaner alternative to chained ?: expressions.