Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if/else vs ternary operator

Considering the evaluation time, are following two equivalent?

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

condition1 ? code1 : code2

Or they are just syntactically different?

like image 348
Pale Blue Dot Avatar asked Nov 02 '09 08:11

Pale Blue Dot


2 Answers

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.

like image 199
Groo Avatar answered Sep 20 '22 12:09

Groo


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.

like image 22
unwind Avatar answered Sep 19 '22 12:09

unwind