0

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:

printf("%f",sqrt(9));

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

  • 1
    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
  • 1
    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
2

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.

1

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

int to double is one of the legal conversions

  • 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
  • 3
    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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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