-2

My Q is why to use switch statement and the conditional operator when we have the (if else && else if)

Example 1 :

unsigned short int any_number ;
any_number = ((15>0)? 10 : 5);//using here the conditional operator
if(15>0)//using if & else
any_number=10;
else
any_number=5;

Example 2 :

unsigned short int my_score;
std::cout << "what score you expect you got at the exam";
cin >> my_score;
switch(my_score)
{
case 90: 
std::cout<<"awesome keep the good work"; break;
case 80 :
std::cout<<"study harder next time"; break ;
case 20:
std::cout << "quit school"; break;
}

if(my_score==90)
std::cout<<"awesome keep the good work";
else if (my_score==80)
std::cout<<"study harder next time";
else if (my_score==20)
std::cout << "quit school";

other than its costs less lines using swith and conditional operators i dont find them useful at all i like more the (if else) more it gives us more space can any one till me the diffrence if there is one ?


  • 1
    For switch and elseif, you may get the answer from [How does switch compile in Visual C++ and how optimized and fast is it?](https://stackoverflow.com/questions/2596320/how-does-switch-compile-in-visual-c-and-how-optimized-and-fast-is-it) or [Is 'switch' faster than 'if'?](https://stackoverflow.com/questions/6805026/is-switch-faster-than-if) – Louis Go May 05 '20 at 03:06
  • This doesn't' address the question, but you don't need those parentheses in the conditional statement. `any_number = 15>0 ? 10 : 5;` does exactly the same thing. – Pete Becker May 05 '20 at 12:37

4 Answers4

2

There are many reasons why we need switch statement, it is faster and cleaner(my opinion), but there is another reason: if you switch over an enum variable, and if you forgot to handle some enum values, the compiler can catch it for you.

c++ warning: enumeration value not handled in switch [-Wswitch]

Tiger Yu
  • 744
  • 3
  • 5
1

main reason is readability

a long sequence of if elses is sometimes harder to read and maintain than a switch statement.

BTW the performance difference will surely disappear in production code created by a modern compiler.

The ?: construct allows you to do thing not expressable in ifs

cout << (j>42?"a":"b")

for example

pm100
  • 48,078
  • 23
  • 82
  • 145
0

switch case is faster! for this point, you can use those two structures to write two functionally equivalent codes, and then compare the compiled assembly code. details you can refer to this: Efficiency analysis of switch and if else

road
  • 49
  • 4
0

Your main concern is code readability and how error-prone it is. For example, when not used with switch, case and breaks (!), it's probably safer to go for if-else.

In C++ is it better to use switch and case statements or to use if statements? Personally I find the answers there as great as they are simple.

catalin
  • 1,927
  • 20
  • 20