且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++运算符中的隐式类型转换规则

更新时间:2022-03-24 21:45:13

在C ++操作符对同一类型的对象。

因此,如果它们不相同,那么将被提升为匹配另一个。

操作结果的类型与操作数相同(转换后)。

In C++ operators (for POD types) always act on objects of the same type.
Thus if they are not the same one will be promoted to match the other.
The type of the result of the operation is the same as operands (after conversion).

If either is      long          double the other is promoted to      long          double
If either is                    double the other is promoted to                    double
If either is                    float  the other is promoted to                    float
If either is long long unsigned int    the other is promoted to long long unsigned int
If either is long long          int    the other is promoted to long long          int
If either is long      unsigned int    the other is promoted to long      unsigned int
If either is long               int    the other is promoted to long               int
If either is           unsigned int    the other is promoted to           unsigned int
If either is                    int    the other is promoted to                    int
Both operands are promoted to int

注意。操作的最小大小为 int 。因此,在操作之前, short / char 被提升为 int

Note. The minimum size of operations is int. So short/char are promoted to int before the operation is done.

在所有的表达式中, int 被提升为 code>,然后再执行操作。该操作的结果是 float

In all your expressions the int is promoted to a float before the operation is performed. The result of the operation is a float.

int + float =>  float + float = float
int * float =>  float * float = float
float * int =>  float * float = float
int / float =>  float / float = float
float / int =>  float / float = float
int / int                     = int
int ^ float =>  <compiler error>