4

A simplified version of my code is:

#include "externalstuff.h"
void main(){
    printf("Hello?");
    /* make calls to externalstuff
    ....
    */
}

I did not write externalstuff.h, so I'm not sure what is going on there exactly.

The calls to externalstuff take some time to execute. I would expect that "Hello?" would get printed, then I would have to wait for those external calls to finish, then my program would end. But what seems to be happening is that "Hello?" only gets printed right before my program ends, after a long wait for the externalstuff.

Is it possible that something in externalstuff.h is delaying this output? If so, how?

I'm using gcc in cygwin on Widnows 7.

Dramal
  • 167
  • 2
  • 10
  • 2
    The 'hold-up' is the fact that you don't add a newline to the end of the format string. Output is line buffered by default; that means, output appears when a newline is generated. – Jonathan Leffler Feb 04 '15 at 17:08

1 Answers1

10

Buffering delays the output of your program. When you call printf, the output is stored in a buffer until one of three things happen:

  • The length of internal buffer becomes insufficient for holding the output, or
  • You call fflush(stdout) to initiate sending the buffer to console explicitly, or
  • You print '\n' character, and the output is sent to console (as opposed to sending the output to a file).

If you don't like this behavior, and do not mind somewhat slower performance, you can call

setbuf(stdout, NULL);

to disable buffering.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Thank you for the clear explanation. This has been bothering me for a while. Now I understand it. – Dramal Feb 04 '15 at 17:23