Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do while loop with a cout statement

Tags:

c++

do-while

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?

like image 682
N.Ba Avatar asked Nov 05 '15 14:11

N.Ba


People also ask

What is do while loop in C++ with examples?

The C++ do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop. The C++ do-while loop is executed at least once because condition is checked after loop body.

How do you write do while in C++?

Syntax. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again.

Do while loop C++ meaning?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


1 Answers

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.

like image 78
MicroVirus Avatar answered Sep 26 '22 03:09

MicroVirus