c - Reason for the Output -
#include<stdio.h> int main(void) { int a=5; printf("%d"+1,a); } output: d. didn't how output coming: d ?
you passed first argument of printf "%d"+1; "%d" seen const char * points memory location %d stored. pointer, if increment one, result point following element, which, in case, d.
a not used, should not problem since in general (i don't know if it's standard-mandated edit: yes is, see bottom) stack cleanup responsibility variadic functions caller (at least, cdecl way, may or may not ub, don't know*).
you can see easier way:
#include<stdio.h> int main(void) { int a=5; const char * str="%d"; printf(str + 1, a); }
str ---------+ | v +----+----+----+ | % | d | \0 | +----+----+----+ str + 1 ----------+ | v +----+----+----+ | % | d | \0 | +----+----+----+ thus, ("%d"+1) (which "d") interpreted format string, , printf, not finding %, print is. if wanted instead print value of a plus 1, should have done
printf("%d", a+1); edit: * ok, it's not ub, @ least c99 standard (§7.19.6.1.2) it's ok have unused parameters in
fprintf: if format exhausted while arguments remain, excess arguments evaluated (as always) otherwise ignored.
and printf defined have same behavior @ §7.19.6.3.2
the printf function equivalent fprintf argument stdout interposed before arguments printf.
Comments
Post a Comment