For example, when we have three conditions in a while loop:
while (true || false || false)
{
//Do something...
}
I am talking of conditions separated by the ||
operator only. I believe when we encounter this while loop, as soon as the first true
statement is encountered, we skip the other conditions.
I know this is true if we have two conditions in the while loop separated by the ||
operator. But, if we have more than two conditions, do we skip the further conditions, further down the while loop - when the first true
condition is encountered?
This is because, the while
loop does not know, how many more conditions we have in the while
loop. And would go further.
For two conditions, we would skip evaluating the conditions further, when the first true
condition is encountered. But, when there are multiple conditions, separated by the ||
operator, would we still skip evaluating the other conditions, when the first true
condition is encountered?
It would be helpful if you can tell me, what happens at Compile time and Run time, in this case (when we have multiple conditions in the while
loop, separated by the ||
operator).
How do we know when to skip the further conditions?
Thank you for all your help!
If you literally have
while(true || false || false)
, or equivalent compile-time constants that the compiler can deduce at compile time, then this will compile to the same code aswhile(true)
, becausetrue || false || false
can be calculated at compile-time to be true. The compiler would also omit any code following thewhile
loop, unless it could determine you're using abreak;
or some other construct that would allow thewhile
loop to be exited.Likewise, if you had something like
while(true && false)
, the entirewhile
loop would be omitted from the compile-time code, because it would be deemed unreachable.If you are using expressions with variables whose values cannot be determined at compile-time, such as
while(node == null || node.Value != value)
, then at run-time the first expression (node == null
) will be evaluated, and if it's found to betrue
then the remainder of the expression will be short-circuited as specified by the docs that Guru Stron noted in his answer. (In the example I just gave, that would preventnode.Value
from throwing a null reference exception.)