I saw this code in C and run it:
int i,j;
scanf("%d %d"+scanf("%d %d",&i,&j));
printf("%d %d",i,j);
Input:
1 2 3
Output:
3 2
This is quite unexpected (reverse order and three inputs).
Please explain this.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This:
Is horrible code! But what’s happening?
First, the inner scanf is called. It stores 1 and 2 into
iandjrespectively (it should be obvious why this is). It then returns 2, because that is the number of things it stored. That then “skips” the first two characters of the outer scanf’s format statement, making it" %d". Then scanf wants to store3from the input somewhere, but no pointer to a variable was given in the outer scanf call. So what happens next? It’s undefined behavior, but the actual fact is that the second (outer) scanf call is just reusing (or stomping on, if you prefer) the arguments passed to the first (inner) scanf. So 3 is stored ini, and that’s it.