Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Chapter 2. Staring With Functions

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

#include <stdio.h>

  printf("hello, world\n");

  return 0;
Compile and run this program before moving on. If all goes well, it will display the text string "hello, world" to your 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
hello, world
[email protected]:~/book$
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.

  Published under the terms of the GNU General Public License Design by Interspire