为什么在 C++11中unsigned short * unsigned short
转换为?int
如int
这行代码所示,它太小而无法处理最大值。
cout << USHRT_MAX * USHRT_MAX << endl;
在 MinGW 4.9.2 上溢出
-131071
因为(来源)
USHRT_MAX = 65535 (2^16-1) 或更大*
INT_MAX = 32767 (2^15-1) 或更大*
和(2^16-1)*(2^16-1) = ~2^32
。
我应该期待这个解决方案有什么问题吗?
unsigned u = static_cast<unsigned>(t*t);
这个节目
unsigned short t;
cout<<typeid(t).name()<<endl;
cout<<typeid(t*t).name()<<endl;
给出输出
t
i
在
gcc version 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC)
gcc version 4.8.2 (GCC)
MinGW 4.9.2
既
g++ p.cpp
g++ -std=c++11 p.cpp
这证明在这些编译器上t*t
转换为。int
有用的资源:
https://bytes.com/topic/c-sharp/answers/223883-multiplication-types-smaller-than-int-yields-int
http://www.cplusplus.com/reference/climits
http://en.cppreference.com/w/cpp/language/types
编辑:我已经在下图中展示了这个问题。