That is a ternary expression. Ternary expressions take the form:
condition ? <result_if_true> : <result_if_false>
Ternary expressions can be translated to an if
statement:
if (condition) {
<result_if_true>;
} else {
<result_if_false>;
}
An advantage of ternary expressions over the equivalent if
statements is variable declaration. For example, the following if
statement and ternary expression are equivalent, but it is clear which is more concise:
int seconds = 4;
// ===== USING IF STATEMENT =====
string secs_string;
if (seconds == 1) {
secs_string = "second";
} else {
secs_string = "seconds";
}
cout << "You have " << seconds << " "<< secs_string << " remaining." << endl;
// Output: You have 4 seconds remaining.
// ===== USING TERNARY EXPRESSION =====
string secs_string = (seconds == 1) ? "second" : "seconds";
cout << "You have " << seconds << " "<< secs_string << " remaining." << endl;
// Output: You have 4 seconds remaining.
Note that using an if
requires a seprate declaration of the string outside of the if
statement whereas with a ternary expression, this can be done inline.
Further Reading