Why can't I use an integer as a condition for a while loop in C#? [closed]

泄露秘密 提交于 2020-01-22 03:41:22

问题


I am getting an error using while loop in this manner, and I don't understand why:

int count = 5;
while(count--)    //here showing an error
{
    Console.WriteLine("Number : {0}", count);
}

However, in C, the code works properly. I am little bit confused about why I am getting this error. Can anyone explain why?


回答1:


C# does not define an implicit conversion from int to bool. The while loop condition must be a bool.

You should use while(count-- != 0) instead.

In C# you have a bool type which accepts True or False as value. In C everything other than 0 is true and 0 indicates null. So you can have if (1) in C but 1 is not a logical expression in C#.




回答2:


C# does not allow implicit casts from int to bool(ean). You should explicitly do that:

int count = 5;
while(count-- != 0)
{
    Console.WriteLine("Number : {0}", count);
}



回答3:


While loop is using bool values to determine if continue loop or exit loop

In Your example count value is int and this cause error/

Simple refactorig is this:

            int count = 5;

            while (count != 0 )
            {
                count--;
                Console.WriteLine("Number : {0}", count);
            }

Now when count value will by 0 it will break loop




回答4:


This will fix it!

while (count-- >= 0)//here showing an error
            {
                Console.WriteLine("Number : {0}", count);
            }


来源:https://stackoverflow.com/questions/35816069/why-cant-i-use-an-integer-as-a-condition-for-a-while-loop-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!