C程序设计语言(第2版•新版)(英文版)
在计算机发展的历史上,没有哪一种程序设计语言像C语言这样应用广泛。本书原著即为C语言的设计者之一Dennis M.Ritchie和著名计算机科学家Brian W.Kernighan合著的一本介绍C语言的权威经典著作。我们现在见到的大量论述C语言程序设计的教材和专著均以此书为蓝本。原著第1版中介绍的C语言成为后来广泛使用的C语言版本——标准C的基础。人们熟知的“hello,World"程序就是由本书首次引入的,现在,这一程序已经成为众多程序设计语言入门的第一课。原著第2版根据1987年制定的ANSIC标准做了适当的修订.引入了最新的语言形式,并增加了新的示例,通过简洁的描述、典型的示例,作者4.11.1 File inclusion794.11.2 Macro Substitution804.11.3 Conditional Inclusion82Chapter5- Pointers and arrays……………………,…,,……,………………835.1 Pointers and ddresses835.2 Pointers and Function Arguments845.3 Pointers and arrays875.4 Address arithmetic905.5 Character pointers and functions………935.6 Pointer Arrays; Pointers to Pointers965.7 Multi-dimensional Arrays5.8 Initialization of Pointer Arrays.....................................1015.9 Pointers vs. Multi-dimensional arrays..................................1015.10 Command-line Arguments ...............................................1025.11 Pointers to functions1065.12 Complicated Declarations. .........108Chapter 6- structures1146.1 Basics of structures番垂。垂看4垂非垂。音番·.垂垂·看看垂1146.2 Structures and functions1166.3 Arrays of Structures1186. 4 Pointers to structures垂·垂·看。音;4,1226.5 Self-referential structures1246.6 Table Lookup..........1276.7 Typedef.1296.8 Unions…1316.9 Bit-fields132Chapter 7-Input and Output...1357. 1 Standard Input and output. .....................................1357.2 Formatted Output-printf1377.3 Variable-length Argument Lists··.····387.4 Formatted Input- Scanf.1407.5 Filc access∴·····14276 Error Handling-Stderr and Exit………………………1457.7 Line Input and output....……,,………………………………1467. 8 Miscellaneous Functions1477.8.1 String Opcrations1477.8.2 Character Class Testing and conversion1487.8.3 Ungetc…1487.8.4 Command Execution1487.8.5 Storage Management1487.8.6 Mathematical functions1497.8.7 Random number generation·····4149Chapter8- The UNIX System Interface.……,…15181 File descriptors………151528.3 Open, Creat, Close, Unlink1538.4 Random access - Lseek ..............................................................................................1558.5 Example- An implementation of Fopen and8.6 Example-Listing Directories1598.7 Example-A Storage Allocator·:··::163ppendix a - refereArence manual.168A 1 Introduction168A,2 Lexical conventions看垂音垂音4168A. 2. 1 Tokens..168A.2.2 Comments..wwwwwwmwwwwwwww 168A. 2. 3 Identifiers168A 2.4 Kevwords169A 2.5 Constants169A 2.6 String Literals171A.3 Syntax Notation………,…,…,…,…,…,…,…,…,…,…,……………………,171A 4 Meaning of Identifiers171A.4.1 Storage Class..17A.4.2 Basic Types172A.4.3 Derived types…………,…,,…,…,…,…,,…,……,………………………,173A.4.4 Type qualifiers…………….……………………………………173A. 5 Objects and lvalues……173A 6 Conversions173A.6.1 Integral Promotion174A.6.2 Integral Conversions.............................174A.6.3 Integer and Floating..…174A.6.4 Floating Typcs174A 6.5 Arithmetic Conversions…174A.6.6 Pointers and Integers…………………175A 6.7 Void176A 6. 8 Pointers to Void176A7 Expressions...........................176A 7.1 Pointer Conversion……177A 7.2 Primary Expressions177A. 7. 3 Postfix Expressions177A. 7. 4 Unary Operators179A.7.5 Casts181A.7.6 Multiplicative Operators181A.7.7 Additive Operators………182A.7.& Shift Opcrators182A 7.9 Relational Operators183A.7.10 Equality Operators.……183A.7.11 Bitwise AND Operator.……,…,…,…,…,…,……………183A7 12 Bitwise ExclusiVe OR Opcrator184A 7.13 Bitwise Inclusive OR Operator184A.7.14 Logical AND Operator…...……,…,….,………………………………184A.7.15 Logical OR Operator…..,.,…,…,,…,,,…….…184A 7 16 Conditional operato184A7.7 Assignment Expressions……185A 7.18 Comma Operator185A.7.19 Constant Expressions.........................................186A 8 Declarations186A.8.1 Storagc Class Spccificrs187A 8.2 Type Specif188A.8.3 Structure and union declarations,……18A 8.4 Enumerations191A.8.5 Declarators192A.8.6 Meaning of Declarators193A 8.7 Initialization196A.8.8 Type names………198A.8.9 Typedef.…,…,……,…,…,…,…,,…,………………………………………………19A 8.10 Type equivalenceA 9 Statements199A.9.1 Labeled Statements.A.9.2 Expression Statement.200A.9.3 Compound Statement200A 9.4 Selection statements··-201A.9.5 Iteration statements….……………,…,201A.9.6 Jump statements……,……………………………………202A 10 External declarations….………………203A 10.1 Function Definitions203A.10.2 External declaration5……204A.11 Scope and Linkage,,.,.,,,,………205A. 11. 1 Lexical Scope205A 11.2 Linkage.206A.12 Preprocessing………206A.12.1 Trigraph Sequences…………....…………...….…………207A.12.2 Line splicing……………………………………207A 12.3 Macro Dcfinition and Expansion207A 12.4 File inclusion00A 12.5 Conditional Compilation.............. 210A.12.6 Line control∴.……211A 12. 7 Error Generation211A 12.8 Pragmas翻D音音音212A 12.9 Null directive…212A. 12.10 Predefined names ..........................................................................................212grammar212Appendix b-standard library·..··.·+········220B. 1 Input and Output: ..220B.1.1 File operations....,.,.,,,,,,,,…,,……,220B 1.2 Formatted Output......222B 1.3 Formatted Input223B 1.4 Character Input and output functions音看番音番25B.1.5 Direct Input and Output Functions……………,.….……………………………25B.1.6 File positioning Functions…...,.,,,,,,,,……,…26B. 1. 7 Error Functions226B2 Character Class Tests: 226B.3 String Functions:< string.h>…,………………,27B 4 Mathematical FunctionsB 5 Utility Functions: 229B 6 Diagnostics: ..231B8 Non-local Jumps: B7 Variable Argument Lists: ·····4231.···232B9 Signals: 233B 11 Implementation-defined limits: and 234Appendix c -Summary of Changes…………236PrefaceThe computing world has undergone a revolution since the publication of The cProgramming Language in 1978. Big computers arc much bigger, and personal computershave capabilities that rival mainframes of a decade ago. During this time, C has changed tooalthough only modestly, and it has spread far beyond its origins as the language of the UNIXoperating system.The growing popularity of C, the changes in the language over the years, and the creation ofcompilers by groups not involved in its design, combined to demonstrate a need for a moreprecise and more contemporary definition of the language than the first edition of this bookprovided. In 1983, the American National Standards Institute(ANSD) established a committeewhose goal was to produce an unambiguous and machine-independent definition of thelanguage C", while still retaining its spirit. The result is the ANSi standard for CThe standard formalizes constructions that were hinted but not described in the first editionparticularly structure assignment and enumerations. It provides a new form of functiondeclaration that permits cross-checking of definition with use. It specifies a standard librarywith an extensive set of functions for performing input and output, memory managementstring manipulation, and similar tasks. It makes precise the behavior of features that were notspelled out in the original definition, and at the same time states explicitly which aspects ofthe language remain machine-dependentThis Second Edition of The C Programming Language describes C as defined by the ANSIstandard. Although we have noted the places where the language has evolved we have chosento write exclusively in the new form. For the most part, this makes no significant differencethe most visible change is the new form of function declaration and definition. Moderncompilers already support most features of the standardWe have tried to retain the brevity of the first edition. C is not a big language, and it is notwcll served by a big book. Wc have improved the exposition of critical fcaturcs, such aspointers, that are central to C programming. We have refined the original examples, and haveadded new examples in several chapters. For instance, the treatment of complicateddeclarations is augmented by programs that convert declarations into words and vice versaAs before, all cxamples have bccn tested directly from the text, which is in machinc-rcadablcformppendix A, the reference manual, is not the standard, but our attempt to convey theessentials of the standard in a smaller space. It is meant for easy comprehension byprogrammers, but not as a definition for compiler writers-- that role properly belongs to thestandard itself. Appendix b is a summary of the facilities of the standard library. It too ismeant for reference by programmers, not implementers Appendix C is a concise summary ofthe changes from the original versionAs we said in the preface to the first edition, C wears well as one's experience with itgrows".With a decade more experience, we still feel that way. We hope that this book willhelp you learn C and use it welWe are deeply indebted to friends who helped us to produce this second edition. Jon bently,Doug Gwyn, Doug Mcllroy, Peter Nelson, and rob pike gave us perceptive comments onalmost every page of draft manuscripts. We are grateful for careful reading by Al Aho, DennisAllison, Joe Campbell, G.R. Emlin, Karen Fortgang, Allen Holub, Andrew Hume, DaveKristol, John Linderman, Dave Prosser, Gene Spafford, and Chris van Wyk. We also receivedhelpful suggestions from Bill Cheswick, Mark Kernighan, Andy Koenig, Robin Lake, TomLondon, Jim Reeds, Clovis Tondo, and Peter Weinberger. Dave Prosser answered manydetailed questions about the ANSI standard. We used Bjarne Stroustrup's C++ translatorextensively for local testing of our programs, and dave Kristol provided us with an ANSI Ccompiler for final testing. Rich Drechsler helped greatly with typesettingOur sincere thanks to allBrian w. KernighanDennis m. ritchiePreface to the first editionC is a general-purpose programming language with features economy of expression, modernflow control and data structures, and a rich sct of operators c is not a vcry high level"language, nor a big"one, and is not specialized to any particular area of application. But itsabsence of restrictions and its generality make it more convenient and effective for manytasks than supposedly more powerful languagesC was originally designed for and implemented on the uNiX operating system on the dECPDP-ll, by Dennis ritchie. The operating system, the C compiler, and essentially all UNIXapplications programs(including all of the software used to prepare this book)are written inC. Production compilers also exist for several other machines, including the IBM System/370the Honeywell 6000, and the Interdata 8/32. C is not tied to any particular hardware orsystem, however, and it is easy to write programs that will run without change on anymachine that supports C.This book is mcant to help the reader learn how to program in C. It contains a tutorialintroduction to get new users started as soon as possible, separate chapters on each majorfeature, and a reference manual. Most of the treatment is based on reading, writing andrevising examples, rather than on mere statements of rules. For the most part, the examplesare complete, real programs rather than isolated fragments. All examples have been testeddirectly from the text, which is in machine-readable form. Besides showing how to makeeffective use of the language, we have also tried where possible to illustrate useful algorithmsand principles of good style and sound designThe book is not an introductory programming manual; it assumes some familiarity with basicprogramming concepts like variables, assignment statements, loops, and functionsNonetheless, a novice programmer should be able to read along and pick up the languagealthough access to more knowledgeable colleague will helpIn our cxpcricncc, C has proven to bc a pleasant, expressive and versatile language for a widcvariety of programs. It is easy to learn, and it wears well as on's experience with it grows. Wehope that this book will help you to use it wellThe thoughtful criticisms and suggestions of many friends and colleagues have added greatlto this book and to our pleasure in writing it. In particular, Mike Bianchi, Jim Blue, StFeldman, Doug Mcllroy Bill Roome, Bob Rosin and Larry rosler all read multiple volumeswith care. We are also indebted to Al aho Steve bourne, Dan Dvorak, chuck Haley debbieHaley, Marion Harris, Rick Holt, Steve Johnson, John Mashey, Bob Mitze, Ralph MuhaPeter Nelson, Elliot Pinson, Bill Plauger, Jerry Spivack, Ken Thompson, and PeterWeinberger for helpful comments at various stages, and to Mile lesk and Joe Ossanna forinvaluable assistance with typesettingBrian w. KernighanDennis m. ritchieChapter 1-a Tutorial IntroductionLet us begin with a quick introduction in C. Our aim is to show the essential elements of thelanguage in rcal programs, but without getting bogged down in details, rulcs, and exceptionsAt this point, we are not trying to be complete or even precise(Save that the examples aremeant to be correct). We want to get you as quickly as possible to the point where you canwrite useful programs, and to do that we have to concentrate on the basics: variables andconstants, arithmetic, control flow, functions, and the rudiments of input and output. We arcintentionally leaving out of this chapter features of c that are important for writing biggerprograms. These include pointers, structures, most of Cs rich set of operators, several control-flow statements, and the standard libraryThis approach and its drawbacks. Most notable is that the complete story on any particularfeature is not found here, and the tutorial, by being brief, may also be misleading. Andbecause the examples do not use the full power of C, they are not as concise and elegant asthey might be. We have tried to minimize these effects, but be warned. Another drawback isthat latcr chapters will ncccssarily repeat somc of this chaptcr. We hope that the repetitionwill help you more than it annoysIn any case, experienced programmers should be able to extrapolate from the material in thischapter to their own programming needs. Beginners should supplement it by writing smallsimilar programs of their own. Both groups can use it as a framework on which to hang themore detailed descriptions that begin in Chapter 2.1.1 Getting StartedThe only way to learn a new programming language is by writing programs in it. The firstprogram to write is the samc for all languagesPrint the wordshello worlThis is a big hurdle to leap over it you have to be able to create the program text somewherecompile it successfully, load it, run it, and find out where your output went. With thescmechanical details mastered, everything else is comparativelyn C, the program to print hello, world"is#include printf("hello, world\n")iJust how to run this program depends on the system you are using. As a specific example, onthe unix operating system you must create the program in a file whose name ends in.csuch as hello. c, then compile it with the commandc hello10If you haven't botched anything, such as omitting a character or misspelling something, thecompilation will procced silently, and make an cxccutablc filc called a out. If you run acutby typing the commanda. outit will printhello, worldOn othcr systcms, thc rulcs will bc diffcrent; check with a local cxpcrtNow, for some explanations about the program itself. A C program, whatever its size, consistsof functions and variables. a function contains statements that specify the computingoperations to be done, and variables store values used during the computation. C functions arelike the subroutines and functions in Fortran or the procedures and functions of Pascal. Ourexample is a function named main. Normally you are at liberty to give functions whatevernames you like, but main"is special your program begins executing at the beginning ofmain. This means that every program must have a main somewherehain will usually call other functions to help perform its job, some that you wrote, and othersfrom libraries that are provided for you. The first line of the program+include tells the compiler to include information about the standard input/output library: the lineappears at the beginning of many C source files. The standard library is described in Chapter7 and Appendix bOne method of communicating data between functions is for the calling function to provide alist of values, called arguments, to the function it calls. The parentheses after the functionname surround the argument list. In this example, main is defined to be a function that expectsno arguments, which is indicated by the empty list(#include include information about standardlibrarymaindefine a function caiied mainthat received no argument valuestatements of main are enclosed in bracesprint=( hello, world\n")main calis library function printfto print this sequence of charactersAn represents the newline characterThe first C programThe statements of a function arc enclosed in braces ) The function main contains only oncstatementprintf("hello, world\n")i
用户评论