Hacker News new | ask | show | jobs
by matthavener 5358 days ago
Why?
2 comments

The code

    printf("goodbye, Dennis");
would give

    $ ./goodbye
    goodbye, Dennis$ 
What you want is to add a newline ('\n') at the end:

    printf("goodbye, Dennis\n");
Now you get

    $ ./goodbye
    goodbye, Dennis
    $
That's why the canonical "hello, world" program contains the line

    printf("hello, world\n");
"\n" is a linebreak which would guarantee the text is printed and place whatever output came afterwards on the next line.
Isn't the output stream at least guaranteed to be flushed once on completion of the program, though?
Yes, it flushes completely outputting all characters. None of which contain a newline.

Flushing doesn't automatically add newlines for you in C. It flushes the buffers you gave it, it doesn't make new stuff up to print out along with your buffers.

(Right, I didn't mean to suggest it added a newline; just that adding a newline flushes the buffer, which was one half of the problem with missing a newline—but that if this is the only line of the program, this half of the problem is obviated.)
Adding a newline doesn't flush anything. You'd want to call fflush() to do that.
printf prints to standard output, which is line-buffered by default when reading from a tty on UNIX variants. This can lead to strange problems for those who try to use it to track which parts of a program are being executed, as demonstrated by the following program with an infinite loop:

  #include <stdio.h>
  int main(int c, char **v) {
    printf("Hello\nJello");
    while(1) ;
    return 0;
  }