I'm looking at some custom code regarding unreachable code. In short, I have a macro that marks certain code as logically unreachable. This can be used as:
int boolToInt(bool b)
{
switch (b)
{
case true: return 1;
case false: return 0;
}
MY_UNREACHABLE("All cases are covered within the switch");
}
Similarly, I'm trying to reuse this macro at locations where the compiler already knows the code is unreachable.
while (true)
{
if (++i == 42)
return j;
// ...
}
MY_UNREACHABLE("Infinite loop that always returns/continues, never breaks");
That said, in some cases, MSVC still gives the unreachable code warning on the custom handling within the unreachable macro. A simplified version looks like:
// MSVC: cl.exe /std:c++latest /W4
// Clang: clang++ -O3 -std=c++2a -stdlib=libc++ -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wc++98-compat"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic warning "-Wunreachable-code"
#else
#pragma warning( default: 4702 )
#endif
#ifdef __clang__
#define DISABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic push") _Pragma("clang diagnostic ignored \"-Wunreachable-code\"")
#define REENABLE_WARNING_UNREACHABLE _Pragma("clang diagnostic pop")
#else
#define DISABLE_WARNING_UNREACHABLE __pragma(warning(push)) __pragma(warning( disable : 4702 ))
#define REENABLE_WARNING_UNREACHABLE __pragma(warning(pop))
#endif
[[noreturn]] void g();
#define MY_UNREACHABLE(msg) DISABLE_WARNING_UNREACHABLE; g() REENABLE_WARNING_UNREACHABLE
[[noreturn]] void my_exit(int);
[[noreturn]] void f()
{
my_exit(0);
//g(); // Test if warning works without the macro
MY_UNREACHABLE("Custom message");
}
Reproduction at Compiler Explorer
From what I understand from [the microsoft documentation] (https://learn.microsoft.com/en-us/cpp/preprocessor/pragma-directives-and-the-pragma-keyword?view=vs-2019), I should be able to use the __pragma with this warning push/pop to disable this warning within the invocation of my macro. (It even has an example doing so)
What should be changed here to suppress the warning in MSVC?