C 字面量和溢出

C literals and overflow

在我的机器上,int 是 32 位,下面的代码:

int64_t m = (int64_t) 1 << 60;
int64_t n = (int64_t) 2048 * 2048 * 2048;

给出了 2^60 和 2^33 的数学预期结果,尽管标准似乎说 1 和 2048 应该被视为“int”。

我应该将这个结果视为运气,还是 C99 标准保证我不会溢出?

转换优先于许多其他操作,您可以在此处查看顺序http://users.eecs.northwestern.edu/~wkliao/op-prec.htm

所以你实际上一直在使用 int64_t(顾名思义,它是一个带符号的 64 位整数),这就是你不会溢出的原因。