c++ - char 类型乘以另一个 char

标签 c++ implicit-conversion integer-promotion

C/C++ 中两个字符相乘的结果类型是什么?

unsigned char a = 70;
unsigned char b = 58;
cout << a*b << endl; // prints 4060, means no overflow
cout << (unsigned int)(unsigned char)(a*b) << endl; // prints 220, means overflow

我希望将两个类型 T(例如 char、short、int)相乘的结果变成 T。似乎是 int对于 char因为sizeof(a*b)是 4.

我写了一个简单的函数来检查乘法结果的大小:

template<class T>
void print_sizeof_mult(){
  T a;
  T b;
  cout << sizeof(a*b) << endl;
}

print_sizeof_mult<char>() , print_sizeof_mult<short>() , 和 print_sizeof_mult<int>()是 4 和 print_sizeof_mult<long>()是 8。

这些结果是否仅适用于我的特定编译器和机器架构?或者是否在某处记录了 C/C++ 中基本操作的输出类型?

最佳答案

根据 C++ 标准(4.5 积分提升)

1 A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

和(5 个表达式)

10 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

....

  • Otherwise, the integral promotions (4.5) shall be performed on both operands.61 Then the following rules shall be applied to the promoted operands:

最后(5.6 乘法运算符)

2 The operands of * and / shall have arithmetic or unscoped enumeration type; the operands of % shall have integral or unscoped enumeration type. The usual arithmetic conversions are performed on the operands and determine the type of the result.

类型 charshort 的转换等级低于类型 int 的等级。

关于c++ - char 类型乘以另一个 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530754/

相关文章:

c++ - 奇怪的编译器错误 : Cannot convert parameter from 'int' to 'int &&'

linux - 为什么编译器添加额外的 'sxtw' 指令(进一步导致内核 panic )?

Scala 多重隐式转换?

c# - 在 PowerShell 中隐式转换为 C# 中定义的结构的 bool 失败

c - 当 C 表达式中发生整数溢出时会发生什么?

c - 为什么组合 uint8_t 的两个移位会产生不同的结果?

c++ - 积分推广与运营商+=

c++ - 如何创建具有 N 种不同类型的变量成员的模板类,以便

c++ - 找不到 lopencv_core 和其他库变量

c++ - 在当前类的构造函数中调用其他类定义的虚函数