1

Why does this hang without first printing?

#include <stdio.h>

void main() {
    printf("hello world");
    while (1) {}
}
sepp2k
  • 353,842
  • 52
  • 662
  • 667
Joseph Mark
  • 9,088
  • 4
  • 28
  • 31

2 Answers2

10

Because you haven't flushed the standard output. Try fflush. Even better, for C++ use...

std::cout << "hello world" << std::endl;

Separately, you'd have a better chance of it flushing itself if you added a \n, but not all implementations follow the Standard when it comes to such things.

Tony Delroy
  • 99,066
  • 13
  • 167
  • 246
  • Do either the C or the C++ standards require that `\n` flushes the stream? – user657267 Oct 21 '14 at 08:20
  • No, it´s only a common behaviour. – deviantfan Oct 21 '14 at 08:25
  • @user657267: the standards says `stdout` can be in line buffered or unbuffered mode, with the former being the default when connected to an interactive terminal (as the user probably wants to see the output in a timely fashion), and the latter used when output's written to a file, pipe etc. as that's more efficient. See [here](http://stackoverflow.com/questions/5229096/does-printf-always-flush-the-buffer-on-encountering-a-newline) for citations. With C++ iostreams, `cout` - by default - flushes before input from `cin`, ensuring the user sees the relevant prompts... they're *"tied"* streams. – Tony Delroy Oct 21 '14 at 08:31
  • @TonyD Thank you. I looked it up myself in the meantime and found: `What constitutes an interactive device is implementation-defined.` so technically it doesn't seem to be mandated. – user657267 Oct 21 '14 at 08:40
3

Call fflush(stdout); after printf.

This will force the stdout buffer to be flushed and printed.

V-X
  • 2,859
  • 17
  • 28