Is there a difference between x++ and ++x in java?

后端 未结 16 2624
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:34

Is there a difference between ++x and x++ in java?

16条回答
  •  遇见更好的自我
    2020-11-22 03:27

    When considering what the computer actually does...

    ++x: load x from memory, increment, use, store back to memory.

    x++: load x from memory, use, increment, store back to memory.

    Consider: a = 0 x = f(a++) y = f(++a)

    where function f(p) returns p + 1

    x will be 1 (or 2)

    y will be 2 (or 1)

    And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.

    Generally, just use x = x + 1. It's way simpler.

提交回复
热议问题