4 ms·
So according to this, if (b) a = *b; else a = 3; Since dereferencing 0 is undefined, the compiler can assume that a = 3 never needs to be executed
by EGreg 12y ago
So according to this,
if (b)
a = *b;
else
a = 3;
Since dereferencing 0 is undefined, the compiler can assume that a = 3 never needs to be executed??
But b may legitimately be 0 and then the second branch SHOULD be entered
How does this fit with what the author said? The compiler cant just go back and assume b is never zero just because it's being dereferenced, since the dereference is guarded.
That's why his last part doesnt make sense -- that even f you try to prevent a bad dereference, undefined behavior is triggered.
- mikeash 12y agoNo, that's not true at all. You check before you dereference, which is completely legitimate. If b is NULL then the dereference never happens, exactly as it should be. To invoke undefined behavior and strange optimizations, you'd need to rearrange the code a bit: a = *b; if (!b) a = 3; Here, the compiler can omit the if statement and its contents entirely, because b cannot be NULL, because the first line would invoke undefined behavior if it were. A check for NULL before you dereference is always safe. It's when you do it the other way around that the compiler can start doing strange things.