Effect of “+1” after the format string parameter to printf()

  • A+
Category:Languages

I have some problems related with this code. The parameter of printf is of type const char* and ... (variable argument list).

1) Why the output of the program is d and not 127?
2) Is it that the +1 would get converted into string and passed to parameter variable of type const char*?

#include<stdio.h> int main() {    printf("%d"+1 , 127); //how this will get executed?    return 0; } 

Output:

d 

 


First parameter is a pointer to char.
The literal "%d" would be a pointer to the '%', which is implicitly followed by 'd' and '/0'. It is a pointer to char, because that is the C representation of string literals: sequences of characters with a '/0' at the end; represented for use as parameters etc. as a pointer to char.
But "%d"+1, according to pointer arithmetic, is a pointer to 'd', followed by '/0'.
Both are zero-terminated, as fitting for a parameter to printf.

So the output is the same as

printf("d", ignored); 

127 turns into "ignored", i.e. it is ignored, because the "d" tells printf not to expect anything, because it does not have any of the special character sequences, e.g. "%someletter". So it will not expect, not look for anything and will not do any printing beyond the perfectly normal string it thinks to have been given.
Note however that the additional parameters, those not covered by anything in the format string, do get evaluated and then ignored. This is relevant, because any side effects (e.g. function calls) of that evaluation do in fact occur.
See e.g. here for details:
http://en.cppreference.com/w/c/io/fprintf

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: