Sqrt () of type int in C

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

int start = Data -> start_number; double localSum; for (start; start <= end; start++) { localSum += sqrt(start); } 

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

thanks

+4
source share
4 answers

Type conversions that do not cause loss of precision cannot trigger warnings. They are executed implicitly.

 int --> double //no loss in precision (eg 3 became 3.00) double --> int //loss in precision (eg 3.01222 became 3) 

What causes the warning and what does not depends a lot on the compiler and the flags provided to it, however, most compilers (at least the ones I used) do not consider implicit type conversions dangerous enough to guarantee a warning, since this is a function in language specifications.


To warn or not to warn:

C99 Justification claims it as a recommendation

One of the important results of studying this problem (implicit casting) is the understanding that high-quality compilers can look good for such dubious code and suggestions of (optional) diagnostics, and that conscientious instructors could well warn programmers of the problems of implicit type conversion.

C99 Justification (April 2003): Page 45

+11
source

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

The same thing happens and vice versa: if you pass a double function (with a known prototype) with an argument int , the compiler will generate the required conversion code.

Does the compiler warn about such transformations only the compiler and the level of warning that you requested on the command line.

To convert int -> double , which is usually (with 32-bit (or 16-bit) int and 64-bit doubles in IEEE754 format) lossless, getting a warning for this conversion is probably difficult, if possible at all.

To convert double -> int , with gcc and clang, you need to specifically ask for such warnings using -Wconversion , or they will compile the code without any problems.

+3
source

Int can be safely automatically increased to two, because there is no risk of data loss. The converse is not true. To turn double into int, you must explicitly cast it.

+1
source

C compilers do some automatic casting with double and int. You can also do the following:

 int start = Data -> start_number; int localSum; for (start; start <= end; start++) { localSum += sqrt(start); } 

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

0
source

Source: https://habr.com/ru/post/1443451/


All Articles