简体   繁体   English

C中递增和递减运算符

[英]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? 如果我们只写一个++它会显示22,如果我们写一个 - 它显示20,而当它被分配给c时,它显示为21和22,为什么会这样?

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. 因此,a的第一个值被赋值给c,然后a递增.c的hence值为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. 现在a的当前值是22.在c = a--的情况下,a的值(即22被分配)到c然后a减少。 Hence value of c is 22. 因此c的值是22。

c = a++;

a++ means return the value of a and increment the value of a so a++装置返回的值a和递增的值a这样

c = 21;/* Because a = 21 before incrementing */

a-- means the same return the value and decrement so a--表示同样返回值并递减

c = 22;

When we are at the line c = a-- 当我们在线c = a--

a is 22 because of the previous a++ operation after this line a will be decremented and a will be 21. a22因为之前的a++操作,此行a将递减, a将为21。

Yes since you are assigning the value to c the value of a is returned to it before ++ or -- 是因为你的值赋给ca之前返回到它++--

There are postfix and prefix operators in C. When you use postfix operator then assignment happens first then operation . C中有postfixprefix运算符。当你使用postfix运算符时,首先进行赋值然后运算 If you want to do assignment and operation in one line then you have to use prefix operator where operation happens first then assignment . 如果你想在一行中进行赋值和操作,那么你必须使用prefix运算符,其中操作先发生,然后分配 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--; c=a--;
is equivalent to 相当于
c=a; a-=1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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