简体   繁体   中英

Why returning double from float returning method does not cause any error/warning in c++

Well I was trying to compile following code (just a snippet) in Java :

class MyClass{
        public float get100(){
        return 100.05;  // returning 100.05f should work
    }
}

But as you can see 100.5 being a double in nature but get100() is returning float by its declaration, javac gives error as: can't convert double to float .

Which is totally understandable. But Here is what i noticed about c++

I tried following code (Almost similar to the one 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 is running fine in c++ ..

Can anyone tell me why is it so? or does it mean c++ compiler is smart enough that it can auto convert double to float ?

But as double is of higher range than float , how is that working in c++ ?

Any help/Suggestion is appreciated. Thanks in advance.

Yes, the C++ compiler is smart enough that it can auto convert double to float. The Java compiler could do the same thing, but the designers of Java decided that it's better to not allow it, in case it is a mistake by the programmer.

cppreference.com on implicit conversions :

Floating point conversions

A prvalue of an floating-point type can be converted to prvalue of any other floating-point type. If the conversion is listed under floating-point promotions, it is a promotion and not a conversion.

  • If the source value can be represented exactly in the destination type, it does not change.

  • If the source value is between two representable values of the destination type, the result is one of those two values (it is implementation-defined which one)

  • Otherwise, the behavior is undefined.

Here, the case is the second rule. 100.05 is not exactly representable as a float or a double . For values such as 0.375 or 34 , the first rule would be applied, as the source value can be represented exactly.

As for Java, a return is an assignment context. JLS§5.2 states:

Assignment contexts allow the use of one of the following: * an identity conversion (§5.1.1) * a widening primitive conversion (§5.1.2) * a widening reference conversion (§5.1.5) * a boxing conversion (§5.1.7) optionally followed by a widening reference conversion * an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

Note that an implicit narrowing conversion is not permitted here, unless the value being returned is a constant value (ie a final field, or literal expression the compiler can evalulate).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM