Hi all. I am trying to implement a code in a textbook but it is giving me an error
[code]
unsigned int
pow(int val,int exp)
{
for (unsigned int res=1;exp>0;--exp)
res=res*val;
return res;
}
#include <iostream>
extern unsigned int pow(int,int);
using namespace std;
int main()
{
int val=2;
int exp=15;
cout<<"The powers of 2\n";
for (int i=0;i<=exp;++i)
cout<<i<<": "
<< pow(val,i)<<endl;
return 0;
}
[code]
The error message I'm getting is
error: ‘res’ was not declared in this scope
14 | return int(res);
The output is supposed to look like
its /code in the ending block.
pow is the name used in cmath, perhaps that is a conflict. I highly advise using another name.
res is only scoped in the for loop. you can't return it because it was destroyed.
fix it by saying
int res{1};
for(...)
...
return res; //now its ok, it still exists here.
for fun (its not significantly better than the for loop) (the commented out chunks allow bigger exponents, but its rare to need more than ^16 at least in my code..). It does a lot less work for large exponents, which it turned out that I almost never use.. /facepalm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
longlong ipow(longlong p, unsignedlonglong e)
{
constlonglong one = 1;
constlonglong *lut[2] = {&p,&one};
longlong result = 1;
result *= lut[!(e&1)][0]; p *= p;
result *= lut[!(e&2)][0]; p *= p;
result *= lut[!(e&4)][0]; p *= p;
result *= lut[!(e&8)][0]; //p *= p;
//result *= lut[!(e&16)][0]; p *= p;
//result *= lut[!(e&32)][0]; p *= p;
//result *= lut[!(e&64)][0];
return result;
}
> The error message I'm getting is error: ‘res’ was not declared in this scope
In a for loop, the names declared by the init-statement (and the names declared in the condition) are within the scope of the for loop statement.
1 2
for( unsignedint res=1; exp>0 ; --exp ) { /* body of loop */ }
// res is out of scope now; it is no longer declared
Rewrite as:
1 2 3 4 5 6
longlong pow( int val, unsignedint exp )
{
longlong res = 1 ; // declared outside the for statement
for( ; exp>0 ; --exp ) res *= val ;
return res; // ok: res is in scope now
}