4 ms·
Thats not lazy evaluation so much as "this loop literally doesn't do anything"
by octo_t 13y ago
Thats not lazy evaluation so much as "this loop literally doesn't do anything"
- jerf 13y agoIt does do something. It loops forever. The optimized version does nothing. This is a major difference in performance. No sarcasm; this sort of thing can manifest in real code, and when it does it will generally be a great deal more complicated. "Bugs that only appear at certain optimization levels" are not the absolute worst types of bugs to debug, but they're certainly up there on the great Hierarchy of Sucky Bugs.
- garenp 13y agoIf an empty loop does no computation (i.e. has no observable side-effects), then arguably there should be no difference in observable behavior from the program. Of course, sometimes we "know" something that the compiler can't "see", and so must indicate as such in our code (e.g. using something stored inside the loop, adding volatile, ...). Probably the most common (or at least my favorite) example of DCE leading to a surprise, is when embedded programmers use so-called "delay loops" which can be eliminated by the compiler because it too is "empty" (the loop produces nothing that is used outside of the loop).
- scott_s 13y agoAn empty loop that has no computation but loops forever has an observable side-effect.
- nhaehnle 13y agoGo read page 14 of this: http://isocpp.org/files/papers/N3690.pdf http://isocpp.org/files/papers/N3690.pdf ;-) Essentially, C++ does not consider looping forever to be a side effect. You have to do something like writing to a volatile variable to ensure that the compiler does what you want.
- gizmo686 13y agoThe relevent part of page 14: "The implementation may assume that any thread will eventually do one of the following: — terminate, — make a call to a library I/O function, — access or modify a volatile object, or — perform a synchronization operation or an atomic operation. [ Note: This is intended to allow compiler transformations such as removal of empty loops, even when termination cannot be proven. — end note ]"
- demallien 13y agoYup, when I was young and naive, I would not initialize structs to zero explicitly when they were allocated on the stack. One day I had a bug that only appeared in production code, which is bad, as I was working on an embedded system, so production code = no debugger. Took me a while to figure that one out! The compiler writer that thought that it would be a good idea to zero out stack variables, but only if the code was -O0 deserves to be taken out back and shot!