Search code examples
c++c++17constants

To evaluate constant in run time via function c++17


i have simple constant that i like to evaluate its value in run time ( or if you suggest better way ) .

inline float deg_to_rad(float p_y) {
    return p_y * static_cast<float>(Math_PI) / 180.f;
}

class TEST {  
    public: 
        const float _MOVEMENT_ = deg_to_rad(90);

}   

is there better way to do it ?


Solution

    1. Using a function doesn't require moving evaluation to runtime. Just add constexpr to the function and it will work at compile-time.

    2. const float _MOVEMENT_ = deg_to_rad(90); will work even without a constexpr function, with the function you have right now.

      But it is advisable to:

      • Make it static to share it across all instances of the class.

      • Make it constexpr (to make things easier)

      • Rename so that it doesn't use a reserved identifier (any identifier starting with _[A-Z] or containing __ is reserved).

      • Not name it in uppercase since it's not a macro (C/C++ uses uppercase for macros by convention, other languages tend to use it for constants since C macros often were used as constants, but it's weird IMO to make a full circle and use it for all constants in C/C++).

        Same for the class name.

      Overall, you end up with static constexpr movement = deg_to_rad(90);.