Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use While(1) in C#?

Tags:

c#

I know this has probably already been answered somewhere, I just can't find it. Why doesn't C# allow me to use while(1)? I know that 'There is no conversion between the bool type and other types' in C# but why? What are the reasons for this, when in c++ it's perfectly acceptable.

like image 501
anon Avatar asked Jul 24 '10 15:07

anon


1 Answers

It is to keep programmers from accidentally doing something they did not want to do.

Consider this common pitfall in C/C++:

int x = getValue();
if (x = 10) {
  // do something
}

This will compile and run, but produce unexpected results (the programmer likely meant to check that x equals 10, not assign to x -- otherwise, why would he need the test at all? It will always evaluate to true).

By forcing conditionals to be of boolean type, you avoid this issue.

like image 56
danben Avatar answered Oct 05 '22 15:10

danben