Hacker News new | ask | show | jobs
by quelsolaar 1139 days ago
Im in the WG14 so ive been involved in the discussions.

It fails for 2 reasons:

In order to make it easy to implement it had to be made so limited, that it in no way useful.

The second reason, and the real killer, is the "as if" rule. It states that any implementation can do what ever it wants, as long as the output of the application is the same. This means that how a compiler goes about implementing something is entirely up to the compiler. This means that any expression can be compile or execution time. You can even run the pre-processor at run time if you like! This enables all kinds of optimizations.

In reality, modern compilers like gcc, llvm and MSVC are far better at optimizing than what constexpr permits. However since the specification specifies exactly what can be in a constexpr, the implementations are required to issue an error if a constexpr does something beyond this.

2 comments

Okay, so that's a good start, but I still don't get it.

> In order to make it easy to implement it had to be made so limited, that it in no way useful.

Such as?

> The second reason, and the real killer, is the "as if" rule.

Why is that a problem? It sounds like a benefit. It means that the optimization can't break anything, which to me is kind of the point.

> Such as?

Loops, function calls.... things available in C++

>Why is that a problem? It sounds like a benefit. It means that the optimization can't break anything, which to me is kind of the point

As-if is great! but the problem is that constexpr tricks people in to thinking that something is done at compile time, and the as-if rule overrides that and lets the implementation do it when ever it wants. constexpr is a feature over ridden by a fundamental rule of the language.

"Modern compilers" still fail at:

    const int bla = 23;
    const int blub[bla] = { 0 };
(see: https://www.godbolt.org/z/hjessMhGK)

Isn't this exactly what constexpr is supposed to solve?

If so why not fix const? Why add a whole new keyword? Why complicate the language?
Don't know, you're in WG14, not me :D

Maybe 'const' can't be fixed without breaking existing source code?

I don't really have a problem with adding a new keyword for 'actually const', maybe calling it 'constexpr' means C++ people have wrong expectations though, dunno.

For me, having constexpr being explicit about only accepting actual constant expressions, and creating an error otherwise (instead of silently falling back to a 'runtime expression') is fine, but the existing keyword 'const' has an entirely different meaning, there's just an unfortunate naming collision with other languages where const means 'compile time constant'.