?: Ternary Conditional

expression1 ? expression2 : expression3;

The above code syntax would simply read:

if (expression1)
{
     expression2;
}
else 
{
     expression3;
}

This operator can be a more efficient way to do a simple if statement, especially if the resulting value is being stored in a common variable. Sometimes this operator is referred to as an "inline if" statement.


The example below will assign the larger of x or y to the common variable z:

int x = 5;
int y = 10;
int z = (x > y) ? x : y;
// z = 10




 author: Ryan Hunt, editor: Charles Feduke
 Send comments on this topic.