Search code examples
c++castingc++builderlong-double

C++ Builder 2009 Float vs Long Double


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;


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".