簡體   English   中英

這個for循環實際上如何工作?

[英]How does this for-loop actually work?

閱讀一些主題我找到了這段代碼,我想知道它是如何工作的,因為它是主要的:

5
2

代碼:

static int a = 7;

int test()
{
  return a--;
}

int main()
{
  for(test();test();test())
  {
    cout << test() << "\n";
  }
  return 0;
}

運作順序如下:

  1. a在啟動時全局初始化。 到7
  2. 首先命中for循環的初始化程序, test() a遞減到6,然后返回先前的值(7),這將被忽略。
  3. 命中for循環的test()test() a遞減到5,然后返回通過非零測試的先前值(6),以便for循環可以繼續。
  4. cout聲明; test() a遞減到4,返回發送到cout的先前值(5)
  5. 執行for循環的increment語句。 test() a遞減到3,返回先前的值(4),忽略該值。
  6. for循環的測試用例被擊中。 test() a遞減為2,返回先前值(3),該值通過非零測試並繼續循環。
  7. cout聲明; test() a遞減為1,返回發送到cout的先前值(2)
  8. 執行for循環的increment語句。 test() a遞減為0,返回先前值(1),忽略該值。
  9. for循環的測試用例被擊中。 test() a遞減為-1,返回先前值(0),這將使非零測試失敗並且循環終止。

現在。 從6或8開始循環,看看會發生什么。 = P

形式的for循環:

for (a; b; c) {
    // stuff
}

相當於:

{
    a;
    while (b) {
        // stuff
        c;
    }
}

暫無
暫無

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

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