top | item 7665765

(no title)

ahy1 | 12 years ago

> Most C++ code uses switch frequently, usually without taking advantage of fallthrough.

I am not so sure about this. Thinking back on my uses of switch in C and C++, I am not able to remember using switch without taking advantage of fallthrough. Maybe I am just not a typical C++ programmer...

discuss

order

dbaupp|12 years ago

Rust still offers an equivalent to things like

  switch (x) {
  case 0: case 1: foo(); break;
  case 2: case 3: bar(); break;
  default: baz();
  }
in the form of

  match x { 
      0 | 1 => foo(),
      2 | 3 => bar(),
      _ => baz()
  }
In any case, Rust's match is so much more powerful than switch, offering (nested) pattern matching like Haskell's `case`.

DerekL|12 years ago

There's two different kinds of fallthrough in C++. The most common is using the same code for multiple values. Rust already supports this by allowing multiple values and ranges of values for each pattern.

The much more rare use of fallthrough is executing code for one case, and then continuing on to execute the code for the next case. This seems to be much more rare. In fact, in my large Android application, I turned on warnings for this type of fallthrough, and out of hundreds of switch statements, only eight used it, and all but one was a mistake.