C Programming Tutorial - 4th Edition (K&R Version) (Pages 5-16) PDF
C Programming Tutorial - 4th Edition (K&R Version) (Pages 5-16) PDF
1 Introduction
C is called a high level, compiler language. The aim of any high level computer language is to provide an easy and natural way of giving a programme of instructions to a computer (a computer program). The language of the raw computer is a stream of numbers called machine code. As you might expect, the action which results from a single machine code instruction is very primitive and many thousands of them are required to make a program which does anything substantial. It is therefore the job of a high level language to provide a new set of black box instructions, which can be given to the computer without us needing to see what happens inside them and it is the job of a compiler to ll in the details of these "black boxes"
Chapter 1: Introduction
so that the nal product is a sequence of instructions in the language of the computer.
C is one of a large number of high level languages which can be used for general purpose programming, that is, anything from writing small programs for personal amusement to writing complex applications. It is unusual in several ways. Before C, high level languages were criticized by machine code programmers because they shielded the user from the working details of the computer, with their black box approach, to such an extent that the languages become inexible: in other words, they did not not allow programmers to use all the facilities which the machine has to oer. C, on the other hand, was designed to give access to any level of the machine down
to raw machine code and because of this it is perhaps the most exible of all high level languages.
Surprisingly, programming books often ignore an important role of high level languages: high level programs are not only a way to express instructions to the computer, they are also a means of communication among human beings. They are not merely monologues to the machine, they are a way to express ideas and a way to solve problems. The C language has been equipped with features that allow programs to be organized in an easy and logical way. This is vitally important for writing lengthy programs because complex problems are only manageable with a clear organization and program structure. C allows meaningful variable names and meaningful function names to be used in programs without any loss of eciency and it gives a complete freedom of style; it has a set of very exible loop construc-
Chapter 1: Introduction
tions (for, while, do) and neat ways of making decisions. These provide an excellent basis for controlling the ow of programs.
Another unusual feature of C is the way it can express ideas concisely. The richness of a language shapes what it can talk about. C gives us the apparatus to build neat and compact programs. This sounds, rst of all, either like a great bonus or something a bit suspect. Its conciseness can be a mixed blessing: the aim is to try to seek a balance between the often conicting interests of readability of programs and their conciseness. Because
The Compiler
this side of programming is so often presumed to be understood, we shall try to develop a style which nds the right balance. C allows things which are disallowed in other languages: this is no defect, but a very powerful freedom which, when used with caution, opens up possibilities enormously. It does mean however that there are aspects of C which can run away with themselves unless some care is taken. The programmer carries an extra responsibility to write a careful and thoughtful program. The reward for this care is that fast, ecient programs can be produced. C tries to make the best of a computer by linking as closely as possible to the local environment. It is no longer necessary to have to put up with hopelessly inadequate input/output facilities anymore (a legacy of the timesharing/mainframe computer era): one can use everything that a computer has to oer. Above all it is exible. Clearly no language can guarantee intrinsically good programs: there is always a responsibility on the programmer, personally, to ensure that a program is neat, logical and well organized, but it can give a framework in which it is easy to do so. The aim of this book is to convey some of the C philosophy in a practical way and to provide a comprehensive introduction to the language by appealing to a number of examples and by sticking to a strict structuring scheme. It is hoped that this will give a avour of the kind of programming which C encourages.
Chapter 1: Introduction
The Compiler
shall see later, this approach provides a exible way of compiling programs which are split into many les.
Chapter 1: Introduction Phase 1 scans a source program, perhaps generating an intermediate code (quadruples or pcode) which helps to simplify the grammar of the language for subsequent processing. It then converts the intermediate code into a le of object code (though this is usually not executable yet). A separate object le is built for each separate source le. In the GNU C compiler, these two stages are run with the command gcc -c; the output is one or more .o les. Phase 2 is a Linker. This program appends standard library code to the object le so that the code is complete and can "stand alone". A C compiler linker suers the slightly arduous task of linking together all the functions in the C program. Even at this stage, the compiler can fail, if it nds that it has a reference to a function which does not exist. With the GNU C compiler this stage is activated by the command gcc -o or ld.
To avoid the irritation of typing two or three separate commands (which are often cumbersome) you will normally nd a simple interface for executing compiler. Traditionally this is an executable program called cc for C Compiler: cc filename gcc filename On GNU systems, this results in the creation of an executable program with the default name a.out. To tell the compiler what you would like the executable program to be called, use the -o option for setting the name of the object code: gcc -o program-name filname For example, to create a program called myprog from a le called myprog.c, write gcc -o myprog myprog.c
1.4 Errors
Errors are mistakes which we the programmers make. There are dierent kinds of error: Syntax Errors in the syntax, or word structure of a program are caught before you run it, at compilation time by the compiler program. They are listed all in one go, with the line number, in the text le, at which the error occurred and a message to say what was wrong. For example, suppose you write sin (x) y = ; in a program instead of y = sin (x);, which assigns the value of the sin of x to y. Upon compilation, you would see this error message:
eg.c: In function main: eg.c:12: parse error before y (If you compile the program in Emacs, you can jump directly to the error.) A program with syntax errors will cause a compiler program to stop trying to generate machine code and will not create an executable. However, a compiler will usually not stop at the rst error it encounters but will attempt to continue checking the syntax of a program right to the last line before aborting, and it is common to submit a program for compilation only to receive a long and ungratifying list of errors from the compiler. It is a shock to everyone using a compiler for the rst time how a single error can throw the compiler o course and result in a huge and confusing list of non-existent errors, following a single true culprit. The situation thus looks much worse than it really is. Youll get used to this with experience, but it can be very disheartening. As a rule, look for the rst error, x that, and then recompile. Of course, after you have become experienced, you will recognize when subsequent error messages are due to independent problems and when they are due to a cascade. But at the beginning, just look for and x the rst error. Intention Errors in goal or purpose (logical errors) occur when you write a program that works, but does not do what you intend it to do. You intend to send a letter to all drivers whose licenses will expire soon; instead, you send a letter to all drivers whose licenses will expire sometime. If the compilation of a program is successful, then a new le is created. This le will contain machine code which can be executed according to the rules of the computers local operating system. When a programmer wants to make alterations and corrections to a C program, these have to be made in the source text le itself using an editor; the program, or the salient parts, must then be recompiled.
10
Chapter 1: Introduction
typed in the wrong case, the compiler will complain and it will not produce an executable program.
1.6 Declarations
Compiler languages require us to make a list of the names and types of all variables which are going to be used in a program and provide information about where they are going to be used. This is called declaring variables. It serves two purposes: rstly, it provides the compiler with a denitive list of the variables, enabling it to cross check for errors, and secondly, it informs the compiler how much space must be reserved for each variable when the program is run. C supports a variety of variable types (variables which hold dierent kinds of data) and allows one type to be converted into another. Consequently, the type of a variable is of great importance to the compiler. If you fail to declare a variable, or declare it to be the wrong type, you will see a compilation error.
1.7 Questions
1. 2. 3. 4. 5. What is a compiler? How is a C program run? How is a C program compiled usually? Are upper and lower case equivalent in C? What the two dierent kinds of error which can be in a program?
Example Listing
11
Text is easy, but we also want to be able to print out the contents of variables. These can be inserted into a text string by using a control sequence inside the quotes and listing the variables after the string which get inserted into the string in place of the control sequence. To print out an integer, the control sequence %d is used:
printf ("Integer = %d",someinteger);
The variable someinteger is printed instead of %d. The printf function is described in full detail in the relevant chapter, but well need it in many places before that. The example program below is a complete program. If you are reading this in Info, you can copy this to a le, compile and execute it.
12
("Astronomy is %dderful \n",1); ("And interesting %d \n",2); ("The ear%d volves around the sun \n",3); ("And makes a year %d you \n",4); ("The moon affects the sur %d heard \n",5); ("By law of phy%d great \n",6); ("It %d when the the stars so bright \n",7); ("Do nightly scintill%d \n",8); ("If watchful providence be%d \n",9); ("With good intentions fraught \n"); ("Should not keep up her watch divine \n"); ("We soon should come to %d \n",0);
2.3 Output
Astronomy is 1derful \n" And interesting 2 The ear3 volves around the sun And makes a year 4 you The moon affects the sur 5 heard By law of phy6d great It 7 when the the stars so bright Do nightly scintill8 If watchful providence be9 With good intentions fraught Should not keep up her watch divine We soon should come to 0
2.4 Questions
1. 2. 3. 4. Write a command to print out the message "Wow big deal". Write a command to print out the number 22? Write two commands to print out "The 3 Wise Men" two dierent ways. Why are there only a few reserved command words in C?