1

This is just really confusing me. The 10 should get coerced to 10.0 in the same way regardless of whether or not it's a variable, right?

int n = 10;
printf("%d\n", (int) pow(n, 2));   // Prints 99
printf("%d\n", (int) pow(10, 2));  // Prints 100
Peatherfed
  • 178
  • 1
  • 10
  • The big hint is that [`pow`](https://en.cppreference.com/w/c/numeric/math/pow) is a *floating point* function. And that for certain constant values, the compiler might be able to evaluate the result at compile-time. I suggest you take a look at the generated assembly for the code you show, I'll bet that `pow(10, 2)` isn't actually called at all and the compiler just have replaced it with the value `100.0`. – Some programmer dude Jul 06 '22 at 06:03
  • https://godbolt.org/z/eMnr7rdYG – 0___________ Jul 06 '22 at 06:09
  • 1
    On low optimizer settings, the compiler might not optimize away the first pow() call but only the second. For deterministic results, use `n*n`. – Lundin Jul 06 '22 at 06:19
  • Generally speaking, if you want to get the "power" of integers, with an integer result, write your own function which simply uses a loop to multiply the integers and return the result. Using floating-point functions for integer operations will introduce rounding errors. – Some programmer dude Jul 06 '22 at 06:30

0 Answers0