简体   繁体   中英

Returned uint64_t seems truncated

I would like to return a uint64_t but the result seems truncated:

In lib.c :

uint64_t function()
{
    uint64_t timestamp = 1422028920000;
    return timestamp;
}

In main.c :

uint64_t result = function();
printf("%llu  =  %llu\n", result, function());

The result:

394745024  =  394745024

At compilation, I get a warning:

warning: format '%llu' expects argument of type 'long long unsigned int', but argument 2 has type 'uint64_t' [-Wformat]
warning: format '%llu' expects argument of type 'long long unsigned int', but argument 3 has type 'int' [-Wformat]

Why is the compiler thinking that the return type of my function is an int ? How can we explain that the reslut printed is different from the value sent by the function function() ?

You are correct, the value is being truncated to 32 bits.

It's easiest to verify by looking at the two values in hex:

1422028920000 = 0x14B178754C0
    394745024 =    0x178754C0

So clearly you're getting the least significant 32 bits.

To figure out why: are you declaring function() properly with a prototype? If not, compiler will use the implicit return type of int that explains truncation (you have 32-bit int s).

In main.c , you should have something like:

uint64_t function(void);

Of course if you have a header for your lib.c file (say, lib.h ), you should just do:

#include "lib.h"

instead.

Also, don't use %llu . Use the proper one, which is given by the macro PRIu64 , like so:

printf("%" PRIu64 " = %" PRIu64 "\n", result, function());

These macros were added in C99 standard and are located in the <inttypes.h> header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM