最近在公司做项目发现uint64_t类型的变量赋值时,发生overflow的错误。先就此写了以下的测试程序,希望对大家有所帮助。
#include <stdlib.h>
/*
* Copyright 徐洪志(Macrosan). All rights reserved.
* Data: 2013-4-20
*/
//
// 此程序是演示了对uint64_t类型变量的赋值
#include <stdio.h>
#define DEF_TEST(size) (size)
typedef unsigned long long int uint64_t;
int main(void)
{
uint64_t lba = 0;
lba = 1024*1024*1024*1024*1024*1024; //2^60 Error
printf("lba: %llu\n", lba);
lba = 1024*1024*1024*1024*1024*1024llu; //2^60 Error
printf("lba: %llu\n", lba);
lba = 1024llu*1024*1024*1024*1024*1024; //2^60 Right
printf("lba: %llu\n", lba);
lba = (uint64_t)1024*1024*1024*1024*1024*1024; //2^60 Right
printf("lba: %llu\n", lba);
lba = DEF_TEST(1024*1024*1024*1024*1024*1024); //2^60 Error
printf("lba: %llu\n", lba);
lba = DEF_TEST(1024*1024*1024*1024*1024*1024llu); //2^60 Error
printf("lba: %llu\n", lba);
lba = DEF_TEST(1024llu*1024*1024*1024*1024*1024); //2^60 Right
printf("lba: %llu\n", lba);
lba = (uint64_t)DEF_TEST(1024*1024*1024*1024*1024*1024); //2^60 Error
printf("lba: %llu\n", lba);
lba = DEF_TEST((uint64_t)1024*1024*1024*1024*1024*1024); //2^60 Right
printf("lba: %llu\n", lba);
lba = DEF_TEST(1024*1024*1024*1024*1024*1024llu); //2^60 Error
printf("lba: %llu\n", lba);
#define BIG_NUM 1024*1024*1024*1024*1024*1024 //2^60 宏定义
lba = DEF_TEST(BIG_NUM); //2^60 Error
printf("lba: %llu\n", lba);
lba = DEF_TEST((uint64_t)BIG_NUM); //2^60 Right
printf("lba: %llu\n", lba);
return 0;
}
上述代码执行结果:
lba: 0
lba: 0
lba: 1152921504606846976
lba: 1152921504606846976
lba: 0
lba: 0
lba: 1152921504606846976
lba: 0
lba: 1152921504606846976
lba: 0
lba: 0
lba: 1152921504606846976
结论:对于uint64_t类型变量进行赋值操作时,需要显示的指定右操作数是uint64_t类型的(虽然在右操作数比较小的情况下,比如1000等,不会出现overflow的错误)。
显示指定有两种方方式加上llu后缀,或者添加强制类型转换(uint64_t)。
另对于将一个计算的表达式赋给一个uint64_t类型的变量,比如:
lba = 1024*1024*1024*1024*1024*1024;
要在第一个1024后添加llu后缀或者强制类型转换添加(uint64_t)。
1) lba = 1024llu*1024*1024*1024*1024*1024;
2) lba = (uint64_t)1024*1024*1024*1024*1024*1024;