2.1. What are functions?
Functions are the building blocks of C programs.
The majority of a C program is made up of named blocks of
code called functions. When you write a
program you will write many functions to perform the tasks you need.
There are, however, a lot of common tasks such as displaying text to
the screen that a lot of programmers will need. Instead of having
everyone reinventing the wheel, GNU systems come with
libraries of pre-defined functions for many of
these tasks. Over the years, thousands of such functions have
accumulated. If you were writing a program that plays the game,
BINGO, you would have to write the game specific functions yourself
but you would find that others have already written functions for
generating random numbers, displaying results to the screen, getting
input from the player etc.
Every C program must have a function called
main(), this is where execution of the program
begins. The code of a program could be
completely contained in main() but it is more usual
to split a program into many small functions.
The first piece of useful code we will look at is a classic.
When compiled and run it will display a simple greeting to your screen.
This program defines a function called
main() and calls (uses) a
function called printf().
printf() is a function provided for us by the
"Standard Device Input/Output library". This library
comes with every GNU system. Here's our little program:
Example 2-1. hello.c
Compile and run this program before moving on. If all goes well,
it will display the text string "hello, world"
terminal (the standard output device). Here's the compilation command
just in case you've forgotten:
[email protected]:~/book$ gcc -Wall -o hello hello.c
[email protected]:~/book$ ./hello
If you got any error or warning messages check that your code matches
the code in this book exactly. Any messages you got should tell you
the line of code where your mistake is. If you've typed the code in
correctly you will get no such messages.