2

我想返回 auint64_t但结果似乎被截断:

lib.c

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

main.c

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

结果:

394745024  =  394745024

在编译时,我收到一个警告:

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]

为什么编译器认为我的函数的返回类型是 an int?我们如何解释打印的结果与函数发送的值不同function()

4

1 回答 1

8

你是对的,该值被截断为 32 位。

通过查看十六进制的两个值最容易验证:

1422028920000 = 0x14B178754C0
    394745024 =    0x178754C0

很明显,你得到了最低有效的 32 位。

找出原因:您function()是否使用原型正确声明?如果不是,编译器将使用int解释截断的隐式返回类型(你有 32 位int)。

main.c中,你应该有类似的东西:

uint64_t function(void);

当然,如果您的lib.c文件有标题(例如lib.h),您应该这样做:

#include "lib.h"

反而。

另外,不要使用%llu. 使用正确的,由宏给出PRIu64,如下所示:

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

这些宏是在 C99 标准中添加的,位于<inttypes.h>标题中。

于 2015-02-10T12:57:23.497 回答