Why use abs() or fabs() instead of conditional negation?

前端 未结 9 716
南方客
南方客 2021-01-31 07:38

In C/C++, why should one use abs() or fabs() to find the absolute value of a variable without using the following code?

int absoluteVal         


        
9条回答
  •  时光说笑
    2021-01-31 08:06

    ...and would you make it into a macro, you can have multiple evaluations that you may not want (side efffects). Consider:

    #define ABS(a) ((a)<0?-(a):(a))
    

    and use:

    f= 5.0;
    f=ABS(f=fmul(f,b));
    

    which would expand to

    f=((f=fmul(f,b)<0?-(f=fmul(f,b)):(f=fmul(f,b)));
    

    Function calls won't have this unintended side-effects.

提交回复
热议问题