Reputation:
I'm trying to calculate power of a number using recursion. What here I'm trying to do is setting the base argument as base* pow and reducing the pow argument every time.
I get an error: source.cpp:21:1: warning: control reaches end of non-void function [-Wreturn-type]
int power(int base, int pow){
if(pow!= 0){
return power(base* pow, pow- 1);
}
if(pow== 0){
return base;
}
}
int main() {
int x= power(2, 3);
cout<<x;
}
What am I doing wrong here?
Upvotes: 2
Views: 93
Reputation: 60218
You need to tell the compiler that the function always returns a value (even though in this case, it obviously does). Also, your recursive formula is incorrect. You could do something like this instead:
int power(int base, int pow){
if(pow != 0){
return base * power(base, pow - 1);
}
return 1;
}
Here's a demo.
Upvotes: 2