9

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?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

4 Answers4

7

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;
}
devoln
  • 396
  • 4
  • 12
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.

Andrey Semashev
  • 10,046
  • 1
  • 17
  • 27
2

Visual Studio has __assume(0) for this use-case.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • It would be nice if this were standardized. Something like `[[unreachable]]`. – Aykhan Hagverdili Mar 23 '20 at 08:56
  • 3
    @Ayxan The proposal working through is actually a function: [`std::unreachable()`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0627r3.pdf). Probably for C++23. – Barry Mar 23 '20 at 13:33
1

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

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93