logoalt Hacker News

jonasenordintoday at 3:38 PM2 repliesview on HN

I haven't kept up with C++ in a few years - what does constexpr do for local variables?

  constexpr double a0 = 1.5707288;

Replies

loegtoday at 4:48 PM

It is required to be evaluated at compile time, and it's const.

An optimizing compiler might see through a non-constexpr declaration like 'double a0 = ...' or it might not. Constexpr is somewhat more explicit, especially with more complicated initializer expressions.

show 1 reply
fancy_pantsertoday at 3:48 PM

The compiler can substitute the value how it sees fit. It's like #define, but type-safe and scoped.

Maybe it's folded into expressions, propagated through constant expressions, or used it in contexts that require compile-time constants (template parameters, array sizes, static_assert, other constexpr expressions).

I mean, not in this case of pi/2, where it's more about announcing semantics, but in general those are the purposes and uses.

show 2 replies