Do compilers `constexpr` everything?

Viewed 193

Do compilers try to constexpr1 everything? Not just functions/variables/things explicitly marked constexpr by the programmer? Before someone comments

yeah duh, that's what optimization is

A better phrasing of this question might be: at max optimization does the compiler go until it cannot constexpr anything else? Or is there some limitation practical or otherwise that means it can only constexpr some subset of the program?

1 read: evaluate/solve at compile-time

1 Answers

The compiler must do everything the language requires.

On top of that the compiler can do whatever it likes as long as the result is as if it didn't do anything extra.

So it is totally up to the compiler what it does and there are lots of non-optimizing or barely optimizing compilers out there. A good optimizing compiler will go a long way trying to evaluate as much as possible at compile time but generally only up to some internal limit. Otherwise it might never finish. The compiler would have to solve the halting problem otherwise.

That said it's always fun to have some pages of c++ code that do lots of computations and have the compiler produce a binary that contains just puts("The answer is 42.\n");.

Related