Reputation: 467
I was working with some of the interview questions when I found this code.
#include<stdio.h>
int main()
{
short int a=5;
printf("%d"+1,a); //does not give compiler error
return 0;
}
It prints the following:
d
I am unable to understand how the printf function works here.
Upvotes: 8
Views: 579
Reputation: 81986
Let's look at the first argument to the printf()
call.
"%d" + 1
This points to the same thing as ptr
does in the following code.
char *ptr = "%d";
ptr = ptr + 1;
So, what does it mean to increment a pointer? Well, we advance the pointer sizeof(*ptr) * 1
bytes forward.
So, in memory we have:
%d\0
^^
||
|This is where ("%d" + 1) points to.
This is where ("%d") points to.
So, your code is more or less functionally equivalent to doing:
short int a = 5;
printf("d", a);
Which will evaluate and then ignore the extra function argument and print d
.
One more thing: You're very close to causing undefined behavior in that code. printf("%d", a)
is using the wrong format string. The correct format string for a short int
is "%hd"
.
You can find a full table of format strings here.
Upvotes: 15
Reputation: 4471
This is my answer based off @DCoder 's comment. "%d"
is a pointer to the first character of the two character array %d
. Incrementing this by one gives a pointer to d
. The fact that there is a second argument now does not matter as the result of the expression "%d"+1
is simply the character d
. If you try adding 0
your output is 5
as expected. If you try adding 2
, there is no output as there is only ""
is being passed to printf
.
Upvotes: 1
Reputation: 6057
In this case printf("%d"+1,a);
= printf("d",a)
.
You are specifying printf
to print from +1 position which is "d"
, so printf
will simply print d
on screen.
Upvotes: 1
Reputation: 122493
"%d" + 1
does pointer arithmetic, the compiler sees it as "d"
, so
printf("%d"+1,a);
becomes:
printf("d", a);
You can see why it outputs d
in your compiler.
As @sharth points out in the comment, the extra argument a
here is evaluated and discarded.
Upvotes: 6