With and Without ios::sync_with_stdio(0);

With ios::sync_with_stdio(0);cin.tie(0);
#include<bits/stdc++.h>

using namespace std;

int main(){

ios::sync_with_stdio(0);cin.tie(0);

cout << “1st step” << “\n”;

int tc;

cin >> tc;

while(tc–){

cout << “hello” << “\n”;

}

}

Output:
1
1st step
hello

Without ios::sync_with_stdio(0);cin.tie(0);
Output:
1st step
1
hello

Why is the order of output different in both cases?

Refer this gkg link

You should know when to include those statement for fast IO and when not.

Thanks. But I didn’t understand that blog. That’s why I posted here.

@juniorrk
cin.tie(0);

This statement takes care of linking of input and output(cin and cout). If we do not write this statement then by default both input and output streams(cin and cout) are linked in a way that before each I/O operation kind of buffer is flushed(That means if we use cin after cout than output stream buffer is cleared and that data is printed to terminal).

By writing above statement we untie those stream flushes. So as the result previous line cout may not be displayed before next line cin.

Now seeing your code(It has some typos like tc-- in while loop, but ignoring it)

With ios::sync_with_stdio(0);cin.tie(0);

One thing what we know is when we type something it is visible to us but not visible to terminal until we press enter.

So when you enter 1 it is not visible to terminal.

When you pressed enter it is the text you have typed so there is no need to think about streams at this point.

Even before typing, “1st step” was in buffer but it is waiting until every IO operation is completed and at last print everything.

After you pressed Enter key, while loop run 1 times and “hello” is also added to buffer after “1st step”

There is no more things to do. So both things are printed one by one.

Read what i have written once again and hopefully you will get what i want to say.

.
.

Now another case :grin:

Without ios::sync_with_stdio(0);cin.tie(0);

Every statement is executed and buffer is flushed everytime at every I/O operation.

“1st step”
It is printed even before taking input from cin. (Because cin flushed cout output stream and printed contents on terminal)

Than input is taken, which is what you have entered from keyboard. It will be visible to terminal when you press enter key. It is simply the text which you have typed.

Remaining execution is done and “hello” is printed once.

Hope you got your doubts cleared. For reference visit this stackoverflow link

Please Upvote :+1: if it helped. :grin: It motivates me to write more answers. (PS: writing answer at 1AM for you)

2 Likes