Re:C and C++ Prioritize Performance over Correctness
by gpderetta on Friday August 18, 2023 @03:50PM
(#37181155)
Unfortunately constexpr doesn't imply constant evaluation. Your function can still potentially be executed at runtime.
If you use the result in an expression that requires a constant (an array bound, a non-type template parameter, a static_assert, or, in c++20, to initialize a constinit variable), then that will force constant evaluation and you'll see the error.
Having said that, compilers have bugs (or simply not fully implemented features), so it is certainly possible that both GCC and clang will fail to correctly catch constant time evaluation UB in some circumstances.
Re:C and C++ Prioritize Performance over Correctness
by mxmlnkn on Friday August 18, 2023 @04:02PM
(#37181317)
Ah thanks, I was not aware that these compile-time checks are only done when it is evaluated in a compile-time evaluating context.
To add to your list, using C++20 consteval instead of constexpr also triggers the error.
Compiled with -std=c++17 and clang 16.0.0 on godbolt: https://godbolt.org/z/qxxWW93Tx