Let's say we have following
Integer a = 0;
a = a++;
System.debug(a)
why it shows 0?
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communityIncrementing modifies in place. You don't need to reassign at all. However, using the ++a
operator returns the value after increment, as opposed to the a++
operator, which returns the value before increment.
Speaking from a technical point of view, with the postfix operator, the compiler basically does this internally:
temp = a; // rvalue storage
a = a + 1; // ++ operator
a = temp; // lvalue assignment
As Adrian says, you shouldn't assign the value, as the prefix and postfix ++ and -- operators modify the variable being referenced.
Using a prefix operator (a = ++a
) would change it to:
a = a + 1; // ++ operator
temp = a; // rvalue storage
a = temp; // lvalue assignment
You should generally not use a prefix or postfix operator on the variable being assigned to (the lvalue
); in practice, the increment and decrement operators are typically used to modify an accumulator or counter, not modify the value currently being assigned to.