printf not printing the correct values

I wrote a small code of C.

#include<stdio.h>
int main()
{
    int a  = 0;
    printf("Hello  World %llu is here %dn",a, 1);
    return 0;
}

It is printing the following ouput

Hello World 4294967296 is here -1216225312

With the following warning on compilation

prog.cpp: In function 'int main()':

prog.cpp:5: warning: format '%llu' expects type 'long long unsigned int', but argument 2 has type 'int'

I know i need to cast the int to long long unsigned int, but i could not understand the fact that why the later values got corrupted.

Thanks in advance


%llu expects a 64-bit integer. But you only gave it a 32-bit integer.

The effect is that what printf is reading is "shifted" over by 32-bits with respect to what you've passed. Hence your "1" is not being read in the right location.

EDIT:

Now to explain the output:

a and 1 are being stored 32-bits apart because they are both 32-bit integers. However, printf expects the first argument to be a 64-bit integer. Hence it reads it as a + 2^32 * 1 which is 4294967296 in your case. The second value that is printed is undefined because it is past the 1 .


Because the code causes an Undefined Behavior .
An Undefined Behavior inherently means tha all bets are off.

printf is not type safe. You have to be careful in telling printf the proper format desrciptor while printing out types.


The format you passed to printf() leads it to expect 12 bytes on the stack, but you only push 8 bytes. So, it reads 4 bytes you didn't push, and gives you unexpected output.

Make sure you pass what printf() expects, and heed your compiler's warnings.

链接地址: http://www.djcxy.com/p/72216.html

上一篇: 如何打印一个int64

下一篇: printf不能打印正确的值