The traditional first C program is one that outputs ``Hello world''.
Here it is:
#include <stdio.h>
int main()
/* My first C program */
{
printf("Hello world\n");
}
This shows the basic structure of a program in C.
We will need to do some output, so we need to gain access to the standard input/ouput routines, by use of the #include <stdio.h> statement. For now, you can treat this as a something you just have to have; later we will explain it further. We will not keep showing it in every example.
The program has a standard name, main.
All programs and sub-programs (functions) have a name: main is a reserved name for the program which controls all of the others. Further, main is of int type: it can return an integer value. main is the function that is obeyed when your program first starts, so in practice it is the function which controls all others (and hence the name).
All functions may have a list of parameters: in this case main has none so the list () is empty. We will see later how and why main can have parameters.
Secondly note the way we write comments, using `/*' and `*/' as delimiters. Comments are ignored by the C compiler and can thus appear anywhere (except in the middle of a string).
/* My first C program */
Next, the body of the code is enclosed in braces {}.
Thirdly, simple statements are terminated by a semi-colon. This use of this delimiter means that the layout of a C program can be flexible: white spaces (space characters, tabs, returns) between words are not generally relevant, except in literal strings (such as between ``Hello'' and ``world'').
Here is the same program in a worse style, though it still does exactly the same:
main()
{printf("Hello world\n");}
or, worse still
main(
)
{
printf(
"Hello world\n"
)
;
}
Again it is imperative that you use a tidy, readable style. Unix provides a tool which automatically puts a standard form on any program you write. It is called the C beautifier (If it is available on your system, type ``man cb'' to find out more).
printf is a simple way of outputing to the stdout stream, which in fact is the screen.
Note the use of \n to represent the newline character. Backslash is used as an escape character by C for a small number of special layout control characters.
Here is a different program, which might seem to output a different message, but in fact it has exactly the same output:
main()
{
printf("Hell");
printf("o ");
printf("world\n");
}
maspjw@