Are compilers allowed to eliminate infinite loops?

Viewed 8538

Can optimizing compiler delete infinite loops, which does not changes any data, like

while(1) 
  /* noop */;

From analyzing a data flow graph compiler can derive, that such loop is "dead code" without any side effects.

Is deleting of infinite loops prohibited by C90/C99 standards?

Does C90 or C99 standards permit compiler to deleting such loops?

Upd: "Microsoft C version 6.0 did essentially this optimization.", see link by caf.

label: goto label;
return 0;

will be transformed to

return 0;
6 Answers

There's no way to detect infinite loops universally: see the Halting Problem. So the best any compiler could do is take a decent guess - for example the obvious case mentioned in the OP.

But why would this be desirable? I could see emitting a warning and still allowing the behavior, but to remove the loop is not an "optimization" - it changes the behavior of the program!

The loop is not dead code, it is basically preventing the program from ever reaching whatever comes after it. This is not what would happen if the loop was removed, so the compiler can not remove the loop.

It might replace it with a platform-dependent idle-instruction to signal the processor that the thread is not going to do anything any more.

What the compiler can do is remove any code that comes after the loop, because it is unreachable and will never be executed.

This has been discussed many times before on comp.lang.c (eg. here) without, as far as I know, any consensus outcome.

They are a necessity when writing daemons. Why'd you want to call them dead code?

Related