c++ - 将两个 uint16_t 数字相乘得到一个 int

标签 c++

看一下下面的代码片段:

#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

shortchar 被视为“存储类型”,并在进行计算之前隐式转换为 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/

相关文章:

c++ - memset 和 struct 以及 getter/setter

c++ - 调用构造函数时程序停止运行,c++

c++ - c++11 中的命名空间问题?

python - 如何将 Python 代码转换为 C++

c++ - C++中关联packaged_task和thread

c++ - 关于 'case'中 'switch'语句中的大括号

c++ - 如何解码存储从 glm::value_ptr() 返回的值的变量的值?

c++ - QTimer 与 Windows 8 的奇怪准确性

c++ - 如何使用 GDI+ 绘制具有填充颜色的(贝塞尔曲线)路径?

c++ - 将参数转发给工作队列函数时出现编译错误