Domanda

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!

È stato utile?

Soluzione

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

Altri suggerimenti

They are called shorthand if-else or ternary operators.

See this article for more information.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top