Reputation: 31
In the following 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 );
}
the output is
Value of c is 21
Value of c is 22
if we write just a++ it shows 22 and if we write a-- it shows 20 whereas when it is assigned to c as above it shows as 21 and 22 , why so?
Upvotes: 3
Views: 1234
Reputation: 965
In case of a++, ++ is a postfix operator. So first value of a is assigned to c and then a is incremented.Hence value of c is 21.
Now the current value of a is 22. In case of c=a--, value of a(i.e 22 is assigned) to c and then a is decremented. Hence value of c is 22.
Upvotes: 2
Reputation: 2946
c=a++;
is equivalent to
c=a;a+=1;
andc=a--;
is equivalent to
c=a; a-=1;
Upvotes: 0
Reputation: 1598
There are postfix
and prefix
operators in C. When you use postfix
operator then assignment happens first then operation. If you want to do assignment and operation in one line then you have to use prefix
operator where operation happens first then assignment. If you modify your code as below then you will get expected output
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
Upvotes: 0
Reputation: 19864
c = a++;
a++
means return the value of a
and increment the value of a
so
c = 21;/* Because a = 21 before incrementing */
a--
means the same return the value and decrement so
c = 22;
When we are at the line c = a--
a
is 22
because of the previous a++
operation after this line a
will be decremented and a
will be 21.
Yes since you are assigning the value to c
the value of a
is returned to it before ++
or --
Upvotes: 1