Run a while loop with the cout statement

So, I have a general question about the do / while . I am learning C ++ and I know that you can write something like this:

 do{ .... } while(a<10 && cout<<"message"); 

The thing is, I know that this is possible in C ++, but are we really doing this? I mean, what is the " cout " thing inside?

+5
source share
3 answers

The fact is that some people do this (i.e., perform a function as part of an assessment of a condition). This makes sense in a shell script, but if you are not using a shell script, it is sometimes unclear what value is returned for some functions. I could not tell you that the message cout <"message" is being returned from hand to hand, but I know that if you write it inside the body of the loop, it will do what I want and it will "throw out" the return value if I do not use it.

To write cleaner code that others, including your future self, can understand, I would only evaluate conditions that explicitly return true / false, rather than “0 / not-0” or “0/1,” which may differ in different languages.

Bottom line: let the compiler make things more efficient for you and the code for other people, not the compiler.

+3
source

Your while loop is equivalent

 do { ... cout << "message"; while(a < 10 && cout); 

because cout << ... returns cout again. Then the question arises: what does it mean to write statements like

 while( cout ); 

or

 if (cout) ... 

The cout object has a conversion to boolean , which is used here. This implementation checks !fail() , therefore

 if (cout) ... 

equivalently

 if (!cout.fail()) ... 

and

 do { ... } while(cout); 

equivalently

 do { ... } while(!cout.fail()); 

Finally, fail returns true if the thread could not complete the output .

+7
source

If you want to make a conclusion after testing the condition, you need to either do it or add one more test of the condition inside the loop, and support both of them, which is the expectation of an error.

 do { if (a < 10) cout << "message"; } while (a < 10); 

It is rare to see cout << on its own in any condition, although, as you usually can assume, it will succeed if your machine is not lit.

On the other hand, the extraction operator >> usually included in the condition:

 while (cin >> x) 

is idiomatic C ++.

0
source

All Articles