If an object is declared const
, its value is guaranteed to be available only at runtime, but if it's declared constexpr
, the value is guaranteed to be available both during compilation and at runtime. So if I have an object whose value is available during compilation, are there any situations where I should not declare it constexpr
?
const int magicValue = 42; // Does this ever make sense
// (using const instead of constexpr)?
For functions, if a function can return a value computed during compilation when passed arguments with values available during compilation, would it ever make sense to not declare the function constexpr
?
struct Point { int x; int y; };
Point midPoint(Point p1, Point p2) // Does this ever make
{ // sense (not declaring
return { (p1.x + p2.x) / 2 , (p1.y + p2.y) / 2 }; // the function
} // constexpr)?
The only case I can conceive of is when you don't want to commit to the function being able to compute a compile-time constant when called with known-at-compile-time arguments, e.g., if you want to preserve the flexibility to change midPoint
's implementation without changing its interface (thus potentially breaking callers). For example, you might want to preserve the flexibility to add non-constexpr
side-effects to midPoint
, e.g., IO.
constexpr
function? If the arguments are supplied at run-time, it will be computed at run-time. If the arguments are known at compile-time, even a non-constexpr
function might be computed at compile-time. It's nothing to do with whether the function is marked asconstexpr
. – jogojapan Jan 3 '14 at 10:52