Where should I look at if I want to switch between float and double precision at compile time. Its like, if user wants everything in float instead of double precision how I can maintain this flexibility? In other words, how should I define a variable that could be either float or double precision conditionally?
Asked
Active
Viewed 3,606 times
3
-
2At compile time or run time? – user7116 Jan 24 '13 at 22:24
3 Answers
17
If it is OK to make the switch at compile time, a simple typedef
would do:
#ifdef USE_DOUBLES
typedef double user_data_t;
#else
typedef float user_data_t;
#endif
Use user_data_t
in your code, and set USE_DOUBLES
if you want doubles
at compile time:
g++ -DUSE_DOUBLES=1 myprogram.cpp

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
Compile both copies, slap a shell script redirector in front, and viola! – user7116 Jan 24 '13 at 22:29
-
@Shibli There are several ways. Using `-D...` compiler option works for many UNIX compilers. On Windows you can set use `/D`, or add `USE_DOUBLES` to the list of preprocessor definitions in the properties of your C/C++ project. – Sergey Kalinichenko Jan 24 '13 at 22:31
-
I put `-DUSE_DOUBLES=1` into my make file directly and checked the type of a variable which was float. So, how can use this for a make file? – Shibli Jan 24 '13 at 22:38
-
@Shibli How did you check the type of the variable? You declared all your variables that must change between `float` and `double` as `user_data_t`, right? – Sergey Kalinichenko Jan 24 '13 at 22:41
-
I declared a new variable as `user_data_t temp` then checked the type as `cout << typeid(temp).name();` then it gave `f`. – Shibli Jan 24 '13 at 22:43
-
1@Shibli I just tried what you did: I compiled a small program ([link to pastebin](http://pastebin.com/bZNkW6Bq)) with `g++ -DUSE_DOUBLES=1 x.cpp` command, and got a `d`; when I compiled with `g++ x.cpp`, I got an `f`. – Sergey Kalinichenko Jan 24 '13 at 23:08
1
Without knowing exactly how you intent to use the data, it's hard to recommend the correct solution.
Have a look at the union date type.
http://msdn.microsoft.com/en-us/library/5dxy4b7b(v=VS.80).aspx
Templates would also be a viable option depending on the usage.

Inisheer
- 20,376
- 9
- 50
- 82
1
I prefer not to have #define
s in my code.
I would have two different headers with two different typedef
s, and allow build options to choose which header is included.

Peter Wood
- 23,859
- 5
- 60
- 99