Why put 'f' when using float?

 
float x = 5.0f;


I heard that without putting the 'f', compiler thinks that x is double. But I declared what type of variable i'm going to use by putting 'float'.

I'm not sure what's going on here. Can someone explain what's going on?
For example,
1
2
3
4
5
6
7
8
9
10
11
12
void f(float){
    std::cout <<"void f(float)\n";
}

void f(double){
    std::cout <<"void f(double)\n";
}

//...

f(5.0);
f(5.0f);
> float x = 5.0f;
> I heard that without putting the 'f', compiler thinks that x is double.

No, it does not. We have explicitly declared that x is a variable of type float.
1
2
3
4
float a = 5.0 ; // type of 'a' is float
float b = 7 ; // type of 'b' is float
float c = 'C' ; // type of 'c' is float
float d = 5.0L: ; // type of 'd' is float 


A floating-point-literal-suffix (f or F for float, l or L for long double) can be used when we want to specify the type of a floating point literal; the type of a floating point literal without a suffix is double.
1
2
3
4
5
6
auto a = 5.0 ; // type of 'a' is double
auto b = 5.0f ; // type of 'b' is float
auto c = 5.0L ; // type of 'c' is long double
auto d = 5 ; // type of 'd' is int
std::sqrt( 5.0 ) ; // type of argument is double
std::sqrt( 5.0F ) ; // type of argument is float 
Topic archived. No new replies allowed.