3 ms·
c++11 style attribute. There are already similar attributes [[unlikely]] and [[likely]] which can be attached to any statement. Having [[unreachable]] wouldn't
by Karliss 4y ago
c++11 style attribute. There are already similar attributes [[unlikely]] and [[likely]] which can be attached to any statement. Having [[unreachable]] wouldn't be that surprising. C++23 also introduced [[assume(expr)]] which is basically conditional unreachable. I don't see a reason why standard committee couldn't have defined that [[assume(false)]] can be used for that purpose instead of new builtin. Either of the two would have been more consistent in my opinion, only reason I see for choosing a builtin function is because GCC and Clang already had __builtin_unreachable() builtin functions, so making it a function might in theory reduce the work for them.
- chrisseaton 4y agoApparently you can add attributes to case labels, so yeah that does work.
- int_19h 4y agoThere are also conditional expressions to consider. With the function approach, you can effectively mark any subexpression as unreachable, so e.g. this is possible: auto x = (y == 1) ? foo : (y == 2) ? bar : ... std::unreadchable();
- deleted 4y ago[deleted]
- chrisseaton 4y agoYou could can 'inject' it via writing a function never_fails, that tests the condition, and branches to unreachable if it fails, then returns the same condition. That should let the compiler understand that the condition is always true.
- int_19h 4y agoSure, you can adapt a different solution to this case - but why, when a magic function can be used everywhere a pragma or similar could, and also covers this case naturally? A pragma or an attribute would make more sense if you needed to do that in the middle of class declarations, say. But here, we're only concerned about executable code. Nor is it unprecedented to have a standard library function triggering UB when called - it's just that this one has a precondition that's always false, so it's always UB.
- bluGill 4y ago[[assume(expr)]] has a lot of controversy about what you can do with it. I haven't read the latest papers (I really should), but there is a good argument to be made that the expression means flag an error if this happens, but otherwise keep running. There are embedded systems where they have to keep running no matter what. They want to use [[assume]] as a hint to program provers about what shouldn't happen, but they still want the compiler to generate the error handling code for that condition. Unreachable by contrast means don't generate code and nobody will argue otherwise. Again, I'm not up on the latest papers, but that was the situation last I checked.