Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqrt() of int type in C

Tags:

c

int

double

sqrt

I am programming in the c language on mac os x. I am using sqrt, from math.h, function like this:

int start = Data -> start_number;
double localSum;

for (start; start <= end; start++) {
    localSum += sqrt(start);
}

This works, but why? and why am I getting no warning? On the man page for sqrt, it takes a double as parameter, but I give it an int - how can it work?

Thanks

like image 936
user1090614 Avatar asked Nov 01 '12 13:11

user1090614


3 Answers

Type conversions which do not cause a loss in precision might not throw warnings. They are cast implicitly.

int --> double //no loss in precision (e.g 3 became 3.00)
double --> int //loss in precision (e.g. 3.01222 became 3)

What triggers a warning and what doesn't is depends largely upon the compiler and the flags supplied to it, however, most compilers (atleast the ones I've used) don't consider implicit type-conversions dangerous enough to warrant a warning, as it is a feature in the language specification.


To warn or not to warn:

C99 Rationale states it like a guideline

One of the important outcomes of exploring this (implicit casting) problem is the understanding that high-quality compilers might do well to look for such questionable code and offer (optional) diagnostics, and that conscientious instructors might do well to warn programmers of the problems of implicit type conversions.

C99 Rationale (Apr 2003) : Page 45

like image 180
Anirudh Ramanathan Avatar answered Sep 21 '22 16:09

Anirudh Ramanathan


The compiler knows the prototype of sqrt, so it can - and will - produce the code to convert an int argument to double before calling the function.

The same holds the other way round too, if you pass a double to a function (with known prototype) taking an int argument, the compiler will produce the conversion code required.

Whether the compiler warns about such conversions is up to the compiler and the warning-level you requested on the command line.

For the conversion int -> double, which usually (with 32-bit (or 16-bit) ints and 64-bit doubles in IEEE754 format) is lossless, getting a warning for that conversion is probably hard if possible at all.

For the double -> int conversion, with gcc and clang, you need to specifically ask for such warnings using -Wconversion, or they will silently compile the code.

like image 31
Daniel Fischer Avatar answered Sep 19 '22 16:09

Daniel Fischer


Int can be safely upcast automatically to a double because there's no risk of data loss. The reverse is not true. To turn a double to an int, you have to explicitly cast it.

like image 44
Tyler Lee Avatar answered Sep 21 '22 16:09

Tyler Lee