Is "for(;;)" faster than "while (true)"? If not, why do people use it?
for (;;) {
//Something to be done repeatedly
}
I have seen this sort of thing used a lot, but I think it is rather strange...
Wouldn't it be much clearer to say while(true)
, or something along those lines?
I'm guessing that (as is the reason for many-a-programmer to resort to cryptic code) this is a tiny margin faster?
Why, and is it really worth it? If so, why not just define it this way:
#define while(true) for(;;)
See also: Which is faster: while(1) or while(2)?
- It's not faster.
- If you really care, compile with assembler output for your platform and look to see.
- It doesn't matter. This never matters. Write your infinite loops however you like.
I prefer for(;;)
for two reasons.
One is that some compilers produce warnings on while(true)
(something like "loop condition is constant"). Avoiding warnings is always a good thing to do.
Another is that I think for(;;)
is clearer and more telling.
I want an infinite loop. It literally has no condition, it depends on nothing. I just want it to continue forever, until I do something to break out of it.
Whereas with while(true)
, well, what's true got to do with anything? I'm not interested in looping until true becomes false, which is what this form literally says (loop while true is true). I just want to loop.
And no, there is absolutely no performance difference.
Personally I use for (;;)
because there aren't any numbers in it, it's just a keyword. I prefer it to while (true)
, while (1)
, while (42)
, while (!0)
etc etc.
Because of Dennis Ritchie
I started using
for (;;)
because that's the way Dennis Ritchie does it in K&R, and when learning a new language I always try to imitate the smart guys.This is idiomatic C/C++. It's probably better in the long run to get used to it if you plan on doing much in the C/C++ space.
Your
#define
won't work, since the thing being #define'd has to look like a C identifier.All modern compilers will generate the same code for the two constructs.