'c program Warning the control reaches the end of non-void function
so this is a simple c programming using recursion which returns the power of the input value, but for some reason it showing error
#include <iostream>
//int sum = 1;
int powerOfNumber(int n, int p) {
if (n != 0) {
p--;
return powerOfNumber(n , p) * n;
}
if (n == 0) {
return 1;
}
}
int main()
{
std::cout <<powerOfNumber(5, 2);
return 0;
}
Solution 1:[1]
Your stop condition must be in terms of p, not n, because that's the variable you are substracting the value, either way you could substract the value of n
Solution 2:[2]
You have a bug that the condition needed to be
if (p != 0) {
...
}
if ( p == 0)
return 0;
rather than if (n != 0) { ... } if ( n == 0) ....
But you might still get the same warning though if the compiler couldn't deduce that there'll be always be a return.
You could simply rewrite it to:
int powerOfNumber(int n, int p) {
if (p != 0) {
p--;
return powerOfNumber(n , p) * n;
}
return 1;
}
so that there's always a return statement unconditionally.
P.S.: Be aware that if you are using a large input for either n or p, you might run to integer overflow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Niels-Bored |
| Solution 2 | P.P |
