0
0
C++programming~5 mins

Ternary operator in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the ternary operator in C++?
The ternary operator is a shorthand way to write an if-else statement. It uses the syntax: condition ? expression_if_true : expression_if_false;
Click to reveal answer
beginner
How does the ternary operator work?
It evaluates the condition first. If the condition is true, it returns the first expression; if false, it returns the second expression.
Click to reveal answer
beginner
Rewrite this if-else using the ternary operator:<br>
if (a > b) {
  max = a;
} else {
  max = b;
}
max = (a > b) ? a : b;
Click to reveal answer
intermediate
Can the ternary operator be nested in C++?
Yes, you can nest ternary operators inside each other, but it can make the code harder to read.
Click to reveal answer
beginner
What is a common use case for the ternary operator?
It is often used for simple conditional assignments or returning values based on a condition in a single line.
Click to reveal answer
What does the ternary operator syntax look like in C++?
Acondition ? expr1 : expr2
Bif (condition) expr1 else expr2
Ccondition ? expr1, expr2
Dexpr1 ? condition : expr2
What value does the ternary operator return if the condition is false?
AThe second expression
BIt returns nothing
CThe condition itself
DThe first expression
Which of these is a valid use of the ternary operator?
Aint x = if (a > b) a else b;
Bint x = (a > b) ? a : b;
Cint x = a > b ?;
Dint x = a ? b :;
Is it recommended to nest ternary operators?
AOnly if you use parentheses
BYes, always for clarity
CNo, it can make code hard to read
DOnly in comments
What is the main advantage of using the ternary operator?
AIt creates new variables
BIt replaces loops
CIt makes code longer
DIt shortens simple if-else statements
Explain how the ternary operator works and write a simple example.
Think of it as a shortcut for if-else.
You got /4 concepts.
    Describe when you might choose to use the ternary operator instead of a full if-else statement.
    Consider short and clear code.
    You got /4 concepts.