Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.
Power Function in C
Chapter 6, Lecture 28 of our free C programming course: write a power function in C that handles positive, zero and negative exponents, with examples from embedded C programming.
Welcome back to the free C programming course on EmbeddedPathashala. In this free C tutorial we build a power function in C that raises a floating point number to an integer exponent, so that a call such as ep_ipow(2.0, -3) returns 0.125. It is a small problem, but it teaches four habits every firmware developer needs: handling more than one case inside a function, choosing the right data type, protecting against bad input, and thinking about speed. If you want to learn embedded C programming, you will meet this pattern again whenever you scale a sensor value, compute a gain in decibels or build a lookup table at start-up.
What You Will Learn
- How to design a power function in C for any integer exponent, including negative ones
- Why a negative exponent means “take the reciprocal of the positive power”
- How to compile and run a complete working program and read its output
- What happens for exponent zero, base zero and very large results
- A faster method called exponentiation by squaring and when it is worth using
- Why embedded teams often write their own power function instead of calling the library
Prerequisites
You should already know how to declare a function, pass arguments and return a value (lectures 5 to 20 of this chapter), and you should be comfortable with for and while loops from the control statements chapter. A gcc compiler on Linux, Windows or a cross-compiler for your board is enough to try every example.
The Problem: Computing a Power in C
Mathematics writes a power as a raised to n. The base a can be any real number, so we store it in a floating point variable. The exponent n counts multiplications, so it is naturally an integer. C has no operator for powers. The caret symbol is bitwise exclusive OR, a classic beginner trap, so we need a function.
The rules are short. If n is positive, multiply the base by itself n times. If n is zero, the answer is 1 for every base. If n is negative, compute the power for the positive version of n and then take the reciprocal. That last rule comes straight from algebra: a to the power minus 3 equals 1 divided by a cubed.
Decision flow of the power function
Step 1: Receive base and exponent
The caller passes a floating point base and an integer exponent.
▼
Step 2: Count = absolute value of exponent
Negative exponents are converted to a positive repeat count.
▼
Step 3: Multiply result by base, count times
Result starts at 1.0, so a count of zero leaves it unchanged.
▼
Exponent positive or zero: return result as it is.
Exponent negative: return 1.0 divided by result.
Complete Power Function in C with Output
Here is a full program with two versions of the function. The first uses a fast method that we explain later, and the second is the plain loop that matches the flow chart above. Save it as ep_power.c.
#include <stdio.h>
/* raise a double to an int power, negative exponents allowed */
static double ep_ipow(double base, int exp)
{
double result = 1.0;
long n = exp;
if (n < 0)
n = -n;
while (n > 0) {
if (n & 1)
result *= base;
base *= base;
n >>= 1;
}
return (exp < 0) ? 1.0 / result : result;
}
static double ep_ipow_simple(double base, int exp)
{
double result = 1.0;
int i, count = (exp < 0) ? -exp : exp;
for (i = 0; i < count; i++)
result *= base;
return (exp < 0) ? 1.0 / result : result;
}
int main(void)
{
printf("2.0 ^ 10 = %f\n", ep_ipow(2.0, 10));
printf("2.0 ^ -3 = %f\n", ep_ipow(2.0, -3));
printf("1.5 ^ 4 = %f\n", ep_ipow(1.5, 4));
printf("7.0 ^ 0 = %f\n", ep_ipow(7.0, 0));
printf("simple 2.0 ^ -3 = %f\n", ep_ipow_simple(2.0, -3));
printf("0.0 ^ -1 = %f\n", ep_ipow(0.0, -1));
printf("10.0 ^ -6 = %g\n", ep_ipow(10.0, -6));
return 0;
}
Compile and run it with the commands below. We used gcc 13 with warnings enabled, and the program compiled without a single warning.
gcc -Wall -Wextra -o ep_power ep_power.c
./ep_power
2.0 ^ 10 = 1024.000000
2.0 ^ -3 = 0.125000
1.5 ^ 4 = 5.062500
7.0 ^ 0 = 1.000000
simple 2.0 ^ -3 = 0.125000
0.0 ^ -1 = inf
10.0 ^ -6 = 1e-06
Reading the Simple Power Function Line by Line
Start with ep_ipow_simple, because it mirrors the problem statement. The parameter list declares a double base and an int exponent, so the compiler knows exactly how to convert whatever the caller passes. Inside, result starts at 1.0. This is the multiplicative identity: multiplying by it changes nothing, which is why an exponent of zero needs no special if at all.
The ternary expression (exp < 0) ? -exp : exp turns the exponent into a non-negative repeat count. The loop then multiplies result by base that many times. Finally the return statement decides whether to hand back the product or its reciprocal. Notice the reciprocal uses 1.0, not 1. Dividing the integer 1 by a double would still work because of type conversion, but writing 1.0 makes the intent obvious to every reader.
Tip: An older textbook style puts the zero case first with if (n == 0) return 1;. It works, but the version above is shorter because the loop naturally runs zero times when the count is zero. Fewer special cases mean fewer places for bugs.
Edge Cases Every Power Function in C Must Consider
| Input | Result | Why it matters |
|---|---|---|
| Any base, exponent 0 | 1.0 | Result never changes from its starting value. |
| Base 0.0, positive exponent | 0.0 | Zero times anything stays zero. |
| Base 0.0, negative exponent | inf | Reciprocal of zero. Mathematically undefined, so the hardware returns infinity. |
| Negative base, odd exponent | Negative | The sign survives an odd number of multiplications. |
| Very large exponent | inf or 0.0 | The value leaves the range of the type. |
The zero base with a negative exponent deserves special attention. Our program printed inf instead of crashing, because floating point division by zero follows the IEEE 754 rules on most modern hardware. A real project should decide on a policy: return an error code, return a documented sentinel value, or assert during development. Silent infinity travelling through a control loop is a classic cause of motors running at full speed.
Faster Power Function in C: Exponentiation by Squaring
The plain loop needs as many multiplications as the exponent. Raising a number to the power 1000 takes 1000 multiplications. The first function in our program uses a smarter idea. Look at the exponent in binary. Every set bit tells you that a particular repeated square of the base belongs in the answer. The loop squares the base each round, shifts the exponent right by one bit, and multiplies into the result only when the lowest bit is 1.
| Exponent | Plain loop multiplications | Squaring method rounds |
|---|---|---|
| 10 | 10 | 4 |
| 100 | 100 | 7 |
| 1000 | 1000 | 10 |
The number of rounds equals the number of bits in the exponent, so the work grows logarithmically. The function also stores the repeat count in a long so that negating the most negative int cannot overflow on platforms where long is wider.
Real-World Uses in Embedded C Programming
- Unit scaling: converting readings between microvolts, millivolts and volts uses powers of ten, such as
ep_ipow(10.0, -6)for micro. - Audio and signal gain: decibel to linear gain conversions repeat multiplications of a fixed ratio.
- Filter and timer maths: exponential decay factors and prescaler values are powers of two.
- Calibration tables: computed once at boot, then stored in an array for fast lookup.
Many teams avoid the standard pow() function on small microcontrollers. It works on double, needs the maths library linked with -lm, and can add several kilobytes of flash. A short integer-exponent function in your own source is smaller, easier to review and easy to test. On cores without a double precision unit, prefer float arguments to keep the arithmetic fast.
Common Mistakes and Troubleshooting
Mistake 1: using the caret operator. In C, 2 ^ 3 equals 1, because it is bitwise XOR, not a power.
Mistake 2: calling abs() on a floating point value. Use fabs() for doubles. For an integer exponent, abs() needs stdlib.h included, and omitting it was common in very old code.
Mistake 3: forgetting to start result at 1.0. Starting at 0 makes every answer 0.
Mistake 4: comparing the answer with ==. Floating point rounding means a result like 0.1 raised to a power may differ from the expected constant in the last bit. Compare with a small tolerance.
Best Practices, Performance and Safety
- Use
doubleorfloatfor the base andintfor the exponent, and say so in the prototype. - Document what the function returns for a zero base with a negative exponent.
- Keep the function
staticif only one file uses it, so the compiler can inline it. - Prefer the squaring method when exponents can be large, and the plain loop when exponents are tiny and code clarity matters most.
- Write a few test calls, like the ones in
mainabove, whenever you change the logic. - Remember that unchecked huge results can overflow to infinity, and infinity can poison later calculations.
Summary and Key Takeaways
- C has no power operator, so you write a power function in C using a loop.
- Negative exponents use the reciprocal of the positive power.
- Starting the result at 1.0 removes the need for a separate zero case.
- Exponentiation by squaring cuts the work from n multiplications to about log2(n) rounds.
- Handle a zero base with a negative exponent deliberately, never by accident.
Conclusion
You have written, compiled and tested a power function in C that behaves correctly for positive, zero and negative exponents, and you have seen how a small change in the algorithm turns a slow loop into a fast one. This is exactly the thinking that firmware reviews reward: a clear contract, deliberate edge-case handling and awareness of cost. In the next lectures we study where variables live and how long they survive, which decides whether a function like this can safely remember anything between calls.
Frequently Asked Questions
Is there a power operator in C?
No. The caret is bitwise XOR. Use the pow() library function from math.h or write your own power function in C for integer exponents.
How do I handle a negative exponent?
Compute the power with the absolute value of the exponent, then return 1.0 divided by that result.
What does any number to the power zero return?
It returns 1. With the result variable starting at 1.0 and a loop that runs zero times, this happens automatically.
Why not always use pow() from math.h?
It works on doubles, needs the maths library and can increase code size on small microcontrollers. A custom integer-exponent function is lighter.
Why did the program print inf for 0.0 to the power -1?
The function takes the reciprocal of zero, and IEEE 754 floating point division by zero gives infinity instead of stopping the program.
Is exponentiation by squaring always better?
It is faster for large exponents, but for small exponents the plain loop is just as quick and easier to read.
Keep Going With the Free Embedded C Course
Continue to the next lecture, share this free C tutorial with a friend, and keep building the embedded C programming skills employers look for.
Need Help or More Information?
Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments