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

后端 未结 9 1376
野的像风
野的像风 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:25

    Question 1: Float division

    int a = 2, b = 3;
    float c = static_cast(a) / b;  // need to convert 1 operand to a float
    

    Question 2: How the compiler works

    Five rules of thumb to remember:

    • Arithmetic operations are always performed on values of the same type.
    • The result type is the same as the operands (after promotion)
    • The smallest type arithmetic operations are performed on is int.
    • ANSCI C (and thus C++) use value preserving integer promotion.
    • Each operation is done in isolation.

    The ANSI C rules are as follows:
    Most of these rules also apply to C++ though not all types are officially supported (yet).

    • If either operand is a long double the other is converted to a long double.
    • If either operand is a double the other is converted to a double.
    • If either operand is a float the other is converted to a float.
    • If either operand is a unsigned long long the other is converted to unsigned long long.
    • If either operand is a long long the other is converted to long long.
    • If either operand is a unsigned long the other is converted to unsigned long.
    • If either operand is a long the other is converted to long.
    • If either operand is a unsigned int the other is converted to unsigned int.
    • Otherwise both operands are converted to int.

    Overflow

    Overflow is always a problem. Note. The type of the result is the same as the input operands so all the operations can overflow, so yes you do need to worry about it (though the language does not provide any explicit way to catch this happening.

    As a side note:
    Unsigned division can not overflow but signed division can.

    std::numeric_limits::max() / -1  // No Overflow
    std::numeric_limits::min() / -1  // Will Overflow
    

提交回复
热议问题