floating point literals in the present of typedef

This topic is 3531 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

In one of my sources I define a new type "real" that resolves either to float or double (depending on some compiler flag)
typedef double real;
// respectively:
typedef float real;


One problem I'm facing now is how I should treat floating point literals. Somewhere in the code I may have the following:
real c = 1.234567891011


When I'm compiling with real as double everything is fine, switching to float however produces a warning about a truncation (as it's a double literal). Then I began adding casts everywhere I'm using literals:
real c = static_cast<real>(1.234567891011)


However this tends to be hard to read, especially if there are many floating point literals in a single expression. Can you think of a way to handle this in a better and less verbose way?

Share on other sites
You're not magically getting any precision out of manually casting it, why does the truncation warning bother you? Besides, if you need to manually specify such literals, why compile with floats to begin with?

Share on other sites
You could do something like:
#if WHAT_EVER_CONDITION_YOU_USE_FOR_FLOATS  typedef float real;  #define R(x) x ## f#else  typedef double real;  #define R(x) x#endifreal f = R(1.5);

Share on other sites
You could write a macro to optionally add the 'f' at the end of floating literals:

#define USE_DOUBLE 0#if USE_DOUBLE  typedef double real;#else  typedef float real;#endif/* macro */#if USE_DOUBLE  #define REAL(F) (F)#else  #define REAL(F) (F##f)#endifint main( ){  real x = REAL(1.234567891011);  return 0;}

It's not the prettiest thing, but it should work.

<edit>From now on I'm going to right the code then hit the reply button [smile]