What does this code do? a = x ? y : z;

The line of code below is using something called the conditional operator, or very commonly known as the turnary operator ( there is only one ternary operator in C++ ).

//Treat a,x,y,z as integers set to some value.
a = x ? y : z;

This operator takes the form: condition ? truePart : falsePart

To most people, this is simply a shorthand if statement, equivalent to the code below.

if( x ){
  a = y;
  a = z;

As you can see its great for simplifying basic if statements. However the functionality does not stop there. Say I wanted to call a specific function based on a condition, we could write something like the code below.

int val = analogRead( A0 );
val ? funcA( val ) : funcB( val );

This is very similar to the first example shown. The next extension of this has equivalent behavior, however it produces slightly smaller code ( for this example ):

( val ? funcA : funcB )( val );

 What is happening here is the ternary operator is returning a function pointer, rather than the result of the function. So we can then add brackets at the end which calls the function.

What may be overlooked by many is the fact the turnary operator is actually returning a value, not just running code inside its true/false parts. When the true/false parts are l-values then the operator will return an l-value. View the snippet below to see some examples.

( val ? a : b )++;
( val ? a : b ) = analogRead( A1 );

Thanks for reading, if you gained something from this article please rate the topic! Smile

Tags: ternary
Last update:
2014-03-03 09:08
Christopher Andrews
Average rating: 4.8 (5 Votes)

You can comment this FAQ

Chuck Norris has counted to infinity. Twice.