2.2. A Line-by-Line Dissection

We'll do a quick description of what each line does. Don't worry if your not sure about some parts, we'll do plenty more examples.

#include <stdio.h>
    

This line tells GCC to include information about how to use the functions from the Standard Device Input/Output library. Usually the standard input device is your keyboard and the standard output device a terminal (which is displayed on your monitor. This library is very widely used, we'll come across a lot of functions from it in this book.

int
main()
     

These two lines begin the definition of the function main(). We'll explain the first of these two lines later.

{
     

The open curly braces signals the beginning of a block of code. All code between this curly brace and it's matching closing brace is part of the function main().

  printf("hello, world\n");
     

This line is a function call, the function is already defined for you. When you call printf() you must pass it an argument to tell it what to display.

  return 0;
    

The return statement ends execution of the function main(), any statements after this line would not be executed. When main() ends your program exits. When a function ends, it can pass a value back to whoever called it, this is done by placing the value after return. main() always returns an integer (a positive or negative number with no decimal point). We tell the compiler to expect this by preceding the definition of main() with int. When returning from main() it is convention to return zero if no problems were encountered.

}
     

The closing curly brace signals the end of the block of code that makes up main().

The two lines that make up the body of main() are known as statements. More specifically they are simple statements (as opposed to compound statements which we will encounter in chapter 4). Statements are to C what sentences are to spoken languages. A semi-colon ends a simple statement. The blank lines in the program are optional, C never requires a blank line but they make code much easier to read.

We mentioned that our function main() returns the value zero. For most functions the return value can be used within the program but since returning from main() signals the end of the program it returns it to the shell. The return value of a program is stored by the shell, if you want to see it, type the following:

ciaran@pooh:~/book$ gcc -Wall -o hello hello.c
ciaran@pooh:~/book$ ./hello
hello, world
ciaran@pooh:~/book$ echo $?
0
ciaran@pooh:~/book$