1

i have following C code:

#include <stdio.h>

main()
{
    double wurzelZwei;
    wurzelZwei = sqrt(2.0);
    printf("Wurzel 2: %lf\n", wurzelZwei);
}

Why is the return value of sqrt "1073742463" and the compiler/linker does only show a warning and no fatal error when the "math.h" libary is not included?

MH2K9
  • 11,951
  • 7
  • 32
  • 49
Max Gunter
  • 213
  • 1
  • 14
  • 8
    The standards only mandate *a diagnostic*. The compiler is not prohibited to do anything it wants after that, whch might even make things work despite being ill-formed. Consider compiling with `-std=c11 -Wall -Wextra -pedantic-errors`. – Deduplicator Dec 14 '14 at 14:31

1 Answers1

11

In C89 and earlier it is allowed to call a function that has not been declared. When doing so, that function is assumed to have return type int. This is called an implicit declaration.

When you call a function that way, but it has been defined with a return type other than int, you invoke undefined behavior just as if you had explicitly declared the function with a different return type than you defined it with.

So in your case what happens is that you implicitly declare sqrt with the default return type int, so the return value you get from sqrt is (falsely) interpreted as an int and that int is then converted to double when you store it in wurzelZwei.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • Thanks, but why is the result of sqrt exactly an integer with the value "1073742463" and not "0" for example? – Max Gunter Dec 14 '14 at 15:14
  • 1
    @MaxGunter a) Undefined behavior and b) because the first four bytes of the value returned by sqrt happen to spell the number "1073742463" when interpreted as an integer (that or because the register that the result would have been stored in if the function actually returned an int, happens to contain that number at that point in time - it really depends on your compiler, libc and calling convention). – sepp2k Dec 14 '14 at 15:37