Implicit type conversion rules in C++ operators

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

    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
    

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

    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 =>  
    

提交回复
热议问题