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?
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.
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.
while True: ... means infinite loop. The while statement is often used of a finite loop.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With