簡體   English   中英

內部增量i ++輸出不變的結果

[英]inner increment i++ output unchanged result

我正在閱讀《 C Primer Plus》這本書,並遇到了如下代碼片段:

int main()
{
    int x = 30;

    printf("x in outer block: %d at %p\n", x, &x);
    {
        int x = 77; // new x , hides first x
        printf("x in inner block: %d at %p\n", x, &x);
    }
    printf("x in outer block: %d at %p\n", x, &x);
    while (x++ < 33) //original x
    {
        int x = 100;
        x++;
        printf("x in while loop: %d at %p\n", x, &x);
    }
    printf("x in outer block: %d at %p\n", x, &x);

    return 0;
}

它輸出:

In [23]: !./a.out
x in outer block: 30 at 0x7ffee7243788
x in inner block: 77 at 0x7ffee7243784
x in outer block: 30 at 0x7ffee7243788
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in outer block: 34 at 0x7ffee7243788

這讓我很困惑

x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780
x in while loop: 101 at 0x7ffee7243780

我如何使其輸出?

x in while loop: 101 at 0x7ffee7243780
x in while loop: 102 at 0x7ffee7243780
x in while loop: 103 at 0x7ffee7243780

發生這種情況的原因是,在while循環范圍內,每次執行將變量x重新定義為等於100,這將x定義在外部,因此您不會將其遞增3倍,而是將其遞增3倍。 在每個新的迭代中, 新的 x都會增加1,您會在輸出中看到101。

每次進入while循環時,將內部x值重置為100,您可以添加一個外部var,然后在while循環中將其遞增,將其值添加到100。

int main()
{
    int x = 30;
    int y = 0;
    printf("x in outer block: %d at \n", x);
    {
        int x = 77; /* new x , hides first x*/
        printf("x in inner block: %d at \n", x);
    }
    printf("x in outer block: %d at\n", x);

    while (x++ < 33) /*original x*/
    {
        int x = 100;/*value resets on every entry to 100*/
        x++;
        x +=y;
        ++y;/*value is incremented on every entry */

        printf("x in while loop: %d at\n", x);
    }
    printf("x in outer block: %d at \n", x);
    return 0;
}

這里有很多解釋,所以

讓我直接回答您的問題“ 如何輸出?

while (x++ < 33) //original x
{
    //int x = 100;
    static int x = 100;
    x++;
    printf("x in while loop: %d at %p\n", x, &x);
}

我會說一些關於static變量和一般storage classes

在此while循環中:

while (x++ < 33) //original x
{
    int x = 100; // this x hides the original x
    x++;
    printf("x in while loop: %d at %p\n", x, &x);
}

在循環體中聲明的x隱藏原始x (在while循環表達式中用作計數器)。 while循環的每次迭代中while您都將獲得內部x相同值101 ,因為while循環的每次迭代都會創建x新實例(內部x ),並使用值100初始化,並在循環主體的末尾銷毀' x

我如何使其輸出?

如果希望內部x的最后一個值在while循環的每次迭代中都保持不變,則可以簡單地將其設為靜態:

while (x++ < 33) //original x
{
    static int x = 100;
    x++;
    printf("x in while loop: %d at %p\n", x, &x);
}

暫無
暫無

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

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