简体   繁体   中英

How does this condition work in this while-loop?

while ((len = var1) != -1)
{

   // do something

}

Which is being compared to -1? len or var1 ?

This is Java EE.

The return value of an assignment var = val is the assigned value val . So what happens here is that len is assigned with the value of var1 , and if (after the assignment) its value is not equal to -1 , the loop is entered.

The most technical answer, I suppose, would be that you are comparing len to -1, but that doesn't really capture what's going on.

What's really going on is that, for every check, you are setting len to var1 , and then comparing len . So, if I'm not mistaken, even though the computer is actually comparing len , it will always have just been replaced with the value from var1 , so the code will be functionally identical to

len = var1;
while(var1 != -1)
{ 
    len = var1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM