HN2new | past | comments | ask | show | jobs | submitlogin

Because while(1) still has a condition that is checked on every loop iteration when optimizations are disabled. for(;;) can be read as "forever".


FWIW, GCC and Perl generate the same code for both.

http://stackoverflow.com/questions/885908/while-1-vs-for-is-...


Interesting. Looks like they'd be the same performance wise, since

for (;;);

is the same as

{ while (true) { ; ; } }

I originally asked this question cos it's used this way in first C program in the link. Bit of a tangent though :P


That issue disappeared before the 1980's. Check your compiler.


Any compiler/interpreter worth its salt will notice when an expression being tested in a conditional is constant and generate code that doesn't actually test it at run time. for (;;) is arguably more "idiomatic" C, though.


for(;;), being equivalent to for(;1;), also has that condition that has to be checked. So, it all boils down to how compilers treat the two.

And to add oil to the fire, here are some even 'better' ways to do this:

  do {
    ...
  } while(1);
At least that fits the common macro pattern "do{...}while(0)" (http://stackoverflow.com/questions/257418/do-while-0-what-is...).

Of course, all of these are inferior to:

  considered:
    ...
  goto considered;


I do doubt that even for a for(;;), a jmp (x86) is use instead of a conditional jump like jz.


Compilers are smart! For common things like this, they will easily optimise away any conditional jumps.


It is, you can easily check that yourself. for(;;) compiles to exactly one jmp in GCC (tested with gcc 4.7.0)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: