简体   繁体   中英

Increment & decrement operators in C

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?

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(ie 22 is assigned) to c and then a is decremented. Hence value of c is 22.

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 --

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

c=a++;
is equivalent to
c=a;a+=1;
and c=a--;
is equivalent to
c=a; a-=1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM