Why is returning a double from a float return method not throwing errors / warnings in C ++
Well, I was trying to compile the following code (just a snippet) into Java
:
class MyClass{
public float get100(){
return 100.05; // returning 100.05f should work
}
}
But as you can see 100.5
both double
in nature, but the get100()
returns float
on its declaration, javac
gives an error such as: can't convert double to float
.
This is understandable. But here's what I noticed aboutc++
I've tried the following code (pretty much the same as mentioned above):
#include<iostream>
using namespace std;
class MyClass{
public:
float get100(){
return 100.05;
}
};
int main(){
MyClass m;
cout<<m.get100()<<endl;
return 0;
}
and this code works fine in c++
..
Can anyone tell me why this is so? or does this mean the c++
compiler is smart enough to convert double
to float
?
But since it double
has a higher range than float
, how does it work in c++
?
Any help / suggestion is greatly appreciated. Thank you in advance.
source to share
cppreference.com about implicit conversions :
Floating point conversions
A floating point class value can be converted to a prvalue of any other floating point type. If the conversion is listed in a floating point list, it is a promotion, not a conversion.
If the original value can be represented exactly in the target type, it is not changed.
If the original value is between two representable values of the destination type, the result is one of the two values (it's implementation defined which)
Otherwise, the behavior is undefined.
Here, chance is the second rule. 100.05
is not exactly representable as float
or double
. For values such as 0.375
or 34
, the first rule will be applied since the original value can be represented exactly.
As far as Java is concerned, a return
is the destination context. JLS §5.2 states:
Destination contexts allow one of the following: * identity conversion (§5.1.1) * primitive conversion extension (§ 5.1.1) * reference conversion extension (§5.1.5) * boxing conversion (§5.1.7), optionally followed by extension reference conversion * conversion for unboxing (clause 5.1.8) followed by an extended primitive conversion.
Note that implicit narrowing of the conversion is not allowed here, unless the return value is a constant value (i.e., a finite field or literal expression that the compiler can predict).
source to share