#include <iostream> using namespace std; int main() { { int x=1; cout << x << endl; { cout << x << endl; int x=2; cout << x <<endl; { cout << x <<endl; int x=3; cout << x <<endl; } cout << x <<endl; } cout << x << endl; } return 0; }
输出结果 1 1 2 2 3 2 1
#include <iostream> using namespace std; int main() { { int x1=1; cout << x1 << endl; { cout << x1 << endl; int x2=2; cout << x2 <<endl; { cout << x2 <<endl; int x3=3; cout << x3 <<endl; } cout << x2 <<endl; } cout << x1 << endl; } return 0; }
输出结果 1 1 2 2 3 2 1
/*
* 在第一例每个语句块中,虽然变量名都一样,但是int x= ;之后x就变成另外一个变量了
* 且生存周期仅限于当前的语句块中
*/