4 ms·
I'm glad my compiler searches for those situations and removes the unneeded if. I write a lot of generic code - often I need the if only in some situations and
by bluGill 7y ago
I'm glad my compiler searches for those situations and removes the unneeded if. I write a lot of generic code - often I need the if only in some situations and write it trusting the compiler will figure out the situations I don't need it and remove the if. Without this I'd have to spend a lot of effort maintaining hundreds of almost the same copies of my code different only where there is a might or might not be needed if. Not to mention all the likely bugs when someone doesn't select the right version of my code to use.
- mark-r 7y agoIn the given example, the if check for null was NOT unneeded at all, it was vital for proper program operation. Optimizing it away caused a bug that should not have occurred.
- bluGill 7y agoThat happens once in a while when you try to exploit undefined behavior. I don't do that in my code. I use undefined behavior sanitizer to prove that statement (without that tool I make mistakes)
- mark-r 7y agoBut it's not the programmer trying to exploit undefined behavior, it's the compiler. That's just wrong. How would you check for a null pointer in a way that the compiler can't optimize away?
- eru 7y agoLike this: if (ptr) *ptr = 2; I sort-of agree with you that 'exploiting' undefined behaviour is a bad thing. But that's what C (and C++) are all about: the undefined behaviour everywhere allows the compiler to make lots of optimizations without having laboriously to prove that they are safe. And those languages are all about speed at the expense of safety. If you want (more) safety, there are languages for that. Including C dialects you get via various compiler flags. Eg the Linux kernel uses a special gcc compiler flag to keep all null checks. For this very reason. See https://people.csail.mit.edu/nickolai/papers/wang-undef-2012-08-21.pdf https://people.csail.mit.edu/nickolai/papers/wang-undef-2012... for an overview with examples from the kernel, and lots of cases where the kernel authors opted for a compiler flag to effectively use a more defined dialect of C.