Question

Will use a constexpr instead of const better help compile to optmize? I have some value that are constant. I could use an enum instead of but they aren't all of same type and I don't want to use #defines for ovious reasons. They are declared like below code. My question is: if I use constexpr will it increase possibilities to compiler replace the value where it's used by the literal constant value or it doesn't differ if I use const? I know it's up to each compiler if does or doesn't the optmization but a "general" answer as it behave in most compiler is very welcome. Also, assuming the result are different for simple locals like this it's different too if instead of they are member of a struct/class? is const folding most hard to be performed in this cases?

e.g,

int foo()
{
  constexpr int x = 10;
  constexpr int y = x * 3;
  do_domsething(y + n);
}

versus

int foo()
{
  const int x = 10;
  const int y = x * 3;
  do_domsething(y + n);
}
Was it helpful?

Solution

Today, constexpr is still pretty new and might fall through some optimization cracks. Calculation of the variable's own value is required to be performed at compile time, of course. In the long run, I'd expect the same optimization opportunities for each. Obviously when that happens is compiler-specific.

Just use whichever one has clearer meaning to you and anyone else working on the code, not only in terms of behavior but also intent.

Among other things, note that constexpr guarantees the constant has the same value always, whereas const allows it to have a different value each time initialization is reached (it can't be changed except by initialization, of course). But nearly every compiler on the planet will determine that for your example, the values really are constant.

One more thing: constexpr compile-time evaluation (like template argument calculation) is active even when optimizations are disabled.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top