An if/else statement is useful for blocks of work. When a decision only chooses between two short values, the conditional operator can express that choice inside an initializer.
Its shape is condition ? valueWhenTrue : valueWhenFalse. The question mark separates the condition from the first value, and the colon introduces the alternative.
#include <iostream>
#include <string>
int main() {
bool quietSession = true;
std::string sign = quietSession ? "Quiet room" : "Conversation room";
std::cout << sign << "\n";
return 0;
}
The condition is true, so this prints Quiet room. If it were false, the initializer would use "Conversation room". Only the selected alternative is evaluated. The conditional operator produces a value; the declaration then uses that value to initialize sign.
The name ternary operator refers to its three parts: a condition and two alternatives. You do not need a separate if block or braces for this expression. You still need the semicolon that ends the declaration.
Keep this form short. A chain of nested question marks is difficult to read, and several assignments or actions belong more naturally in an if/else block. Choose the notation that makes the decision clearer rather than the notation with the fewest characters.
Replace "Pending" in the declaration of desk with the whole conditional expression. Start with hasBooking, then put the booked visitor's label after ? and the other label after :. The supplied value is false, so the second label should appear. The existing output statement prints whichever value the expression selects.
desk with the conditional operator, selecting "Check-in desk" when hasBooking is true and "Registration desk" otherwise. Expect Go to: Registration desk.Edit main.cpp, press Run to inspect the Console, then Submit to check these results.