6 ms·
> the condition of an if statement is always evaluated first I am not sure about Rust, but gcc will definitely elide an if check if it detects pointer derefere
by perryizgr8 3y ago
> the condition of an if statement is always evaluated first
I am not sure about Rust, but gcc will definitely elide an if check if it detects pointer dereference inside the if block. The reasoning was that if a pointer is being dereferenced, it must be non null. Because if it is null that would be undefined behavior and compiler is allowed to do whatever wants in that case anyway. So
if (ptr != NULL) {
val = *ptr
// do something with val
}
becomes
// null check removed
val = *ptr
// do something with val
So no, the condition is not guaranteed to be evaluated first, or even evaluated at all. I would be surprised if Rust compiler is not doing these sorts of optimisations.
- nolist_policy 3y agoSource? I think you remember it wrong: The compiler will only optimize the if away if you already potentially invoked UB. Like this: val = *ptr; // May be *NULL if (*ptr != NULL) ...
- vardump 3y agoThat's not true. Only if you dereferenced the pointer before the if-statement.
- aw1621107 3y ago> but gcc will definitely elide an if check if it detects pointer dereference inside the if block As others have stated, this is almost certainly incorrect. > The reasoning was that if a pointer is being dereferenced, it must be non null. The key here is "if a pointer is being dereferenced". In that case the pointer is only dereferenced if the condition evaluates to true and does nothing otherwise. The optimizer would be incorrect to turn that into an unconditional dereference.