Using inline and constexpr in C++

Viewed 390

I am working on a robot program for FRC robotics and was curious about if inline or constexpr or both are appropriate for declaring constants.

inline constexpr double PI = wpi::math::pi 
inline constexpr double TWO_PI = 2.0 * wpi::math::pi;
inline constexpr units::radian_t PI_RAD = units::radian_t(PI);
inline constexpr units::radian_t TWO_PI_RAD = units::radian_t(TWO_PI);

1 Answers

Omit inline for variables declared in source files; it merely invites name collisions. C++17 added support for inline variables for header files: by all means use it there to avoid stupid things like this:

#ifndef HEADER_HH
#define HEADER_HH
#include<algorithm>
/* inline */ constexpr int bound=30;
inline int clip(int x) {return std::min(x,bound);}
#endif

Any program that #includes this header in two different source files is ill-formed, no diagnostic required(!), because std::min takes its arguments by reference and thus odr-uses the internal-linkage bound which is a different variable in every translation unit, denying a single definition for clip.

In C++20, though, you can use export constexpr (or, for module-private variables, extern constexpr) in a module interface unit with no need for inline.

All this applies for normal const (as you must use if the initializer is not a constant expression), with the added bonus that inline lets you define a non-constexpr static class member inside the class (which is useful even in a source file; put the class in an anonymous namespace to prevent collisions in that case).

Related