问题
I read a c++ tutorial that says arithmetic operators return the smallest data type possible (i.e. if 2 ints are added the return type will be int, if a float and a double are added the return type will be double). However, it also said that arithmetic operations on shorts return ints. Considering that shorts take up less memory than ints, why does that happen? Was the tutorial mistaken? The tutorial was for c++11, so maybe that has been deprecated in c++14? Thanks!
回答1:
Considering that shorts take up less memory than ints, why does that happen?
That's because the standard says so.
Was the tutorial mistaken?
No.
From the C++11 Standard (note the usual arithmetic conversion bit):
5 Expressions
...
9 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.
Integral promtions is defined in the standard as:
4.5 Integral promotions
1 A prvalue of an integer type other than
bool,char16_t,char32_t, orwchar_twhose integer conversion rank (4.13) is less than the rank ofintcan be converted to a prvalue of typeintifintcan represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of typeunsigned int.
As per above a short is promoted to an int before some of the binary operators are applied to the operands.
The section about operators + and - specifically mentions that usual arithmetic conversions are performed on the operands:
5.7 Additive operators
1 The additive operators
+and-group left-to-right. The usual arithmetic conversions are performed for operands of arithmetic or enumeration type.
回答2:
The type int is the "natural size" for the target system. Integer types that are smaller than int are promoted to int in arithmetic expressions so that the processor can be most efficient. That may be less of a concern these days, but it's still part of the C and C++ languages.
来源:https://stackoverflow.com/questions/39060852/why-does-the-addition-of-two-shorts-return-an-int