Reputation: 25
I have come across the following piece of code and i'm not being able to understand the scanf
portion.
int main()
{
int i,j;
scanf("%d %d"+scanf("%d %d",&i,&j));
printf("%d %d",i,j);
return 0;
}
I ran the code on inputs 4 8 9 and it returned 9 8.
Can someone please explain the working?
Upvotes: 2
Views: 72
Reputation: 154198
The inner scanf("%d %d",&i,&j)
returns a count, like 2,1, EOF (or maybe 0).
Adding that count to the format string "%d %d"
, offsets the format by the count, such as by 2, to form " %d"
. This is simply pointer addition. @John Bollinger
Then code does the equivalent of scanf(" %d");
which is undefined behavior (UB) as it is missing a matching int *
to go with the " %d"
. @mch
Can someone please explain the working?
Its not "working", it is UB.
A variation that treads on thin ice. It will "work" if the first scanf()
returns 2. Yet this all looks like hacker code to me.
int main() {
int i,j;
scanf("%d %d"+scanf("%d %d",&i,&j), &i);
printf("%d %d",i,j);
return 0;
}
Upvotes: 5