4 ms·
What does 'removing a statement' even mean? C statements aren't translated one-for-one to machine code, so you can't just talk about 'removing a statement'. I
by eru 7y ago
What does 'removing a statement' even mean?
C statements aren't translated one-for-one to machine code, so you can't just talk about 'removing a statement'.
In any case, lots of undefined behaviour is in the standard exactly so that the compiler can take advantage of the situation.
That's mostly so that the optimizer's job is simpler.
Eg the compiler can assume that you are checking for null yourself already, so reasoning-by-contradiction it can assume that when an execution path looks like it might access a null pointer, that it means this path is dead code. (And there's lots of dead code around.)
Similarly, the compiler is allowed to assume that loops that have no side-effects terminate. (Or rather, non-terminating loops without side-effects are undefined behaviour. So you can't rely on them to implement a busy wait.) See "C Compilers Disprove Fermat’s Last Theorem" https://blog.regehr.org/archives/140 https://blog.regehr.org/archives/140 for more about this.
- mark-r 7y agoThe whole point of the null pointer example is that "you are checking for null yourself" doesn't work in that situation, because the compiler optimizes out the check. It becomes impossible to do the right thing.
- eru 7y agoNo, the compiler doesn't optimize out proper null-checks. Eg the compiler leaves this one in: if(ptr) *ptr = 2; But if you do something like this: int* next = ptr + 1; if(ptr) { *ptr = 2; ptr = next; } Then the compiler 'knows' that you must have already checked the ptr for null, and can elide the redundant check.
- mark-r 7y agoSo what you're saying is that this is guaranteed to work: if(ptr) ptr->action1(); if(ptr) ptr->action2(); While this might blow up: if(ptr) { ptr->action1(); ptr->action2(); } That's the only if statement in all of C that works that way, and violates the principle of least surprise in a huge way.