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.