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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -