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

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

    Division of integers: cast any one of the operands, no need to cast them both. If both operands are integers the division operation is an integer division, otherwise it is a floating-point division.

    As for the overflow question, there is no need to explicitly cast, as the compiler implicitly does that for you:

    #include 
    #include 
    
    using namespace std;
    int main()
    {
        signed int a = numeric_limits::max();
        unsigned int b = a + 1; // implicit cast, no overflow here
        cout << a << ' ' <<  b << endl;
        return 0;
    }
    

提交回复
热议问题