Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-7071601

clarify semantics of postfix increment/decrement

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 8
    • specification
    • None
    • unknown
    • generic

      wording of JLS 15.14.2 is misleading:

      "The value of the postfix increment expression is the value of the variable before the new value is stored"

      While helpful, this doesn't fully explain why programs like the following evaluates to 0:

      int result = 0;
      for (int i = 0 ; i < 100 ; i ++) {
          result = result++;
      }
      print(result); //0!!

      This behavior is consistent across all compilers - in fact the compiler simply translates this using the following JVM opcodes:

      2: iload_1 //load local variable on stack
      3: iinc 1, 1 //increment local variable (does not use stack)
      6: istore_1 //store top of stack (= unincremented value) on local variable

            abuckley Alex Buckley
            mcimadamore Maurizio Cimadamore
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: