1

Look this example:

#include <iostream>
#include <stdio.h>

int main()
{
    std::ios::sync_with_stdio(false);
    std::cout << "a";
    printf("b");
    std::cout << "c";
}

On gcc 9.2 I'm getting acb as output. I was expecting bac, because, if I understood correctly, std::cout would be using its buffer. Why was it printed in this order?

Additional question: setting std::ios::sync_with_stdio(false) would improve performance (in the above example, for instance)?

João Paulo
  • 6,300
  • 4
  • 51
  • 80

1 Answers1

3

The default typical behaviour for the stdout stream is line buffering, so that output is perfectly reasonable. printf does not flush immediately, for that use fflush(stdout).

To your second question, one would expect that performance is improved when synchronisation is not required. However, it is always better to profile and check, obviously for this small snippet, it won't much matter.


Edit: Answer corrected based on this post.

Mansoor
  • 2,357
  • 1
  • 17
  • 27