In the spirit of questions like Do your loops test at the top or bottom?:
Which style do you use for an infinite loop, and why?
- while (true) { }
- do { } while (true);
- for (;;) { }
- label: ... goto label;
In the spirit of questions like Do your loops test at the top or bottom?:
Which style do you use for an infinite loop, and why?
I usually use
for(;;) { }
which I always think of as "for-ever".Some languages offer a
repeat { }
construct which will natively loop forever. I find thefor(;;) { }
construct visually the most similar to this because it is so different from the normalfor()
construct. This is an important attribute for an infinite loop thatwhile(1) { }
doesn't really have.I now prefer the "
for (;;)
" idiom because it seems to 'stick out' more. I used to use the "while (true)
" idiom because I thought it expressed intent better, but I've switched over because I think the "for (;;)
" idiom is well known enough to adequately express intent as well as I believe it's better by being more visible.Kind of like how Stroustrup made the new casts in C++ purposefully ugly - so they stick out.
offtopic: if you think about what you are trying to express, you usually won't need an infinite loop.
Infinite tail-recursion ;)
It's somewhat compiler-dependant...
PLEASE DO COME FROM (23)