c# - assigning value to bool inside while loop -


i know newbie c# question implementing small program following:

namespace consoleapplication {     class program { static void main(string[] args)         {     bool isrun = false;                 int number = 0;                 while (isrun = (true) && number < 3)                 {                     ++number;                     console.writeline("number = {0}", number.tostring());                     console.writeline();                 }                 console.writeline(isrun.tostring());                 console.readline(); } } } 

at end of while loop, have expected bool value true, is printed false. why that? different c++ have done , same thing in c# giving me false

while(number<3) { = true; } if(is){ cout<<true; } 

the reason you're seeing behavior due operator precedence involved. here && binds more = code in loop bound following

while (isrun = (true && number < 3)) {   ... } 

once number > 3 && expression false , assigned isrun value , simultaneously terminates loop. hence once loop exits see isrun false

to behavior looking need manually correct precedence parens.

while ((isrun = (true)) && number < 3) {   ... } 

note: in general, @servey pointed out, assignment of locals expressions inside loop predicate considered bad practice. many c# users surprised code compiles @ because they've been conditioned use == in loops.

it's more idiomatic set isrun true on first line of loop pattern.

while (number < 3) {   isrun = true;   ... } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -