int j=5,k=9;
printf("%d...%d");
This question was in a book. output given : 5 9 But when i try this i got : garbage values, please explain this to me. The explanation in the book says tha开发者_开发知识库t printf takes values of first two assignments of the program
Your book authors are relying on stupid behavior. (I don't know if it is undefined
or implementation defined
or just plain stupid
.)
They are relying on your stack-allocated j
and k
variables magically being there when printf(3)
is called. Because printf(3)
will use its format string to determine what types of how many objects to read, it would magically interpret the j
and k
variables, located on the stack, as arguments to printf(3)
, as if they had been passed to it intentionally.
This is relying too much on the magic of "how it all works behind the scenes". Unless this code block is surrounded with "This code might show you ..." and "Never do something this stupid..." then the book is probably not worth reading any further.
First, if you write
int j=5,k=9;
printf("%d...%d", j, k);
You will get 5 9.
Now, printf
is a function that can get a variable number of arguments, it parses the String, which is always the first argument and decide where to put a value from the given arguments. This means that there is no enforcement by the compiler regarding the arguments given to the function and that's why you don't get any error.
If the arguments are pushed to the stack in function call (which is the case most of the time) than printf
will see %d
and put the next int on the stack as the number (and so on), since you didn't assign arguments except of the basic string, the data on the stack is not related to the function call (it is related, but it's not what you want :) )
Pick up some other book , printf("%d...%d"); doesnt make any sense . You have to supply the two integer arguments to replace the %d in format string .
Try:
int j=5,k=9;
printf("%d %d", j, k);
精彩评论