簡體   English   中英

受混亂束縛,需要清楚說明職位增幅

[英]Bound by confusion, needs clear explanation of post increment

伙計們,我是編程新手,我對發布增量值的結果感到驚訝,現在我發現並執行了以下代碼,如果for循環顯示1.初始化2.檢查條件是否為false后,我很困惑終止3.增量。 我在哪里發生++? 我在哪里等於1?

int main()
{
int i, j;

for (int i =0; i<1; i++)
{
    printf("Value of 'i' in inner loo[ is %d \n", i);




    j=i;
    printf("Value of 'i' in  outter loop is %d \n", j);
            // the value of j=i is equals to 0, why variable i didn't increment here?
}
    //note if i increments after the statement inside for loop runs, then why j=i is equals to 4226400? isn't spose to be 1 already? bcause the inside statements were done, then the incrementation process? where does i increments and become equals 1? 
    //if we have j=; and print j here
//j=i;  //the ouput of j in console is 4226400
//when does i++ executes? or when does it becomes to i=1?



return 0;
}

如果Post增量使用該值並加1? 我迷路了...請解釋...非常感謝。

我不確定您要問的是什么,但有時將初學者重寫為while循環會更容易理解:

 int i = 0;
 while (i < 1)
 {
     ...
     i++;  // equivalent to "i = i + 1", in this case.
 }

您的循環聲明了新變量i ,它遮蓋了先前在main()聲明的i 因此,如果在循環之外將i分配給j ,則會調用未定義的行為,因為i並未在該上下文中初始化。

在第一次迭代之前, i初始化為0 正如您所說的,這是“初始化”階段。

然后評估循環條件。 循環繼續為真值。

然后執行循環體。 如果有continue; 語句,這將導致執行跳到循環的結尾,就在}之前。

然后評估增量運算符的副作用。

因此,在第一次迭代之后, i變為1 i在第二次迭代的整個過程中都保持值為1

看起來您的變量名沖突: i在循環之前和循環內部聲明。

for語句中聲明的i是唯一將成為1的i 。它將在循環體執行后立即執行。

在觀察變量值的同時,嘗試設置一個斷點並使用調試器逐步執行循環(這是我通過調試器逐步執行的意思的視頻)。

要消除具有兩個名為i變量的不確定性,可以將for循環更改為:

for (i = 0; i < 1; i++) // remove the `int`

這將確保您的代碼中只有一個i

對@CarlNorum的答案的評論,看起來不怎么好:

C標准定義

for ( A; B; C ) STATEMENT

意思與

{
    A;
    while (B) {
        STATEMENT
        C;
    }
}

(其中包含任意數量的語句的{}塊本身就是一種語句)。 但是continue; for循環中的語句將跳到下一個語句C;之前C; ,而不是對表達式B的下一個檢驗。

for (i=0; i<x; i++)

相當於

i=0;
while(i<x) {
    // body
    i = i + 1;
}

暫無
暫無

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

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