Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 if n is an integer, we can use sqrt((double) n) to convert the value of n to double.

But the following code works fine on my system:


Then also it is giving the same result as sqrt((double)9). Why is my compiler not following the book?

share|improve this question
Because the C language has moved on and improved since the first version of K&R was published. – Bart van Ingen Schenau Jun 1 '13 at 16:08
While a programming classic, I'm going to say that it's not a great idea to use K&R to learn production C. – World Engineer Jun 1 '13 at 16:11
@World Engineer which book do you recommend? – user1369975 Jun 1 '13 at 19:15
King's C Programming: A Modern Approach is good, so is C in a Nutshell if you're not learning programming for the first time. – World Engineer Jun 1 '13 at 19:22

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.

share|improve this answer

because of implicit conversion, new compilers will upgrade some types to fit the target type,

int to double is one of the legal conversions

share|improve this answer
But why does the book say that ""The library routine sqrt expects a double type and will produce nonsense if inadvertently handled something else"? – user1369975 Jun 1 '13 at 15:01
because type conversion became standard after K&R was published – ratchet freak Jun 1 '13 at 15:34
@ratchetfreak: I'd assume type conversion became standard after the first edition of K&R was published, but before the second edition of K&R was published. – Brendan Jun 1 '13 at 20:28

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.