0

I am expecting a similar behavior for Cout and Clog since both are buffered outputs. But when i am trying, it comes out different.

COUT:

int main()
{
    cout<<"Hello World" ;
    while(1);
    return 0;
}

Output: Nothing --> Since Cout is not flushed

CLOG:

int main()
{
    clog<<"Hello World" ;
    while(1);
    return 0;
}

Output: Hello World

Question: Both COUT and CLOG are buffered, so why not the output is same. How is "Hello World" being printed without the buffer being flushed

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 1
    `while(1);` is undefined and the output of the two programs could be anything – 463035818_is_not_an_ai Apr 01 '22 at 12:07
  • 1
    I suggest to use some `std::this_thread::sleep_for(std::chrono::milliseconds(1000));` instead of the infinite loop – 463035818_is_not_an_ai Apr 01 '22 at 12:08
  • 1
    What is `clog`? Most error handlers flush automatically so that you always have the most current information in the log. – NathanOliver Apr 01 '22 at 12:08
  • @NathanOliver • [`std::clog`](https://en.cppreference.com/w/cpp/io/clog) is a buffered stream, and is synchonized with stdio, and "safe" to use concurrently in multiple threads (ignoring the interleaving issue). In contrast to `std::cerr` which is unbuffered. – Eljay Apr 01 '22 at 12:50

1 Answers1

0

First of all, I don't understand the purpose of the infinite loop. If you are trying to put the thread to sleep check this post StackOverflow post about thread sleeping in cpp,

Secondly, if you want to flush the stream use std::cout << std::flush;.

As for the difference between those: basically clog is a rarely used output stream similar to cerr. Basically clog outputs to stderr, similar to cerr, and not stdout. Checking these might help you understand the difference: COUT vs CERR vs CLOG, Tutorialspoint.

Now onto the difference between stdout and stderr. Stdout is always buffered and is flushed automatically at a convenient time or when requested explicitly to do so, meanwhile stderr is not fully buffered and always prints stuff immediately, without needing to be flushed explicitly.

Alex D
  • 16
  • 2