Search code examples
c++floating-point-precisiondouble-precision

Switching between float and double precision at compile time


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?


Solution

  • 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