-1

Oh, I've something missed with this example...

int a=1;
int b=1;
int c=1;
System.out.println(a+++b---c++);

Is not it the same as next?

System.out.println( (a++) + (b--) - (c++) ); 

It seems the result is 0, but that's definitely wrong, so what's going on here?

2 Answers2

1

I get 1 (and that's what I expect, 1 + 1 - 1 is 1). Using the eclipse indenter (and adding output for a b and c after the operation)

int a = 1;
int b = 1;
int c = 1;
System.out.println(a++ + b-- - c++);
System.out.printf("a=%d b=%d c=%d%n", a, b, c);

I see

1
a=2 b=0 c=2

And, the reason is that post increment doesn't take effect until the next statement. While pre increment (for example, ++a) takes effect immediately.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

By using debugger i watch all variables for following to expression

a=b=c=1

A. a++ + b-- - c++ = 1 + 1- 1 =0

After A => a=2 b=0 c=2

B. (a++) + (b--) - (c++) = 2 + 0 - 2

After B=> a=3 b=-1 c=3

There is no difference between a++ + b-- - c++ and (a++) + (b--) - (c++) when we execute these expression in different class there is same result for same input.

Bhuwan Prasad Upadhyay
  • 2,916
  • 1
  • 29
  • 33