How does the ternary operator work?

2019-01-04 14:53发布

Please demonstrate how the ternary operator works with a regular if/else block. Example:

Boolean isValueBig = value > 100 ? true : false;

Exact Duplicate: How do I use the ternary operator?

12条回答
时光不老,我们不散
2楼-- · 2019-01-04 15:02

The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.

To use your example, changing from the use of a ternary expression to if/else you could use this statement:

Boolean isValueBig = null;
if(value > 100)
{ 
    isValueBig = true 
}
else
{
    isValueBig = false;
}

In this case, though, your statement is equivalent to this:

Boolean isValueBig = (value > 100);
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-04 15:03

As quoted from the ?: Operator MSDN page, "the conditional operator (?:) returns one of two values depending on the value of a Boolean expression."

So you can use the ternary operator to return more than just booleans:

   string result = (value > 100 ) ? "value is big" : "value is small";
查看更多
欢心
4楼-- · 2019-01-04 15:04
Boolean isValueBig;

if (value > 100)
{
   isValueBig = true;
}
else 
{
   isValueBig = false;
}
查看更多
Summer. ? 凉城
5楼-- · 2019-01-04 15:12
Boolean isValueBig = ( value > 100  ) ? true : false;


Boolean isValueBig;

if(  value > 100 ) { 
      isValueBig = true;
} else { 
     isValueBig = false;
}
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-04 15:14

Bad example, because you could easily write

Boolean isValueBig = value > 100 ? true : false;

as:

bool isValueBig = value > 100

Beyond that, everyone else has already answered it. I would just not recommend using ternary operators to set bool values, since what you are evaluating is already a boolean value.

I realize it was just an example, but it was worth pointing out.

查看更多
够拽才男人
7楼-- · 2019-01-04 15:15

PHP Example

<?php

  // Example usage for: Ternary Operator
  $action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

  // The above is identical to this if/else statement
  if (empty($_POST['action'])) {
    $action = 'default';
  } else {
    $action = $_POST['action'];
  }

?>

"The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE."

PHP Documentation on Comparison Operators

查看更多
登录 后发表回答