Joan Venge
Joan Venge

Reputation: 331370

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);

Upvotes: 1

Views: 93

Answers (3)

Vlad
Vlad

Reputation: 35594

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.

Upvotes: 4

Yuushi
Yuushi

Reputation: 26080

Assuming you define something like float add(float a, float b) { return a + b; }, then it will be the second. Function calls have a higher operator precedence that unary minus, hence it would call the function, and then unary minus the result.

Upvotes: 1

David G
David G

Reputation: 96845

The latter, because the sign matters when it comes to addition/subtraction.

Upvotes: 1

Related Questions