2

Until now, I used fflush(stdout) when using printf without \n, since we have to flush the buffer.

But I found that the below code also works fine.

#include <stdio.h>

int main(void){
    printf("hello world");
    // without fflush(stdout)
}

// output: "hello world"

Is the outcome differs with the compiler? or am I misunderstand something?

jwkoo
  • 2,393
  • 5
  • 22
  • 35
  • 8
    On a healthy exit, the buffer is flushed anyways. – Thomas Jager Aug 27 '19 at 15:30
  • 7
    The buffer is automatically flushed under several circumstances: (1) when the buffer is full, (2) when you print a `\n` character and the output is going to a "terminal" (e.g. is not being redirected to a file), (3) when the program exits, and (4) under some systems, at least, when the program is waiting for input (meaning it's good if any prompts get flushed). You only need the explicit call to `fflush(stdout)` if none of those is true. – Steve Summit Aug 27 '19 at 15:31
  • @SteveSummit Thanks for your comment, so the examples which are mentioning that using printf without fflush(stdout) will output error is partially correct? (of course they are emphasizing on using fflush) – jwkoo Aug 27 '19 at 15:33
  • I'm sorry, I don't quite understand your question. I'm not sure which examples you're talking about, and I'm not sure what "will output error" means. – Steve Summit Aug 27 '19 at 15:35
  • @SteveSummit the link is here : https://www.quora.com/Why-do-we-use-the-functions-fflush-stdin-and-fflush-stdout-in-c – jwkoo Aug 27 '19 at 15:37
  • @SteveSummit " students often have problems like “my prompt doesn't appear!” quite not seems to be right, because it works in my case. – jwkoo Aug 27 '19 at 15:37
  • 1
    @jwkoo The problem students often have is that they write "printf("Enter a number: "); scanf("%d", &number)`, and they wonder why their prompt doesn't appear. (Because, I guess, not all systems implement #4 in my list above.) – Steve Summit Aug 27 '19 at 15:41
  • @SteveSummit using scanf after printf also does work fine – jwkoo Aug 27 '19 at 15:42
  • On many systems, yes. But perhaps not on all. – Steve Summit Aug 27 '19 at 15:44
  • @SteveSummit Thanks for your big help. – jwkoo Aug 27 '19 at 15:45
  • When you think about it, there is some magic going on behind the scenes on those systems that flush the `stdout` stream when waiting for input on the `stdin` stream. Not all systems have this magic. – Ian Abbott Aug 27 '19 at 17:05

0 Answers0