c++ - 添加两个 unsigned char 变量,结果为 int

标签 c++

有代码:

#include <iostream>
int main(){
  unsigned char a = 4, b = 255;
  int g = (unsigned char)a + (unsigned char)b;
  std::cout << g << std::endl;
  return 0;
}

结果:

259

为什么结果是 259,而不是 3?如果加了两个unsigned char变量,应该会溢出,result应该是3,然后把unsigned char 3转成int 3。

最佳答案

加法运算会先promote其操作数为 int,然后再进行加法运算。这就是 C 的工作原理。如果要截断,则需要将其分配回更窄的类型,例如 unsigned char

关于c++ - 添加两个 unsigned char 变量,结果为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7538448/

相关文章:

C++ - Fastor vs. Eigen vs C-tran : Speed differences in tensor contraction

c++ - 搜索二叉搜索树后输出错误

c++ - 在编译时选择全局作用域函数

c++ - 创建 C++ 类的 stub 版本

c++ - 当鼠标在 Qt 中窗口的自定义小部件上时如何移动整个窗口?

python - 在 Python 中使用 UEye API

c++ - cout uint8_t 作为整数而不是字符

c++ - 我可以使用 decltype() 或其他方法通过指针获取真实类型吗?

C++ STL :map search by iterator to another map

c++ - "a member template of a class"在 C++ 标准中指的是什么?