sqrt() of int type in C

user1090614 picture user1090614 · Nov 1, 2012 · Viewed 14.8k times · Source

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

Answer

Anirudh Ramanathan picture Anirudh Ramanathan · Nov 1, 2012

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