Question

I'm looking at some legacy code, which tries to cast a long double into a float. From reading http://www.cplusplus.com/forum/beginner/34088/ it looks like the long double has a sizeof() of 16 where the float has a sizeof() of 8.

When the float variable is referenced after the cast, you get a floating point overflow exception which is to be expected...

When running in debug mode, the IDE will show you the exception every time, unless you ignore all of that type. I do not wish to do this, as I wish to solve the problem properly.

So this boils the question down to:

Is there a way to do such a cast, without getting the overflow (or alternative to casting that would get me the same info)?

Current casting looks like: floatVar = (float) longDoubleVar;

Was it helpful?

Solution

Converting a value of type long double to a value of type float is well-defined and meaningful. If the result is too large to store in a float, the result is a floating-point exception, which by default has no effect; the stored value is +inf or -inf.

A floating-point exception is not a C++ exception; it's specific to floating point, and will not be seen when your code runs, unless you've gone out of your way to install a floating-point trap handler. Maybe your IDE installs a trap handler; if so, you'll have to consult the documentation to figure out how to disable this "feature".

OTHER TIPS

The float will never be able to hold the contents of the long double UNLESS you know that the contents of the long double can fit inside the float without truncating data.

Generally the compiler will issue a warning that warns of possible data loss. C++ offers many forms of casting but unfortunately going from a larger data type to a smaller data type will always run the risk of overflow. I would assume that in the case that you have here the long double variables contents is larger than the float can hold.

The only way that overflow would not occur would be if you are going from a smaller data type to a larger. The exception is if the contents of the larger one will fit into the boundaries of the smaller type (which in some cases will still throw a warning)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top