Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between for(;;) and while (true) in C#?

Tags:

c#

Syntactically I see that they loop indefinitely until a break statement is reached, but are they compiled to the same thing? Is the for slightly faster because it doesn't have a condition to check? Aside from code readability, is there even a difference?

like image 996
Corey Ogburn Avatar asked Jul 27 '10 20:07

Corey Ogburn


People also ask

What does while true mean in C?

while loops use only Boolean expression and when it is true. So when it gets true it'll execute until it gets false. while(false) means the condition is false which will end the loop. while(True) means the condition is True which will continue the loop.

What is the difference between while and while true?

The while loop in python runs until the "while" condition is satisfied. The "while true" loop in python runs without any conditions until the break statement executes inside the loop.

What is the difference between for and while 1?

no functional difference at all, just a matter of taste.

What is while True used for?

In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.


2 Answers

Given this input:

private static void ForLoop()
{
    int n = 0;
    for (; ; )
    {
        Console.WriteLine(n++);
    }
}

private static void WhileLoop()
{
    int n = 0;
    while (true)
    {
        Console.WriteLine(n++);
    }
}

...you get this output:

.method private hidebysig static void  ForLoop() cil managed
{
  // Code size       14 (0xe)
  .maxstack  3
  .locals init ([0] int32 n)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  dup
  IL_0004:  ldc.i4.1
  IL_0005:  add
  IL_0006:  stloc.0
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000c:  br.s       IL_0002
} // end of method Program::ForLoop


.method private hidebysig static void  WhileLoop() cil managed
{
  // Code size       14 (0xe)
  .maxstack  3
  .locals init ([0] int32 n)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  dup
  IL_0004:  ldc.i4.1
  IL_0005:  add
  IL_0006:  stloc.0
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000c:  br.s       IL_0002
} // end of method Program::WhileLoop

Remarkably similar, I would say (identical, even).

like image 126
Fredrik Mörk Avatar answered Sep 18 '22 16:09

Fredrik Mörk


In modern compilers, absolutely nothing.

Historically, however, for(;;) was implemented as a single jump, while while(true) also had a check for true.

I prefer while(true), since it makes it more clear what I am doing.

like image 45
Mike Caron Avatar answered Sep 22 '22 16:09

Mike Caron