Is the behavior of return x++; defined?
Yes, it’s equivalent to: int bar() { int temp = x; ++x; return temp; }
Yes, it’s equivalent to: int bar() { int temp = x; ++x; return temp; }
You hit the nail on the head. Your understanding is correct. The difference between pre and post increment expressions is just like it sounds. Pre-incrementation means the variable is incremented before the expression is set or evaluated. Post-incrementation means the expression is set or evaluated, and then the variable is altered. It’s easy to think … Read more
x = x++; is equivalent to int tmp = x; x++; x = tmp;
i = 5; System.out.println(++i); //6 This prints out “6” because it takes i, adds one to it, and returns the value: 5+1=6. This is prefixing, adding to the number before using it in the operation. i = 6; System.out.println(i++); //6 (i = 7, prints 6) This prints out “6” because it takes i, stores a … Read more
Let’s take a look at the intermediary language code for that: IL_0000: nop IL_0001: ldc.i4.s 2A IL_0003: stloc.0 // c IL_0004: ldloc.0 // c This loads the constant integer 42 onto the stack, then stores it into the variable c, and loads it immediately again onto the stack. IL_0005: stloc.1 IL_0006: ldloc.1 This copies the … Read more
Post-increment usually involves keeping a copy of the previous value around and adds a little extra code. Pre-increment simply does it’s job and gets out of the way. I typically pre-increment unless the semantics would change and post-increment is actually necessary.
After the first a++ a becomes 4. So you have 3 * 4 = 12. (a becomes 5 after the 2nd a++, but that is discarded, because the assignment a = overrides it)
The loop is equivalent to: int x = 2; { int y = 2; while (y > 0) { System.out.println(x + ” “+ y + ” “); x++; y–; // or –y; } } As you can see from reading that code, it doesn’t matter whether you use the post or pre decrement operator in … Read more
++i is slightly more efficient due to its semantics: ++i; // Fetch i, increment it, and return it i++; // Fetch i, copy it, increment i, return copy For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the … Read more