Transcription of ebook - The C Programming Language Ritchie & kernighan
1 To the first 1 - A Tutorial Getting Variables and Arithmetic The for Symbolic Character Input and File Character Line Word Arguments - Call by Character External Variables and 2 - Types, Operators and Variable Data Types and Arithmetic Relational and Logical Type Increment and Decrement Bitwise Assignment Operators and Conditional Precedence and Order of 3 - Control Statements and Loops - While and Loops - Break and Goto and 4 - Functions and Program Basics of Functions Returning External Scope Header Static Register Block The C File Macro Conditional 5 - Pointers and Pointers and Pointers and Function Pointers and Address Character Pointers and Pointer Arrays; Pointers to Multi-dimensional Initialization of Pointer Pointers vs.
2 Multi-dimensional Command-line Pointers to Complicated 6 - Basics of Structures and Arrays of Pointers to Self-referential Table 7 - Input and Standard Input and Formatted Output - Variable-length Argument Formatted Input - File Error Handling - Stderr and Line Input and Miscellaneous String Character Class Testing and Command Storage Mathematical Random Number 8 - The UNIX System File Low Level I/O - Read and Open, Creat, Close, Random Access - Example - An implementation of Fopen and Example - Listing Example - A Storage A - Reference Lexical String Syntax Meaning of Storage Basic Derived Type Objects and Integral Integral Integer and Floating Arithmetic Pointers and Pointers to Pointer Primary Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise Exclusive OR Bitwise Inclusive OR Logical AND Logical OR Conditional Assignment Comma Constant Storage Class Type Structure and Union Meaning of Type Type Labeled Expression Compound Selection Iteration Jump External Function External Scope and
3 Lexical Trigraph Line Macro Definition and File Conditional Line Error Null Predefined B - Standard Input and Output: < >.. File Formatted Formatted Character Input and Output Direct Input and Output File Positioning Error Character Class Tests: < >.. String Functions: < >.. Mathematical Functions: < >.. Utility Functions: < >.. Diagnostics: < >.. Variable Argument Lists: < >.. Non-local Jumps: < >.. Signals: < >.. Date and Time Functions: < >.. Implementation-defined Limits: < > and < >..212 Appendix C - Summary of , ,Chaschangedtoo,althoughonlymodestly,and ithasspreadfarbeyonditsoriginsasthelangu ageoftheUNIX operatingsystem. ThegrowingpopularityofC,thechangesinthel anguageovertheyears,andthecreationofcomp ilersbygroupsnotinvolvedinitsdesign, ,theAmericanNationalStandardsInstitute(A NSI)establishedacommitteewhosegoalwastop roduce``anunambiguousandmachine-independ entdefinitionofthelanguage C'', while still retaining its spirit.
4 The result is the ANSI standard for C. Thestandardformalizesconstructionsthatwe rehintedbutnotdescribedinthefirstedition , ,withanextensivesetoffunctionsforperform inginputandoutput,memorymanagement,strin gmanipulation, ,andatthesametimestatesexplicitlywhichas pectsofthelanguage remain machine-dependent. , ,thismakesnosignificantdifference; already support most features of the standard. , ,suchaspointers,that are central to C Programming . We have refined the original examples, and have added , ,allexamples have been tested directly from the text, which is in machine-readable form. AppendixA,thereferencemanual,isnotthesta ndard, , , version. Aswesaidintheprefacetothefirstedition,C` `wearswellasone'sexperiencewithitgrows'' .Withadecademoreexperience, C and use it well.
5 ,DougGwyn,DougMcIlroy,PeterNelson, ,DennisAllison,JoeCampbell, ,KarenFortgang,AllenHolub,AndrewHume,Dav eKristol,JohnLinderman,DaveProsser,GeneS pafford, ,MarkKernighan,AndyKoenig,RobinLake,Tom7 London,JimReeds,ClovisTondo, 'sC++translatorextensivelyforlocaltestin gofourprograms,andDaveKristolprovidedusw ithanANSIC compiler for final testing. Rich Drechsler helped greatly with typesetting. Our sincere thanks to all. Brian W. KernighanDennis M. Ritchie 8 Preface to the first editionCisageneral-purposeprogramminglan guagewithfeatureseconomyofexpression,mod ernflowcontrolanddatastructures, ``veryhighlevel'' Language ,nora``big''one , supposedly more powerful languages. Cwasoriginallydesignedforandimplementedo ntheUNIX operatingsystemontheDECPDP-11, ,theCcompiler,andessentiallyallUNIX applicationsprograms(includingalloftheso ftwareusedtopreparethisbook) ,includingtheIBMS ystem/370,theHoneywell6000,andtheInterda ta8 ,however,anditiseasytowriteprogramsthatw illrunwithoutchangeonanymachinethatsuppo rts C.
6 ,separatechaptersoneachmajorfeature, ,writingandrevisingexamples, ,theexamplesarecomplete, , ,wehavealsotriedwherepossibletoillustrat eusefulalgorithmsandprinciplesof good style and sound design. Thebookisnotanintroductoryprogrammingman ual;itassumessomefamiliaritywithbasicpro grammingconceptslikevariables,assignment statements,loops, ,anoviceprogrammershouldbeabletoreadalon gandpickupthelanguage,although access to more knowledgeable colleague will help. Inourexperience,Chasproventobeapleasant, ,anditwearswellason' that this book will help you to use it well. The thoughtful criticisms and suggestions of many friends and colleagues have added greatly ,MikeBianchi,JimBlue,StuFeldman,DougMcIl royBillRoome, ,SteveBourne,DanDvorak,ChuckHaley,Debbie Haley,MarionHarris,RickHolt,SteveJohnson ,JohnMashey,BobMitze,RalphMuha,PeterNels on,ElliotPinson,BillPlauger,JerrySpivack ,KenThompson,andPeterWeinbergerforhelpfu lcommentsatvariousstages,andtoMileLeskan dJoeOssannaforinvaluableassistance with typesetting.
7 Brian W. KernighanDennis M. Ritchie 9 Chapter 1 - A Tutorial ,butwithoutgettingboggeddownindetails,ru les, ,wearenottryingtobecompleteorevenprecise (savethattheexamplesaremeanttobecorrect) .Wewanttogetyouasquicklyaspossibletothep ointwhereyoucanwriteusefulprograms,andto dothatwehavetoconcentrateonthebasics:var iablesandconstants,arithmetic,controlflo w,functions, ,structures,mostofC'srichsetofoperators, severalcontrol-flow statements, and the standard library. ,andthetutorial,bybeingbrief, , , than it annoys. Inanycase, , detailed descriptions that begin in Chapter 2. Getting StartedThe only way to learn a new Programming Language is by writing programs in it. The firstprogram to write is the same for all languages: Print the words hello, world Thisisabighurdle;toleapoverityouhavetobe abletocreatetheprogramtextsomewhere,comp ileitsuccessfully,loadit,runit, details mastered, everything else is comparatively easy.
8 In C, the program to print ``hello, world'' is #include < > main() { printf("hello, world\n"); } ,ontheUNIX operatingsystemyoumustcreatetheprogramin afilewhosenameendsin``.c'',such as , then compile it with the command cc 'tbotchedanything,suchasomittingacharact erormisspellingsomething,thecompilationw illproceedsilently, typing the command will print 10 hello, worldOn other systems, the rules will be different; check with a local expert. Now, ,whateveritssize, , ,but``main''isspecial-yourprogrambeginse xecutingatthebeginningofmain. This means that every program must have a main somewhere. mainwillusuallycallotherfunctionstohelpp erformitsjob,somethatyouwrote,andothersf rom libraries that are provided for you. The first line of the program, #include < >tellsthecompilertoincludeinformationabou tthestandardinput/outputlibrary; 7and Appendix B.
9 Onemethodofcommunicatingdatabetweenfunct ionsisforthecallingfunctiontoprovidealis t of values, called arguments, to the function it calls. The parentheses after the function ,mainisdefinedtobeafunctionthatexpectsno arguments, which is indicated by the empty list ( ). #include < > include information about standardlibrarymain() define a function called main that received no argument values{ statements of main are enclosed in braces printf("hello, world\n"); main calls library function printf to print this sequence of characters} \n represents the newline characterThe first C program Thestatementsofafunctionareenclosedinbra ces{}.
10 Thefunctionmaincontainsonlyonestatement, printf("hello, world\n");Afunctioniscalledbynamingit,fo llowedbyaparenthesizedlistofarguments,so thiscallsthefunctionprintfwiththeargumen t"hello,world\n".printfisalibraryfunctio nthatprints output, in this case the string of characters between the quotes. Asequenceofcharactersindoublequotes,like "hello,world\n", for printf and other functions. Thesequence\ninthestringisCnotationforth enewlinecharacter, \n(aworthwhileexperiment), \n to include a newline character in the printf argument; if you try something like printf("hello, world ");11the C compiler will produce an error message. printfneversuppliesanewlinecharacterauto matically,soseveralcallsmaybeusedtobuild up an output line in stages. Our first program could just as well have been written #include < > main() { printf("hello, "); printf("world"); printf("\n"); }to produce identical output.