Your code is not quite correct - your base-case isn't actually the base. (See below.)
Other then that -- assuming you make sure all the preconditions are enforced, it seems essentially fine.
Some notes on the definition of
::pow
:
- since this is functional-style code it can be made constexpr with no pain (assuming C++14 or later).
- x and y can (should) be marked locally constant.
- Your name
::pow(int, int)
can be conflated with
::std::pow()
, especially given the using declaration
using namespace std;
.
- yours will not be called in favor of
std::pow()
if, for instance, one of the arguments is floating point. that's okay, except that the standard version has different semantics. You should change the name.
- Since you can't handle negative exponents, you better mark your exponent as unsigned and document why.
- For moderately large
x
and/or
y
the integer representation of the return value will overflow, resulting in undefined behavior (probably a nonsense answer).
- For sufficiently large y, the stack will overflow (unless your compiler optimizes accumulative-recursive functions) and crash your program.
The standard library doesn't provide an integer version of pow(). Even the version which accepts integers has their arguments promoted to
double
, because
double
supports floating point exceptions, infinities, and things. This helps the code return a defined result in more cases.
You can trade strict correctness for clarity - you have to choose where the border of "acceptably correct" is.
More advanced techniques can help introduce simplifying abstractions, but you stand the risk of getting the content lost in noise.
This fixes the the issue with the base-case:
1 2 3 4
|
int power(int const x, unsigned const y) {
if (y == 0) return 1;
else return x * power(x, y - 1);
}
|