4 ms·
bool foo(some_struct* bar) { if (bar->blah()) { return true; } if (bar == nullptr) { return false; }
by kllrnohj 2y ago
bool foo(some_struct* bar) {
if (bar->blah()) {
return true;
}
if (bar == nullptr) {
return false;
}
return true;
}
Can the compiler eliminate that nullptr comparison in your opinion yes or no? While this example looks stupid, after inlining it's quite plausible to end up with code in this type of a pattern. Dereferencing a nullptr is UB, and typically the "platform-specific" behavior is a crash, so... why should that if statement remain? And then if it can't remain, why should an explicit `_Nonnull` assertion have different behavior than an explicit deref? What if the compiler can also independently prove that some_struct->blah() always evaluates to false, so it eliminates that entire branch - does the `if (bar == nullptr)` still need to remain in that specific case? If so, why? The code was the same in both cases, the compiler just got better at eliminating dead code.