Do while loop with a cout statement

五迷三道 提交于 2019-12-10 13:46:52

问题


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?


回答1:


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.




回答2:


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.




回答3:


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++.



来源:https://stackoverflow.com/questions/33546984/do-while-loop-with-a-cout-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!