Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • tail = modulus capacity
  • tail increments by one
like image 286
ahodder Avatar asked Sep 09 '26 14:09

ahodder


2 Answers

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

like image 195
T.J. Crowder Avatar answered Sep 11 '26 02:09

T.J. Crowder


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++;
like image 34
feralin Avatar answered Sep 11 '26 03:09

feralin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!