Type of char multiply by another char

孤人 提交于 2019-12-31 04:07:47

问题


What is the type of the result of a multiplication of two chars in 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

I expect the result of multiplying two number of type T (e.g., char, short, int) becomes T. It seems it is int for char because sizeof(a*b) is 4.

I wrote a simple function to check the size of the result of the multiplication:

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

print_sizeof_mult<char>(), print_sizeof_mult<short>(), and print_sizeof_mult<int>() are 4 and print_sizeof_mult<long>() is 8.

Are these result only for my particular compiler and machine architecture? Or is it documented somewhere that what type is the output of basic operations in C/C++?


回答1:


According to the C++ Standard (4.5 Integral promotions)

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.

and (5 Expressions)

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:

and at last (5.6 Multiplicative operators)

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.

Types char and short have conversion ranks that are less than the rank of the type int.



来源:https://stackoverflow.com/questions/43530754/type-of-char-multiply-by-another-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!