In C, scanf returns the number of successful assignments. What does this program print (assume the user types two valid integers)?\n\n#include<stdio.h>\n\nint main()\n{\n int i;\n i = scanf("%d %d", &i, &i);\n printf("%d\n", i);\n return 0;\n}

Difficulty: Medium

Correct Answer: 2

Explanation:


Introduction / Context:
scanf returns the count of input items successfully assigned, not the values read. Even if both conversions write to the same variable, the return value reflects how many conversions succeeded.



Given Data / Assumptions:

  • The user supplies two valid integers separated by whitespace.
  • Both %d conversions succeed.
  • The same address &i is passed twice (this is questionable practice but does not change scanf's return count).


Concept / Approach:
For a call scanf("%d %d", &i, &i), scanf attempts two assignments. If both parse steps succeed, it returns 2, regardless of using the same destination address. The final stored value of i will be the second integer, but the printed value is the return count.



Step-by-Step Solution:
User inputs two integers, e.g., 10 20.First %d stores 10 into i → success 1.Second %d stores 20 into i → success 2.Return value = 2 → assigned to i → printf prints 2.



Verification / Alternative check:
Replace the second &i with a different variable &j. The return value remains 2 as long as both conversions succeed.



Why Other Options Are Wrong:
1: would indicate only one successful conversion.Garbage value / Error: scanf legitimately returns an int which can be stored and printed.



Common Pitfalls:
Confusing scanf's return value with the data read; assuming using the same destination makes scanf fail—it does not.



Final Answer:
2

More Questions from Library Functions

Discussion & Comments

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