c++ - 大整数值的定义

标签 c++ casting int64

我有一个项目,我处理不适合整数的大数字(ns-timestamps)。因此,我想使用例如int64_t,目前正在编写测试用例(是!)。

为了检查大量的行为,我从类似的东西开始

int64_t val = 2*std::numeric_limits<int>::max();
qDebug() << "long val" << val;

返回

long val -2

(就像我将 val 定义为 int 一样)。

但是如果我写

int64_t val = std::numeric_limits<int>::max();
val *= 2;
qDebug() << "long val" << val;

我明白了

long val 4294967294

这看起来是正确的。

所以对我来说,似乎 2*max() 首先存储在一个整数中(在此步骤中被截断),然后复制到 int64。为什么会这样?编译器知道结果是 int64 类型,因此 2*max() 应该直接适合。

最佳答案

So for me it looks as if the 2*max() is first stored in an integer (truncated in this step) and then copied to the int64

这是绝对正确的。根据语言规范,当表达式的所有部分都适合 int 时,计算将以整数进行。在您的情况下,2max() 都适合 int,因此乘法以整数完成,导致溢出。

The compiler knows that the result is of type int64 so that it the 2*max() should fit directly.

在这种情况下,表达式分配给的结果并不重要:表达式本身决定了它的计算方式。您可以通过将 max() 转换为 int64 来获得相同的结果:

int64_t val = 2*(int64_t)std::numeric_limits<int>::max();

关于c++ - 大整数值的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24628081/

相关文章:

c++ - 在 Openmp 区域内抛出 std::runtime_error 会使程序崩溃

c++ - 为什么我们不对 cout 使用格式说明符?

c++ - 是否可以将 double 数组转换为 char *?

c++ - 我是否需要 64 位处理器才能使用 64 位数据类型

c - 如何将字符串转换为 int64_t?

json - Yojson 解析 int64 (ocaml)

c++ - 使用 erase 和 remove 从字符串中删除字符

c++ - 模板实例化问题

java - 为什么我们在 Java 中为子对象分配父引用?

VB6 IsNumeric 会出错吗?