2

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

unwind
  • 391,730
  • 64
  • 469
  • 606
Jav
  • 1,445
  • 1
  • 18
  • 47
  • 3
    http://stackoverflow.com/questions/9225567/how-to-print-a-int64-t-type-in-c – Luka Mikec Feb 10 '15 at 12:58
  • 2
    Have you created a header file that declares the functions in your lib.c file ? And did you include that header file in main.c ? – nos Feb 10 '15 at 12:59
  • @JoachimPileborg Yes, the `#include is used in both files. Furthermore, to answer unwind, the file `lib.c` is the implementation of a `lib.h` – Jav Feb 10 '15 at 12:59
  • 1
    @Jav: He's not talking about `#define ` (though that's incorrect anyways --- I assume you mean `#include`), he's talking about declaring `function` in a header, and then including it in `main.c`. – Tim Čas Feb 10 '15 at 13:00
  • @TimČas indeed : *include – Jav Feb 10 '15 at 13:01
  • OKay -_- ... I had not included the `lib.h` – Jav Feb 10 '15 at 13:02
  • @Jav: Had you enabled compiler warnings, the compiler would've told you about that. I'd recommend using `-Wall`, myself (assuming you're using GCC or CLang; I don't know what other compilers use). – Tim Čas Feb 10 '15 at 13:03
  • stupid mistake. Thank you guys! – Jav Feb 10 '15 at 13:04

1 Answers1

8

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.

unwind
  • 391,730
  • 64
  • 469
  • 606