-2

This is a backstory, you can skip to the question in bold below if you don't wanna read it.

Recently while solving a problem I accidentally had an infinite loop in it. But I didn't know so I tried to debug the code, and obviously a good way to debug ( or at least a way that I'm used to ) is to place a few flags in the code, that would print to the console that the program has finished successfully until that part. But later I saw that even when I place the flag as the first thing in the program, it still wouldn't print anything. I managed to fin the bug by using return 0 instead of placing flags, but this got me wondering,

Why doesn't the following program print "A" right away?

#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"A";
    int k=1;
    while(k)k++;
}

Edit: Even after changing the cout<<"A"; into cout<<"A"<<endl; the problem continued existing. I'm using C++ 14 GNU GCC compiler

1 Answers1

2

That is because output is buffered by default, so you are leaving it up to the program to decide when it will actually render your output to the screen.

If you force it by using cout<<"A"<<endl;, you will get an immediate flush and a print, as you expect.

kabanus
  • 24,623
  • 6
  • 41
  • 74