Self-referential format (a classic quine-style string): what exact output does this program produce? #include<stdio.h> char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}"; int main() { printf(str, 34, str, 34); return 0; }

Difficulty: Medium

Correct Answer: char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}"; main(){ printf(str, 34, str, 34);}

Explanation:


Introduction / Context:
This is a well-known technique where a format string contains a description of itself. By passing the string to printf along with character code 34 (the double quote) and the string pointer itself, the program reconstructs a readable representation of its own source.



Given Data / Assumptions:

  • str is a format string containing %c and %s placeholders.
  • 34 is the ASCII code for the double-quote character.
  • printf returns the number of characters printed but here we only care about the printed text.


Concept / Approach:
printf(str, 34, str, 34) substitutes the first %c with a double quote, the %s with the entire contents of str, and the last %c with a double quote again. The literal text outside the format specifiers is printed verbatim, thereby emitting an assignment of str followed by a call pattern that mirrors main’s printf.



Step-by-Step Solution:
Replace first %c → ".Replace %s → the exact bytes of str.Replace last %c → ".Remaining literal text prints unchanged.The concatenated result matches option (a) precisely.



Verification / Alternative check:
Running the code prints the string definition and the main call pattern on one line. Counting quotes confirms balanced quoting.



Why Other Options Are Wrong:
Option (b) omits the quoted replication of str's content. “No output” and “error” are false; the code compiles and runs. The last option misinterprets the substitution behavior.



Common Pitfalls:
Confusing %c with the character code 34; forgetting that %s consumes the whole string until '\0'; missing that the printed output contains both the definition and the function call text.



Final Answer:
char *str = "char *str = %c%s%c; main(){ printf(str, 34, str, 34);}"; main(){ printf(str, 34, str, 34);}

Discussion & Comments

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