if/else vs ternary operator

2019-01-15 19:38发布

Considering the evaluation time, are following two equivalent?

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

condition1 ? code1 : code2

Or they are just syntactically different?

4条回答
聊天终结者
2楼-- · 2019-01-15 19:51

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.

查看更多
疯言疯语
3楼-- · 2019-01-15 19:57

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.

查看更多
三岁会撩人
4楼-- · 2019-01-15 19:57

Yes & Yes.

Only profit is to save lines of code.

查看更多
干净又极端
5楼-- · 2019-01-15 19:58

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

查看更多
登录 后发表回答