用cout语句执行while循环 [英] Do while loop with a cout statement

查看:135
本文介绍了用cout语句执行while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对 do / while 循环有一个一般性的问题。我正在学习C ++,我知道您可以编写类似的内容:

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");

重点是,我知道这在c ++中是可能的,但是我们真的做到了吗?我的意思是, cout 东西在内部一段时间了吗?

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?

推荐答案

事实是有人这样做(即,将函数作为条件评估的一部分)。这在Shell脚本中很有意义,但是如果您不使用Shell脚本,则有时不清楚某些函数的返回值是什么。我无法告诉您cout<<<<<>"消息"会立即返回,但是我确实知道,如果将其写入循环主体中,它将满足我的要求,并且如果我将它丢弃返回值

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.

要编写更清晰的代码(包括您的未来自我),其他人可以理解,我只会评估明显返回true / false的条件,而不是 0 / not-0或 0/1(在不同语言中可能有所不同)。

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.

这篇关于用cout语句执行while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