Question

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.

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top