C++:for循环的范围?

Joh*_*ohn 1 c++ scope loops

#include <iostream>
using namespace std;

int main() {
    int i;
    for(i=0; i <= 11; i+=3)
        cout << i;
    cout << endl << i << endl;
}
Run Code Online (Sandbox Code Playgroud)

output is: 0 3 6 and 9 and then once it exits the loop its 12. The addresses of i inside the loop and out appear the same

What I need to know is: Is the i inside the for loop the same as the i that was initialized outside the for loop because the variable i was first initialized before the for loops i was ever created?

das*_*ang 11

是的,循环中的i与循环外部的i相同,因为您只声明了一次.

如果由于某种原因你想要它是不同的(我强烈建议反对,你应该为不同的变量选择不同的名称)你可以在for循环中重新声明i:

for (int i = 0; i ...
Run Code Online (Sandbox Code Playgroud)