What is the shorthand if-else statement called in C?
A
Quick if B
Ternary operator C
Short circuit operator D
Logical selector
Analysis & Theory
The ternary operator (`? :`) is used in C for shorthand if-else statements.
Which of the following is the correct syntax of a ternary operator?
A
condition then result1 else result2 B
condition ? result1 : result2 C
condition : result1 ? result2 D
if condition then result1 else result2
Analysis & Theory
Correct syntax: `condition ? value_if_true : value_if_false`.
What is the output?
```c
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
printf("%d", max);
```
A
10 B
20 C
30 D
0
Analysis & Theory
Since `a > b` is false, `b` (20) is assigned to `max`.
What does the ternary operator return?
A
Only true or false B
Only integers C
The value of either the true or false expression D
A pointer
Analysis & Theory
The ternary operator returns the value of the expression chosen based on the condition.
What is the output?
```c
int x = 5;
printf("%s", (x % 2 == 0) ? "Even" : "Odd");
```
A
Even B
Odd C
5 D
Error
Analysis & Theory
`x % 2 == 0` is false, so it prints "Odd".
Which of the following is equivalent to this ternary?
```c
x = (a > b) ? a : b;
```
A
if (a > b) x = b; else x = a; B
x = max(a, b); C
if (a > b) x = a; else x = b; D
x = a if a > b else b;
Analysis & Theory
This is a standard `if-else` rewritten using ternary.
Can a ternary operator be nested in C?
A
No B
Only once C
Yes, but not recommended D
Yes, and it's required
Analysis & Theory
Ternary operators can be nested, but it may reduce readability.
What is the output?
```c
int a = 5, b = 10;
printf("%d", (a < b) ? (b - a) : (a - b));
```
A
5 B
-5 C
15 D
0
Analysis & Theory
`a < b` is true, so it evaluates `b - a` = 5.
Which of the following uses a ternary to assign "Yes" or "No"?
A
char* res = (flag) ? "Yes" : "No"; B
res = (flag == 1) if "Yes" else "No"; C
res = flag ? Yes : No; D
if (flag) res = Yes; else res = No;
Analysis & Theory
Correct ternary syntax to assign strings: `condition ? "Yes" : "No"`.
Is this a valid usage of the ternary operator?
```c
(a > b) ? printf("A") : printf("B");
```
A
Yes B
No C
Only if inside a function D
Only in C++
Analysis & Theory
Yes, the ternary operator can be used with function calls like `printf()`.