if/else vs ternary operator

两盒软妹~` 提交于 2019-11-26 22:04:17

问题


Considering the evaluation time, are following two equivalent?

if(condition1)
{
    //code1
}
else
{
    //code2
}

condition1 ? code1 : code2

Or they are just syntactically different?


回答1:


The difference is that the latter station can be used to return a value based on a condition.

For example, if you have a following statement:

if (SomeCondition())
{
    text = "Yes";
}
else
{
    text = "No";
}

Using a ternary operator, you will write:

text = SomeCondition() ? "Yes" : "No";

Note how the first example executes a statement based on a condition, while the second one returns a value based on a condition.




回答2:


Well ... In the former case, you can have any amount or type (expression vs statement) of code in place of code1 and code2. In the latter case, they must be valid expressions.




回答3:


Yes & Yes.

Only profit is to save lines of code.




回答4:


Yes, these are two different syntactical forms and will work identically and most likey identical code will be emitted by the compiler.



来源:https://stackoverflow.com/questions/1659992/if-else-vs-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!