This one prints 100:
int j=2;
int i= pow(10,2);
printf("%d\n", i);
and this one prints 99:
int j=2;
int i= pow(10,j);
printf("%d\n", i);
Why?
This one prints 100:
int j=2;
int i= pow(10,2);
printf("%d\n", i);
and this one prints 99:
int j=2;
int i= pow(10,j);
printf("%d\n", i);
Why?
What's going on is that you have a C implementation whose standard library has a very low quality implementation of pow
which is returning inexact results even when the exact result is representable in the type (double
). The call to pow(10,2)
seems to producing the value just below 100.0
, which, when rounded to an integer, yields 99. The reason you don't see this when the arguments are constant is that the compiler took the liberty to optimize out the call alltogether and replace it with a constant 100 at compiletime.
If your intent is to do integer powers, don't use the pow
function. Write a proper integer power function, or when the exponent is known, just write out the multiplication directly.
In the first case, I suspect the compiler has optimized the value to 10*10
without actually calling pow
(compilers do actually do this). In the second case, it looks like you have a floating-point rounding error. The result is almost 100 but not quite, and the implicit cast to int
truncates it.
The pow
function operates on double
, not int
.
In general (but not always), when you convert doubles to integers, you call round()
. Eg:
int i = (int) round(pow(10,j));
If your C library doesn't have this, you can emulate:
#define round(x) floor((x)+0.5)
pow
returns double
and so if the result is not exactly 100
but slightly less than it will truncate when converting to an int
and you will receive the 99
result you are seeing. It would be interesting to see what the results look like for a double
variable and %f
format.
The reason you won't see it when you use literals is because of constant folding which will cause the call to pow
to be optimized out and replaced with a constant. We can see the version that uses constants when we generate the assembly no call to pow
is made it just moves the end result 100
(see it live):
movl $100, -4(%rbp)
while the version the second version actually calls pow
(see it live):
call pow