简体   繁体   English

Switch 语句和条件运算符 c++

[英]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)我的问题是当我们有 (if else && else if) 时为什么要使用 switch 语句和条件运算符

Example 1:示例 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:示例 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?除了使用 swith 和条件运算符的成本更少之外,我发现它们一点用都没有,我更喜欢(如果其他)更多,它给了我们更多的空间,如果有的话,任何人都可以告诉我差异吗?


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.我们需要 switch 语句的原因有很多,它更快更干净(我认为),但还有另一个原因:如果你切换了一个枚举变量,并且如果你忘记处理一些枚举值,编译器可以捕获它你。

c++ warning: enumeration value not handled in switch [-Wswitch] c++ 警告:枚举值未在开关 [-Wswitch] 中处理

main reason is readability主要原因是可读性

a long sequence of if elses is sometimes harder to read and maintain than a switch statement.一长串的 if else 有时比 switch 语句更难阅读和维护。

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 The?: 构造允许你做在 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. switch case 更快,对于这一点,您可以使用这两个结构编写两个功能等效的代码。 and then compare the compiled assembly code: details you can refer to this: Efficiency analysis of switch and if else然后对比编译出来的汇编代码:细节可以参考这篇: switch和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 .例如,当不与switchcasebreak s (,) 一起使用时,对于if - else来说,go 可能更安全。

In C++ is it better to use switch and case statements or to use if statements? 在 C++ 中使用 switch 和 case 语句还是使用 if 语句更好? Personally I find the answers there as great as they are simple.就我个人而言,我发现那里的答案很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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