if/else vs ternary operator

后端 未结 4 1470
青春惊慌失措
青春惊慌失措 2020-12-07 03:04

Considering the evaluation time, are following two equivalent?

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

condition1 ? code

相关标签:
4条回答
  • 2020-12-07 03:22

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

    0 讨论(0)
  • 2020-12-07 03:25

    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.

    0 讨论(0)
  • 2020-12-07 03:36

    Yes & Yes.

    Only profit is to save lines of code.

    0 讨论(0)
  • 2020-12-07 03:37

    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.

    0 讨论(0)
提交回复
热议问题