您的位置:首页 > 其它

for循环变量作用域的范围

2014-12-09 10:33 387 查看
#include <iostream>

using namespace std;

int main(){
int a,b,min;
cout<<"Enter two numbers:"<<endl;
cin>>a>>b;
min=a>b?b:a;
for (int d=2; d<min; d++)
if (((a%d)==0)&&((b%d)==0)) break;
if(d==min)
{cout<<"No common denominators\n";return 0;}
cout<<"The lowest common denominator is %d"<<endl<<d;
return 0;

}

在windows下,用g++编译这段代码会报错。

 error: name lookup of `d' changed for new ISO `for' scoping

 error:   using obsolete binding at `d'

------------------------------------------------------------

橙色字体的意思是for循环在“初始化”定义的部分变量作用域的一个问题。g++在此把此变量作用域限定在了for循环中,或者说出了for循环定义的变量就无效了。

应该把红色字体改成:

int d;
for (d=2; d<min; d++)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: