什么是“?”和“:”顺序实际上叫什么? [英] What is the "?" and ":" sequence actually called?
问题描述
这可能是一个棘手的问题,但是我无法弄清楚是什么? exp:other_exp
序列被调用。
This may be a bonehead question, but I cannot figure out what the ? exp : other_exp
sequence is called.
示例:
int结果=(true)吗? 1:0;
我已经尝试过使用Google机器,但是很难在不知道该怎么称呼的情况下对它们进行Googilize。
I've tried using the Google machine, but it's hard to Googilize for something without knowing what it's called.
谢谢!
推荐答案
它称为条件运算符,也可以称为三元运算符,因为它是三元运算符(一个需要3个操作数(参数)的运算符),并且通常是唯一的运算符,因此可以执行此操作。
It is called the the conditional operator or alternativly the ternary operator as it a ternary operator (an operator which takes 3 operands (arguments)), and as it's usually the only operator, that does this.
作为内联if(iif),三元if或问号运算符。
It is also know as the inline if (iif), the ternary if or the question-mark-operator.
实际上,这是一个相当有用的功能,因为它们是表达式,而不是语句,因此可以在例如 constexpr
函数,赋值等中使用。
It is actualy a rather useful feature, as they are expressions, rather than statements, and can therefore be used, for instance in constexpr
functions, assigments and such.
C ++语法为;
logical-or-expression ? expression : assignment-expression
它用作;
condition ? condition_is_true_expression : condition_is_false_expression
即,如果 condition
计算结果为 true
,表达式计算结果为 condition_is_true_expression
,否则表达式计算结果为 condition_is_false_expression
。
That is, if condition
evaluates to true
, the expression evaluates to condition_is_true_expression
otherwise the expression evaluates to condition_is_false_expression
.
因此,在您的情况下,将始终为结果
分配值 1
。
So in your case, result
would always be assigned the value 1
.
注1;使用条件运算符时,一个常见的错误是忘记它的运算符优先级。
Note 1; A common mistake that one makes while working with the conditional operator, is to forget that it has a fairly low operator precedence.
注2;某些函数式语言不提供此运算符,因为它们具有表达式'if ... else'
构造,例如OCaml;
Note 2; Some functional languages doesn't provide this operator, as they have expression 'if...else'
constructs, such as OCaml;
let value = if b then 1 else 2
注3;一个很好用的有趣用例是使用条件运算符来确定要向其分配值的两个变量中的哪个。
Note 3; A funny use case, which is perfectly valid is using the conditional operator, to decide, which of two variable to assign a value to.
(condition ? x : y) = 1;
请注意括号是必需的,因为如果没有括号,这实际上是您可以得到的;
Notice the parentheses are necessary, as this is really what you get without them;
condition ? x : (y = 1);
这篇关于什么是“?”和“:”顺序实际上叫什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!