"In C," writes Keith Lucas, "literal floating point number are interpreted as double precision floating point numbers. For example, if you have '0.0' in your code, the compiler will determine the type of '0.0' to be 'double'. In some compilers, such as the Visual C++ 6 compiler that we use, if a literal 'double' is used for a function with a 'float' parameter, a compiler warning is issued because the literal could be less accurate."
Keith continued, "My former coworker thought of an ingenious way to fix this problem. He defined a constant with a manual cast for double he intended to use..."
/** * Various numeric constants for the UI library, used to * avoid the "truncation from const double" compiler warning **/ #define HMI_0P0 ((float) 0.00) #define HMI_P05 ((float) 0.05) #define HMI_P07 ((float) 0.07) #define HMI_P10 ((float) 0.10) #define HMI_P14 ((float) 0.14) #define HMI_P15 ((float) 0.15) #define HMI_P20 ((float) 0.20) #define HMI_P25 ((float) 0.25) #define HMI_P26 ((float) 0.26) #define HMI_P30 ((float) 0.30) #define HMI_P40 ((float) 0.40) #define HMI_P50 ((float) 0.50) #define HMI_P60 ((float) 0.60) #define HMI_P65 ((float) 0.65) #define HMI_P70 ((float) 0.70) #define HMI_P75 ((float) 0.75) #define HMI_P80 ((float) 0.80) #define HMI_P90 ((float) 0.90) #define HMI_1P0 ((float) 1.00)
"Along with the obvious benefit of fixing the compiler warning," Keith added, "this also eliminates the dreaded use of 'magic numbers,' thereby making code more readable. For example, if I wanted to use 100%, I could use '1.0F', and no one would understand what that meant. However, if I use 'HMI_1P0' it is blatantly obvious what it means because of the well thought out constant."