Implicit type conversion rules in C++ operators

后端 未结 9 2217
情书的邮戳
情书的邮戳 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:46

    Whole chapter 4 talks about conversions, but I think you should be mostly interested in these :

    4.5 Integral promotions [conv.prom]
    An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; other-
    wise, the source rvalue can be converted to an rvalue of type unsigned int.
    An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first
    of the following types that can represent all the values of its underlying type: int, unsigned int,
    long, or unsigned long.
    An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type int if int can represent all
    the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can rep-
    resent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the
    bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
    An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true
    becoming one.
    These conversions are called integral promotions.

    4.6 Floating point promotion [conv.fpprom]
    An rvalue of type float can be converted to an rvalue of type double. The value is unchanged.
    This conversion is called floating point promotion.

    Therefore, all conversions involving float - the result is float.

    Only the one involving both int - the result is int : int / int = int

提交回复
热议问题