简体   繁体   中英

Switch statement and conditional operators c++

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?


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]

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

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

Your main concern is code readability and how error-prone it is. For example, when not used with switch , case and break s (,), 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM