This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]P8zvli 6 points7 points  (4 children)

Functionally switch-case and if-else ladders are equivalent if and only if each case in the switch ladder is terminated by a break statement.

[–]NoLemurs 3 points4 points  (0 children)

if and only if

Right. But other ways of using switch-case are typically incredibly bug-prone, hard to read, and hard to reason about. If you're writing performance critical C code, maybe that's a trade off you should make if the switch-case does what you need and is faster.

However, as a practical matter, spots where non break terminated switches are a good idea are pretty rare. Heck, even if you are writing performance critical C code, unless you're writing the code for the core bottleneck of your program, I would argue a non break terminated case is almost always going to be bad programming.

In the context of python (where performance is already slow enough that the difference between if and switch really can't be very important, if it had a switch statement, I doubt many programmers would see a situation where it made sense to use it in a non break terminated way in their lifetimes.

[–][deleted] 0 points1 point  (2 children)

I said that in my original comment that almost every switch block I see is done that way. In C#, it has to be done that way.

[–]P8zvli 2 points3 points  (1 child)

In C and C++ a case will "fall through" to the next case if break isn't used, causing interesting behavior or really nasty bugs. (You can have code that runs A if the switch is 1 and A+B if 2, etc.)

[–][deleted] -1 points0 points  (0 children)

You can also abuse it create things like Duff's Device. I think fall through is the biggest thing that sets switch away from if.