看一下下面的代码片段:
#include <iostream>
#include <cstdint>
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
int main(int argc, char** argv)
{
constexpr uint16_t b = 2;
constexpr uint16_t c = 3;
constexpr const auto bc = b * c;
std::cout << "b: " << type_id_with_cvr<decltype(b)>().pretty_name() << std::endl;
std::cout << "b * c: " << type_id_with_cvr<decltype(bc)>().pretty_name() << std::endl;
}
这会产生以下结果:
b: unsigned short const
b * c: int const
为什么两个无符号整数相乘会得到一个整数?
编译器:g++ 5.4.0
最佳答案
无符号短
值在乘法之前隐式转换为int
。
short
和 char
被视为“存储类型”,并在进行计算之前隐式转换为 int
。这就是原因
unsigned char x = 255, y = 1;
printf("%i\n", x+y); // you get 256, not 0
关于c++ - 将两个 uint16_t 数字相乘得到一个 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699813/