在无限循环的情况下,cout无法正常工作 [英] cout not working in the case of an infinite loop

查看:100
本文介绍了在无限循环的情况下,cout无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main(int argc, char* argv[]) 
{
    while(1)
    {
        cout<<"123";
    }
    return 0;
}

我写了这个小程序,它将打印"123",然后进入无限循环.但是它不会在屏幕上打印任何内容.是什么原因呢?

I wrote this small program which would print "123" and then go in an infinite loop. But it does not print anything on the screen. What is the reason for this?

推荐答案

有两个原因.

首先,最有可能缓冲输出.也就是说,发送到cout的文本不会立即打印,而是保留在缓冲区中,并且仅在刷新缓冲区时打印(通过cout.flush()或通过打印endl发生).

Firstly, the output is most probably buffered. That is, the text sent to cout is not printed immediately, but kept in a buffer and printed only on flushing the buffer (which happens by cout.flush() or by printing endl).

第二,我想一个空的无限循环是未定义的行为.也就是说,具有无限循环的程序实际上可以执行任何操作.特别是,允许​​优化程序对程序中的所有内容进行优化.

Secondly, I suppose that an empty infinite loop is undefined behavior. That is, a program with an infinite loop can in fact do absolutely anything; in particular, an optimizer is allowed to optimize anything out of the program.

这篇关于在无限循环的情况下,cout无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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