Edition 4.1
The GNU C Programming Tutorial
Mark Burgess
Faculty of Engineering, Oslo College
Ron Hale-EvansCopyright © 2002 Free Software Foundation, Inc.
Permission is granted to copy, distaibute and/or modify this document under
‘the terms of the GNU Fre Documentation License, Version 1.1 or any later
version published by the Free Software Foundation; there being no Invariant
Section, with the Front-Cover Texts being “A GNU Manual’, and with the
BadeCover Texts as in (a) below. A copy of the license is included in the
section entitled “GNU Free Documentation Lions”,
(a) The FSF’s BadeCover Text is: “You have fieadom to aopy and modify
‘this GNU Manu, like GNU software. Copies published by the Free Software
Foundation raise fimds for GNU development.”Preface
‘This book is a tutorial for the computer programming language C. Unlike BASIC or
Pascal, C was not written asa teaching aid, but as a proféssional tool. Programmers love
CC! Moreover, C is a standard, widely-used language, and a single C program can often be
made to nm on many different kinds of computer. As Richard M, Stallman remarks in
GNU Coding Standards, “Using another language is like using a non-standard feature: it
‘will cause trouble for users.” (See http: //www.gnu.org/prep/standards_toc. html.)
Skeptics have said that everything that can gp wrong in C, does, True, it can be umfor-
giving, and holds some difficlties that are not obvious at first, but that is because it does
not withhold its powerful capabilities from the beginner. If you have come to C sacking a
powerful language for writing everyday ccmputer programs, you will not be disappointed.
‘To ert the most from this book, you should have some basic computer literacy — you
should be able to run a program, edit a text: file, and so on, You should also have acess to
a computer running a GNU system such as GNU/Linux. (Ror more information on GNU
and the philosophy of free software, see http: //sww .gmu.org/philosophy/.)
‘The tutorial introduces basic ideas in a logical order and progresses steadily. ‘You do
not need to follow the order of the chapters rigprously, but if you are a beginner to C, it is
recommended that you do, Later, you can retum to this book and aopy C code fiom it; the
many examples range from tiny programs that illustrate the use of one simple feature, to
complete applications that fill several pages. Along the way, there are also brief discussions
of the philosophy behind C.
(Computer languages have been around so Jong that: some jargon has developed. You
should not ignore this jargon entirely, because it i the Ianguage that programmers speak.
Jargon is explained wherever necessary, but kept toa minimum, There is also a glossary at
‘the back of the book,
‘The authors of this book hope you will learn everything you neod to write simple C
programs from this book, Further, it is rdleased under the GNU Fie Documentation
License, so as the computers and robots in the fantasies of Douglas Adams say, “Share and
Enjoy!”
The first edition of this book was written én 1987, then upelated and rewritten in 1999. Tt
twas originally published by Dabs Press. After it went out of print, David Atherton of Dabs
«and the original author, Mark Burgess, agreed to release the manuscript. At the request of
the Free Softuare Foundation, the book wns further revised by Ron Hale-Bvans in 2001 and
2002.
‘The current adition is written in Teninfo, which is a documentation system using a single
source file to produce both onkine information. and printed output. You ean read this tutorial
online with either the Emacs Info render, the stand-alone Info render, or a World Wide
Web browser, or you can rend it as a. printed book.‘The advantages of C 1
1 Introduction
What is a highalevel language? Why is C unusual?
Any sufficiently complex ob ject has Jeves of detail; the amount of detail we see depends
‘on how closely we scrutinize the object. A computer has many levels of detail.
‘The terms Jow level and high level are often wed to describe these layers of complexity
jn computers. ‘The Jow level is buried in the computer's microchips and microcinonits. The
{ow level is the level at which the computer seams most: primitive and mechanical, whereas
the high level describes the computer in Jess detail, and makes it easier to use.
‘You can see high Jewels and low levels in the workings of a car, Tn a car; the nuts, bolts,
and pistons of the low level can be grouped together conceptually to form the higher-level
engine. Without knowing anything about the nuts and bolts, you can treat the engine as a
black box: a simple unit that: behaves in predictable ways. At an even higher level (the one
mest people use when driving), you can see a car as a group of these black boxes, including
the engine, the steering, the brakes, and so on. At a high level, a computer also becomes
group of black boxes.
Cis a high-Jovel language. The aim of any high-level computer Janguage is to provide
an easy, natural way to give a list of instructions (a computer program) to a computer.
‘The native language of the computer is a stream of numbers called machine language. As
you might expect, the action resulting from a single machine language instruction & very
ptimitive, and many thousmds of them can be required to do something substantial. A
high-level Janguage provides a set of instructions you can recambine creatively and give
to the imaginary black bawes of the computer. The high-level language software will then
‘translate these high-level instructions into lovelevel machine language instructions.
1.1 The advantages of C
Cisne of a large mmber of high-level languages designed for general-purpose program
ning, in other words, for writing anything from small programs for personal ammsement: to
complex industrial applications,
(Chas many advantages:
«Before C, machine language programmers criticized high-level languages because, with
‘heir black box approach, they shielded the user from the working details of the cam-
puter and all its facilities. C, however, was designed to give access to any level of the
computer down to raw machine language, and becanse of this, it is perhaps the most
flexible high-level language.
© Chas features that allow the programmer to organize programs in a clear, easy, logical
way. For example, C allows meaningful names for variables without: any loss of effi
ciency, yet it gives a complete freedom of programming style, including flexible ways
of making decisions, and a set of flexible commends for performing tasks repetitively
(for, winile, do).
© Cis sucinct, Tt permits the creation of tidy, compact programs. ‘This feature can
be a mixed blessing, however, and the C progtammer mst balance simplicity and
readability,2 Chapter 1: Introduction
© Callows commands that are invalid in other languages. This is no defect, but a powerfull
freodom which, when used with caution, makes many things possible, Tt does mean,
that there are concealed difficulties in C, but if you write carefully and thoughtfully,
you can create fast, efficent programs.
With G, you can use every resource your compnter offers, C tries to link closely with
‘the local environment, providing facilities for gaining access to common peripherals,
like disk drives and printers. When new peripherals are invented, the GNU community
quickly provides the ability to program them in C as well. In fact, most of the GNU
project is written in G (as are many other operating systems).
For the reasons outlined above, C is the preeminent high-level language. Clearly, no
Tanguage can guarantee good programs, but C can provide a framework in which it is easy
‘to program well.
1.2 Questions for Chapter 1
1. Exqlhin the distinction betwee high levels and low levels,
2 What isa “black box"?
3. Name a few advantages to programming in the C language.‘The compiler 3
2 Using a compiler
How to use a compiler. What can go wrong.
‘The operating system is the layer of software that drives the hardware of a computer and
provides the user with a comfortable work environment. Operating systems vary, but most
Inve a shell, or text interface. ‘You use the GNU shell every time you type in a command
‘that launches an email program or text editor under GNU.
In the following sections of this chapter, we will explore how to create a C progyam fiom,
the GNU shell, and what might go wrong when you do,
2.1 Basic ideas about C
First a note about a programming language that is different fiom the C programming,
language, the GNU shell. When you enter commands in the GNU shell, they are executed
immediately. Moreover, the shell is a programming language, in that the commands you
type are a program, because you can also create a text file containing many shell cammands.
‘When you nin this file, the commands will be executed in sequence.
On the other hand, consider C. While a shell command file can be executed directly, a
C program must: be created in two stages
1. First, the program is written in the form of text files with a text editor such as GNU
Emacs. This fom of the program is called the source code. A computer cannot execute
source code directly.
2 Second, the completed source code is processed with a compiler — a program that
generates a new file containing a machine-lnguage translation of the source code.
‘This file is called an executable file, or executable. The executable file is said to have
been compiled from the source code,
‘To mm the compiled program, you must usually type the name of the executable file
precded by a period and a slash, as in this example:
-/uyprogram
‘The “dot-slash” prefix tells the GNU shell to look in the cument ditectory for the executable.
‘You usually do not need to type ‘./? in front of commands for programs that: came with
your GNU system, such as emacs, because the computer already knows where to look for
‘the executables of those programs, which were placed in special directories when your GNU
system was installed.
A Cpregram is made up of, among other components, variables and fianctions. A variable
is a way to hold some data which may vary, hence the name, For example, a variable might
hold the mmber 17, and later the mumiber 41, Another variable might hold the word “Sue”.
‘A finetion is a segment of text in the soume code of a program that tells the computer
what to do. Programming consists, in large part, of writing functions.4 Chapter 2: Using a compiler
2.2 The compiler
When you compile a program, the compiler usually operates
phases called passes. The sequence happens approximately like this:
an orderly sequence of
1. First, the compiler reads the source code, perhaps generating an intermediate code
(such as pseudo-code) that simplifies the source code for subsequent processing,
2. Next, the compiler converts the intermediate code (if there is any) or the original
source code into an object code file, which contains machine language but is not yet
executable. The compiler builds a separate object file for each source file. These are
only temporary and are deleted by the compiler after compilation.
3. Finally, the compiler runs a linker. The linker merges the newly-created object code
with some standard, built-in object code to produce an executable file that can stand
alone.
GNU environments use a simple command to invoke the C compiler: gee, which stands for
“GNU Compiler Collection”. (It used to stand for “GNU C Compiler”, but now GCC ean
compile many more languages than just C.) Thus, to compile a small program, you will
usually type something like the following command:
gee filename
On GNU systems, this results in the creation of an executable program with the default
name ‘a.out’. To tell the compiler you would like the executable program to be called
something else, use the ‘-o’ option for setting the name of the object code:
gee -o program-name filename
For example, to create a program called ‘myprog’ from a file called ‘myprog.c’, write
gee -o myprog myprog.c
‘To launch the resulting program ‘nyprog’ from the same directory, type
-/myprog,
2.3 File names
GCC uses the following file name conventions:
Source code file rogram.name.