我有一个项目,我处理不适合整数的大数字(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 theint64
这是绝对正确的。根据语言规范,当表达式的所有部分都适合 int
时,计算将以整数进行。在您的情况下,2
和 max()
都适合 int
,因此乘法以整数完成,导致溢出。
The compiler knows that the result is of type
int64
so that it the2*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/