Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java beginner, operator precedence table

I look at the operator precedence table and ++ operator comes before = operator. But to compute this expression, b=a++; first, a is assigned to b and then a is incremented. This is confusing. Which one comes first, ++ or =?

like image 273
nrtn93 Avatar asked Nov 28 '25 06:11

nrtn93


2 Answers

Yes, ++ has higher precedence than =. But you need to think of the ++ post-increment operator as 2 operations -- increment the variable and yield the old value -- that happen before the operator with lower precedence, =.

Here is what happens:

  1. Post-increment Operator ++: Increment a.
  2. Post-increment Operator ++: Yield the old value of a.
  3. Operator =: Assign the old value of a to b.

It's equivalent to this code.

int resultOfPostIncrement = a;
a = a + 1;
b = resultOfPostIncrement;
like image 155
rgettman Avatar answered Nov 29 '25 18:11

rgettman


As opposed to what many people seem to think, b is NOT assigned before incrementing a when we write int b = a++;. It is assigned the former value of a, but later in the timeline than the actual increment of a.

Therefore, it does not contradict what precedence tells you.


To convince you, here is a little example that convinced me:

int a = 1;
int b = a++ + a++;

At the end, b equals 3, not 2, and a is also 3. What happens because of precedence is:

  • the left a++ is evaluated first, incrementing a, but still evaluated to the former value 1 by definition of the operator
  • the right a++ is evaluated, reading the new value 2 (proving that the first increment already happened), incrementing it to 3, but still evaluating to 2
  • the sum is calculated 1 + 2, and assigned to b

This is because you should see a++ as both an instruction and an expression.

  • the instruction increments a
  • the expression evaluates to the former value of a

It's the same kind of things as in b = a, which also is an instruction and an expression:

  • the instruction assigns the value of a to b
  • the expression evaluates to the assigned value
like image 32
Joffrey Avatar answered Nov 29 '25 19:11

Joffrey



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!