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++?
✗ Incorrect
The ternary operator uses the syntax: condition ? expression_if_true : expression_if_false.
What value does the ternary operator return if the condition is false?
✗ Incorrect
If the condition is false, the ternary operator returns the second expression.
Which of these is a valid use of the ternary operator?
✗ Incorrect
Option B correctly uses the ternary operator to assign the greater of a or b to x.
Is it recommended to nest ternary operators?
✗ Incorrect
Nesting ternary operators is allowed but can make code difficult to understand.
What is the main advantage of using the ternary operator?
✗ Incorrect
The ternary operator shortens simple if-else statements into one line.
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.