Recently while going through a c++ tutorial I encountered a for loop that looked like this:
for (;;){
//Do stuff
}
Is this an infinite loop? Why would I use this rather that while(1)
?
Recently while going through a c++ tutorial I encountered a for loop that looked like this:
for (;;){
//Do stuff
}
Is this an infinite loop? Why would I use this rather that while(1)
?
Yes, it's infinite. Traditionally, compilers would generate a warning when you use while(1)
, but not when you use for(;;)
. I don't know if this is still the case.
It's an infinite loop. More precisely, if the condition in a for
is empty, it is considered true
. As for while ( true )
vs. for (;;)
: historically for (;;)
was the idiomatic form (used by Kernighan and Ritchie), perhaps partially because early C didn't have booleans. Using while ( 1 )
wouldn't pass code review anywhere I've worked. With booleans, while ( true )
definitely seems more intuitive than for (;;)
, but while ( 1 )
is confusing. But in pre-boolean times, everyone had a #define
for true
or TRUE
or some such, so it's a weak argument. In the end, if you're an old C programmer, like me, who originally learned from Kernighan and Ritchie, you just instinctively use for (;;)
. Otherwise... it probably depends on where and from whom you learned C++.
Of course, when at work, you follow the house conventions, what ever they are.
Is this an infinite loop?
Yes.
Why would I use this rather that
while(1)
?
Because of (bad, IMO) taste. By the way, I would go for while (true)
, if I really had to create an infinite loop.