Increment and decrement operators in C
In the next program
main()
{
int a = 21;
int b = 10;
int c ;
c = a++;
printf("Value of c is %d\n", c );
c = a--;
printf("Value of c is %d\n", c );
}
output
Value of c is 21
Value of c is 22
if we only write a ++ it shows 22, and if we write a it shows 20, whereas when c is assigned as above it is displayed as 21 and 22, why is that?
source to share
In the case of ++ ++, this is a postfix operator. So the first value of a is assigned to c and then a is incremented. The value for c is 21.
Now the current value of a is 22. In the case of c = a--, the value of a (ie 22 is assigned) to c and then a is decremented. Therefore, the value of c is 22.
source to share
c = a++;
a++
means returning a value a
and increasing a value a
, so
c = 21;/* Because a = 21 before incrementing */
a--
means the same as value and decrement, so
c = 22;
When we're on the line c = a--
a
is 22
due to the previous operation a++
after this line a
is decremented and a
equals 21.
Yes, since you are assigning a value c
, the value is a
returned to it before ++
or--
source to share
In C. there are operators postfix
and prefix
. When you use an operator postfix
then the assignment is done and then the operation . If you want to perform assignment and operation on one line, you need to use the statement prefix
where the operation is performed and then the assignment . If you change your code below you will get the expected result
c = ++a;
printf("Value of c is %d\n", c );
c = --a;
printf("Value of c is %d\n", c );
This link will give you more understanding
source to share