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.
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.
What are the reasons for this, when in c++ it's perfectly acceptable.
Because C# isn't C++. The languages share a similar syntax but they're distinct. C# isn't a successor to C++, it's an entirely new language.
I know that 'There is no conversion between the bool type and other types' in c# but why?
Why should there be? There's no logical conversion I can think of between an integer and a boolean value.
Why doesn't c# allow me to use while(1)?
Is there really something that wrong about using while(true)
? =) On a slightly more serious note, while(...)
is basically saying, "whilst the condition described inside the brackets evaluates to true, perform the following action(s)". There's really no logical way for the C# compiler to convert 1 to either true or false, hence it doesn't let you use it.
You answered your own question: "There is no conversion between the bool type and other types." The C# compiler does this to help enforce correctness and avoid common mistakes, like putting an assignment expression inside a while that always evaluates to true (using one equals sign instead of two).
if 0
is false
then which one should be true, 1
or -1
? The first is what is assumed to be correct, but the second actully has all its bits set and is equal to ~0
(not false).
It forces a boolean evaluation. Similarly, in order to protect assignment in an if
statement's condition from providing a boolean value.
if (x = y)
this assignment will be evaluated in the sense that "did x get assigned y" - as opposed to "is x equal to y" - not what the programmer likely intended.
If you want an infinitely looping condition us while(true)
; if you want to loop while a variable is a specific value, set a Bool to true prior to the loop:
Bool valid = (x == 42);
while(valid){//...
精彩评论