-3

In C, since the addition operator (+) takes precedence before subtraction (-), I assume the following expression will return 0:

5 - 1 + 4

But no, it return 8 instead. Why is that?

P.S.: The expression was tested in Objective-C.

EDIT: Apparently my assumption about addition taking precedence over subtraction is wrong. Please feel free to close this post if it is deemed as not helpful.

Andree
  • 3,033
  • 6
  • 36
  • 56
  • 2
    FWIW, I'm not aware of any number system where addition has precedence over subtraction. – Mysticial Apr 19 '14 at 02:37
  • 1
    See [Operators in C and C++](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence). Ignore the C++ ones and the rest apply to Objective-C since it is a superset of C. – rmaddy Apr 19 '14 at 02:48

1 Answers1

4

Because addition doesn't take precedence over subtraction. Both have the same precedence, and are associated left to right., so 5 - 1 + 4 is equivalent to (5 - 1) + 4.

(The order of evaluation is unspecified, which matters only if the operands have side effects.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631