79486217

Date: 2025-03-05 10:47:47
Score: 3
Natty:
Report link

A constexpr function can also be evaluated at runtime, so it does not need to satisfy constexpr requirements on every execution path.

The compiler checks whether the specific path taken during a constexpr function call meets constexpr requirements based on the given arguments. If it does, the computation is performed at compile time. If it does not, the computation occurs at runtime. If a non-constexpr result is used in a constexpr context, a compilation error occurs.

Consider the following code:

constexpr int f(int val) {
    if (val == 42) {
        std::abort();
    }
    else {
        std::abort();
    }
    return 42;
}
int main() {
    return f(1);
}

This code compiles successfully with MSVC /C++17, even though the function can never actually be a valid constexpr.

After extensive testing, I suspect that MSVC requires a constexpr function to have at least one theoretically valid constexpr path, even if that path is never reachable.

Regarding the OP’s issue, I believe this is a bug in the MSVC compiler.

Consider the following code, tested with Visual Studio Community 2022 version 17.13.2 using /std:c++23preview (since goto is only allowed in constexpr starting from C++23):

constexpr int f(int val) {
    switch (val) {
    case 42:
        std::abort();
        goto abor;
    default:
        return 43;
    }
    abor:
    std::abort();
}

This code compiles. However, the following code does not compile:

constexpr int f(int val) {
    switch (val) {
    case 42:
        std::abort();
        break;
    default:
        return 43;
    }
    std::abort();
}

Even though both versions are logically equivalent, the break version fails to compile while the goto version succeeds. This is quite strange.

Through further testing, I discovered that break and case seem to influence constexpr evaluation in an unexpected way. The exact reason is unclear—perhaps this is a bug in MSVC?

Does anyone know how to report this issue?

Reasons:
  • RegEx Blacklisted phrase (2): Does anyone know
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (0.5):
Posted by: 許恩嘉