Search code examples
c++floating-pointintegerinteger-arithmetic

What is the operations order of these two functions


I was writing a function to calculate the volume of a sphere when I encounter a problem and I don't know why if I change 4/3 * PI to PI * 4/3 I got different result. What is the order of evaluation, if I use parenthesis like (4/3) * PI and PI * (4/3) I got the wrong answer in both cases.

#define PI 3.141592

float Volume(int radius){
      return (4/3 * PI * pow(radius, 3));
}

float Volume(int radius){
      return (PI * 4/3 * pow(radius, 3)); //the good one
}

Solution

  • According to the C++ Standard (5.6 Multiplicative operators)

    1 The multiplicative operators *, /, and % group left-to-right.

    Thus this expression

    4/3 * PI 
    

    is evaluated like

    ( 4/3 ) * PI 
    

    So in this sub-expression 4 / 3 there is used the integer arithmetic and result is equal to 1.

    This expression

    PI * 4/3
    

    also is evaluated from left to right like

    ( PI * 4 )/3
    

    but in this case there is used the float arithmetic. The operand 4 is converted to the type of the variable PI that has the type double due to the usual arithmetic conversions. Then in turn the operand 3 is also converted to the type double because its left operand (expression) ( PI * 4 )has the type double.

    In this expression

    PI * (4/3)
    

    again inside the parentheses there is used the integer arithmetic and the result of the sub-expression is 1.