One possible explanation for this is that cout
and printf
use separate buffers. cout
outputs on the terminal screen either when it is flushed using the endl
command, or if the buffer is full (generally 512 bytes).
I am not sure about printf
(so feel free to correct me if I'm wrong), but it also follows a similar behaviour. So what happens is that at the end of the program, both the buffers are flushed, and so the output you see is achieved.
I ran the code on my machine (GCC 4.8.1) along with the modification as below
cout << i << " . ";
printf("%d ", i);
The output I observed was 0 1 2 0 . 1 . 2 .
which seems to indicate that printf flushes first in my case. I have no idea if it is by design (mentioned somewhere in the standard), or if it depends on the context.