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

前端 未结 8 1362
生来不讨喜
生来不讨喜 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 10:57

    The relevant issue is that the compiler is allowed to reorder code whose side effects do not conflict. The surprising order of execution could occur even if the compiler produced non-terminating machine code for the infinite loop.

    I believe this is the right approach. The language spec defines ways to enforce order of execution. If you want an infinite loop that cannot be reordered around, write this:

    volatile int dummy_side_effect;
    
    while (1) {
        dummy_side_effect = 0;
    }
    
    printf("Never prints.\n");
    

提交回复
热议问题