Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is program termination of a C++ program observable behavior?

Tags:

c++

c++11

I could have also phrased this as What constitutes observable behavior?

The C++ Standard talks a lot about observable behavior, but I am not really sure if program termination is part of observable behavior.

That is, given a program such as:

int main() {
  for(;;) {}
  return 0;
}

is a conforming implementation allowed to ever terminate this program?

like image 356
Martin Ba Avatar asked Nov 18 '10 10:11

Martin Ba


1 Answers

Yes it is legal for the compile to generate an empty main body for the above code (thus terminating almost immediately).

The C++0x FCD says 6.5 says (pay special attention to the note):

A loop that, outside of the for-init-statement in the case of a for statement,
* makes no calls to library I/O functions, and
* does not access or modify volatile objects, and
* performs no synchronization operations (1.10) or atomic operations (Clause 29)

may be assumed by the implementation to terminate. [ Note: This is intended to allow compiler transformations, such as removal of empty loops, even when termination cannot be proven. — end note ]

So the compiler can assume that your for loop will terminate and since the body is empty it can optimize it away altogether.


The quotation from the draft was copied from this question and verified against my copy.

like image 190
Motti Avatar answered Sep 20 '22 11:09

Motti