constexpr Functions: Optimization vs Guarantee -- Andreas Fertig
Constexpr has been around for a while now, but many don’t fully understand its subtleties. Andreas Fertig explores its use and when a constexpr expression might not be evaluated at compile time.
constexpr Functions: Optimization vs Guarantee
by Andreas Fertig
From the article:
The feature of constant evaluation is nothing new in 2023. You have constexpr available since C++11. Yet, in many of my classes, I see that people still struggle with
constexprfunctions. Let me shed some light on them.What you get is not what you see
One thing, which is a feature, is that
constexprfunctions can be evaluated at compile-time, but they can run at run-time as well. That evaluation at compile-time requires all values known at compile-time is reasonable. But I often see that the assumption is once all values for aconstexprfunction are known at compile-time, the function will be evaluated at compile-time.I can say that I find this assumption reasonable, and discovering the truth isn’t easy. Let’s consider an example (Listing 1).
constexpr auto Fun(int v) { return 42 / v; ① } int main() { const auto f = Fun(6); ② return f; ③ }TheconstexprfunctionFundivides 42 by a value provided by the parameterv①. In ②, I callFunwith the value6and assign the result to the variablef.

In C++, the presence of a user-declared (but not explicitly deleted) copy constructor is enough for the type to be considered copy-constructible by traits like
While C++ doesn’t have native syntax for returning multiple values like some other languages, modern C++ offers powerful tools to accomplish the same goal. With features like
Visual Studio 2022 version 17.14 is now generally available! This post summarizes the new features you can find in this release for C++. You can download Visual Studio 2022 from the
C++’s undefined behaviour impacts safety. Sandor Dargo explains how and why uninitialised reads will become erroneous behaviour in C++26, rather than being undefined behaviour.