简体   繁体   中英

Emulating GCC's __builtin_unreachable in Visual Studio?

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?

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.

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;
}

对于此用例,Visual Studio 具有__assume(0)

C++23 will have std::unreachable as a cross-platform alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM