Emulating GCC's __builtin_unreachable in Visual Studio?

Viewed 1704

I have seen this question which is about emulating __builtin_unreachable in an older version of GCC. My question is exactly that, but for Visual Studio (2019). Does Visual Studio have some equivalent of __builtin_unreachable? Is it possible to emulate it?

3 Answers

By the way, before std::unreachable() is available you can implement it as a compiler-independent function, so that you don't have to define any macros:

#ifdef __GNUC__ // GCC 4.8+, Clang, Intel and other compilers compatible with GCC (-std=c++0x or above)
[[noreturn]] inline __attribute__((always_inline)) void unreachable() {__builtin_unreachable();}
#elif defined(_MSC_VER) // MSVC
[[noreturn]] __forceinline void unreachable() {__assume(false);}
#else // ???
inline void unreachable() {}
#endif

Usage:

int& g()
{
    unreachable();
    //no warning about a missing return statement
}

int foo();

int main()
{
    int a = g();
    foo(); //any compiler eliminates this call with -O1 so that there is no linker error about an undefined reference
    return a+5;
}

MSVC has the __assume builtin which can be used to implement __builtin_unreachable. As the documentation says, __assume(0) must not be in a reachable branch of code, which means, that branch must be unreachable.

Related