Is program termination of a C++ program observable behavior?
I could have also phrased this as What constitutes observable behavior?开发者_StackOverflow
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?
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.
Is program termination of a C++ program observable behavior?
Yes, finishing the exectution of a program is an observable behavior since the program return an error code.
- 0 when no error
- not 0 value when not successful
Normal terminal does not show this states which is why you do not "see" it.
Is a conforming implementation allowed to ever terminate this program?
The program can not exit, but depending on the different OS, it can be terminated by for example signal, interruption ...
--EDIT--
The answer of the second question is a little bit erroneous
As Martin and Motti explained in a previous answer :
The discussion is based on allowed optimizations that the compiler can safely perform. Since the removal of a dead loop is explicitly allowed the compiler is free to junk the above loop thus allowing the program to terminate
精彩评论