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?
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?
a--
is Post-Decrement, what you need --a
Pre-Decrement. Please read Increment and decrement operators on Wiki
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int x;
int y;
// Increment operators
x = 1;
y = ++x;
// x is now 2, y is also 2
y = x++;
// x is now 3, y is 2
// Decrement operators
x = 3;
y = x--;
// x is now 2, y is 3
y = --x;
// x is now 1, y is also 1
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).
you should use --a (pre decrement operator), you are using post decrement operator a--
The result of the postfix -- operator is the value of the operand. As a side effect, the value of the operand object is decremented (that is, the value 1 of the appropriate type is subtracted to it).
You are using the post decrement. Post decrement means first use the value in a variable or
anything then decrement the value in the variable. So in this case first value of a
will assigned to c
. And the decrement is done. You can check printing the value of a
.