0

I know the difference between const and constexpr, this is not a question answered by simply re-stating their differences.

Rather I would like to know practical use-cases where you would prefer const over constexpr variables.

Cases like const references or const methods, etc. are obviously excluded as const does something entirely different for them.

The only case I can think of are values that should never change but are initialized from a value unknown at compile-time (read from a file, received from a socket, etc.).

I have looked at this but it did not answer my question.

Rares Dima
  • 1,575
  • 1
  • 15
  • 38
  • I think the question you link to (and the question that _that_ then links to_) make it clear enough: use `constexpr` when you can - it sometimes lets the compiler generate better code. If there's a case when you can't use it (because the function result or the value you want to put in a variable is computed at runtime, rather than being known at compile time), use `const` instead. That said, the compiler is often smart enough to figure that out anyway these days, but there's nothing like hedging your bets. – Paul Sanders Apr 30 '22 at 23:38
  • 2
    "_The only case I can think of are values that should never change but are initialized from a value unknown at compile-time_": That is pretty much the answer. – user17732522 May 01 '22 at 00:20

0 Answers0