ahodder
ahodder

Reputation: 11439

Why can't a variable be incremented in an assignment operator?

As a preface, I am using eclipse 3.7.2 on Mint 12x64

Suppose you have the given fields:

tail = 10;
capacity = 10;

Now suppose you were to execute this statement:

tail++ %= capacity;

Why is the statement illegal? Is the statement ambiguous? To me it seems that it would evaluate in the an order such as:

Upvotes: 3

Views: 146

Answers (2)

feralin
feralin

Reputation: 3408

The reason why your sample does not compile is because tail++ is a value, not a variable. The ++ operator takes a variable (and increments it), and then returns a value, which you then try to assign to. You can only assign to variables, hence the compiler error. If you want to make your sample work, you could try:

tail %= capacity;
tail++;

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1073959

The result of the expression tail++ is a value, not a variable. From the JLS, Section 15.14.2:

The result of the postfix increment expression is not a variable, but a value.

You can't assign to a value, only to a variable (or field).

Upvotes: 7

Related Questions