Faustus
Faustus

Reputation: 267

Behavior of postfix and prefix operators (Java)

Suppose I have a+++b. The compiler computes (a++)+b and not a+(++b). Why?

Upvotes: 1

Views: 124

Answers (2)

TulaGingerbread
TulaGingerbread

Reputation: 455

Strictly speaking, ++a is not prefix operator in Java, it's unary. And it has less precedence than postfix operator (a++).

At general, compiler will execute operators with higher precedence first. So, first postfix operator (in your case a++ is executed first, and additive operator + second.

Upvotes: 1

Augustus Francis
Augustus Francis

Reputation: 2670

Because Postfix Operator has more precedence over prefix operator.

the advantage of having a simple and well-memorizeable precedence list in which all postfix operators come before any of the prefix operators is sufficient to tolerate the minor drawback of always having to use parentheses to compose pre- and postfix operators ++/--, as this composition is used very seldom.

Upvotes: 1

Related Questions