3 ms·
The compiler may remove the nullptr check in: ptr->foo = 1; if (ptr == nullptr) return; but it may not remove the nullptr check in: if (ptr == nul
by nlewycky 2y ago
The compiler may remove the nullptr check in:
ptr->foo = 1;
if (ptr == nullptr)
return;
but it may not remove the nullptr check in:
if (ptr == nullptr)
return;
ptr->foo = 1;
- Bjartr 2y agoI guess I've misunderstood that other story then, thanks.
- thayne 2y agoTo explain why it can be removed in the former: Since it is UB to dereference a null pointer, the compiler can assume that ptr isn't null after it is dereferenced[1]. Therefore, the if condition will always be false. In fact if ptr is null, unless the foo field has a very large offset, the behavior you would probably expect would be for the dereference to segfault before reaching the if, so it doesn't really matter if it is optimized away.
- krackers 2y ago>so it doesn't really matter if it is optimized away. There are cases in which the optimization can result in behavior other than segfaulting, see https://research.swtch.com/ub#null https://research.swtch.com/ub#null
- thayne 2y agoSure. That's why I said "the behavior you would probably expect", but that isn't necessarily what happens.