• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Doubt regarding question from danchisholm on operators

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I am trying to analyze this question from danchisholm regarding operators:



I broke down the following piece of code
int a = 1;
a += ++a + a++; System.out.print(a);

to

a = a + (++a + a++);

Now we need to analyse the bracket contents first so I get

a = a+ (2+2); and the value of a at this point is 3

So according to me when I reach the statement

a = a+ (2+2);

I should be remembering the value of a as 3 and the operation should equate to

a = 3 + (4);

But the compiler resolves the value of

a = a+ (2+2);

to

a = 1 + (4);

Why is it so?

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the left side of the assignment is guaranteed (and protected from possible changes) until the right side is completely processed, due to the lowest preference of the assignment operators (=, +=, *=, ...)

Greetings.
 
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The compound assignment operators have a very specific evaluation process:
- Evaluate the value of the variable in the LHS, and save that value.
- Evaluate the RHS expression.
- Perform the operation of the saved value of the LHS with the RHS value.
- Cast the result to the type of the LHS variable.
- Assign the result to the variable in the LHS.

Appart from this, in the RHS, you have ++a + a++. When you have a binary operator, the left operand is evaluated first, and then the right operand is evaluated. Sometimes it can make a difference on the final result (but this time it doesn't.)
 
These are the worst of times and these are the best of times. And this is the best tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic