Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

I have a doubt of precedence in operators += and ++  RSS feed

 
Eduardo Ucha
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt because I think that  the precedenceof  x++ is higger of +=. Look at this


It is suposed that += is sustituted by x=x +...


I don't understand why x=1 in the first x in the sum because x++ is executed before because of its precedence, but it isn't. The x++ and ++x take in account the value of x at the moment of the increment.



At the end the value of x is 3 but is overwritten with the value of 8

Well I dont understand why the last x is 2 and the first is 1. if I take in account the precedence the value of the first x at the moment of the sum it would be 3 because the increments of the value in the others operands has been executed but it's not.
 
Stephan van Hulst
Saloon Keeper
Posts: 7808
142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Operator precedence does not affect order of evaluation. Expressions are always evaluated from left to right. The only thing operator precedence does is determine which operands bind to which operators.

The fact that the ++ operator has highest precedence just means that ++x + x++ will be evaluated as (++x) + (x++) and not as ++(x + x)++.
 
Eduardo Ucha
Greenhorn
Posts: 3
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so much, it is just the answer that I needed. I understand this situations now better.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!