Practical C Prog Free ebook download

       

  Pract i cal   C  Programming,   3rd  Edi t i on    By  St eve  Oual l i ne   3rd  Edi t i on  August   1997 

  I SBN:   1- 56592- 306- 5  

  This new edition of "Practical C Programming" teaches users not only the mechanics or programming, but also how to create programs that are easy to read, maintain, and debug. It features more extensive examples and an introduction to graphical development environments. Programs conform to ANSI C.

Table of Contents Preface

  How This Book is Organized Chapter by Chapter Notes on the Third Edition Font Conventions Obtaining Source Code Comments and Questions Acknowledgments Acknowledgments to the Third Edition

  1. What Is C?

  How Programming Works Brief History of C How C Works How to Learn C

  2. Basics of Program Writing

  Programs from Conception to Execution Creating a Real Program Creating a Program Using a Command-Line Compiler Creating a Program Using an Integrated Development Environment Getting Help on UNIX Getting Help in an Integrated Development Environment

  IDE Cookbooks Programming Exercises

  3. Style

  Common Coding Practices Coding Religion Indentation and Code Format Clarity Simplicity Summary

  4. Basic Declarations and Expressions

  Elements of a Program Basic Program Structure Simple Expressions Variables and Storage

  Variable Declarations Integers Assignment Statements printf Function Floating Point Floating Point Versus Integer Divide Characters Answers Programming Exercises

  5. Arrays, Qualifiers, and Reading Numbers

  Arrays Strings Reading Strings Multidimensional Arrays Reading Numbers Initializing Variables Types of Integers Types of Floats Constant Declarations Hexadecimal and Octal Constants Operators for Performing Shortcuts Side Effects

  • x or x++ More Side-Effect Problems Answers Programming Exercises

  6. Decision and Control Statements

  if Statement else Statement How Not to Use strcmp Looping Statements while Statement break Statement continue Statement Assignment Anywhere Side Effect Answer Programming Exercises

  7. Programming Process

  Setting Up Specification

  Code Design Prototype Makefile Testing Debugging Maintenance Revisions Electronic Archaeology Marking Up the Program Using the Debugger Text Editor as a Browser Add Comments Programming Exercises

  8. More Control Statements

  for Statement switch Statement switch, break, and continue Answers Programming Exercises

  9. Variable Scope and Functions

  Scope and Class Functions Functions with No Parameters Structured Programming Recursion Answers Programming Exercises

  10. C Preprocessor

  #define Statement Conditional Compilation include Files Parameterized Macros Advanced Features Summary Answers Programming Exercises

  11. Bit Operations

  Bit Operators The and Operator (&)

  Bitwise or (|) The Bitwise Exclusive or (^) The Ones Complement Operator (Not) (~) The Left- and Right-Shift Operators (<<, >>) Setting, Clearing, and Testing Bits Bitmapped Graphics Answers Programming Exercises

  12. Advanced Types

  Structures Unions typedef enum Type Casting Bit Fields or Packed Structures Arrays of Structures Summary Programming Exercises

  13. Simple Pointers

  Pointers as Function Arguments const Pointers Pointers and Arrays How Not to Use Pointers Using Pointers to Split a String Pointers and Structures Command-Line Arguments Programming Exercises Answers

  14. File Input/Output

  Conversion Routines Binary and ASCII Files The End-of-Line Puzzle Binary I/O Buffering Problems Unbuffered I/O Designing File Formats Answers Programming Exercises

  15. Debugging and Optimization

  Debugging Interactive Debuggers

  Debugging a Binary Search Runtime Errors The Confessional Method of Debugging Optimization Answers Programming Exercises

  Floating-Point Format Floating Addition/Subtraction Multiplication Division Overflow and Underflow Roundoff Error Accuracy Minimizing Roundoff Error Determining Accuracy Precision and Speed Power Series Programming Exercises

  17. Advanced Pointers

  Pointers and Structures free Function Linked List Structure Pointer Operator Ordered Linked Lists Double-Linked Lists Trees Printing a Tree Rest of Program Data Structures for a Chess Program Answers Programming Exercises

  18. Modular Programming

  Modules Public and Private The extern Modifier Headers The Body of the Module A Program to Use Infinite Arrays

  The Makefile for Multiple Files Using the Infinite Array Dividing a Task into Modules Module Division Example: Text Editor Compiler Spreadsheet Module Design Guidelines Programming Exercises

  19. Ancient Compilers

  K&R-Style Functions Library Changes Missing Features Free/Malloc Changes lint Answers

  20. Portability Problems

  Modularity Word Size Byte Order Problem Alignment Problem NULL Pointer Problem Filename Problems File Types Summary Answers

  21. C's Dustier Corners

  do/while goto The ?: Construct The , Operator volatile Qualifier Answer

  22. Putting It All Together

  Requirements Specification Code Design Coding Functional Description

  Expandability Testing Revisions A Final Warning Program Files Programming Exercises

  General Design Declarations switch Statement Preprocessor Style Compiling Final Note Answer

  A. ASCII Table

  B. Ranges and Parameter Passing Conversions

  C. Operator Precedence Rules

  D. A Program to Compute a Sine Using a Power Series Glossary Index

