Ternary operator used as a format selector in printf: what is printed?\n\n#include<stdio.h>\nint main()\n{\n char str[] = "C-program";\n int a = 5;\n printf(a > 10 ? "Ps\n" : "%s\n", str);\n return 0;\n}

Difficulty: Easy

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\n" and "%s\n".
  • 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\n". 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\n".Call printf("%s\n", str) → prints the contents of str → "C-program".


Verification / Alternative check:
Change a to 11. Then the format becomes "Ps\n" 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

More Questions from Control Instructions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion