在for语句中直接定义并初始化,如代码所示:
#include<iostream>
#include<Windows.h>
using namespace std;
#define NUM 6
int main(void) {
for(int i=0; i<NUM; i++) {
cout << "第" << i << "次坐飞机!" << endl;
}
cout << "一共做了" << i << "次飞机!" << endl;//这里的变量i,编译器认为其没有初始化
system("pause");
return 0;
}
这样就会出错,编译器提示:
此时,for循环之外的变量i被编译器认定为没有定义,认为i是没有声明的标识符!
上述问题解决办法:
#include<iostream>
#include<Windows.h>
using namespace std;
#define NUM 6
int main(void) {
int i=0;
//i不写也可以,如:for(;i<6; i++) {};
for(i; i<NUM; i++) {
cout << "第" << i << "次坐飞机!" << endl;
}
cout << "一共做了" << i << "次飞机!" << endl;
system("pause");
return 0;
}
如代码所示,在for循环之外定义i,也囊括了for循环之外的变量i.
在for循环外面定义,for循环里面初始化也可以:
#include<iostream>
#include<Windows.h>
using namespace std;
#define NUM 6
int main(void) {
int i;
for(i=0; i<NUM; i++) {
cout << "第" << i << "次坐飞机!" << endl;
}
cout << "一共做了" << i << "次飞机!" << endl;
system("pause");
return 0;
}
总结:在for循环里面定义的i,在for循环之外就是未定义的变量!!!