0

The title is self-explanatory. Consider the following code:

   int n = 5;
   n = n--;

It gives n = 5. As far as I understood the expression n-- is first evaluated, returning 5 (i.e. POSTdecrement). This expression gets assigned to the LHS, here n. After this execution, n gets diminished. Thus I expected n = 4.

Why don't I see 4?

LT_ichinen
  • 73
  • 4
  • *"After this execution, n gets diminished"* - why would it happen *after* the expression? Then what did `n--` do? – UnholySheep Nov 15 '21 at 12:32
  • 1
    *"After this execution, n gets diminished"* -> yes, but there's only *one* assignment, not two, and it takes the value of the expression, which, with `n--`, is `n` *before* the decrement. – ernest_k Nov 15 '21 at 12:32
  • To get the expected result use `--4` – Jelle Nov 15 '21 at 12:32
  • Use assignment or use increment but not both. Not really much reason for java to have these operators. – Nathan Hughes Nov 15 '21 at 12:33

3 Answers3

5

n-- yields 5 and then sets n to 4

n = sets n to the value of the right-hand expression, which is 5

Mixing the increment/decrement operators with an assignment to the same variable rarely does anything useful.

user16632363
  • 1,050
  • 3
  • 6
0

This is not fully correct, there is 2 forms to do it --n and n--, thats is where you will do the rest on N. With the --n before you first rest and then return the value, and the other side is the opposite.

You first pass the value and then rest the value, try doing it the other way.

0

Given n=5, n-- return 5 but n value is 4.

Given n=5, --n return 4 and n value is 4.

That's why n has still the same vlaue

Florian S.
  • 280
  • 2
  • 5