3 ms·
The 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
by mark-r 7y ago
The 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.