Operators: ?:

Conditional expression operator.

Syntax

condition?expression‑1:expression‑2

Discussion

The ?: operator is a special kind of operator evaluating expression-1 or expression-2 based on whether condition is true or false. If condition is true, it evaluates expression-1. Otherwise expression-2 is evaluated. The conditional expression operator provides an efficient shorthand for deciding which of two expressions to consider. The following example demonstrates the usage of the operator to select the string to display in a Text view depending on the value of a variable temperature:

var float temperature = ...

TextView.String = ( temperature > 37.0 )? "FEVER" : "NORMAL";

Without the conditional expression operator the above expression had to be implemented by using the if-else statement. As such, the conditional expression operator can be considered as a shorthand for the code below:

var float temperature = ...

if ( temperature > 37.0 )
  TextView.String = "FEVER";
else
  TextView.String = "NORMAL";

If the expressions involved in the conditional operator result in different data types, Chora tries to promote the operands to a common data type. For example, if the left operand has the type int32 and the right results in float, the left operand is promoted (type converted) to float and the complete expression returns float too. The following example demonstrates it:

var bool  condition = false;
var float var1      = 13.69;
var int32 var2      = 1251;

var float result = condition? var1 : var2;  // result = 1251.0

If there is no rational promotion possible, the data type of the left expression dominates and forces the right expression to be converted to the type of the left expression. For example, if the left expression results in a user defined enum and the right expression results in int32 data type, the value of the right expression is automatically converted to the enum data type. In this way, the data type resulting from the conditional operator is always the same regardless of the condition:

var bool             condition = false;
var Core::Direction  var1      = Core::Direction.TopLeft;
var int32            var2      = 3;

var Core::Direction  result = condition? var1 : var2;  // result = Core::Direction.BottomLeft