C: Substract double from integer

I have a question that can save a lot of debugging time for many people ...

For function:

void my_func(double value) 

Is there a difference between the next two lines of code?

 double my_value = 1 - value; 

and

 double my_value = 1.0 - value; 

those. that value is double , if I use 1 - value , can I feel safe that the result will be the correct real number, for example, when using 1.0 - value ?

+5
source share
5 answers

There is no difference. To subtract double from int , int must be upgraded to double . I personally prefer to use 1.0 , because I think it makes it clearer that this is not an integer subtraction. But this is purely a style issue.

+11
source

Yes, you are guessing correctly, but for more complex expressions you have to be very careful in mixing integer and floating-point values. For example, an innocent looking code:

 double x = 1 / 2; 

saves 0 to x , because the calculation is performed on int values, and the result is converted to double .

+3
source

You're right. Operator - works on objects of the same type. This implies an implicit type, and int is converted to double.

Note that this can be a source of errors when mixing signed and unsigned types.

+3
source

In your example, both will behave the same.

those. given that the value is double if I use a 1-value, can I feel safe that the result will be the correct real number, for example, when using 1.0 - value?

With 1.0 - value you also cannot guarantee that it will be the correct number. Check out some floating point arithmetic document.

+3
source

If any operand of an arithmetic operator is a floating point, the calculation is performed in floating point arithmetic. The calculation is performed in double if both operands are not floating, in which case the calculation is performed in float.

+1
source

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


All Articles