Aug 20, 2019

[C++][Go] Optimizing away a “while(1);”

#include <iostream>

int main() {
  while(1) 
    ;
  std::cout << "Hello" << std::endl;
}
or this:
endless:
  goto endless;


ISO Reference:
https://timsong-cpp.github.io/cppwp/intro.progress#1

The implementation may assume that any thread will eventually do one of the following:
  • terminate, 
  • make a call to a library I/O function, 
  • perform an access through a volatile glvalue, 
  • or perform a synchronization operation or an atomic operation.
In C++, modifying a global (or local) variable is not a side-effecting operation. Only actions in the list above count as defined behavior thus compiler will not end an infinite loop. (in C++17 this isn't true anymore, compiler will honor an infinite loop no matter how.)

More Reference:
https://blog.regehr.org/archives/161


GO:
Go however has this issue of optimizing away the infinite loop in go 1.8:
https://github.com/golang/go/issues/19182

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.