for循环变量作用域的范围

来源:互联网 发布:overture mac 中文版 编辑:程序博客网 时间:2024/05/01 06:18
#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++)



0 0
原创粉丝点击