By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
425,992 Members | 934 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 425,992 IT Pros & Developers. It's quick & easy.

Does "while(ifs)" works the same way "while(!eof.ifs())"?

P: 1
Hello there.

Today, I was developing a college work software and then I saw thoe 2 types of while. My teacher asked me how does the "while(ifs)" (considering my ifstream was ifs) (that was the one I was using) should work, I didn't know what to answer.

Both of em works to check the enf of the file in, right? Whats the advantage in using while(ifs)? How does the "ifs" works.

Thanks in the advance. :)
Jun 6 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
A while loop continues as long as the condition is true.

True is not false. False is 0. Therefore, any non-zero value is true.

Functions that return a value become an instance of their return type. That is,

Expand|Select|Wrap|Line Numbers
  1. int MyFunction();
  2.  
  3. int result = MyFunction();   //return used to intialize result
  4.  
  5.  
So, by calling MyFunction you can use result in your while loop:

Expand|Select|Wrap|Line Numbers
  1. while(result != 0)
  2. {
  3.  
  4. }
  5.  
and you will stay in the loop as long as result is not zero.

Alternatively, you could code this loop to be:

Expand|Select|Wrap|Line Numbers
  1. while(result)
  2. {
  3.  
  4. }
  5.  
because result is true if it is not zero.

Alternatively, you can skip using result since it's not required to be an actual variable and recode the while loop to be:

Expand|Select|Wrap|Line Numbers
  1. while (MyFunction())
  2. {
  3.  
  4. }
  5.  
Nothing new happens here. MyFunction() is still called. But the return is put into a temporary int created by the compiler. That int is then tested by the while loop.

In summary, there are not different kinds of while loops. There are different ways of stating whether an expression is true. The loop merely evaluates the expression.
Jun 6 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.