可以在if、switch、 while和for语句的控制结构内定义变量。定义在控制结构当中的变量只在相应语句的内部可见,–旦语句结束,变量也就超出其作用范围了:
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int get_num()
{
srand((unsigned)time(NULL));
return rand() % 10;
}
int main()
{
while (int i = get_num()) // 每次迭代时创建并初始化i
cout << i << endl;
i = 0;//错误:在循环外部无法访问i
return 0;
}
而如果想访问i的话,就需要把i定义在外面
#include<iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int get_num()
{
srand((unsigned)time(NULL));
return rand() % 10;
}
int main()
{
int i;
while (i = get_num()) // 每次迭代时创建并初始化i
cout << i << endl;
i = 0;
return 0;
}