Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast float to int, or int to float?

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.

like image 469
C. Korb Avatar asked May 31 '16 12:05

C. Korb


1 Answers

How about a template:

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

Usage:

std::printf("%d %f", SecondsPerMinute<int>, SecondsPerMinute<double>);
like image 179
Kerrek SB Avatar answered Oct 09 '22 17:10

Kerrek SB