Jav
Jav

Reputation: 1607

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()?

Upvotes: 2

Views: 2722

Answers (1)

unwind
unwind

Reputation: 399703

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 ints).

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.

Upvotes: 8

Related Questions