Reputation:
So, I left the for loop totally empty and did the following:
using System;
public class Program
{
public static void Main()
{
int i = 0;
for(;;){
if(i < 5){
Console.WriteLine(i);
i++;
}
else
{
break;
}
}
}
}
I knew that it would work, but I don't know how why it works. Could someone explain to me why this works and how the for loop understands that syntax?
I'm new to C# so take it easy on me.
Upvotes: 0
Views: 84
Reputation: 96
Each part of a for loop (;;) contains a statement. As you know first section for initialization then condition checking and finally the increment/decrement section.
If you leave them empty then the loop will iterate for infinite times like it happens for while(true).
Upvotes: 2
Reputation: 368
There is no difference between for(;;)
and while(true)
. You can use whatever you like.
Upvotes: 2
Reputation: 77876
A for(...)
loop with no initialization, condition, iteration step for(;;)
is an Infinite Loop which runs forever unless an explicit exit condition given
Upvotes: 1