Search code examples
cdecrementpostfix-operator

Why is the -- operator not subtracting from the value when executed?


Why is the decrement operator -- not bringing the value down by 1 when executed?

int a = 20;
int c ;

c = a--;

Inspecting the value of c now, it should be 19, yet it comes out as 20. What am I missing?


Solution

  • what you're using is called a postfix operator. It will get executed [decrement the value] after the assignment = operator has finished its execution with the existing value.

    To be clear, in case of post decrement, the ..-- operator is evaluated and the decrement is scheduled once the other evaluations including that operand are finished. It means, the existing value of the operand is used in the other evaluation [in =] and then the value is decreased.

    If you want, try printing the value of a itself. It will print the decremented value.


    EDIT:

    If my choice of words in my answer created any confusions, for the reference, from the c99 standard, chapter 6.5.2.4, [emphasis mine]

    [For increment] The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented [......]

    The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).