Hello world in C
Here is the generic ``Hello world'' program in C:
#include <stdio.h>
int main (void) {
printf ("hello world\n");
return 0;
}
Notes:
- #include <stdio.h> is a pre-processor
directive , i.e., it is interpreted by a program called the
`pre-processor', cpp (any line starting with the # character is
interpreted by cpp). In this case, #include
<stdio.h> simply includes the file
/usr/include/stdio.h into the source code (i.e., the line
#include <stdio.h> is replaced by the contents of
/usr/include/stdio.h), before passing it on to the C
compiler.
- The angle brackets around stdio.h indicate that this
is an include-file provided by the C compiler itself (if you
wanted to include your own file, then use double quotes
instead).
- The reason that we include /usr/include/stdio.h is
that it contains a function prototype for the
function printf which we call at line
3. Function prototypes are used by ANSI-standard C to check that
you are calling the function with the right number and type of
arguments.
- main (void) is a function. Every C program
must contain at least one function definition called
main. "void" means that the function main doesn't
have any arguments. The fact that main (void) is followed by
a curly bracket means that this is the definition of
main. (To call a function, you give its name, its
arguments (in parentheses), and then a semicolon).
- printf ("hello world\n"); is an example of a
function being called. "hello world\n" is the
argument (in this case a character string).
- A semicolon is used to delimit statements in C. This is one of
the most confusing things about C for beginning programmers. We
will soon learn some rules for when and where to use
semicolons.
- return 0; is an statement that instructs
the main () function to return an integer value of
zero to the calling program (in this case, the operating
system).
Note also the strange character sequence `\n' in the string
constant "hello world\n". `\n' is called a newline
character, and is regarded as a single character in C (i.e., it
occupies one byte of storage). `\n' is known as an escape
sequence, and the back-slash character is called the escape
character.