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.
类型 char
和 short
的转换等级低于类型 int
的等级。
关于c++ - char 类型乘以另一个 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43530754/