Confusion

The work of if/else if statements and switch is same. Why should we use switch if we can use if/else if better?
Last edited on
Last edited on
You can't use switch on a string, so you would have to use if else in that situation.

I prefer switch as they look neater to me.

Also, you need to be careful with switch or if,else because they could indicate a bad code design.

https://daedtech.com/switch-statements-are-like-ants/#:~:text=Switch%20statements%20are%20often%20(and,red%20flag%E2%80%9D%20for%20interpersonal%20relationships.

switches can be more efficient. They often resolve by the compiler to a lookup table instead of a branch. Also the fall-through (break or no-break) and default can be made to do logic cleaner for some problems.

anything can be turned into an integer for a switch, but this extra step costs a little.
Topic archived. No new replies allowed.