簡體   English   中英

為什么我不能在 while 循環中聲明這個變量?

[英]Why can't I declare this variable within while loops?

我對編程很陌生,所以如果這個問題看起來有點愚蠢,請原諒我,但為什么當我嘗試運行這段代碼時它不起作用:

    int calculate_quarters(int cents)
{
    while((25 <= cents) && (cents < 50))
    {
        int quarters = 1;
    }
    while((50 <= cents) && (cents < 100))
    {
        int quarters = 2;
     }
     return quarters;
}

但是當我嘗試運行這段代碼時,它運行得很好嗎?

 int calculate_quarters(int cents)
{
    int quarters = 0;
    while((25 <= cents) && (cents < 50))
    {
        quarters = 1;
    }
    while((50 <= cents) && (cents < 100))
    {
        quarters = 2;
     }
     return quarters;
}

變量在聲明它們的塊中的 scope 中。它們的生命周期在塊的末尾結束。

因此,在第一個示例中,您的兩個quarters變量是完全獨立的變量,它們恰好具有相同的名稱。 兩者都在塊的末尾消失,在這種情況下,它們在每次循環迭代時都被創建和銷毀。


這是示例代碼,它通過使用自定義 class 創建局部變量來演示這一點,該變量在構造函數和析構函數中打印內容

#include <iostream>

struct Print {
    Print(int value) : value(value) { std::cout << "Constructor_" << value << "\n"; }
    ~Print()  { std::cout << "Destructor_" << value << "\n"; }
    int value;
};

int main()
{
    std::cout << "Starting loop...\n";
    for(int cents = 0; cents < 10; ++cents) {
        Print object(cents);
    }
    std::cout << "DONE.\n";

}

Output:

Starting loop...
Constructor_0
Destructor_0
Constructor_1
Destructor_1
Constructor_2
Destructor_2
Constructor_3
Destructor_3
Constructor_4
Destructor_4
DONE.

為了更好地了解@hyde 的含義,假設您折疊了循環。 與第一個示例相比,該變量實際上變得不可見,因此您無法返回它。

這是您的情況的可視化圖片:

在此處輸入圖像描述

對於您的第一個代碼, quarters是在 while 循環內聲明的,因此不能從外部 scope 引用它。

但是,對於您的第二個代碼, quarters是在方法中聲明的,因此現在可以在 scope 中引用它。

暫無
暫無

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

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