Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this Loop Working Infinitely

Tags:

c#

loops

This is a simple while loop in C# but it is working infinitely.

int count = 1;
while (count < 10)
{
    count = count++;
}

Why is this so?


2 Answers

The expression count++ returns the original value of count, then increments the value afterwards.

So you are overwriting count with the same value every time. Just do this:

count++;

For the curious, here's a link to Eric Lippert's article which distinguishes between operator precedence and the order of evaluation -- it's an interesting read:

http://blogs.msdn.com/b/ericlippert/archive/2009/08/10/precedence-vs-order-redux.aspx

like image 160
JohnD Avatar answered Sep 14 '25 01:09

JohnD


This will loop infinitely.

There are two types of incrementing a variable:

Here count++ and ++count both are different if you have used ++count it will work.

Here count = count++ means count variable will be incremented by one then assigns the earlier value 1 to the count variable itself so count remains unchanged.

like image 26
Nighil Avatar answered Sep 14 '25 02:09

Nighil