5
votes

I can define a constant as either a float or a 32-bit uint:

const float SecondsPerMinute = 60.0F;

or

const uint32 SecondsPerMinute = 60U;

The const is used in some equations that expect an int and some equations that expect a float. I want to make my compiler and static analysis tools happy so I will static_cast it to the appropriate type as necessary.

Is it better to define the const as a float and cast to an int, or define it as an int and cast it to a float? Does it make a difference, or is this more a matter of personal opinion?

Let's say the constant is used an equal number of times as an int and as a float.

1
If you need to add useless casts to convert 60u to 60f, your static analysis tools are not helping.Alan Stokes
If you define it as float, then at each equation which needs an int, you will cast it as an int and vice versa. So why don't you define two constants one for int and other for float and use them as required ? This definitely will give same performance if not better than any other alternative. Only drawback is your code size will increase.Nishant
There is no loss of information in the conversion in either direction (both representations are exact). And no cast is needed in either direction. So it doesn't matter at all.Alan Stokes
I agree in this simple case the static analysis tools may be making an unnecessary complication, but their purpose is to reveal cases where unintended behavior might result. And in the case of int vs float, you could legitimately lose precision by using a float when an int is expected. Just saying... :)C. Korb
Sure: but where the value is a constant - and a constant exactly representable as int or float - then no warning is justified.Alan Stokes

1 Answers

12
votes

How about a template:

template <typename T>
constexpr T SecondsPerMinute = T(60);

Usage:

std::printf("%d %f", SecondsPerMinute<int>, SecondsPerMinute<double>);