Use of "for (;;)" in a C# application?
Solution 1
Yes, that is an infinite loop. It's an ordinary for loop with no condition expression.
From the documentation for for
:
All of the expressions of the for statement are optional; for example, the following statement is used to write an infinite loop:
for (; ; ) { // ... }
Solution 2
I just want to clarify :
;;
is not a special operator or something - it's a regular for loop.
regular for loop looks like that:
for (do_before_loop**;** finish_loop_when_this_condition_is_false**;** do_after_each_iteration);
if you leave all 3 parts empty you get ;;
- and since you don't have an exit condition - this is an infinite loop.
Solution 3
Normally You write Your loop like this:
for (int i = 0; i < 10; i++)
{
// The rest of the application's code
}
Now, when You want Your loop to be infinite one, You just have to remove the "int i = 0", condition "i < 10", and incrementation "i++". If You do this, then in a for statement You will see only ";;"
for (;;)
{
// The rest of the application's code
}
Solution 4
Yes, it's an infinite loop.
All parameters in the for
statement are optional, and the condition defaults to true
, so it's the same as:
for (;true;)
or:
while (true)
Solution 5
This is the same as for (<initial>; <condition>; <increment>)
, you're simply leaving out initial, condition and increment. In this case, condition will always be considered true.
Related videos on Youtube
JuniorDeveloper1208
Updated on July 09, 2022Comments
-
JuniorDeveloper1208 almost 2 years
I've been looking through some sample source code for an application I use and I came across this line:
for (;;) { // The rest of the application's code }
It looks like this is to create an infinite loop, but I'm not familiar with ";;" and it's very hard to Google unfortunately.
-
JuniorDeveloper1208 over 13 yearsThanks, is it common practice (IE: Not a hack?)
-
Richard J. Ross III over 13 yearsOne thing to note is that you should have a condition on which to break from it, to have a non-ending loop is usually bad... @toleero, it is a matter of style. I like to use the
while (true) {}
loop instead, it is more straight to the point IMO, but either one is standard practice. -
Oded over 13 years@t84 - Fairly common, though many use
while(true){}
for readability. -
Guffa over 13 years@toleero: It's not a hack, but it has a slight smell to it... You should try to put the condition in the loop statement if practically possible, instead of breaking out of the loop.
-
T.E.D. over 13 years@toleero - I don't know about C#, but in C and C++, that is the cannocical way to do an infinite loop.
-
Malcolm Tucker over 7 yearsTechnically, for the loop to be infinite, all you have to remove is the condition (i<10).