views:

325

answers:

4

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;
+3  A: 

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

dirkgently
That would not be a really nice daemon since while(1); technically doesn't put that thread to sleep and as very processor intensive. Better would be something like while(1) Sleep(5000); or something similar
Toad
That is a side-issue. At any rate, `while (1)` is anything but _dead code_ -- which was my point. And yes, I think I saw some code analysis tool report it as such -- an infinite loop.
dirkgently
But `while(1);` *is* essentially dead code -- it doesn't do anything useful except block the CPU. Much better to have something like: char exiting=0; while(!exiting) { exiting = process_event(); }
TMN
@TMN: I was talking about the generic case, when you do something inside the loop. I see where the comments come from now :-)
dirkgently
+6  A: 

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.

Timbo
+5  A: 

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!

Dan
I was waiting for someone to mention the Halting problem!! :) +1 for that.
batbrat
The first rule of the halting problem is that nobody mentions the halting problem.
Martin Beckett
While it's impossible for arbitrary programs, it's certainly possible for sufficiently trivial loops such as this one, though.
fennec
+4  A: 

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

caf
Thanks! Can you find some more links to such threads in usenet?
osgx
I'm sure you can use google just as well as I can.
caf