I tried this code
/*main.c*/
#include <stdio.h>      /* printf */
#include <math.h>       /* sqrt */
int frequency_of_primes (int n) {
  int i, j;
  int freq = n - 1;
  for (i = 2; i <= n; ++i)
  for (j = sqrt(i); j > 1; --j)
    if (i%j==0) {--freq; break;}
  return freq;
}
int main() {
  printf("%f\n", sqrt(4.0));
  return 0;
}
and compiled it with gcc main.c, it reported that undefined reference tosqrt'. I already know add-lm` option can resolve this issue. But what really surprises me is this:
#include <stdio.h>      /* printf */
#include <math.h>       /* sqrt */
// int frequency_of_primes (int n) {
//   int i, j;
//   int freq = n - 1;
//   for (i = 2; i <= n; ++i)
//   for (j = sqrt(i); j > 1; --j)
//     if (i%j==0) {--freq; break;}
//   return freq;
// }
int main() {
  printf("%f\n", sqrt(4.0));
  return 0;
}
The main function also calls sqrt, but ld doesn't report any errors.
That's because the optimizer is handling the constant case you're using.
It's the sqrt(i) call inside frequency_of_primes() that's the problem, the call in main() is optimized out. You can figure that out by reading the generated code for the latter case, it'll just load a constant 2.0 and be done with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With