DEV Community

Discussion on: I've never become overly convinced that switch statements are that much cleaner than `if else if else if else if else`

Collapse
 
jeikabu profile image
jeikabu • Edited

This here. switch in some languages (like F#, rust, and apparently swift- amongst others) has additional "powers".

In C# 8 you can also use it as an expression:

return x switch {
  0: something,
  // More
  _: whatever,
};

Otherwise it's main advantage is clarity for large numbers of options and optional fall through (double-edged sword that it is).

if (x == 0) {
  return something;
} else if (x == 1) {
// 10 more cases
else {
  return whatever;
}

// vs
switch (x) {
  case 0: return something;
  // 10 more
  default: return whatever;
}

Regardless what you do with your brackets/whitespace, the switch logic is clearly only about the value of x.

Also, historically compilers were more likely to turn it into a jump table rather than chain of branches.