hanno
hanno

Reputation: 6513

Compile c code with float instead of double

I have a lengthy numeric integration scheme written in C. I'd like to test my algorithm in floating point precision. Is there a way to tell gcc to demote every occurrence of double to float in the entire program?

Upvotes: 7

Views: 5619

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263177

You can't safely do this without modifying your source code, but that shouldn't be terribly difficult to do.

Using the preprocessor to force the keyword double in your program to be treated as float is a bad idea; it will make your program difficult to read, and if you happen to use long double anywhere it would be treated as long float, which is a syntax error.

As stix's answer suggests, you can add a typedef, either at the top of your program (if it's a single source file) or in some header that's #includeed by all the relevant source files:

typedef double real; /* or pick a different name */

Then go through your source code and change each occurrence of double to real. (Be careful about doing a blind global search-and-replace.)

Make sure that the program still compiles, runs, and behaves the same way after this change. Then you can change the typedef to:

 typedef float real;

and recompile to use float rather than double.

It's not quite that simple, though. If you're using functions declared in <math.h>, you'll want to use the right function for whatever floating-point type you're using; for example, sqrt() is for double, sqrtf() is for float, and sqrtl() is for long double.

If your compiler supports it, you might use the <tgmath.h> header, which defines type-generic macros corresponding to the math functions from <math.h>. If you use <tgmath.h>, then sqrt(x) will resolve to call the correct square root function depending on the type of the argument. It was introduced in the 1999 edition of the ISO C standard, so availability shouldn't be a problem.

Another possible issue (thanks to Kevin Thibedeau for pointing it out) is that unsuffixed floating-point constants are of type double. If a float object appears along with a double constant in an expression, for example f + 1.0, there's likely to be an implicit float-to-double conversion. Appending f or F to a floating constant will specify that it's of type float.

Upvotes: 8

stix
stix

Reputation: 1146

typedef double float; 

Before any doubles that you want to replace should work, however be warned it may confuse some external libraries.

In the future, the best approach is to define your own float type:

#ifdef USE_FLOATS
    typedef float MyFloatType; 
#else 
    typedef double MyFloatType;
#endif

Or use templates, which has the added benefit of allowing you to change the code at runtime to use one or the other.

Upvotes: 0

Related Questions