In C, scanf returns the number of successful assignments. What does this program print (assume the user types two valid integers)?
#include
int main()
{
int i;
i = scanf("%d %d", &i, &i);
printf("%d
", i);
return 0;
}
-
A1
-
B2
-
CGarbage value
-
DError: cannot assign scanf to variable
-
ENone of the above
Answer
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