Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of 1 == 1 or true in While loops

Tags:

c#

I've recently come across a while statement that uses 1 == 1 instead of true.

Example:

while (1 == 1) 
{
   // Do something
}

Instead of:

while (true)
{
   // Do something
}

They both appear to be correct and generate the same result but I wanted to know (apart from why a developer would use 1 == 1 instead of true - style/habit aside) what impact this has from a compiler perspective, is there a greater overhead in using the comparison operator instead of true?

like image 927
Steve Avatar asked Sep 24 '15 15:09

Steve


People also ask

What is the while 1 loop used for?

The while(1) or while(any non-zero value) is used for infinite loop. There is no condition for while. As 1 or any non-zero value is present, then the condition is always true. So what are present inside the loop that will be executed forever.

Is true in while loop?

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.

What is a while true loop called?

while True: ... means infinite loop. The while statement is often used of a finite loop.

What is the use of while true in C++?

C++ while Loop If the condition evaluates to true , the code inside the while loop is executed. The condition is evaluated again. This process continues until the condition is false .


1 Answers

There is no difference. The compiler will optimize them to the same IL.

1 == 1

IL_0000:  nop         
IL_0001:  br.s        IL_0005
IL_0003:  nop         
IL_0004:  nop         
IL_0005:  ldc.i4.1    
IL_0006:  stloc.0     // CS$4$0000
IL_0007:  br.s        IL_0003

true

IL_0000:  nop         
IL_0001:  br.s        IL_0005
IL_0003:  nop         
IL_0004:  nop         
IL_0005:  ldc.i4.1    
IL_0006:  stloc.0     // CS$4$0000
IL_0007:  br.s        IL_0003

Any choice of one or the other is purely stylistic preference on the part of the developer.

like image 200
David L Avatar answered Sep 23 '22 12:09

David L