79794269

Date: 2025-10-19 12:48:07
Score: 1
Natty:
Report link

Is there a way (possibly standard) to know inside foo(const int s) if the function is executed at compile time or at runtime?

The standard ways to detect const if a constexpr function is evaluated at compile time at C++20/C++23:

There are non-standard ways under C++14/C++17:

There isn't any standard way in pre-C++20 through.

Test script:

#if __cplusplus >= 202002L || _MSVC_LANG>= 202002L
#include <type_traits>
#endif
bool is_constant_evaluated() {
#if __cpp_if_consteval >= 202106L
    if consteval { return true; }
    // both MSVC (non-comformant __cplusplus) and by-default _MSVC_LANG and other compiles with conformant __cplusplus
#elif __cplusplus >= 202002L || _MSVC_LANG>= 202002L
    if (std::is_constant_evaluated()) return true;
#elif defined(__GNUC__) // defined for both GCC and clang
    if (__builtin_is_constant_evaluated()) return true;
#elif defined(_MSC_VER)
    if (__builtin_is_constant_evaluated()) return true;
#else
#error "NAWH we don't think we can detect compile time in this compiler";
#endif
    return false;
}
int main() {
    return is_constant_evaluated();
}

And it compiles and works properly even if it's MSVC and C++17/C++14. (assembly here)

Reasons:
  • Blacklisted phrase (1): Is there a way
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Is there a
  • Low reputation (0.5):
Posted by: winapiadmin