N.Ba
N.Ba

Reputation: 93

Do while loop with a cout statement

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

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

The point is, that i know this is possible in c++, but do we really do that? I mean, the "cout" thing inside the while?

Upvotes: 5

Views: 4384

Answers (3)

molbdnilo
molbdnilo

Reputation: 66431

If you want to perform the output after testing the condition, you would need to either do that or add another condition test inside the loop and maintain both of them, which is a bug waiting to happen.

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

It's rare to see cout << by itself in any condition though, as you can usually assume that it will succeed unless your machine is on fire.

On the other hand the extraction operator, >>, usually belongs inside a condition;

while (cin >> x)

is idiomatic C++.

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

The fact is some people do this (i.e. run a function as part of the condition evaluation). It makes sense in a shell script, but if you're not using a shell script, it's sometimes not clear what the return value is for some functions. I couldn't tell you what cout<<"message" returns offhand, but I do know that if you write it inside the loop body, it would do what I want, and it would 'throw away' the return value if I don't use it.

To write cleaner code that others including your future-self can understand, I would only evaluate conditions which obviously return true/false as opposed to "0/not-0", or "0/1" which may different in different languages.

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

Upvotes: 3

MicroVirus
MicroVirus

Reputation: 5477

Your while loop is equivalent to

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

because cout << ... returns cout again. Then, the question is, 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. It's implementation is checking !fail(), so

if (cout) ...

is equivalent to

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

and

do { ... }
while(cout);

is equivalent to

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

Finally, fail returns true if the stream failed to produce output.

Upvotes: 8

Related Questions