Saying hello

The creators of C, Brian Kernighan and Dennis Ritchie, wrote the book on the C programming language. It was called, appropriately, ‘The C Programming Language’, but programmers also call it the C Bible or just K&R. It introduced programmers to the language with a program that prints ‘hello, world’.

The idea of learning a new language by writing a hello-world program spread from K&R to become a widespread programming tradition, observed across languages.

In order to have access to the standard library functions for printing output, we have to add a line at the top of our C file to include the standard input and output header (stdio.h for short). The function puts (‘put string’) accepts a string argument, given here in double quotes, and prints it out on its own line in the output stream.

#include <stdio.h>

int main()
{
    puts("hello, world");
}

Try putting that into a file named hello.c, using make to build it into a program in a file named hello, and running it with ./hello. Do you see the greeting? Once you’ve printed the classic message, you can change what is in the quotes to print just about anything.

Without actually writing any additional functionality, let’s explore ways to rearrange and decompose C programs that will become extremely useful when we have more code to wrangle. First, let’s create a new function. This time, you can pick any name you like, as long as it follows these rules.

I will name mine robert. Since my new function does some work but doesn’t calculate a value, its type will be void, and it doesn’t take any parameters as input, so its parameter list will still just be the empty parentheses. I have also changed main to call the robert function to do the work.

#include <stdio.h>

void robert()
{
    puts("hello, world");
}

int main()
{
    robert();
}

If you try to rearrange the same code so that main comes first and then robert, you will get an error when you try to compile it. That is because when you call the function from main with robert(), the compiler needs to already know that such a function exists and a little bit about how to call it. It doesn’t need to know all the details, though, just the return type, name, and parameters. So, I can give a ‘declaration’ with just that information, and that’s enough as long as I get around to providing a ‘definition’ later on, with the curly brackets and the whole body.

#include <stdio.h>

void robert();

int main()
{
    robert();
}

void robert()
{
    puts("hello, world");
}

In fact, I could even put the definition in a whole other file. Commonly, the declarations for some useful, shared code will go in its own file, called a header and ending with a .h extension, and the definitions will go in a matching .c file, and then the build process links all the pieces together.

You have attempted of activities on this page