I wrote this code:
enum Color
{
kRed,
kGreen,
kBlue,
kUnexistingColor
};
const char* foo(Color color)
{
switch (color)
{
case kRed:
return "red";
case kGreen:
return "green";
case kBlue:
return "blue";
case kUnexistingColor:
default:
__builtin_unreachable();
}
return "";
}
If I call foo with an invalid value, my program just terminates silently or returns "blue" in some other cases. What should really happen if control reaches the point where __builtin_unreachable(); is? Should some error message box on Windows appear, or what?
You told the compiler that the code is unreachable. If you break that promise, you can expect undefined behavior. This is documented here:
If you want to have well-defined behavior, use something else. It's common to put debug-only assertions in such places so you can detect them when running debug builds.
Another common approach is to throw an exception. When you see a crash dump for an unhandled exception raised at that point, you can deduce the supposed "unreachable" code was reached.
You can also write out a message to your log file. Or you can silently return an "error" value and handle that cleanly by not taking any action.
All this entirely depends on how important it is that you know about it and how critical it is to the continued functioning of your program.