-1

I understand that the values of the two would be the same (say 3 to 4). However, does the computer see the two as the same, and would they both be considered expressions?

Thanks in advance!

AlteredCow
  • 9
  • 1
  • 5

3 Answers3

8

Yes to both, except that (value++) evaluates to the old value, whereas (value = value + 1) evaluates to the new value.
The direct equivalent of (value = value + 1) within an expression is (++value).

Note that neither of them are thread-safe.

For added fun, here are two more equivalent options:

value += 1;
value -= -1;
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    True as long as `value` is a simple variable or simple array element reference. If it's something like `method(args).field`, where `method(args)` returns an object reference, then `++method(args).field` calls the method once, while `method(args).field = method(args).field + 1` calls it twice. – ajb Jan 15 '14 at 17:50
  • This is the only answer that really distinguishes between the values of the expressions themselves versus the number that resides within `value` after evaluating either expression. The values of the expressions differ, though `value` will hold the same number after either expression is evaluated (assuming the target has no side effects, as @ajb pointed out). – Mike Strobel Jan 15 '14 at 17:54
2

That's incorrect. Rather, ++value is the same as value=value+1.

++Value is a pre-increment. Value++ is a post-increment.

'Post' means after - that is, the increment is done after the variable is read. 'Pre' means before - so the variable value is incremented first, then used in the expression.

For example:

int i, x;

i = 2;
x = ++i;
// now i = 3, x = 3

i = 2;
x = i++; 
// now i = 3, x = 2
0

No, my friend ++value is equivalent to value=value+1 as it is changing the new value preincrement operator and value++ is changing the old value which is kept in the memory i.e. post incrementing it

Girish
  • 1,717
  • 1
  • 18
  • 30