gcc"表达式溢出",而等效的等效表达式工作正常

e27*_*314 6 c++ gcc c++11

这是我的代码

#include <iostream>
static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);
static const unsigned long long int y = 36 * 36 * 36 * 36;
static const unsigned long long int yy = y * y;

int main()
{
  std::cout << xx << std::endl;
  std::cout << yy << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是编译输出

# g++ -std=c++11 test.cpp -o test
test.cpp:2:62: warning: integer overflow in expression [-Woverflow]
 static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);
Run Code Online (Sandbox Code Playgroud)

这是执行输出

# ./test
18446744073025945600
2821109907456
Run Code Online (Sandbox Code Playgroud)

你能解释为什么我看到这个警告和不同的结果?如果36可以适合char,那么36 ^ 8可以适合unsigned long long int,所以我不确定这里有什么问题,请指教.(我正在使用gcc 4.9.2)

use*_*267 10

static const unsigned long long int xx = (36 * 36 * 36 * 36) * (36 * 36 * 36 * 36);
Run Code Online (Sandbox Code Playgroud)

36 有类型 int

36 * 36有类型int

(36 * 36 * 36 * 36)有类型int

(36 * 36 * 36 * 36) * (36 * 36 * 36 * 36)有类型int和溢出,这实际上是签名类型的未定义行为.

你可能想要

static const unsigned long long int xx = (36ull * 36 * 36 * 36) * (36 * 36 * 36 * 36);
Run Code Online (Sandbox Code Playgroud)

至于第二种情况:

static const unsigned long long int yy = y * y;
Run Code Online (Sandbox Code Playgroud)

y 有类型 unsigned long long

y * y有类型,unsigned long long所以没有溢出.