Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is much simpler:

  int n = printf("Hello, World!\n");
  return n < 0 ? EXIT_FAILURE : EXIT_SUCCESS;


On my machine:

    $ cat main.c
    #include <stdio.h>

    int main(void) {
        int n = printf("Hello, World!\n");
        return n < 0 ? 1 : 0;
    }

    $ cc main.c
    $ a.out
    Hello, World!
    $ echo $?
    0
    $ a.out > /dev/full
    $ echo $?
    0
Problem is, printf is buffered. When redirecting to /dev/full writing to the buffer works. The problem only manifests when the buffer is flushed.

This works, as write is not buffered;

    #include <unistd.h>

    int main(void) {
        int n = write(1, "Hello, World!\n", 14);
        return n < 0 ? 1 : 0;
    }
But even then, to find out what exactly went wrong, we would have to check errno.

It's easier in Go, because fmt functions do have an error return which will report such errors;

    func main() {
        _, err := fmt.Println("Hello, World!")
        if err != nil {
            os.Exit(1)
        }
    }


I was expecting that printf would auto-flush at the newline, but either it doesn’t, or doesn’t report an error? An explicit fflush would probably work.

In any case, hello world examples are used for two purposes, (a) providing a simplest possible program that you can run (with an indication that it worked), and (b) to give a taste of the respective programming language. At least for the latter case, it would be useful to demonstrate the necessary error handling, if any. The above is just showing that this is not entirely trivial in C with its standard library.


The file objects in the library can operate as unbuffered, line-buffered or fully (i.e. block) buffered. When your stdout is connected to a terminal, it is line-buffered and flushes on newline. But when you redirect to a file, it becomes block buffered.


> to give a taste of the respective programming language

The question is, how much of a taste? We could also include structs, manual memory management, pointers, macros, #ifdef guards; because these are all so very common to C programs, they are definitely part of the languages flavour.

Also, which of the error handling techniques in C should be included, because the language doesn't have a standard one, there are no exceptions or multiple returns. Even within the most basic libraries we have everything from checking global error states, inbound messenger variables, magic number returns, errorflags, ...

Again, hello.c is supposed to be simple. As simple as possible. Yes, that excludes a lot of things. These things are what all the other chapters of "The C Programming Language" are about.

As a starter, hello.c is great.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: