注意:我很清楚 a = b ? c : d 是什么意思,可这不是我要问的问题。
三元运算符 a = b ?: c 是什么意思。注意, ?和: 是在一起的
黄舟2017-04-17 12:00:50
b = true
c = false
a = b ?: c // a = true
b = false
c = true
a = b ?: c // a = true
ringa_lee2017-04-17 12:00:50
Although the title of the question is tagged C and C++, I wrote a PHP script to test it, and the results are as follows:
php
<?php $b = true; $c = false; $a = $b ?: $c; var_dump($a); // 输出true $b = false; $c = true; $a = $b ?: $c; var_dump($a); // 输出true
From the output result, the meaning of a = b ?: c
is: if b
is true
, then a = b
, if b
is false
, then a = c
伊谢尔伦2017-04-17 12:00:50
The format should be
(boolean expression) ? a : b
If the content of the boolean expression is true, then a.
If the content of the boolean expression is false, then b.
For example:
java
public int test(int a) { if (a > 0) { return 1; } else { return -1; } }
The above if-else can be replaced by ternary operation, as follows:
java
public int test(int a) { return (a > 0) ? 1 : -1; }