Pr e fa ce

  This book is devot ed t o pr act ical C pr ogr am m ing. C is cur r ent ly t he prem ier language for soft w are developers. That 's because it 's w idely dist r ibut ed and st andar d. New er languages ar e available, such as C+ + , but t hese are st ill evolving. C is st ill t he language of choice for robust , port able program m ing. This book em phasizes t he skills you w ill need t o do real- w or ld program m ing. I t t eaches you not only t h e m echanics of t he C language, but t he ent ir e life cy cle of a C pr ogr am as w ell ( including t he program 's concept ion, design, code, m et hods, debugging, release, docum ent at ion, m aint enance, and revision) . Good st yle is em phasized. To cr eat e a good pr ogr am yo u m ust do m or e t han j ust t y pe in code. I t is an ar t in w hich w r it ing and program m ing skills blend t hem selves t oget her t o form a m ast erpiece. Tr ue ar t can be cr eat ed. A w ell-w r it t en pr ogr am not only funct ions correct ly, but is sim ple and easy t o underst and. Com m ent s allow t he program m er t o include descript ive t ext inside t he program . When clear ly w r it t en, a com m ent ed pr ogr am is highly pr ized.

  A pr ogr am should be as sim ple as possible. A pr ogr am m er should avoid clever t r icks. This book st r esses sim ple, pr act ical rules. For exam ple, t her e ar e 15 oper at or pr ecedence r ules in C. These can be sim plified int o t wo rules:

  1 .

  Multiply and divide com e before add and subtract. 2 .

Put parentheses around everything else

  Consider t w o pr ogr am s. One w as w r it t en by a clev er pr ogr am m er using all t he t r icks. The pr ogr am cont ains no com m ent s, but it w or ks. The ot her program is w ell com m ent ed and nicely st ruct ured, but it doesn't work. Which program is m ore useful? I n t he long run, t he broken one. I t can be fixed. Alt hough t he clever p rogram works now, sooner or lat er all pr ogr am s hav e t o be m odified. The w or st t hing t hat y ou w ill ev er hav e t o do is t o m odify a clev er ly w r it t en pr ogr am . This handbook is w r it t en for people w it h no pr evious pr ogr am m ing experience or program m ers who already k now C and w ant t o im pr ov e t heir st y le and r eliabilit y . You should hav e access t o a com put er and k now how t o use t he basic funct ions such as a t ex t edit or and t he filesy st em . Specific inst ruct ions are given for producing and running program s using t he UN I X operat ing syst em wit h a generic cc com piler or t he Fr ee Soft w ar e Foundat ion's gcc com piler . For MS- DOS/ Windows users, inst ruct ions are included for Borland C+ + , Turbo C+ + , and Microsoft Visual C+ + . ( These com pilers com pile bot h C and C+ + code.) The book also gives exam ples of using t he pr ogr am m ing ut ilit y m ake f or aut om at ed program product ion.

H ow Th is Book is Or g a n iz e d You m ust cr aw l befor e y ou w alk . I n Part I w e t each y ou h ow t o crawl

  These chapt er s enable y ou t o w r it e v er y sim ple pr ogr am s. We st ar t w it h t he m echanics of program m ing and program m ing st yle. Next , y ou lear n how t o use v ar iables and v er y sim ple decision and cont r ol st at em ent s. I n Chapt er 7 , w e t ak e y ou on a com plet e t our of t he soft w ar e life cy cle t o show y ou how r eal pr ogr am s ar e cr eat ed.

  Part I I describes all of t he o t her sim ple st at em ent s and oper at or s t hat ar e used in pr ogr am m ing. You'll also lear n how t o or ganize t hese st at em ent s int o sim ple funct ions. I n Par t I I I w e t ak e our basic declar at ions and st at em ent s and lear n how t hey can be used in t he const r uct ion of adv anced t y pes such as st r uct ur es, unions, and classes. We'll also int r oduce t he concept of point er s. Finally, a num ber of m iscellaneous feat ur es ar e descr ibed

  Part I V . Ch a p t e r b y Ch a p t e r Chapt er 1 giv es a br ief descr ipt ion of t h e C lan gu age an d it s u se. Th is ch apt er in clu des som e back grou n d on t h e h ist or y of t h e lan g u ag e. Chapt er 2 ex plain s t h e basic pr ogr am m in g pr ocess an d giv es y ou en ou gh infor m at ion t o w r it e a v er y sim ple pr ogr am . Chapt er 3 discusses pr ogr am m ing st y le. Com m ent ing a pr ogr am is cov er ed, as w ell as w r it in g clear an d sim ple code.

  Chapt er 4 in t r odu ces you t o sim p le C st at em en t s. Basic v ar iab les an d t h e assign m en t st at em en t ar e cov er ed in det ail, alon g w it h ar it h m et ic oper at or s + , - , * , / , and % . Chapt er 5 cov er s ar r ay s and m or e co m plex v ar iables. Shor t hand oper at or s such as + + an d % = ar e also descr ibed.

  Chapt er 6 ex plains sim ple decision st at em ent s including if , e lse , a n d for. A discussion of = = v er sus = is p r esen t ed . Chapt er 7 t ak es y ou t h r ou gh all t h e n ecessar y st eps t o cr eat e a sim ple pr ogr am fr om specificat ion t hr ough r elease. St r uct ur ed pr ogr am m ing, fast pr ot ot y ping, and debugging ar e also discu ssed. Chapt er 8 descr ibes addit ional cont r ol st at em ent s. I ncluded ar e w h ile , b r e a k , an d con t in u e . Th e sw it ch st at em en t is discu ssed in det ail. Chapt er 9 int r oduces local v ar iables, funct ions, and par am et er s. Chapt er 1 0 descr ibes t h e C pr epr ocessor , w h ich giv es t h e pr og r am m er t r em endous flex ibilit y in w r it ing code. The chapt er also pr ov ides t he pr ogr am m er w it h a t r em en dou s n u m ber of w ay s t o m ess u p. Sim ple r u les t h at h elp k eep t h e pr epr ocessor fr om becom in g a pr oblem ar e descr ibed. Ch ap t er 1 1 discu sses t h e logical C oper at or s t h at w or k on bit s. Chapt er 1 2 ex plain s st r u ct u r es an d ot h er adv an ced t y pes. Th e siz e of oper at or an d t h e e n u m t y pe ar e in clu ded. Ch ap t er 1 3 in t r odu ces C poin t er v ar iables an d sh ow s som e of t h eir u ses. Ch ap t er 1 4 descr ibes bot h buffer ed and unbuffer ed input / out put . ASCI I and binar y f iles ar e d iscu ssed , an d y ou ar e sh ow n h ow t o con st r u ct a sim p le f ile. Chapt er 1 5 descr ibes h ow t o de bu g a pr ogr am , as w ell as h ow t o u se an in t er act iv e debu gger . You ar e sh ow n n ot on ly h ow t o debu g a pr ogr am , bu t also h ow t o w r it e a pr ogr am so t hat it is easy t o debug. This chapt er also descr ibes m any opt im izat ion t ech n iqu es f or m ak in g y ou r pr ogr am r u n fast er an d m or e efficien t ly . Ch ap t er 1 6 u ses a sim ple decim al f loat in g-poin t f or m at t o in t r odu ce y ou t o t h e pr oblem s inher ent in float ing point , such as r oundoff er r or , pr ecision lo ss, ov er flow , an d u n der f low . Chapt er 1 7 descr ibes adv anced uses of point er s for const r uct ing dy nam ic st r uct ur es su ch as lin k ed list s an d t r ees.

  Ch ap t er 1 8 sh ow s h ow t o split a pr ogr am in t o sev er al f iles an d u se m odu lar pr ogr am m ing t echniques. The m a k e ut ilit y is ex plained in m or e det ail. Ch ap t er 1 9 descr ibes t h e old, pr e -ANSI C lan gu age an d associat ed com piler s. Alt h ou gh su ch com piler s ar e r ar e t oday , a lot of code w as w r it t en for t h em an d t h er e ar e st ill a lar ge n u m ber of pr ogr am s ou t t h er e t h at u se t h e old sy n t ax . Ch ap t er 2 0 descr ibes t he pr oblem s t hat can occur w hen y ou port a pr ogr am ( m ov e it f r om on e m ach in e t o an ot h er ) . Ch ap t er 2 1 descr ibes t he do/ w h ile st at em en t , t h e , oper at or , an d t h e ? an d : oper at or s. Chapt er 2 2 det ails t h e st eps n ecessar y t o t ak e a com plex pr ogr am fr om con cept ion t o com plet ion. I nfor mat ion -h idin g an d m odu lar pr ogr am m in g t ech n iqu es ar e em ph asized. Ch ap t er 2 3 list s som e pr ogr am m in g adages t h at w ill h elp y ou con st r u ct good C pr ogr am s. Appendix A list s t he oct al, hex adecim al, and decim al r epr esent at ions of t he ASCI I ch ar act er set t h at is n ow in alm ost u n iv er sal u se. Appendix B list s t he lim it s y ou can ex pect t o com e up against in handling num ber s w it h v ar iou s sizes of m em or y allocat ion . Appendix C list s t h ose im possible -to -r em em ber r ules, t o h elp y ou w h en y ou en cou n t er code w r it t en by r u de people w h o didn ' t u se en ou gh par en t h eses. Appendix D , illust r at es t he m anipulat ion of float ing -poin t ( r eal) n u m ber s, w h ich did not r eceiv e com plet e at t en t ion in t h e r est of t h e book . The Appendix A defines m any of t he t echnical t er m s used t hr oughout t he book . Com pu t er lan gu ages ar e best lear n ed by w r it in g an d debugging pr ogr am s. Sw eat in g ov er a br ok en pr ogr am at 2 : 0 0 in t h e m or n in g on ly t o fin d y ou t y ped " = " w her e y ou should hav e t y ped " = = " is a v er y effect iv e lear ning ex per ience. Ther e ar e m an y pr ogr am m in g ex am ples u sed t h r ou gh ou t t h is book . Som e ex am ples don 't w or k as ex pect ed an d ar e posed as qu est ion s f or t h e r eader t o solv e. You ar e encour aged t o ent er each int o y our com put er , r un t he pr ogr am , and debug it . These ex er cises w ill in t r odu ce y ou t o com m on er r or s in sh or t pr ogr am s so t h at y ou w ill k n ow h ow t o sp ot an d cor r ect t h em in lar ger pr ogr am s of y ou r ow n . You w ill fin d an sw er s t o q u est ion s at t h e en d of each ch ap t er . Also, at t h e en d of m an y ch ap t er s, y ou w ill find a sect ion called " Pr ogr am m ing Ex er cises. " These sect ions cont ain ex er cises t hat m ight be used in a pr ogr am m in g class t o t est y ou r k n ow ledge of C pr ogr am m ing.

N ot e s on t h e Th ir d Ed it ion

  Th e C lan gu age h as ev olv ed sin ce t h e f ir st edit ion of Pr act ical C Pr ogr am m ing w a s pu blish ed. Back t h en , ANSI com piler s w er e r ar e an d com piler s t h at accept ed t h e K& R sy n t ax w er e com m on . Now t h e r ev er se is t r u e. Th e t h ir d edit ion r eflect s t h e in du st r y sh ift t o ANSI com piler s. All pr ogr am s an d ex am ples h av e been u pdat ed t o con f or m t o t h e ANSI st an dar d. I n f act , t h e older K&R sy nt ax is discussed only in Chapt er 1 9 . Ot h er ch an ges/ addit ion s t o t h e book in clu de:

  Addit ional inst ruct ions for m ore com pilers including a generic UNI X com piler, • t he Fr ee Soft w ar e Foundat ions gcc com piler s, Bor land C+ + , Turb o C+ + , an d Micr osoft Visual C+ + .

  • A com plet ely rewrit t en Chapt er 22 . This chapt er now uses a st at ist ics pr ogr am t h at sh ou ld be m or e r elev an t t o a lar ger n u m ber of r eader s.

  Finally, I am a pr act ical per son. I t end t o believ e t hat if y ou k now w hat I m ean and I k now w hat I m ean, t hen t he language has ser v ed it s pur pose. Thr oughout t his book , I u se t h e w or d " h e" t o den ot e a pr ogr am m er . A f ew people in t h e " Polit ically Cor r ect " cr ow d h ave labeled t h is pr act ice as sex ist . Th ey also h av e labeled som e passages in t h e book as bein g v iolen t or r acist .

  Please n ot e t h at w h en I u se " h e, " I r efer t o a pr ogr am m er , w it h n o r egar d t o gen der . Secon dly , w h en I su ggest t h at som e bad pr ogr am m er s sh ou ld be sh o t , I d o n o t speak lit er ally .

  My st y le h as alw ay s been t o com m u n icat e t h in gs clear ly , con cisely , an d w it h a bit of h u m or . I r egr et an y offen se t h at t h is m igh t cau se an y on e.

Fon t Con v e n t ion s

  The follow ing conv ent ions ar e used in t his book :

  I t alic

  is u sed f or d ir ect or ies an d f ilen am es, an d t o em p h asize n ew t er m s an d concept s w hen t hey ar e int r oduced. I t alic is also used t o highlight com m ent s in ex am ples.

  Bold is u sed f or C k ey w or ds.

  Const ant Widt h is used in t ex t for pr ogr am s and t he elem ent s of a pr og r am and inex am ples t o show t he cont ent s of files or t he out put fr om com m ands. A r efer ence in t ex t t o a w or d or it em u sed in an ex am p le or cod e f r ag m en t is also sh ow n in con st an t-w id t h f on t .

  Constant Bold

  is u sed in ex am ples t o sh ow com m an ds or ot h er t ex t th at sh ou ld b e t y p ed lit er ally by t he user . ( For ex am ple, rm foo inst r uct s y ou t o t y pe " r m foo" ex act ly as it appear s in t he t ex t or ex am ple. )

  Constant Italic

  is u sed in ex am ples t o sh ow v ar iables for w h ich a con t ex t -specific subst it ut ion should be m ade. ( The v ar iable filename, for ex am ple, w ou ld be r eplaced by som e act ual filenam e. )

  " " ar e u sed t o iden t ify sy st em m essages or code fr agm en t s in ex plan at or y t ex t .

  % is t h e UNI X sh ell pr om pt .

  [ ]

  su r r ou n d opt ion al v alu es in a descr ipt ion of pr ogr am sy n t ax . ( Th e br ack et s t hem selv es should nev er be t y ped. )

  . . .

  st ands for t ex t ( usually com put er out put ) t hat 's been om it t ed for clar it y or t o sav e space. Th e n ot at ion CTRL-X o r ^X in dicat es u se of con t r ol char act er s. The not at ion inst r uct s y ou t o hold dow n t he " cont r ol" k ey w hile t y ping t he char act er " x " . We denot e ot her k ey s sim ilar ly ( e.g., RETURN indicat es a car r iage r et ur n) . All ex am ples of com m an d lin es ar e follow ed by a RETURN unless ot her w ise indicat ed.

Ob t a in in g Sou r ce Cod e

  Th e ex er cises in t h is book ar e av ailable elect r on ically by FTP an d FTPMAI L. Use FTP if y ou ar e dir ect ly on t h e I n t er n et . Use FTPMAI L if y ou ar e n ot on t h e I n t er n et bu t can send and r eceiv e elect r onic m ail t o I nt er net sit es. ( This includes Com puSer v e users.)

FTP

  I f y ou h av e an I n t er n et con n ect ion ( per m an en t or dialu p) , t h e easiest w ay t o u se FTP is v ia y our w eb br ow ser or fav or it e FTP client . To get t he ex am ples, sim ply point y ou r br ow ser t o: ft p: / / ft p. or eilly . com / published/ or eilly / nut shell/ pr act ical_c3/ ex am ples. t ar . gz I f y ou d on ' t h av e a w eb b r ow ser , y ou can u se t h e com m an d-line FTP client included w it h Window s NT ( or Window s 9 5 ) . I f y ou ar e on a PC, y ou can get ex am ples. zip inst ead o f ex am ples. t ar . gz.

  % ftp ftp.oreilly.com Connected to ftp.oreilly.com. 220 ftp.oreilly.com FTP server (Version 6.34 Thu Oct 22 14:32:01 EDT 1992) ready. Name (ftp.oreilly.com:username ): anonymous 331 Guest login ok, send e-mail address as password. Password: username@hostname Use your username and host here 230 Guest login ok, access restrictions apply. ftp> cd /published/oreilly/nutshell/practical_c3 250 CWD command successful. ftp> binary 200 Type set to I. ftp> get examples.tar.gz 200 PORT command successful. 150 Opening BINARY mode data connection for examples.tar.gz (xxxx bytes). 226 Transfer complete. local: exercises remote: exercises xxxx bytes received in xxx seconds (xxx Kbytes/s) ftp> quit 221 Goodbye. %

FTPM AI L

  FTP MAI L is a m ail ser v er av ailable t o an y on e w h o can sen d elect r on ic m ail t o, an d r eceiv e elect r onic m ail fr om , I nt er net sit es. Any com pany or ser v ice pr ov ider t hat allow s em ail connect ions t o t he I nt er net can access FTPMAI L. You send m ail t o ft pm ail@online. oreilly.com . I n t h e m essage body , giv e t h e FTP com m an ds y ou w an t t o r u n . Th e ser v er w ill r u n an on y m ou s FTP f or y ou , an d m ail t h e files back t o y ou . To get a com plet e h elp file, sen d a m essage w it h n o su bj ect an d t h e sin gle w or d " h elp" in t h e body . Th e follo w in g is an ex am ple m ail m essage t hat get s t he ex am ples. This com m and sends y ou a list ing of t he files in t he select ed dir ect or y and t he r equest ed ex am ple files. The list ing is useful if y ou ar e int er est ed in a lat er v er sion of t h e ex am ples. I f y ou ar e on a PC, y ou can get ex am ples. zip inst ead of ex am ples. t ar . gz.

  Subject:

  reply -to username@hostname (Message Body) Where you want files mailed open cd /published/oreilly/nutshell/practical_c3 dir mode binary uuencode get examples.tar.gz quit .

  A sign at u r e at t h e en d of t h e m essage is accept able as lon g as it appear s af t er " quit ."

Com m e n t s a n d Qu e st ion s

  We h av e t est ed an d v er ified all of t h e in for m at ion in t h is book t o t h e best of ou r abilit y , bu t y ou m ay f in d t h at f eat u r es h av e ch an ged ( or ev en t h at w e h av e m ad e m ist ak es! ) . Please let u s k n ow abou t an y er r or s y ou f in d, as w ell as y ou r suggest ions for fut ur e edit ions, by w r it ing t o: O'Reilly & Associat es, I nc. 1 0 0 5 Gr av en st ein High w ay Nor t h Sebast opol, CA 9 5 4 7 2 1 -8 0 0 -998 -9 9 3 8 ( in US or Can ada) 1 -7 0 7 -8 29 -0515 ( int er nat ional/ local) 1 -7 0 7 -829 -0104 ( FAX)

  You can also sen d u s m essages elect r on ically . To be pu t on t h e m ailin g list or r equ est a cat alog, sen d em ail t o: [email protected] ( v ia t h e I n t er n et ) To ask t echnic al qu est ion s or com m en t on t h e book , sen d em ail t o: book quest ions@or eilly .com ( v ia t he I nt er net ) We hav e a w eb sit e for t he book , w her e w e' ll list ex am ples, er r at a, and any plans for fut ur e edit ions. You ca n access t h is page at : ht t p: / / w w w . or eilly . com / cat alog/ pcp3/ For m or e in for m at ion abou t t h is book an d ot h er s, see t h e O' Reilly w eb sit e: h t t p: / / w w w .oreilly.com

Ack n ow le d g m e n t s

  I w ish t o t h an k m y f at h er f or h is h elp in edit in g an d Ar t h u r Mar qu ez f or h is aid in for m at t ing t his book . I am gr at efu l t o all t h e gan g at t h e Wr it er s' Hav en an d Book st or e, Pear l, Alex , an d Cly de, for t heir cont inued s uppor t . Thank s t o Peg Kov ar for help in edit ing. Special t h an k s t o Dale Dou gh er t y for r ippin g apar t m y book an d for cin g m e t o pu t it t oget her r ight . My t hank s also go t o t he pr oduct ion gr oup of O'Reilly & Associat es—especially Rosanne Wagger and Mik e Sier r a —f or pu t t in g t h e f in ish in g t ouches on t his book . Finally , Jean Gr aham deser v es a special cr edit for put t ing up w it h m y w r it in g all t h ese y ear s.

Ack n ow le d g m e n t s t o t h e Th ir d Ed it ion

  Special t h an k s t o An dy Or am , t h e t ech n ical edit or . Th an k s also t o t h e pr oduct ion st aff at O' Reilly & Associat es. Nicole Gipson Ar igo w as t h e pr oj ect m an ager . Clair em ar ie Fisher O'Lear y and Sher y l Av r uch per for m ed qualit y cont r ol check s. Mik e Sier r a w or k ed w it h t he t ools t o cr eat e t he book . Chr is Reilley and Rober t Rom an o f in e -t u n ed t h e f igu r es. Nan cy Pr iest design ed t h e in t er ior book lay ou t , an d Edie Fr eedm an design ed t h e fr on t cov er . Pr odu ct ion assist an ce, t y peset t in g, an d index ing pr ov ided by Benchm ar k Pr oduct ions, I nc.

Pa r t I : Ba sics

  Th is par t of t h e book t each es y ou t h e basic con st r u ct s of t h e C lan gu age. Wh en y ou ' r e fin ish ed, y ou ' ll be able t o w r it e w ell -design ed an d w ell- t h ou gh t -o u t C pr ogr am s. St y le is em ph asized ear ly so t h at y ou can im m ediat ely st ar t w r it in g pr ogr am s using a good pr ogr am m ing st y le. Alt hough y ou' ll be li m it ed t o sm all pr ogr am s t hr oughout t his par t , t hey 'll be w ell-w r it t en on es. Chapt er 1 giv es a br ief descr ipt ion of t h e C lan gu age an d it s u se. Th is ch apt er in clu des som e back gr ou n d on t h e h ist or y of t h e lan g u ag e.

  Chapt er 2 ex plain s t h e basic pr ogr am m in g pr ocess an d giv es y ou en ou gh infor m at ion t o w r it e a v er y sim ple pr ogr am . Chapt er 3 discusses pr ogr am m ing st y le. Com m ent ing a pr ogr am is cov er ed, as w ell as w r it in g clear an d sim ple code. Chapt er 4 in t r odu ces y ou t o sim ple C st at em en t s. Basic v ar iables an d t h e assign m en t st at em en t ar e cov er ed in det ail, alon g w it h ar it h m et ic oper at or s + , - , * , / , and % . Chapt er 5 cov er s ar r ay s and m or e com plex v ar iables. Shor t hand oper at or s such as + + an d % = ar e also descr ibed. Chapt er 6 ex plains sim ple decision st at em ent s including if , e lse , a n d for. A discussion of = = v er sus = is pr ese n t ed . Chapt er 7 t ak es y ou t h r ou gh all t h e n ecessar y st eps t o cr eat e a sim ple pr ogr am fr om specificat ion t hr ough r elease. St r uct ur ed pr ogr am m ing, fast pr ot ot y ping, and debu ggin g ar e also discu ssed.

Cha pt e r 1 . W ha t I s C? Pr ofanit y is t he one language t hat all pr ogr am m er s under st and

  —Anon. The abilit y t o or ganize and pr ocess infor m at ion is t he k ey t o success in t he m odern age. Com put ers are designed t o handle and process large am ount s of infor m at ion quickly and efficient ly, but t hey can't do any t hing unt il som eone t ells t hem w hat t o do.

  That 's where C com es in. C is a program m ing language t hat allows a soft w are engineer t o efficient ly com m unicat e w it h a com put er. C is a highly flexible and adapt able language. Since it s creat ion in 1970, it 's been used for a wide variet y of program s including firm ware for m icro - cont rollers, operat ing syst em s, applicat ions, and graphics program m ing. C is one of t he m ost m ost w idely used languages in t he w orld and is fairly st able. An im proved C language called C+ + has been invent ed, but it is st ill in developm ent , and it s definit ion is st ill being worked on. C+ + , or iginally k now n as C w it h Classes, adds a num ber of new feat ur es t o t he C language, t he m ost im por t ant of w hich is t he class. Classes facilit at e code r euse t hr ough obj ect -orient ed design ( OOD) . Which is bet t er , C or C+ + ? The answ er depends on w ho y ou t alk t o. C+ + does gr eat t hings for y ou behind y our back , such as aut om at ically calling const r uct ors and dest ruct ors for variables. This pr ocessing m ak es som e t y pes of pr ogr am m ing easy , but it m ak es st at ic check ing of pr ogr am s difficult , and y ou need t o be able t o t ell exact ly w hat your pr ogr am is doing if you ar e w or king on em bedded cont r ol applicat ions. So som e people consider C+ + t he bet t er language because it does t hings aut om at ically and C doesn't . Ot her people consider C bet t er for pr ecisely t he sam e r eason. Also, C+ + is a relat ively new language t hat 's st ill changing. Much m or e C code exist s t han C+ + code, and t hat C code w ill need t o be m aint ained and upgr aded. So C w ill be w it h us for a long t im e t o com e.

  1 . 1 H ow Pr og r a m m in g W or k s Com m unicat ing w it h com put ers is not easy. They require inst ruct ions t hat ar e exact and det ailed. I t w ould be nice if w e could w r it e pr ogr am s in English. Then w e could t ell t he com put er , " Add up all m y check s and deposit s, t hen t ell m e t he t ot al," and t he m achine w ould balance our checkbook. But English is a lousy language w hen it com es t o w rit ing exact inst r uct ions. The language is full of am biguit y and im pr ecision. Gr ace Hopper , t he gr and old lady of com put ing, once com m ent ed on t he inst r uct ions she found on a bot t le of sham poo:

  Wash Rinse

Repeat She t r ied t o follow t he dir ect ions, but she r an out of sham poo

  ( Wash-Rinse -Repeat . Wash- Rinse- Repeat . Wash-Rinse- Repeat...) Of cour se, w e can t r y t o w r it e in pr ecise English. We'd hav e t o be car eful and m ak e sur e t o spell ev er y t hing out and be sur e t o include inst r uct ions for ev er y cont ingency . But if w e w or k ed r eally har d, w e could w r it e pr ecise English inst r uct ions. I t t urns out t hat t here is a group of people who spend t heir t im e t rying t o w r it e pr ecise English. They'r e called t he gover nm ent , and t he docum ent s t hey writ e are called governm ent regulat ions. Unfort unat ely, in t heir effort t o m ake t he regulat ions precise, t he gov er nm ent has m ade t hem alm ost unr eadable. I f y ou'v e ev er r ead t he inst ruct ion book t hat com es w it h your t ax form s, you know w hat pr ecise English can be lik e. St ill, ev en w it h all t he ex t r a v er biage t hat the gover nm ent put s in, problem s can occur. A few years ago California passed a law requiring all m ot orcycle riders t o wear a helm et . Short ly aft er t his law went int o effect , a cop st opped a guy for not w ear ing one. The m an suggest ed t he policem an t ak e a closer look at t he law . The law had t w o r equir em ent s: 1) t hat m ot or cycle r ider s have an appr ov ed cr ash helm et and 2) t hat it be fir m ly st r apped on. The cop couldn't give t he m ot or cyclist a t icket because he did have a helm et firm ly st rapped on—t o his k nee.

  So English, wit h all it s problem s, is out . Now, how do we com m unicat e wit h a com put er? The first com put ers cost m illions of dollars, w hile at t he sam e t im e a good pr ogr am m er cost about $15,000 a y ear . Pr ogr am m er s w er e forced t o program in a language in whic h all t he inst r uct ions w er e r educed t o a ser ies of num ber s, called m achine language. This language could be direct ly input int o t he com put er. A t ypical m achine -language program looks like: 1010 1111 0011 0111 0111 0110 .. and so on for several hundred inst ructions While m achines " t hink" in num bers, people don't . To program t hese ancient m achines, soft w ar e engineer s w ould w r it e t heir pr ogr am s using a sim ple language in w hich each w ord in t he language st ood for a single inst ruct ion. This language w as called assem bly language because t he pr ogr am m er s had t o hand t r anslat e, or assem ble, each line int o m achine code. A t ypical program m ight look like: Program Translation MOV A,47 1 010 1111 ADD A,B 0011 0111 HALT 0111 0110 .. and so on for several hundred instructions This process is illust rat ed by Figur e 1 - 1 .

  Figur e 1 - 1 . Asse m blin g a pr ogr a m Tr anslat ion w as a difficult , t edious, and exact ing t ask. One soft w ar e engineer decided t hat t his w as a per fect j ob for a com put er , so he w r ot e a pr ogr am called an assem bler t hat w ould do t he j ob aut om at ically .

  He show ed his new cr eat ion t o his boss and w as im m ediat ely chew ed out : " How dar e y ou ev en t hink of using such an ex pensiv e m achine for a m er e ` cler ical' t ask." Given t he cost of an hour of com put er t im e v er sus t he cost of an hour of pr ogr am m er t im e, t his at t it ude w as not unreasonable. For t unat ely, as t im e passed t he cost of pr ogr am m er s w ent up and t he cost of com put er s w ent dow n. So let t ing t he pr ogr am m er s w r it e pr ogr am s in assem bly language and t hen using a pr ogr am called an assem bler t o t ranslat e t hem int o m achine language becam e very cost effect iv e. Assem bly language or ganized pr ogr am s in a w ay t hat w as easy for t he pr ogr am m er s t o under st and. How ever , t he pr ogr am w as m or e difficult for t he m achine t o use. The pr ogr am had t o be t r anslat ed befor e t he m achine could execut e it . This m et ho d w as t he st ar t of a t rend. Program m ing languages becam e m ore and m ore convenient for t he pr ogr am m er t o use, and st ar t ed r equir ing m or e and m or e com put er t im e for t ranslat ion int o som et hing useful. Ov er t he y ear s, a ser ies of higher -lev el languages hav e been devised. These languages at t em pt t o let t he pr ogr am m er w r it e in a m edium t hat is easy for him t o underst and, and t hat is also precise and sim ple enough for t he com put er t o under st and. Ear ly high- level languages w er e designed t o handle specific t ypes of applicat ions. FORTRAN w as designed for num ber cr unching, COBOL w as for w r it ing business r epor t s, and PASCAL w as for st udent use. ( Many of t hese languages hav e far out gr ow n t heir init ial uses. Nicklaus Wirt h has been rum ored t o have said, " I f I had known t h at PASCAL w as going t o be so successful, I w ould hav e been m or e careful in it s design." ) 1 . 2 Br ie f H ist or y of C I n 1970 a pr ogr am m er , Dennis Rit chie, cr eat ed a new language called

  C. ( The nam e cam e about because it superceded t he old program m ing language he w as using: B.) C w as designed w it h one goal in m ind: w rit ing operat ing syst em s. The language w as ext rem ely sim ple and flex ible, and soon w as used for m any differ ent t y pes of pr ogr am s. I t quickly becam e one of t he m ost popular pr ogr am m ing languages in t he w or ld . C's popular it y w as due t o t w o m aj or fact or s. The fir st w as t hat t he language didn't get in t he w ay of t he pr ogr am m er . He could do j ust about any t hing by using t he pr oper C const r uct . ( As w e w ill see, t his flexibilit y is also a draw back, as it allows t he program t o do t hings t hat t he program m er never int ended.) The second r eason t hat C is popular is t hat a por t able C com piler w as w idely available. Consequent ly, people could at t ach a C com piler for t heir m achine easily and w it h lit t le ex pense.

  I n 1980, Bj ar ne St r oust r up st ar t ed w or king on a new language, called " C w it h Classes." This language im pr ov ed on C by adding a num ber of new feat ures. This new language was im proved and augm ent ed, and finally becam e C+ + .

  One of t he new est languages, Jav a, is based on C+ + . Jav a w as designed t o be " C+ + w it h t he bugs fixed." At t he t im e of t his w r it ing, Jav a has lim it ed use despit e being heav ily m ar k et ed by Sun Micr osyst em s and ot her s.

  1 .3 H ow C W or k s C is designed as a br idge bet w een t he pr ogr am m er and t he r aw com pu t er. The idea is t o let t he program m er organize a program in a w ay t hat he can easily under st and. The com piler t hen t r anslat es t he language int o som et hing t hat t he m achine can use.

  Com put er pr ogr am s consist of t w o m ain par t s: dat a and inst r uct ions. Th e com put er im poses lit t le or no organizat ion on t hese t w o part s. Aft er all, com put er s ar e designed t o be as gener al as possible. The pr ogr am m er should im pose his or ganizat ion on t he com put er , not t he ot her w ay around.

  The dat a in a com put er is st ored as a serie s of by t es. C or ganizes t hose by t es int o useful dat a. Dat a declar at ions ar e used by t he program m er t o describe t he inform at ion he is w orking w it h. For ex am ple: int total; /* Total number accounts */ t ells C t hat w e w ant t o use a sect ion of t he com put er's m em or y t o st ore an int eger nam ed total. We let t he com piler decide what par t icular byt es of m em or y t o use; t hat decision is a m inor book k eeping det ail t hat w e don't w ant t o w or r y about .

  Our variable total is a sim ple variable. I t can hold only one int eg er and descr ibe only one t ot al. A ser ies of int eger s can be or ganized int o an ar r ay as follow s: int balance[100]; /* Balance (in cents) for all 100 accounts

  • / Again, C w ill handle t he det ails of im posing t hat or ganizat ion on t he com put er 's m em or y. Finally , t her e ar e m or e com plex dat a t y pes. For exam ple, a rect angle m ight have a widt h, a height , a color, and a fill pat t er n. C let s us or ganize t hese four it em s int o one gr oup called a st r uct ur e. struct rectangle { int width; /* Width of rectangle in pixels */ int height; /* Height of rectangle in pixels */ color_type color; /* Color of the rectangle */ fill_type fill; /* Fill pattern */ }; The point is t hat st ruct ures allow t he program m er t o arrange t he dat a t o suit his needs n o m at t er how sim ple or com plex t hat dat a is. Tr anslat ion of t his dat a descr ipt ion int o som et hing t he com put er can

  use is t he j ob of t he com piler, not t he program m er. But dat a is only one part of a program . We also need inst ruct ions. As far as t he com put er is concerned, it knows not hing about t he layout of t he inst ruct ions. I t know s w hat it 's doing for t he current inst ruct ion and w her e t o get t he nex t one, but not hing m or e.

  C is a high- level language. I t let s us w r it e a high- level st at em ent like: area = (bas e * height) / 2.0; /* Compute area of triangle */ The com piler w ill t r anslat e t his st at m ent int o a ser ies of cr ypt ic low - level m achine inst r uct ions. This sor t of st at em ent is called an assignm ent st at em ent . I t is used t o com put e and st ore t he value of an arit hm et ic expression.

  We can also use cont rol st at em ent s t o cont rol t he order of processing. St at em ent s like t he if and sw it ch st at em ent s enable t he com put er t o m ak e sim ple decisions. St at em ent s can be r epeat ed ov er and ov er again by using looping st at em ent s such as w hile and for .

  Gr oups of st at em ent s can be w r apped t o for m funct ions. Thus, w e only hav e t o w r it e a gener al-pur pose funct ion t o dr aw a r ect angle once, and t hen w e can r euse it w henev er w e w ant t o dr aw a new rect angle.

  C pr ovides t he pr ogr am w it h a r ich set of st andard funct ions t hat per for m com m on funct ions such as sear ching, sor t ing, input , and out put . A set of relat ed funct ions can be grouped t oget her in a single source file. Many source files can be com piled and linked t oget her t o form a pr ogr am . One of t he m aj or goals of t he C language is t o or ganize inst r uct ions int o r eusable com ponent s. Aft er all, y ou can w r it e pr ogr am s m uch fast er if you can " bor r ow " m ost of your code fr om som ew her e else. Gr oups of r eusable funct ions can be com bined int o a library. I n t his m anner, when you need, for exam ple, a sort rout ine, you can grab t he st andard funct ion qsort from t he library and link it int o your program .

  The dat a declarat ions, st ruct ures and cont rol st at em ent s, and ot her C language elem ent s, are not for t he com put er 's benefit . The com put er can't t ell t he differ ence bet w een a m illion r andom by t es and a r eal pr ogr am . All t he C language elem ent s ar e designed t o allow t he pr ogr am m er t o ex pr ess and or ganize his ideas clear ly in a m anner t ailored t o him , no t t o t he com put er.

  Or ganizat ion is t he k ey t o w r it ing good pr ogr am s. For ex am ple, in t his book you know t hat t he Table of Cont ent s is in t he front and t he I ndex is in t he back. We use t his st ruct ure because books are organized t hat w ay . Or ganizat ion m ak es t his book easier t o use.

  The C language let s you organize your program s using a sim ple yet pow er ful synt ax. This book goes beyond t he C synt ax and t eaches you st yle rules t hat enable you t o m ake highly readable and reliable pr ogr am s. By com bining a pow er fu l synt ax w it h good program m ing st yle, you can cr eat e pow er ful pr ogr am s t hat per for m com plex and w onder ful oper at ions, y et ar e also or ganized in a w ay t hat m ak es t hem easy for you t o under st and w hen change t im e com es ar ound.

  1 . 4 H ow t o Le a r n C

  Th er e is on ly on e w ay t o lear n h ow t o p r og r am an d t h at is t o w r it e p r og r am s. You ' ll lear n a lot m or e by w r it in g an d debu ggin g pr ogr am s t h an y ou ev er w ill by r eadin g t h is book . Th is book con t ain s m an y pr ogr am m in g ex er cises. You sh ou ld t r y t o do as m any of t hem as possib le. When y ou do t he ex er cises, k eep good pr ogr am m ing st y le in m ind. Alw ay s com m ent y our pr ogr am s, ev en if y ou'r e only doing t he ex er cises for y ou r self. Com m en t in g h elps y ou or gan ize y ou r t h ou gh t s an d k eeps y ou in pr act ice w h en y ou go in t o t h e r eal w or ld. Don ' t let y ou r self be sedu ced by t h e idea t h at " I ' m on ly w r it in g t h ese pr ogr am s for m y self, so I don't need t o com m ent t hem . " Fir st of all, code t hat look s obv ious t o a pr ogr am m er as h e w r it es it is of t en con f u sin g an d cr y pt ic w h en h e r ev isit s it a w eek lat er . Wr it in g com m en t s also h elps y ou t o get or gan ized bef or e y ou w r it e t h e act u al code. ( I f y ou can w r it e out an idea in English, y ou'r e halfw ay t o w r it ing it in C. ) Fin ally , pr ogr am s t en d t o be ar ou n d f ar lon ger t h an ex pect ed. I on ce w r ot e a pr ogr am t hat w as design ed t o w or k on ly on t h e com pu t er at Calt ech . Th e pr ogr am w as h igh ly sy st em-depen den t . Becau se I w as t h e on ly on e w h o w ou ld ev er u se it , t h e pr ogr am w ou ld pr in t t h e f ollow in g m essage if y ou got t h e com m an d lin e w r on g: ?LSTUIT User is a twit A few y ear s lat er , I w as a st udent at Sy r acuse Univ er sit y , and t he Secr et ar y at t he School of Com put er Science needed a pr ogr am t hat w as sim ilar t o m y Calt ech list ing pr ogr am . So I adapt ed m y pr ogr am for her use. Unfor t unat ely , I for got about t he er r or m essage. I magin e h ow h or r if ied I w as w h en I cam e in t o t h e Com pu t er Scien ce of f ice an d w as accost ed by t he Chief Secr et ar y . This lady had so m uch pow er t hat she could m ak e t h e Dean cr in g e. Sh e look ed at m e an d said , " User is a t w it , h u h ! " Lu ck ily sh e h ad a sen se o f h um or , or I w ouldn't be her e t oday .

  Spr ink led t hr oughout t his book ar e m any br ok en pr ogr am s. Spend t he t im e t o figu r e ou t w h y t h ey don ' t w or k . Oft en , t h e pr oblem is v er y su bt le, su ch as a m isplaced sem icolon or t h e u se of

  = inst ead of ==. These pr ogr am s let y ou lear n how t o spot m ist ak es in a sm all pr ogr am . Th en , w h en y ou m ak e sim ilar m ist ak es in a big pr ogr am , and y ou w ill m ak e m ist ak es, y ou w ill be t r ained t o spot t hem .

Cha pt e r 2 . Ba sics of Pr ogr a m W r it ing

  The fir st and m ost im por t ant t hing of all, at least for w r it er s t oday, is t o st rip language clean, t o lay it bare dow n t o t he bone.