簡體   English   中英

C中遞增和遞減運算符

[英]Increment & decrement operators in C

在以下程序中

     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 );
 }

輸出是

Value of c is 21
Value of c is 22

如果我們只寫一個++它會顯示22,如果我們寫一個 - 它顯示20,而當它被分配給c時,它顯示為21和22,為什么會這樣?

在++的情況下,++是后綴運算符。 因此,a的第一個值被賦值給c,然后a遞增.c的hence值為21。

現在a的當前值是22.在c = a--的情況下,a的值(即22被分配)到c然后a減少。 因此c的值是22。

c = a++;

a++裝置返回的值a和遞增的值a這樣

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

a--表示同樣返回值並遞減

c = 22;

當我們在線c = a--

a22因為之前的a++操作,此行a將遞減, a將為21。

是因為你的值賦給ca之前返回到它++--

C中有postfixprefix運算符。當你使用postfix運算符時,首先進行賦值然后運算 如果你想在一行中進行賦值和操作,那么你必須使用prefix運算符,其中操作先發生,然后分配 如果您修改下面的代碼,那么您將得到預期的輸出

     c = ++a; 
     printf("Value of c is %d\n", c );
     c = --a; 
     printf("Value of c is %d\n", c );

此鏈接將為您提供更多理解

c=a++;
相當於
c=a;a+=1;
c=a--;
相當於
c=a; a-=1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM