The C Programming Language by Ritchie says that:
The library routine
sqrt
expects a double type and will produce nonsense if inadvertently handled something else. So ifn
is an integer, we can usesqrt((double) n)
to convert the value ofn
to double.
But the following code works fine on my system:
printf("%f",sqrt(9));
Then also it is giving the same result as sqrt((double)9)
. Why is my compiler not following the book?
4
It depends on whether you’ve declared the function prototype, double sqrt(double);
. (The usual way of doing so is with #include <math.h>
.
If you have, then C will implicitly convert the function parameter to the correct type. If not, the compiler will accept your code anyway, but the 9
will be incorrectly passed as an int
instead of being converted to a double
.
However, there are some compilers that treat sqrt
as an intrinsic function, and “know” that its parameter is a double
even if you don’t declare it.
because of implicit conversion, new compilers will upgrade some types to fit the target type,
int to double is one of the legal conversions
3