Sign in to follow this  

floating point literals in the present of typedef

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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
#endif

real f = R(1.5);

Share this post


Link to post
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)
#endif


int 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]

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this