DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   while loop issue (http://www.daniweb.com/forums/thread167747.html)

winrawr Jan 11th, 2009 4:16 pm
while loop issue
 
Can I do this?

while(variable=functionCall()!=0){

    /* ... */

}

the function I'm calling, is returning a 3, but the variable in the while loop is equal to 1...
I'm not sure what is happening in this statement, Originally I thought it would just always evaluate to true and loop forever since, variable would be successfully set to functionCall()'s return value, therefore evaluating to 1, and 1 does not equal zero, so that too would evaluate to 1 (true) and loop forever... but it sets variable to 1 and then exits the while loop--what's going on?

functionCall() gets input from the user so I can only call it once really, I was going for
while(functionCall()!=0){ }
, but then I wouldn't be able to check the return value within the loop. I could do something else but I wanted to use this method, so I'm just wondering what it's actually doing.

da penguin Jan 11th, 2009 4:25 pm
Re: while loop issue
 
Quote:

variable would be successfully set to functionCall()'s return value
no way, variable is set to true, because functionCall()!=0 is true. in this case true means 1

da penguin Jan 11th, 2009 4:30 pm
Re: while loop issue
 
p.s. And yes, this does loop forever if functionCall() really returns 3

Alibeg Jan 11th, 2009 4:33 pm
Re: while loop issue
 
you should try something like this:
while ((variable = functionCall())!=0)
...
because it seems to me that variable is given the value of evaluation: functionCall()!=0, so you just need to use one more pair of brackets...
I hope this helps :D

winrawr Jan 11th, 2009 4:54 pm
Re: while loop issue
 
@da penguin, oh right, I forgot about right->left order, and you're right it was looping forever--there are two loops working together and I was mistaken with which loop I was in at what time.

@Alibeg, it worked great, thank you!


All times are GMT -4. The time now is 9:44 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC