Reputation: 7602
The following code gives me the output as 'd':
void main()
{
short int a=5;
printf("%d"+1,a);
getch();
}
How does printf()
actually work?
Upvotes: 5
Views: 1458
Reputation: 123458
String literals such as "%d" are array expressions, and in most contexts an array expression will be converted to a pointer expression whose value is the address of the first element of the array:
Item Address 00 01 02 03 ----- ------- -- -- -- -- "%d" 0xfffbec00 '%' 'd' 0 ??
The string literal "%d" starts at address 0xfffbec00 (for example). By writing "%d"+1
, you're adding 1 to the resulting pointer value (giving 0xfffbec01), so you're effectively passing the string literal "d" to printf
.
Since the string "d" does not contain a format specifier, printf
prints the string as-is. The argument a
is evaluated before being passed to printf
, but is otherwise ignored.
Upvotes: 1
Reputation: 726539
printf
does not "see" the format specifier because you are passing a pointer to "%d"
plus one. This is equivalent to passing "d"
by itself:
printf("d", a);
will print d
and ignore a
. This is not specific to printf
, pointer arithmetic works like that with all char
pointers, including pointers obtained from string literals (i.e. double-quoted sequences of characters).
Upvotes: 6
Reputation: 57322
here is the problem printf("%d"+1,a);
it wont display because there is only one format
specifier and this ("%d"+1) generate error
it can be either printf("%d+1",a);
or printf("%d",a+1);
Upvotes: 3