Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout not working in the case of an infinite loop

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

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?

like image 749
Gibreel Abdullah Avatar asked Oct 31 '25 19:10

Gibreel Abdullah


1 Answers

There can be two reasons.

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.

like image 177
Petr Avatar answered Nov 02 '25 10:11

Petr