What is the significance of "ios_base::sync_with_stdio(false)" statement?

Today I was solving this problem, INCPR04 Problem - CodeChef, I implemented a solution with O(length of the array) time complexity. But I was getting TLE. Then I looked up at some of the accepted solutions, their logic was same as mine, but they have added these statements:

I have tried doing the same and added these statements to my code and the solution got accepted. But I don’t exactly know what do these statements do. I have searched it on google and opened the first link but I couldn’t a get a lucid idea of what it is exactly doing. Could someone please elaborate what these statements actually do?

1 Like

I will try to answer this question best of my experience and learning .

In CPP programs you can use both C and CPP style I/O but when you set the ios_base::sync_with_stdio (by default its value is true and synchronization is there, meaning they are sharing same buffers and you will get expected results if you use both C and CPP style I/O) to false it disables the synchronization between the C and C++ standard streams and std::cin becomes faster.

Now, because scanf() works faster than std::cin(), competitive coders use “ios_base::sync_with_stdio(false);” at the beginning of their main() to get faster input (and it really does make a big difference). Also I would like you to go through these links i provided below, they are from stack overflow.

Links :-
Using scanf() in C++ programs is faster than using cin?
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

I hope I was able to answer your question :smile::grin:


Thanks a lot, it really helped!


will this optimization always happen in cpp program i.e can i use these lines for every cpp program?

Yes , you can