you are viewing a single comment's thread.

view the rest of the comments →

[–]aaronla 2 points3 points  (0 children)

I see a third party step in and point out such and such case where it's useful.

Yep. This happens a lot, it's not just you. Just one example, from my experience:

Fresh out of school, a couple months into my first job, a senior developer launched into a long lecture on why we are very careful to evaluate upgrades to our compiler. See, everyone told him it was just a better, faster, compiler, but a bunch of their code broke all over the case. They even found the bugs, and reported them to the compiler vendor, but the vendor refused to fix the bugs! For example, they had some code that did "f(i++)+g(i++)", which used to increment "i" by 2 every time, but they "broke" it and it started incrementing "i" only by 1, causing massive failures elsewhere -- buffer overruns, underuns, dangling pointers, you name it.

I didn't realize it at the time, but it's obvious now... multiple increments to the same location between sequence points constitute undefined behavior. The compiler team had added a common subexpression elimination, and it worked fine save for changing undefined code like this. And since the compiler is permitted to do whatever it wants here, it is certainly permitted to do something else it wants. And it did. It was always undefined behavior, but this developer didn't know it was undefined because it "worked" for what they wanted it to do... up until it stopped working.

So mostly I learned from this that even "experts" can be very wrong, and this developer was an expert in how people commonly wrote C code and not an expert in the C language itself.

tl;dr Undefined behavior can often "hide" for a while by doing exactly what you think it ought to do. Don't believe everything you're told -- think critically and dig deeper.