What is the “?” and “:” sequence actually called? [duplicate]

旧城冷巷雨未停 提交于 2019-12-22 08:15:58

问题


This may be a bonehead question, but I cannot figure out what the ? exp : other_exp sequence is called.

Example:

int result = (true) ? 1 : 0;

I've tried using the Google machine, but it's hard to Googilize for something without knowing what it's called.

Thanks!


回答1:


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.

It is also know as the inline if (iif), the ternary if or the question-mark-operator.

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.

The C++ Syntax is;

logical-or-expression ? expression : assignment-expression

It's used as;

condition ? 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.

So in your case, result would always be assigned the value 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.

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

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);



回答2:


They are called shorthand if-else or ternary operators.

See this article for more information.



来源:https://stackoverflow.com/questions/18638915/what-is-the-and-sequence-actually-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!