Search code examples
c++operatorsoperator-precedence

Would unary negate operator come before the function call?


I don't have a compiler handy but this is itching my curiosity. If I have code like this:

float a = 1;
float b = 2;

-a.add(b);

Would it be run as:

add(-a, b);

or

-add(a, b);

Solution

  • Aside from the fact that float doesn't have add method, of course, the second -- unless the language somehow knows the properties of the add function. Otherwise it can be plain wrong: imagine what would happen if you replace -f(x) with f(-x) for f(x) = x * x!

    If however compiler knows that add is just an addition (for example, it inlines the function), it is allowed to choose whatever way it wants provided that the result stays unchanged.

    For the expression -a.add(b), definitely (-a) + b is different from -(a + b), so the compiler will just choose the right one. According to the precedence table, function call has higher priority, so -(add(a, b)) will be chosen.