As we saw in the hello.c example in the last lecture, Every C program must contain a main
function , since the main function is the first function called when you run your program at
the command line. In its simplest form, a C program is given by
int main(void) {
printf(‘‘Hello world!\n’’);
}
The int stands for the “return type”, which says that the main function returns an integer
if you tell it to do so. We will get into more detail with functions and return types, but you
can return a number to the command line with the return function in C, as in
int main(void) {
printf(‘‘Helloworld!\n’’);
return 2;
}
When you compile and run your program, it will return a 2 to the command line, that
you can access with the $? character, which stores the value returned by the last command
executed, as in
$ ./a.out
Hello world!
$ echo $?
2
Just as in shell scripts, you can specify exit codes in C as well, which perform the same
function as the return function in the previous example:
int main(void) {
printf(‘‘Hello world!\n’’);
exit(2);
}
Compiling and running this example yields the same result as the previous example. The
void statement in main(void) tells the main function that there are no arguments being
supplied to it at the command line. We will get into this in more detail when we look at
functions.
Note that all statements in C programs end with the semicolon ; except for the preprocessor
directives that begin with #.