Ternary Operators

In the general sense a ternary operator is an operator that take in 3 arguments. However, ROBOTC and the C language in general only has one ternary operator. Since there is only one in ROBOTC and C, it is sometimes referred to as the ternary operator.

 

The ternary operator in ROBOTC an C works like an if-else statement. The first argument you pass to the operator is evaluated to see if it equals True or False. The result of this evaluation determines what the operator returns. If the first argument evaluates to True, then the operator will return the second argument passed to it. If the first argument evaluates to False, the operator will return the third argument passed to it.

 

The ternary operator has a very simple syntax.

 

a ? b : c

 

For the ternary operator, a is the first argument which is evaluated to determine if the operator should return b or c. If a evaluates to True, then b is returned. If a evaluates to False, then c is returned.

 

Example:

Say you have a touch sensor input and you want to set a variable to different values depending on the sensor input. You could use a standard if or if-else statement.

 

int var;

if (sensorVal)

var = 50;

else

var = -432;

 

Alternatively, you could use the ternary operator to set the variable

 

int var = sensorVal ? 50 : -432;

 

Both options would set var to 50 when sensorVal is True or set var to -432 when sensorVal is False.