I have the following power function which operates on integers and it works fine:
int ipow( int base, int exp )
{
int result = 1;
while( exp )
{
Section 6.5p4 of the C standard:
Some operators (the unary operator ~, and the binary operators <<, >>, &, ^, and |, collectively described as bitwise operators) are required to have operands that have integer type. These operators yield values that depend on the internal representations of integers, and have implementation-defined and undefined aspects for signed types.
Section 6.5p5 of the C standard:
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.
If it seemed like a good idea to use int
in this code before, it shouldn't now. Both of these sections are saying that your code isn't as portable as it could be.
Your base
variable is too small. Change it to unsigned long long int
, like the others, since it holds numbers greater than 2^32
.