




























































































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!





























































































(^1) Conversion to LaTeX by Ward van Wanrooij. Any layout issues are caused by
my conversion script and do not reflect on the authors. Also available on-line at http://publications.gbdirect.co.uk/c_book/
This book was written with two groups of readers in mind. Whether you are new to C and want to learn it, or already know the older version of the language but want to find out more about the new standard, we hope that you will find what follows both instructive and at times entertaining too. This is not a tutorial introduction to programming. The book is designed for programmers who already have some experience of using a modern high- level procedural programming language. As we explain later, C isn’t really appropriate for complete beginners–though many have managed to use it– so the book will assume that its readers have already done battle with the notions of statements, variables, conditional execution, arrays, procedures (or subroutines) and so on. Instead of wasting your time by ploughing through tedious descriptions of how to add two numbers together and explaining that the symbol for multiplication is *, the book concentrates on the things that are special to C. In particular, it’s the way that C is used which is emphasized. Those who already know C will be interested in the new Standard and how it affects existing C programs. The effect on existing programs might not at first seem to be important to newcomers, but in fact the ‘old’ and new versions of the language are an issue for the beginner too. For some years after the approval of the Standard, programmers will have to live in a world where they can easily encounter a mixture of both the new and the old language, depending on the age of the programs that they are working with. For that reason, the book highlights where the old and new features differ significantly. Some of the old features are no ornament to the language and are well worth avoiding; the Standard goes so far as to consider them obsolescent and recommends that they should not be used. For that reason they are not described in detail, but only far enough to allow a reader to understand what they mean. Anybody who intends to write programs using these old-style features should be reading a different book. This is the second edition of the book, which has been revised to refer to the
final, approved version of the Standard. The first edition of the book was based on a draft of the Standard which did contain some differences from the draft that was eventually approved. During the revision we have taken the opportunity to include more summary material and an extra chapter illustrating the use of C and the Standard Library to solve a number of small problems.
The Success of C
C is a remarkable language. Designed originally by one man, Dennis Ritchie, working at AT&T Bell Laboratories in New Jersey, it has increased in use until now it may well be one of the most widely-written computer languages in the world. The success of C is due to a number of factors, none of them key, but all of them important. Perhaps the most significant of all is that C was developed by real practioners of programming and was designed for practical day-to-day use, not for show or for demonstration. Like any well-designed tool, it falls easily to the hand and feels good to use. Instead of providing constraints, checks and rigorous boundaries, it concentrates on providing you with power and on not getting in your way. Because of this, it’s better for professionals than beginners. In the early stages of learning to program you need a protective environment that gives feedback on mistakes and helps you to get results quickly–programs that run, even if they don’t do what you meant. C is not like that! A professional forester would use a chain-saw to cut down trees quickly, aware of the dangers of touching the blade when the machine is running; C programmers work in a similar way. Although modern C compilers do provide a limited amount of feedback when they notice something that is out of the ordinary, you almost always have the option of forcing the compiler to do what you said you wanted and to stop it from complaining. Provided that what you said you wanted was what you really did want, then you’ll get the result you expected. Programming in C is like eating red meat and drinking strong rum except your arteries and liver are more likely to survive it. Not only is C popular and a powerful asset in the armoury of the serious day-to-day programmer, there are other reasons for the success of this lan- guage. It has always been associated with the UNIX operating system and has benefited from the increasing popularity of that system. Although it is not the obvious first choice for writing large commercial data processing applications, C has the great advantage of always being available on com- mercial UNIX implementations. UNIX is written in C, so whenever UNIX is implemented on a new type of hardware, getting a C compiler to work for
you do want, or bypass it altogether.
Standards
Remarkably, C achieved its success in the absence of a formal standard. Even more remarkable is that during this period of increasingly widespread use, there has never been any serious divergence of C into the number of dialects that has been the bane of, for example, BASIC. In fact, this is not so surprising. There has always been a “language reference manual”, the widely-known book written by Brian Kernighan and Dennis Ritchie, usually referred to as simply “K&R”. The C Programming Language, B.W. Kernighan and D. M. Ritchie, Prentice-Hall Englewood Cliffs, New Jersey, 1978 Further acting as a rigorous check on the expansion into numerous dialects, on UNIX systems there was only ever really one compiler for C; the so-called “Portable C Compiler”, originally written by Steve Johnson. This acted as a reference implementation for C–if the K&R reference was a bit obscure then the behaviour of the UNIX compiler was taken as the definition of the language. Despite this almost ideal situation (a reference manual and a reference im- plementation are extremely good ways of achieving stability at a very low cost), the increasing number of alternative implementations of C to be found in the PC world did begin to threaten the stability of the language. The X3J11 committee of the American National Standards Institute started work in the early 1980’s to produce a formal standard for C. The committee took as its reference the K&R definition and began its lengthy and painstak- ing work. The job was to try to eliminate ambiguities, to define the unde- fined, to fix the most annoying deficiencies of the language and to preserve the spirit of C–all this as well as providing as much compatibility with exist- ing practice as was possible. Fortunately, nearly all of the developers of the competing versions of C were represented on the committee, which in itself acted as a strong force for convergence right from the beginning. Development of the Standard took a long time, as standards often do. Much of the work is not just technical, although that is a very time-consuming part of the job, but also procedural. It’s easy to underrate the procedural aspects of standards work, as if it somehow dilutes the purity of the technical
work, but in fact it is equally important. A standard that has no agreement or consensus in the industry is unlikely to be widely adopted and could be useless or even damaging. The painstaking work of obtaining consensus among committee members is critical to the success of a practical standard, even if at times it means compromising on technical “perfection”, whatever that might be. It is a democratic process, open to all, which occasionally results in aberrations just as much as can excessive indulgence by technical purists, and unfortunately the delivery date of the Standard was affected at the last moment by procedural, rather than technical issues. The technical work was completed by December 1988, but it took a further year to resolve procedural objections. Finally, approval to release the document as a formal American National Standard was given on December 7th, 1989.
Hosted and Free-Standing Environments
The dependency on the use of libraries to extend the language has an impor- tant effect on the practical use of C. Not only are the Standard I/O Library functions important to applications programmers, but there are a number of other functions that are widely taken almost for granted as being part of the language. String handling, sorting and comparison, character manipulation and similar services are invariably expected in all but the most specialized of applications areas. Because of this unusually heavy dependency on libraries to do real work, it was most important that the Standard provided comprehensive definitions for the supporting functions too. The situation with the library functions was much more complicated than the relatively simple job of providing a tight definition for the language itself, because the library can be extended or modified by a knowledgeable user and was only partially defined in K&R. In practice, this led to numerous similar but different implementations of supporting libraries in common use. By far the hardest part of the work of the Committee was to reach a good definition of the library support that should be provided. In terms of benefit to the final user of C, it is this work that will prove to be by far and away the most valuable part of the Standard. However, not all C programs are used for the same type of applications. The Standard Library is useful for ‘data processing’ types of applications, where file I/O and numeric and string oriented data are widely used. There is an equally important application area for C–the ‘embedded system’ area–which includes such things as process control, real-time and similar applications. The Standard knows this and provides for it. A large part of the Standard is the definition of the library functions that must be supplied for hosted
inclined, you could read the book as far as you like and stop, yet still have learnt a reasonably coherent subset of the language. Previous experience of C will render Chapter 1 a bit slow, but it is still worth persevering with it, if only once.
Example programs
All but the smallest of the examples shown in the text have been tested using a compiler that claims to conform to the Standard. As a result, most of them stand a good chance of being correct, unless our interpretation of the Standard was wrong and the compiler developer made the same mistake. None the less, experience warns that despite careful checking, some errors are bound to creep in. Please be understanding with any errors that you may find.
Deference to Higher Authority
This book is an attempt to produce a readable and enlightening description of the language defined by the Standard. It sets out to to make interpretations of what the Standard actually means but to express them in ‘simpler’ English. We’ve done our best to get it right, but you must never forget that the only place that the language is fully defined is in the Standard itself. It is entirely possible that what we interpret the Standard to mean is at times not what the Standard Committee sought to specify, or that the way we explain it is looser and less precise than it is in the Standard. If you are in any doubt: READ THE STANDARD! It’s not meant to be read for pleasure, but it is meant to be accurate and unambiguous; look nowhere else for the authoritative last word.
Address for the Standard
Copies of the Standard can be obtained from: X3 Secretariat, CBEMA, 311 First Street, NW, Suite 500, Washington DC 20001-2178, USA. Phone (+1) (202) 737 8888
Mike Banahan
Declan Brady
Mark Doran
January 1991
Figure 1.1: Diagram showing multiple files going from source, through com- pilation, to object files, and being combined with libraries by the loader to produce a program.
relatively inexpensive. The expansion of the idea to arrange for the loader to scan libraries of object modules, and select the ones that are needed, is an obvious one. The benefit is that if you change one small part of a program then the expense of recompiling all of it may be avoided; only the module that was affected has to be recompiled. All, the same, it’s true that the more work put on to the loader, the slower it becomes, in fact sometimes it can be the slowest and most resource consuming part of the whole procedure. It is possible that, for some systems, it would be quicker to recompile everything in one go than to have to use the loader: Ada has sometimes been quoted as an example of this effect occurring. For C, the work that has to be done by the loader is not large and the approach is a sensible one. Figure 1.1 shows the way that this works.
Figure 1.1. Separate compilation
This technique is important in C, where it is common to find all but the smallest of programs constructed from a number of separate source files. Furthermore, the extensive use that C makes of libraries means that even trivial programs pass through the loader, although that might not be obvious at the first glance or to the newcomer.
1.2 Functions
A C program is built up from a collection of items such as functions and what we could loosely call global variables. All of these things are given names at the point where they are defined in the program; the way that the names are used to access those items from a given place in the program is
governed by rules. The rules are described in the Standard using the term linkage. For the moment we only need to concern ourselves with external linkage and no linkage. Items with external linkage are those that are accessible throughout the program (library functions are a good example); items with no linkage are also widely used but their accessibility is much more restricted. Variables used inside functions are usually ‘local’ to the function; they have no linkage. Although this book avoids the use of complicated terms like those where it can, sometimes there isn’t a plainer way of saying things. Linkage is a term that you are going to become familiar with later. The only external linkage that we will see for a while will be when we are using functions. Functions are C’s equivalents of the functions and subroutines in FORTRAN, functions and procedures in Pascal and ALGOL. Neither BASIC in most of its simple mutations, nor COBOL has much like C’s functions. The idea of a function is, of course, to allow you to encapsulate one idea or operation, give it a name, then to call that operation from various parts of the rest of your program simply by using the name. The detail of what is going on is not immediately visible at the point of use, nor should it be. In well designed, properly structured programs, it should be possible to change the way that a function does its job (as long as the job itself doesn’t change) with no effect on the rest of the program. In a hosted environment there is one function whose name is special; it’s the one called main. This function is the first one entered when your program starts running. In a freestanding environment the way that a program starts up is implementation defined; a term which means that although the Standard doesn’t specify what must happen, the actual behaviour must be consistent and documented. When the program leaves the main function, the whole program comes to an end. Here’s a simple program containing two functions:
#include <stdio.h>
/*
*/
void show_message(void); /*