1

Hey guys I was wondering why my program was just returning junk and I found out that I didn't include math.h. But why did the code even compile and run if there isn't any definition for the function ?

#include <stdio.h>

int main()
{
    int ka = 0;

    ka = sqrt(4);

    printf("ha ist %d", ka);

    system("PAUSE");
    return 0;
}
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
maxiangelo
  • 125
  • 12
  • The compiler should have given you a warning. It's up to you to make sure that A) you have all the warnings enabled, and B) you fix the warnings. If you're using gcc or clang, compiling with `-Wall -Wextra -Werror` will do the trick. – user3386109 Jan 06 '20 at 23:40
  • Visual studio hasn't given me a warning, just recompieled it. – maxiangelo Jan 06 '20 at 23:43
  • 1
    On visual studio, you should be compiling with at least `/W3`. I usually compile with `/W4`. And if you're compiling with the IDE, you need to make sure that the build window is open, so that you actually see the warnings. – user3386109 Jan 06 '20 at 23:44
  • MSVC should also have given you a warning about assigning the floating point square root to an `int ` variable: *possible loss of data*. This level of warning is fairly basic. – Weather Vane Jan 06 '20 at 23:48
  • 2
    @WeatherVane No, `math.h` is not included, so `sqrt()` is assumed to be an `int`-returning function, so there is no loss of data from the compiler's point of view. – Ken Y-N Jan 07 '20 at 00:28
  • clang gives this warning `warning: implicitly declaring library function 'sqrt' with type 'double (double)' [-Wimplicit-function-declaration]` but the program works. – Gerardo Zinno Jan 07 '20 at 01:09
  • Even if you had included "math.h", that would not give a definition of the function. The header merely provides the declaration, which is not strictly necessary because the compiler is allowed to make assumptions about implicitly declared functions. IOW, if you don't declare the function, the compiler assumes it returns an integer. – William Pursell Jan 07 '20 at 01:12

0 Answers0