#include<iostream>
using namespace std;
int pow ( int val, int exp );
int main()
{
int val = 2;
int exp = 10;
cout << pow ( val, exp ) << endl;
}
int pow( int val, int exp )
{
for ( int res=1 ; exp > 0; exp-- )
res = res * val;
return res;
}
在linux下用g++编译会出现如下错误:
error: name lookup of ‘res’ changed for ISO ‘for’ scoping
note: (if you use ‘-fpermissive’ G++ will accept your code)
它说的是 for 循环中在 “初始化”部分 定义的变量的作用域范围的一个问题。
ISO/ANSI C++ 把在此定义的变量的作用域范围限定在 for 循环体 内,或者说,出了循环体之外这个变量就无效了。可以使用‘-fpermissive’使编译通过。
应该把红色部分改成:
int res;
for ( res=1 ; exp > 0; exp-- )