Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a constant by expression in C++?

Tags:

c++

c++11

I need some like this:

const float ratio = 1/60;

How to do this?

like image 510
RPlay Avatar asked Nov 19 '13 07:11

RPlay


3 Answers

Exactly as you have done but tell the compiler the values in the expression are floats with a "f" suffix

const float ratio = 1.0f/60.0f;
like image 67
kfsone Avatar answered Nov 08 '22 18:11

kfsone


You don't really need constexpr, this will work in C or C++:

const float ratio = 1./60;
like image 43
mvp Avatar answered Nov 08 '22 20:11

mvp


If you need a ratio, as opposed to the result of one, you can use std::ratio:

constexpr one_sixtieth = std::ratio<1, 60>();

constexpr auto n = one_sixtieth.num;
constexpr auto d = one_sixtieth.den;

It comes with a set of useful compile time operations.

like image 5
juanchopanza Avatar answered Nov 08 '22 18:11

juanchopanza