Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Post Fix and preFix

 
V Jagannadh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

int a =10;
int y = a++ - ++a ;
System.out.println(y);

This program is printing -2.
But as per operator precedence PreFix has to be done first and then PostFix.Hence it should have print 0 (Zero).Some body please explain.
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi:

int a =10;
int y = a++ - ++a;

//which is:
int y = 10 - 12; //it is 12 because "a" got incremented AFTER the first a++ (which got the value of 11) and then we did ++a (which got the value of 12)

System.out.println(y); //-2

Regards.
 
Tilo Hemp
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
evaluation is done from left to right (if consistent with operator precedence).
post-increment (a++) evaluates to a, and only afterward a is incremented by one.
pre-increment (++a) evaluates to a+1

so the expression is equal to:
int tmp = a; // evaluating "a++" to "a"
a += 1; // post-increment of "a++" -> a is now 11
a += 1; // pre-increment of "++a" -> a is now 12
y = tmp - a; // y is -2

or rather to:
y = a - (a = (a += 1) + 1);
which does not contain the additional variable tmp
 
Ravi Tadysetty
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tilo

According to operator precedence table, for ++ operator, it is right to left associativity. So, it should evaluate from right to left.

http://www.uni-bonn.de/~manfear/javaoperators.php

Thanks
Ravi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic