Practical C programming (Steve Oualline) (Z-Library)

Author: Steve Oualline

科学

There are lots of introductory C books, but this is the first one that has the no-nonsense, practical approach that has made Nutshell Handbooks® famous. C programming is more than just getting the syntax right. Style and debugging also play a tremendous part in creating programs that run well and are easy to maintain. This book teaches you not only the mechanics of programming, but also describes how to create programs that are easy to read, debug, and update. Practical rules are stressed. For example, there are fifteen precedence rules in C (&& comes before || comes before ?:). The practical programmer reduces these to two: multiplication and division come before addition and subtraction. Contrary to popular belief, most programmers do not spend most of their time creating code. Most of their time is spent modifying someone else's code. This books shows you how to avoid the all-too-common obfuscated uses of C (and also to recognize these uses when you encounter them in existing programs) and thereby to leave code that the programmer responsible for maintenance does not have to struggle with. Electronic Archaeology, the art of going through someone else's code, is described. This third edition introduces popular integrated development environments on Windows systems, as well as UNIX programming utilities, and features a large statistics-generating program to pull together the concepts and features in the language.

📄 File Format: PDF
💾 File Size: 10.3 MB
15
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
(This page has no text content)
📄 Page 2
(This page has no text content)
📄 Page 3
Practical C Programming
📄 Page 4
(This page has no text content)
📄 Page 5
Practical C Programming Third Edition Steve Oualline Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
📄 Page 6
Practical C Programming, Third Edition by Steve Oualline Copyright © 1997, 1993, 1991 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. Editor, First and Second Editions: Tim O’Reilly Editor, Third Edition: Andy Oram Production Editor: Nicole Gipson Arigo Printing History: July 1991: First Edition. August 1992: Minor corrections. January 1993: Second Edition. Bugs fixed; programs all now conform to ANSI C. June 1993: Minor corrections. August 1997: Third Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks and The Java Series is a trademark of O’Reilly Media, Inc. Practical C Programming, Third Edition, the image of a cow, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher assumes no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-565-92306-5 [LSI] [2011-02-02]
📄 Page 7
v Table of Contents Preface .............................................................................................. xv How This Book is Organized .........................................................................xvi Chapter by Chapter .........................................................................................xvi Notes on the Third Edition .............................................................................xix Font Conventions ............................................................................................xix Obtaining Source Code ....................................................................................xx Comments and Questions .............................................................................xxii Acknowledgments ..........................................................................................xxii Acknowledgments to the Third Edition .......................................................xxiii I. Basics .................................................................................................. 1 1. What Is C? .......................................................................................... 3 How Programming Works .................................................................................4 Brief History of C ...............................................................................................6 How C Works .....................................................................................................7 How to Learn C ..................................................................................................9 2. Basics of Program Writing.........................................................11 Programs from Conception to Execution .......................................................11 Creating a Real Program ..................................................................................12 Creating a Program Using a Command-Line Compiler ..................................13 Creating a Program Using an Integrated Development Environment ...........16 Getting Help on UNIX .....................................................................................33
📄 Page 8
vi Table of Contents Getting Help in an Integrated Development Environment ...........................34 IDE Cookbooks ................................................................................................34 Programming Exercises ....................................................................................37 3. Style ..................................................................................................38 Common Coding Practices ..............................................................................42 Coding Religion ................................................................................................45 Indentation and Code Format .........................................................................45 Clarity ................................................................................................................46 Simplicity ..........................................................................................................47 Summary ...........................................................................................................48 4. Basic Declarations and Expressions.......................................49 Elements of a Program ....................................................................................49 Basic Program Structure ...................................................................................50 Simple Expressions ..........................................................................................51 Variables and Storage ......................................................................................52 Variable Declarations .......................................................................................53 Integers .............................................................................................................54 Assignment Statements ....................................................................................54 printf Function ..................................................................................................56 Floating Point ...................................................................................................57 Floating Point Versus Integer Divide ..............................................................58 Characters .........................................................................................................60 Answers ............................................................................................................61 Programming Exercises ....................................................................................62 5. Arrays, Qualifiers, and Reading Numbers ...........................63 Arrays ................................................................................................................63 Strings ...............................................................................................................64 Reading Strings .................................................................................................67 Multidimensional Arrays ..................................................................................70 Reading Numbers .............................................................................................71 Initializing Variables .........................................................................................73 Types of Integers .............................................................................................75 Types of Floats .................................................................................................77 Constant Declarations ......................................................................................77
📄 Page 9
Table of Contents vii Hexadecimal and Octal Constants ..................................................................78 Operators for Performing Shortcuts ................................................................78 Side Effects .......................................................................................................79 ++x or x++ ........................................................................................................80 More Side-Effect Problems ..............................................................................81 Answers ............................................................................................................82 Programming Exercises ....................................................................................83 6. Decision and Control Statements ...........................................84 if Statement .......................................................................................................84 else Statement ..................................................................................................85 How Not to Use strcmp ...................................................................................86 Looping Statements ..........................................................................................87 while Statement ................................................................................................87 break Statement ................................................................................................89 continue Statement ..........................................................................................90 Assignment Anywhere Side Effect ..................................................................91 Answer ..............................................................................................................92 Programming Exercises ....................................................................................93 7. Programming Process .................................................................95 Setting Up .........................................................................................................97 Specification .....................................................................................................98 Code Design .....................................................................................................98 Prototype ..........................................................................................................99 Makefile ..........................................................................................................101 Testing ............................................................................................................104 Debugging ......................................................................................................104 Maintenance ...................................................................................................107 Revisions .........................................................................................................107 Electronic Archaeology ..................................................................................107 Marking Up the Program ...............................................................................108 Using the Debugger .......................................................................................108 Text Editor as a Browser ...............................................................................108 Add Comments ...............................................................................................109 Programming Exercises ..................................................................................111
📄 Page 10
viii Table of Contents II. Simple Programming................................................................ 113 8. More Control Statements ......................................................... 115 for Statement ..................................................................................................115 switch Statement ............................................................................................118 switch, break, and continue ..........................................................................123 Answers ..........................................................................................................124 Programming Exercises ..................................................................................125 9. Variable Scope and Functions ............................................... 127 Scope and Class .............................................................................................127 Functions ........................................................................................................130 Functions with No Parameters ......................................................................134 Structured Programming ................................................................................135 Recursion ........................................................................................................136 Answers ..........................................................................................................138 Programming Exercises ..................................................................................138 10. C Preprocessor ............................................................................ 140 #define Statement ...........................................................................................140 Conditional Compilation ................................................................................146 include Files ...................................................................................................148 Parameterized Macros ....................................................................................150 Advanced Features .........................................................................................152 Summary .........................................................................................................152 Answers ..........................................................................................................152 Programming Exercises ..................................................................................154 11. Bit Operations ............................................................................ 156 Bit Operators ..................................................................................................158 The and Operator (&) ....................................................................................158 Bitwise or (|) .................................................................................................160 The Bitwise Exclusive or (^) .........................................................................161 The Ones Complement Operator (Not) (~) .................................................161 The Left- and Right-Shift Operators (<<, >>) ...............................................162 Setting, Clearing, and Testing Bits ................................................................163 Bitmapped Graphics ......................................................................................166
📄 Page 11
Table of Contents ix Answers ..........................................................................................................172 Programming Exercises ..................................................................................172 12. Advanced Types .......................................................................... 173 Structures ........................................................................................................173 Unions ............................................................................................................175 typedef ............................................................................................................177 enum Type .....................................................................................................178 Casting ............................................................................................................179 Bit Fields or Packed Structures ......................................................................179 Arrays of Structures ........................................................................................181 Summary .........................................................................................................182 Programming Exercises ..................................................................................182 13. Simple Pointers ........................................................................... 183 Pointers as Function Arguments ....................................................................188 const Pointers .................................................................................................189 Pointers and Arrays ........................................................................................191 How Not to Use Pointers ...............................................................................195 Using Pointers to Split a String ......................................................................197 Pointers and Structures ..................................................................................200 Command-Line Arguments ............................................................................201 Programming Exercises ..................................................................................206 Answers ..........................................................................................................206 14. File Input/Output....................................................................... 209 Conversion Routines ......................................................................................212 Binary and ASCII Files ...................................................................................215 The End-of-Line Puzzle .................................................................................216 Binary I/O ......................................................................................................218 Buffering Problems ........................................................................................219 Unbuffered I/O ..............................................................................................220 Designing File Formats ..................................................................................224 Answers ..........................................................................................................226 Programming Exercises ..................................................................................227
📄 Page 12
x Table of Contents 15. Debugging and Optimization ............................................... 229 Debugging ......................................................................................................229 Interactive Debuggers ....................................................................................240 Debugging a Binary Search ...........................................................................244 Runtime Errors ...............................................................................................254 The Confessional Method of Debugging ......................................................255 Optimization ...................................................................................................256 Answers ..........................................................................................................264 Programming Exercises ..................................................................................264 16. Floating Point.............................................................................. 265 Floating-Point Format ....................................................................................265 Floating Addition/Subtraction .......................................................................266 Multiplication ..................................................................................................267 Division ...........................................................................................................268 Overflow and Underflow ...............................................................................268 Roundoff Error ...............................................................................................269 Accuracy .........................................................................................................269 Minimizing Roundoff Error ............................................................................270 Determining Accuracy ...................................................................................270 Precision and Speed ......................................................................................272 Power Series ...................................................................................................272 Programming Exercises ..................................................................................275 III. Advanced Programming Concepts....................................... 277 17. Advanced Pointers ..................................................................... 279 Pointers and Structures ..................................................................................279 free Function ..................................................................................................282 Linked List ......................................................................................................283 Structure Pointer Operator ............................................................................286 Ordered Linked Lists ......................................................................................287 Double-Linked Lists .......................................................................................288 Trees ...............................................................................................................292 Printing a Tree ................................................................................................296 Rest of Program ..............................................................................................296 Data Structures for a Chess Program ............................................................300
📄 Page 13
Table of Contents xi Answers ..........................................................................................................302 Programming Exercises ..................................................................................303 18. Modular Programming .......................................................... 304 Modules ..........................................................................................................304 Public and Private ..........................................................................................305 The extern Modifier .......................................................................................306 Headers ...........................................................................................................308 The Body of the Module ...............................................................................310 A Program to Use Infinite Arrays ..................................................................310 The Makefile for Multiple Files .....................................................................313 Using the Infinite Array .................................................................................316 Dividing a Task into Modules .......................................................................322 Module Division Example: Text Editor .........................................................323 Compiler .........................................................................................................324 Spreadsheet ....................................................................................................325 Module Design Guidelines ............................................................................327 Programming Exercises ..................................................................................328 19. Ancient Compilers ..................................................................... 329 K&R-Style Functions ......................................................................................329 Library Changes ..............................................................................................332 Missing Features .............................................................................................333 Free/Malloc Changes .....................................................................................333 lint ...................................................................................................................334 Answers ..........................................................................................................334 20. Portability Problems ................................................................. 337 Modularity ......................................................................................................337 Word Size .......................................................................................................338 Byte Order Problem .......................................................................................338 Alignment Problem ........................................................................................339 NULL Pointer Problem ...................................................................................341 Filename Problems .........................................................................................341 File Types .......................................................................................................342 Summary .........................................................................................................342 Answers ..........................................................................................................343
📄 Page 14
xii Table of Contents 21. C’s Dustier Corners ................................................................... 344 do/while .........................................................................................................344 goto .................................................................................................................344 The ?: Construct ............................................................................................346 The , Operator ................................................................................................346 volatile Qualifier .............................................................................................346 Answer ............................................................................................................347 22. Putting It All Together ............................................................. 348 Requirements ..................................................................................................348 Specification ...................................................................................................348 Code Design ...................................................................................................350 Coding ............................................................................................................355 Functional Description ...................................................................................355 Expandability ..................................................................................................357 Testing ............................................................................................................358 Revisions .........................................................................................................359 A Final Warning .............................................................................................359 Program Files ..................................................................................................359 Programming Exercises ..................................................................................381 23. Programming Adages .............................................................. 382 General ...........................................................................................................382 Design .............................................................................................................383 Declarations ....................................................................................................383 switch Statement ............................................................................................383 Preprocessor ...................................................................................................384 Style ................................................................................................................384 Compiling .......................................................................................................384 Final Note .......................................................................................................384 Answer ............................................................................................................385 IV. Other Language Features ........................................................ 387 A. ASCII Table ................................................................................... 389 B. Ranges and Parameter Passing Conversions.................... 391
📄 Page 15
Table of Contents xiii C. Operator Precedence Rules ..................................................... 393 D. A Program to Compute a Sine Using a Power Series..... 395 Glossary......................................................................................... 399 Index .............................................................................................. 421
📄 Page 16
(This page has no text content)
📄 Page 17
xv Preface This book is devoted to practical C programming. C is currently the premier language for software developers. That’s because it’s widely distributed and stan- dard. Newer languages are available, such as C++, but these are still evolving. C is still the language of choice for robust, portable programming. This book emphasizes the skills you will need to do real-world programming. It teaches you not only the mechanics of the C language, but the entire life cycle of a C program as well (including the program’s conception, design, code, methods, debugging, release, documentation, maintenance, and revision). Good style is emphasized. To create a good program you must do more than just type in code. It is an art in which writing and programming skills blend them- selves together to form a masterpiece. True art can be created. A well-written program not only functions correctly, but is simple and easy to understand. Comments allow the programmer to include descriptive text inside the program. When clearly written, a commented program is highly prized. A program should be as simple as possible. A programmer should avoid clever tricks. This book stresses simple, practical rules. For example, there are 15 oper- ator precedence rules in C. These can be simplified into two rules: 1. Multiply and divide come before add and subtract. 2. Put parentheses around everything else. Consider two programs. One was written by a clever programmer using all the tricks. The program contains no comments, but it works. The other program is well commented and nicely structured, but it doesn’t work. Which program is more useful? In the long run, the broken one. It can be fixed. Although the clever program
📄 Page 18
xvi Preface works now, sooner or later all programs have to be modified. The worst thing that you will ever have to do is to modify a cleverly written program. This handbook is written for people with no previous programming experience or programmers who already know C and want to improve their style and reliability. You should have access to a computer and know how to use the basic functions such as a text editor and the filesystem. Specific instructions are given for producing and running programs using the UNIX operating system with a generic cc compiler or the Free Software Foundation’s gcc compiler. For MS-DOS/Windows users, instructions are included for Borland C++, Turbo C++, and Microsoft Visual C++. (These compilers compile both C and C++ code.) The book also gives examples of using the programming utility make for automated program production. How This Book is Organized You must crawl before you walk. In Part I, Basics, we teach you how to crawl. These chapters enable you to write very simple programs. We start with the mechanics of programming and programming style. Next, you learn how to use variables and very simple decision and control statements. In Chapter 7, Program- ming Process, we take you on a complete tour of the software life cycle to show you how real programs are created. Part II, Simple Programming, describes all of the other simple statements and operators that are used in programming. You’ll also learn how to organize these statements into simple functions. In Part III, Advanced Programming Concepts, we take our basic declarations and statements and learn how they can be used in the construction of advanced types such as structures, unions, and classes. We’ll also introduce the concept of pointers. Finally, a number of miscellaneous features are described Part IV, Other Language Features. Chapter by Chapter Chapter 1, What Is C?, gives a brief description of the C language and its use. This chapter includes some background on the history of the language. Chapter 2, Basics of Program Writing, explains the basic programming process and gives you enough information to write a very simple program. Chapter 3, Style, discusses programming style. Commenting a program is covered, as well as writing clear and simple code.
📄 Page 19
Preface xvii Chapter 4, Basic Declarations and Expressions, introduces you to simple C state- ments. Basic variables and the assignment statement are covered in detail, along with arithmetic operators +, -, *, /, and %. Chapter 5, Arrays, Qualifiers, and Reading Numbers, covers arrays and more complex variables. Shorthand operators such as ++ and %= are also described. Chapter 6, Decision and Control Statements, explains simple decision statements including if, else, and for. A discussion of == versus = is presented. Chapter 7, Programming Process, takes you through all the necessary steps to create a simple program from specification through release. Structured program- ming, fast prototyping, and debugging are also discussed. Chapter 8, More Control Statements, describes additional control statements. Included are while, break, and continue. The switch statement is discussed in detail. Chapter 9, Variable Scope and Functions, introduces local variables, functions, and parameters. Chapter 10, C Preprocessor, describes the C preprocessor, which gives the programmer tremendous flexibility in writing code. The chapter also provides the programmer with a tremendous number of ways to mess up. Simple rules that help keep the preprocessor from becoming a problem are described. Chapter 11, Bit Operations, discusses the logical C operators that work on bits. Chapter 12, Advanced Types, explains structures and other advanced types. The sizeof operator and the enum type are included. Chapter 13, Simple Pointers, introduces C pointer variables and shows some of their uses. Chapter 14, File Input/Output, describes both buffered and unbuffered input/ output. ASCII and binary files are discussed, and you are shown how to construct a simple file. Chapter 15, Debugging and Optimization, describes how to debug a program, as well as how to use an interactive debugger. You are shown not only how to debug a program, but also how to write a program so that it is easy to debug. This chapter also describes many optimization techniques for making your program run faster and more efficiently. Chapter 16, Floating Point, uses a simple decimal floating-point format to intro- duce you to the problems inherent in floating point, such as roundoff error, precision loss, overflow, and underflow.
📄 Page 20
xviii Preface Chapter 17, Advanced Pointers, describes advanced uses of pointers for constructing dynamic structures such as linked lists and trees. Chapter 18, Modular Programming, shows how to split a program into several files and use modular programming techniques. The make utility is explained in more detail. Chapter 19, Ancient Compilers, describes the old, pre-ANSI C language and associ- ated compilers. Although such compilers are rare today, a lot of code was written for them and there are still a large number of programs out there that use the old syntax. Chapter 20, Portability Problems, describes the problems that can occur when you port a program (move it from one machine to another). Chapter 21, C’s Dustier Corners, describes the do/while statement, the , operator, and the ? and : operators. Chapter 22, Putting It All Together, details the steps necessary to take a complex program from conception to completion. Information-hiding and modular programming techniques are emphasized. Chapter 23, Programming Adages, lists some programming adages that will help you construct good C programs. Appendix A, ASCII Table, lists the octal, hexadecimal, and decimal representations of the ASCII character set that is now in almost universal use. Appendix B, Ranges and Parameter Passing Conversions, lists the limits you can expect to come up against in handling numbers with various sizes of memory allocation. Appendix C, Operator Precedence Rules, lists those impossible-to-remember rules, to help you when you encounter code written by rude people who didn’t use enough parentheses. Appendix D, A Program to Compute a Sine Using a Power Series, illustrates the manipulation of floating-point (real) numbers, which did not receive complete attention in the rest of the book. The Glossary defines many of the technical terms used throughout the book. Computer languages are best learned by writing and debugging programs. Sweating over a broken program at 2:00 in the morning only to find you typed “=” where you should have typed “==” is a very effective learning experience. There are many programming examples used throughout this book. Some examples don’t work as expected and are posed as questions for the reader to solve. You are encouraged to enter each into your computer, run the program, and debug it.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List