sqrt() of int type in C

早过忘川 提交于 2019-11-27 08:09:39

问题


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


回答1:


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




回答2:


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.




回答3:


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.




回答4:


C-compilers do some automatic casting with double and int. you could also do the following:

int start = Data -> start_number;
int localSum;

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

Even if the localSum is an int this will still work, but it will always cut of anything beyond the point.
For example if the return value of sqrt() is 1.365, it will be stored as a simple 1.



来源:https://stackoverflow.com/questions/13178618/sqrt-of-int-type-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!