0
0
Cprogramming~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 in C?
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;
}
Using ternary operator:<br>
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 code harder to read. Example:<br>
result = (a > b) ? a : ((b > c) ? b : c);
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 in a concise way instead of writing full if-else blocks.
Click to reveal answer
What does the ternary operator syntax look like in C?
Aexpr1 ? condition : expr2
Bif (condition) expr1 else expr2
Ccondition ? expr1, expr2
Dcondition ? expr1 : expr2
What value does the ternary operator return if the condition is false?
AThe first expression
BThe condition itself
CThe second expression
DIt returns nothing
Which of these is a correct use of the ternary operator?
Amax = if (a > b) a else b;
Bmax = (a > b) ? a : b;
Cmax = (a > b) : a ? b;
Dmax = a > b ? : b;
Is it recommended to use nested ternary operators?
AYes, but they can reduce readability
BNo, they are not allowed
CYes, always for clarity
DNo, they cause syntax errors
What is a benefit of using the ternary operator?
AIt simplifies simple conditional assignments
BIt replaces loops
CIt is slower than if-else
DIt makes code longer
Explain how the ternary operator works and write a simple example in C.
Think of it as a short if-else that returns a value.
You got /4 concepts.
    Describe when you might prefer using the ternary operator instead of a full if-else statement.
    Use it when you want to assign a value quickly based on a condition.
    You got /3 concepts.