Which variables should I typecast when doing math operations in C/C++?

后端 未结 9 1369
野的像风
野的像风 2020-12-02 23:41

For example, when I\'m dividing two ints and want a float returned, I superstitiously write something like this:

int a = 2, b = 3;
float c = (float)a / (floa         


        
9条回答
  •  失恋的感觉
    2020-12-03 00:20

    In general, if operands are of different types, the compiler will promote all to the largest or most precise type:

    If one number is...   And the other is...    The compiler will promote to...
    -------------------   -------------------    -------------------------------
    char                  int                    int
    signed                unsigned               unsigned
    char or int           float                  float
    float                 double                 double
    

    Examples:

    char       + int             ==> int
    signed int + unsigned char   ==> unsigned int
    float      + int             ==> float
    

    Beware, though, that promotion occurs only as required for each intermediate calculation, so:

    4.0 + 5/3  =  4.0 + 1 = 5.0

    This is because the integer division is performed first, then the result is promoted to float for the addition.

提交回复
热议问题