c - use of %d 6 times gives a strange output..why? -
the output of following code on machine strange
#include <stdio.h> void main() { int x = 5,y=6,sum=0; sum=x+y; printf("%d %d %d %d %d %d", sum = x +y ); getch(); }
that undefined behavior.
short answer don't that, , enable compiler warnings detect @ compile time -wformat
or -wall
.
long answer:
the function declaration is:
int printf(const char *format, ...);
meaning knows first argument format, , after there may more. scans format
string, , every specifier (e.g. %d
) tries remove data stack corresponding type (in case, int
).
when calling function, like:
push sum push const_format_string_pointer call printf
in printf, first read const_format_string_pointer, sum, whatever on stack before sum. local variables of calling function (in case x
,y
,sum
). , indeed, did print out 11 , 6, corresponding sum
, y
. %d
print out 5.
the 3 big numbers things compiler added stack it's own need. have meaning in debug mode, compiler specific. also, if compile code optimizations (e.g. -o2
), rid of or of larger numbers, , you'll end printing stuff deeper in stack caller's local functions, such caller's pushed ebp
, or caller's return address, etc.
Comments
Post a Comment