switch vs if else statement

Hi guys!
I have little doubt about which one is better to use?
Statement switch or statement if else?
Depends on the situation. If you have a bunch of enums for example, that you need to check, switch is more concise for that.

But if you're checking for different conditions where it isn't a simple check against an integer, you can't use switch statements.
If you find yourself doing almost the same operation in every single if-else statement, it's a good candidate that it could be factored into a switch statement.

Another aspect is readability. There are some times when I know a switch statement would be possible, but it's more readable to me to just have a simple if-else.

One note is that while you shouldn't waste time with premature optimization < http://wiki.c2.com/?PrematureOptimization >, it is worth mentioning that compilers can use switch statements to just make a constant offset to jump to, making it potentially more efficient, while a series of if-else branches won't typically do this.

I'm sure others here will weigh in with some useful info as well.
Last edited on
If your algorithm says "do one of N things, depending on the value of some expression" then use a switch statement. It makes the code more readable. A classic example is for processing the user's choice from a menu of several choices.

Compare what goes through someone's mind when reading an if/then/else
1
2
3
4
5
6
7
8
9
10
11
if (frizbat == 1)  { // okay, the program will do something for this condition.
   // stuff
} else if (frizbat ==2) {  // Ah. there's an else to... what was that condition?  Oh yeah, frizbat=1
   // more stuff
} else if (frizbat == 3) {  // Golly a frizbat value again. I wonder if there's a pattern?
   // thrash the stuff thrice
} else if (frizbat == 4) {   // Alright. This is probably just procesing frizbat values.
   // force the forsythia for the forth time.
} else if (frizbat == 8 && mode == beginner) {   // woh!  Guess I was wrong.
   ...
}


Now how about a switch statement:
1
2
3
4
switch (frizbat) {  // Okay, I'm going to do things depending on frizbat. There's
    // no ambiguity, no questions, no anxiety, the xanax bottle remains tightly closed.
   ...
}



Description of switch: https://en.cppreference.com/w/cpp/language/switch

Note how the "condition" is limited to integral or enumeration type.
Furthermore, the condition is compared against constant cases for equality.

The condition in 'if' statement is not so limited.

Therefore, there is a subset of tasks where you could use either statement. In those you can choose between the two. In the rest you can't.


When you can choose, there is no "overall better". Maintainability is important. How easy it is to see what the piece of code does? How easy it is to modify, update, or expand?


There is a third alternative:

Functions can be stored like objects. Older textbooks mention function objects, functors. Older yet: function pointers. See http://www.cplusplus.com/reference/functional/function/function/

Those objects can be stored in a map: http://www.cplusplus.com/reference/map/map/
1
2
3
4
using myii = std::function<int(int)>;
std::map<char,myii> table;
table['a'] = [](int x){return x/4;};
table['b'] = std::negate<int>();

Then you can jump to the table somewhat similar to the switch statement:
1
2
3
4
auto it = table.find( 'b' );
if ( it != table.end() ) {
  std::cout << it->second( 42 );
}

Note that the use of table does not change when we add cases and the content of table can be changed during runtime, unlike the 'switch/ if else' that will get longer with more cases.
Last edited on
which one is better to use?

Switch of C++ is somewhat limited in contrast to select of REXX for example. Switch looks only at one single varialbe and jumps according its content. In case your flow control gridiron can't be easily controlled with a single value you are foreced to do an if-(then)-elseif construct.

Example for this (it's REXX, break before next when or otherwise implicit)
1
2
3
4
5
6
7
select
  when 1 - datatype(denum, 'W') then exit 9   /* arg not an integer */
  when denum < 1,
     | denum > 3000 then exit 8               /* outside range */
  otherwise                                   /* input is 1..3000 */
  ...
end

Too complicaed to do same as switch.
Topic archived. No new replies allowed.