Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constexpr does not enforce compile-time evaluation #276

Open
HadrienG2 opened this issue Mar 23, 2024 · 0 comments
Open

Constexpr does not enforce compile-time evaluation #276

HadrienG2 opened this issue Mar 23, 2024 · 0 comments

Comments

@HadrienG2
Copy link

HadrienG2 commented Mar 23, 2024

This book unfortunately perpetuates the widely held belief that putting a constexpr keyword on code will, on its own, force code to be evaluated at compile time. This is inaccurate. You need C++20's consteval for that.

What constexpr actually does is to constrain code into a subset of the language that can be evaluated at compile time. This, in turn, lets you use constexpr functions and expressions in a context where the output expression must be evaluated at compile time for the program to be correct according to the rules of the language. Think about, for example, computing template non-type parameters.

Compilers are not forced to evaluate constexpr operations at compile-time, and indeed, for a sufficiently complex expression, they won't. Conversely, compilers were able to evaluate expressions at compile time a long time before constexpr was a thing, and will commonly perform the associated const-propagation optimization on code where constexpr is not present.

All in all, the only way constexpr may benefit program optimization is that it forces you to constrain yourself into a subset of the language which is known to be amenable to const-propagation on all modern compilers, and lets you get a compiler error otherwise. This is useful, but not as useful as the current text asserts, so please consider amending it and pointing to consteval instead for the kind of optimizations that you are discussing in the book.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant