Optimizing away a “while(1);” in C++0x

前端 未结 8 1286
生来不讨喜
生来不讨喜 2020-11-22 10:37

Updated, see below!

I have heard and read that C++0x allows an compiler to print \"Hello\" for the following snippet

#include 

        
8条回答
  •  情深已故
    2020-11-22 11:11

    I think the correct interpretation is the one from your edit: empty infinite loops are undefined behavior.

    I wouldn't say it's particularly intuitive behavior, but this interpretation makes more sense than the alternative one, that the compiler is arbitrarily allowed to ignore infinite loops without invoking UB.

    If infinite loops are UB, it just means that non-terminating programs aren't considered meaningful: according to C++0x, they have no semantics.

    That does make a certain amount of sense too. They are a special case, where a number of side effects just no longer occur (for example, nothing is ever returned from main), and a number of compiler optimizations are hampered by having to preserve infinite loops. For example, moving computations across the loop is perfectly valid if the loop has no side effects, because eventually, the computation will be performed in any case. But if the loop never terminates, we can't safely rearrange code across it, because we might just be changing which operations actually get executed before the program hangs. Unless we treat a hanging program as UB, that is.

提交回复
热议问题