Re: Optimizing away an endless loop
On Aug 30, 12:46 pm, "Johannes Schaub (litb)" <schaub-johan...@web.de>
wrote:
Johannes Schaub (litb) wrote:
Hello all, i need some advice. Is it actually true that a
C++0x implementation can print "Hello" for the following
snippet?
#include <iostream>
int main() {
while(1)
/* do nothing */;
std::cout << "Hello" << std::endl;
}
C++0x seems to allow an implementation to assume that the
above infinite loop terminates, which to me seems to mean
that it can entirely ignore that this loop never wants to
stop.
Why is this the way it is? Doesn't it harm a lot of programs?
Also, here is another thought I have:
int a = -1;
for(;;) {
if(a > 100) break;
a++;
}
int *p = new int[a];
This loop *does* terminate, does not access volatile objects,
does not call i/o functions, sync or atomic operations. Yet,
the implementation may assume it terminates. If an
implementation is thus free of optimizating it away, would it
not make this program UB?
No. In fact, an implementation is free to optimize it away; a
good optimizing compiler will produce the same code here as if
you'd just written:
int *p = new int[101];
I don't see how this example is different from the print example above.
The loop terminates.
Both examples have code after the loop that depend on the
loop. Yet the rationale that the UB is only risen because the
loop would not terminate is disproven by this. Can someone
show please what paragraph makes these both examples
different?
It's not in the standard; it's in the proposed draft C++0x:
=A76.5/5 in N3000 (which isn't the very latest, but is relatively
recent):
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. =97end note ]
The wording is pretty vague: there's no mention of undefined
behavior, for example. I'd say that there is no undefined
behavior, but that the standard allows alternate semantics
(which may result in undefined behavior if you haven't provided
for them).
--
James Kanze