C++/C The variable in the LOOP STRUCT

 1 #include<iostream>
 2 using namespace std;
 3 void main()
 4 {
 5  for(int i=0;i<5;i++)
 6   cout<<i<<' ';
 7  cout<<endl;
 8  for(int i=5;i<10;i++)
 9   cout<<i<<' ';
10  cout<<endl;
11 }
12 
13 --------------------Configuration: fgyt - Win32 Debug--------------------
14 Compiling...
15 d.cpp
16 E:\Program Files\Microsoft Visual Studio\MyProjects\fgyt\d.cpp(9) : error C2374: 'i' : redefinition; multiple initialization
17         E:\Program Files\Microsoft Visual Studio\MyProjects\fgyt\d.cpp(6) : see declaration of 'i'
18 Error executing cl.exe.
19 
20 d.obj - 1 error(s), 0 warning(s)

 

 1 /*when I compile this program in Visual Studio 2012*/
 2 
 3 #include<iostream>
 4 #include<conio.h>
 5 using namespace std;
 6 void main()
 7 {
 8  for(int i=0;i<5;i++)
 9   cout<<i<<' ';
10  cout<<endl;
11  for(i=5;i<10;i++)
12   cout<<i<<' ';
13  cout<<endl;
14  getch();
15 }
16 
17 1>------ 已啓動生成: 項目: ConsoleApplication9, 配置: Debug Win32 ------
18 1>  源.cpp
19 1>c:\users\wkl7123\documents\visual studio 2012\projects\consoleapplication9\consoleapplication9\源.cpp(50): error C2065: “i”: 未聲明的標識符
20 1>c:\users\wkl7123\documents\visual studio 2012\projects\consoleapplication9\consoleapplication9\源.cpp(51): error C2065: “i”: 未聲明的標識符
21 ========== 生成: 成功 0 個,失敗 1 個,最新 0 個,跳過 0 個 ==========

So I know, loop variable will disappear after the loop end in Visual Studio 2012, but not in VC 6.0

 1 //More...
 2 #include<iostream>
 3 using namespace std;
 4 void main()
 5 {
 6  for(int i=0;i<5;i++)
 7  {
 8   int a=3;
 9   cout<<i<<' ';
10  }
11  cout<<endl;
12  for(i=5;i<10;i++)
13   cout<<i<<' ';
14  cout<<endl;
15  //cout<<"a="<<a<<endl;
16 }

This is a program, it's right though nearly nothing useful. But please stare at this sentence “int a=3;”it will be executed every loop, but system think it's right, because every "a" will disapear when a loop end. So it's easy to know when I add "cout<<"a="<<a<<endl;" in the end of the problem, system will say 

"a: Undeclared identifier".

 To sum up,in Visual Studio 2012, Loop variable will disappear after all the loop end. But the variavle defined in the loop struct will disappear after a single loop end. However in VC6.0 the Loop variable will disappear when the function end. That is to say, 


for(int i=0;i<5;i++)
{...}

    VC 6.0
<====equal===>
int i;
for(i=0;i<5;i++)
{...}

//I think Visual Studio 2012's way is better.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章