Ternary operator used as a format selector in printf: what is printed? #include<stdio.h> int main() { char str[] = "C-program"; int a = 5; printf(a > 10 ? "Ps " : "%s ", str); return 0; }
-
AC-program
-
BPs
-
CError
-
DNone of above
-
ENo output
Answer
Correct Answer: C-program
Explanation
Introduction / Context:This question evaluates whether you recognize that the conditional operator here is selecting the printf format string, not the value printed. It is a common interview trick to test understanding of printf arguments.
Given Data / Assumptions:
- a = 5, so the condition a > 10 is false.
- Two possible format strings: "Ps" and "%s".
- Extra argument str is passed either way.
Concept / Approach:Because the ternary returns a single selected format string, when the condition is false, the format is "%s". The variadic argument list includes str, so printf prints the character array as a C string. No formatting error occurs because the chosen format matches the provided argument.
Step-by-Step Solution:Evaluate condition: 5 > 10 → false.Select format: "%s".Call printf("%s", str) → prints the contents of str → "C-program".
Verification / Alternative check:Change a to 11. Then the format becomes "Ps" and printf is called with an extra, unused argument. This is allowed in C; the extra argument is ignored. Output would be "Ps".
Why Other Options Are Wrong:“Ps” would require a > 10. “Error/None/No output” are incorrect because the code compiles and produces the expected string.
Common Pitfalls:Thinking the second argument is conditionally present; believing mismatched arguments cause automatic errors (they can cause UB if format specifiers do not match, but here they do match).
Final Answer:C-program