Why use a floating / double literal when it is not needed?

Why use a double or floating literal when you need an integer value and the integer literal will be implicitly added to double / float? And when a fractional value is required, why do I need to add f(to make a literal with a floating point), where double will be added to the float?

For example, I often see code similar to the following

float foo = 3.0f;
double bar = 5.0;
// And, unfortunately, even
double baz = 7.0f;

and

void quux(float foo) {
     ...
}

...

quux(7.0f);

But as far as I can tell, they are equivalent

float foo = 3;
// or
// float foo = 3.0;
double bar = 5;
double baz = 7;
quux(9);

I can understand the method call if you are in a language with overload (C ++, java), where it can actually make a functional difference if the function is overloaded (or will be in the future), but I'm more interested in C (and to a lesser extent Objective-C), which has no overload.

/ f? , ?

+4
4

,

double x = 1 / 3;

, . , ( ) , , , .

+4

C , -, . .0 .

void Test( int n , ... )
{
    va_list list ;
    va_start( list , n ) ;
    double d = va_arg( list , double ) ;
    ...
}

- double, undefined, va_arg , .

Test( 1 , 3 ) ; Test( 1 , 3.0 ) ;


: , ?

printf ( ) .

:

printf("%lf" , 3 ) ;   //will cause undefined behavior

, .

, :

printf("%d" , 3.0 ) ;    //undefined behaviour
+3

, , double/float?

-, " " ( ). , , " [type]".

: ( ). , .

f ( ), double float?

, double float . , , double float ( ) , , , float .

+2

, .

, :

#include <math.h>
...
const double sqrt_2 = sqrt(2);

(: ) int 2 to double sqrt. , sqrt(2) sqrt(2.0) , , .

sqrt(2.0) . () , . , double, 2.0, 2 .

, ; sqrt(2.5)

: , ? , , , 2, 2.0? ( .)

0

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


All Articles