4 ms·
The break keyword in switch statements makes sense only if the programmer considers switch as a syntax sugar for goto, which are the semantics in C. Once you ha
by kibwen 8y ago
The break keyword in switch statements makes sense only if the programmer considers switch as a syntax sugar for goto, which are the semantics in C. Once you have a language that doesn't use goto but that still requires breaking each switch case, the only rationale is inertia for people familiar with C. (That said, C# does have goto, right?)
- wongarsu 8y agothe break keyword in switch statements also allows fallthrough, allowing for a terser way to write state machines, at the cost of making the whole construct less intuitive and readable. In a switch expression of course that is moot since break is a statement, and statements can't appear in expressions.
- kibwen 8y agoThe thrust of my above comment is largely about how the idea "enabling fallthrough" demonstrates how poorly the switch statement is usually taught: most people have an intuitive grasp of it as an alternative to if/else if, when in truth it's sugar for a jump table. Break exists to prevent fallthrough rather than enable it! And indeed fallthrough isn't useless, though decades of long experience has demonstrated that it is the wrong default, and newer languages like Go do better by making break the default and having a dedicated fallthrough keyword for when you want it.
- zamalek 8y agoC# doesn't allow fallthrough. Every branch in a case clause must exit the case clause. Fallthrough can only be aachieved with a goto at the end of the case clause. The `break;` requirement is completely superficial; there's no reason why it couldn't be a classical block/statement choice: case "foo" { /* ... */ } case "bar" /* ... */;
- paulirwin 8y agoYes, C# does have goto. Ayende made a blog post [1] about some interesting uses of goto for performance reasons. Also likely for performance reasons, async/await state machines in .NET essentially use goto (br.s in CIL). VB.NET has GoTo as well. 1: https://ayende.com/blog/183553-A/using-goto-in-c https://ayende.com/blog/183553-A/using-goto-in-c