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

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

    Do you need to cast one or two sides? The answer isn't dictated by the compiler. It has to know the exact, precse rules. Instead, the answer should be dictated by the person who will read the code later. For that reason alone, cast both sides to the same type. Implicit truncation might be visible enough, so that cast could be redundant.

    e.g. this cast float->int is obvious.

    int a = float(foo()) * float(c); 
    

提交回复
热议问题