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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With