4
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?

jww
  • 97,681
  • 90
  • 411
  • 885
Gibreel Abdullah
  • 335
  • 1
  • 3
  • 12
  • 4
    Maybe it didn't flush it, try `std::cout<<"123"< – Melkon Sep 18 '15 at 12:56
  • `cout << "123";` does not necesarrily print anything on the screen, as Melkon pointed out, the stream has to be flushed before anything is printed – 463035818_is_not_an_ai Sep 18 '15 at 12:58
  • 6
    -5? Unduly harsh? Is it really obvious that `<<` is buffering? Then there is the UB sting. This question ain't so bad. OP even got the `main` prototype correct. – Bathsheba Sep 18 '15 at 13:03
  • Maybe because it isn't an MCVE. With beginner question, one never knows if code doesn't print because, for example, it didn't even compile. – juanchopanza Sep 18 '15 at 13:19
  • Possible duplicate of [std::cout not working inside a for-loop](https://stackoverflow.com/questions/6451198/stdcout-not-working-inside-a-for-loop) – jww Mar 28 '18 at 18:00

2 Answers2

8

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.

Community
  • 1
  • 1
Petr
  • 9,812
  • 1
  • 28
  • 52
1

Most likely the process CPU burn (due to the tight loop) has blocked the streaming to the console.

Technically though the behaviour of your program is undefined as, essentially, the loop does not have any input /output or side effects.

A compiler is permitted to optimise out your function body, which would also yield no output.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483