Implicit type conversion rules in C++ operators

后端 未结 9 2218
情书的邮戳
情书的邮戳 2020-11-22 00:21

I want to be better about knowing when I should cast. What are the implicit type conversion rules in C++ when adding, multiplying, etc. For example,

int + fl         


        
9条回答
  •  一个人的身影
    2020-11-22 00:42

    Since the other answers don't talk about the rules in C++11 here's one. From C++11 standard (draft n3337) §5/9 (emphasized the difference):

    This pattern is called the usual arithmetic conversions, which are defined as follows:

    — If either operand is of scoped enumeration type, no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.

    — If either operand is of type long double, the other shall be converted to long double.

    — Otherwise, if either operand is double, the other shall be converted to double.

    — Otherwise, if either operand is float, the other shall be converted to float.

    — Otherwise, the integral promotions shall be performed on both operands. Then the following rules shall be applied to the promoted operands:

    — If both operands have the same type, no further conversion is needed.

    — Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank shall be converted to the type of the operand with greater rank.

    — Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.

    — Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type shall be converted to the type of the operand with signed integer type.

    — Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

    See here for a list that's frequently updated.

提交回复
热议问题