Practical C++ Programming
Total Page:16
File Type:pdf, Size:1020Kb
Practical C++ Programming Steve Oualline O'Reilly & Associates, Inc. Beijing · Cambridge · Köln · Paris · Sebastopol · Taipei · Tokyo Page iv Practical C++ Programming by Steve Oualline Copyright © 1995 O'Reilly & Associates, Inc. All rights reserved. Printed in the United States of America. Editors: Adrian Nye and Dale Dougherty Production Editor: Nicole Gipson Printing History: August 1995 First Edition. January 1997: Minor corrections. Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks and The Java Series is a trademark of O'Reilly & Associates, 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 & Associates, 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. This book is printed on acid-free paper with 85% recycled content, 15% post-consumer waste. O'Reilly & Associates is committed to using paper with the highest recycled content available consistent with high quality. ISBN. 1-56592-139-9 [12/98] Page v Table of Contents Preface xv I: The Basics 1 1: What Is C++? 3 3 A Brief History of C++ 3 C++ Organization 4 How to Learn C++ 6 2: The Basics of Program Writing 9 Programs from Conception to Execution 12 Creating a Real Program 13 Creating a Program Using a Command-Line Compiler 13 Creating a Program Using an Integrated Development Environment 16 Getting Help in UNIX 32 Getting Help in an Integrated Development Environment 33 Programming Exercises 33 3: Style 35 Comments 36 C++ Code 4 41 Naming Style 42 Coding Religion 43 Indentation and Code Format 43 Page vi Clarity 44 44 Simplicity 45 Consistency and Organization 46 Further Reading 46 Summary 46 4: Basic Declarations and Expressions 49 The Elements of a Program 49 Basic Program Structure 50 Simple Expressions 51 The cout Output Class 53 Variables and Storage 53 Variable Declarations 54 Integers 55 Assignment Statements 56 Floating Point Numbers 57 Floating Point Versus Integer Divide 58 Characters 59 Programming Exercises 60 Answers Chapter Questions 61 5: Arrays, Qualifiers, and Reading Numbers 63 Arrays 63 Strings 64 Reading Data 67 Initializing Variables 69 Multidimensional Arrays 70 Types of Integers 72 Types of Floats 74 74 Constant and Reference Declarations 74 Qualifiers 76 Hexadecimal and Octal Constants 78 Operators for Performing Shortcuts 78 Side Effects 79 Programming Exercises 82 Answers to Chapter Questions 82 Page vii 6: Decision and Control Statements 85 if Statement 85 else Statement 87 How Not to Use strcmp 88 Looping Statements 88 while Statement 88 Break Statement 91 continue Statement 92 The Assignment Anywhere Side Effect 92 Programming Exercises 94 Answers to Chapter Questions 95 7. The Programming Process 97 Setting Up 99 The Specification 100 Code Design 101 The Prototype 102 The Makefile 103 103 Testing 105 Debugging 106 Maintenance 108 Revisions 108 Electronic Archaeology 109 Mark Up the Program 109 Use the Debugger 110 Use the Text Editor as a Browser 110 Add Comments 110 Programming Exercises 113 II: Simple Programming 115 8: More Control Statements 117 for Statement 117 switch Statement 120 switch, break, and continue 125 Programming Exercises 127 Answers to Chapter Questions 128 Page vii 9: Variable Scope and Functions 129 Scope and Storage Class 129 Functions 133 Summary of Parameter Types 146 Structured Programming Basics 146 Recursion 148 148 Programming Exercises 149 Answers to Chapter Questions 149 10. The C++ Preprocessor 151 #define Statement 151 Conditional Compilation 157 #include Files 159 Parameterized Macros 160 Advanced Features 162 Summary 163 Programming Exercises 163 Answers to Chapter Questions 164 11: Bit Operations 167 Bit Operators 168 The AND Operator (&) 168 Bitwise OR ( | ) 171 The Bitwise Exclusive OR (^) 171 The Ones Complement Operator (NOT) (-) 171 The Left and Right Shift Operators (<<, >>) 172 Setting, Clearing, and Testing Bits 173 Bitmapped Graphics 176 Programming Exercises 181 Answers to Chapter Questions 182 III: Advanced Types and Classes 183 12: Advanced Types 185 Structures 185 185 Unions 188 typedef 190 Page ix enum Type 191 Bit Fields or Packed Structures 193 Arrays of Structures 195 Programming Exercises 196 13: Simple Classes 197 Stacks 197 Improved Stack 201 Using a Class 203 Introduction to Constructors and Destructors 205 Automatically Generated Member Functions 210 Shortcuts 211 Style 212 Programming Exercises 214 14: More on Classes 217 Friends 217 Constant Functions 219 Constant Members 220 Static Member Variables 222 Static Member Functions 223 The Meaning of static 224 Programming Exercises 225 225 15: Simple Pointers 227 Constant Pointers 232 Pointers and Printing 233 Pointers and Arrays 233 Splitting Strings 237 Pointers and Structures 240 Command-Line Arguments 241 Programming Exercises 245 Answers to Chapter Questions 245 Page x IV: Advanced Programming Concepts 249 16: File Input/Output 251 C++ File I/O 252 Conversion Routines 256 Binary and ASCII Files 260 The End-of-Line Puzzle 261 Binary I/O 262 Buffering Problems 263 Unbuffered I/O 264 Designing File Formats 268 C-Style I/O Routines 270 C-Style Conversion Routines 273 C-Style Binary I/O 276 Programming Exercises 278 278 Answers to Chapter Questions 278 17: Debugging and Optimization 281 Debugging 281 Serial Debugging 289 Divide and Conquer 290 Debug-Only Code 290 Debug Command-Line Switch 290 Going Through the Output 292 Interactive Debuggers 292 Debugging a Binary Search 296 Runtime Errors 307 The Confessional Method of Debugging 309 Optimization 309 The Power of Powers of 2 311 How to Optimize 314 Case Study: Inline Functions Versus Normal Functions 316 Case Study: Optimizing a Color-Rendering Algorithm 316 Programming Exercises 317 Answers to Chapter Questions 317 Page xi 18: Operator Overloading 319 Operator Functions 322 Operator Member Functions 330 Full Definition of the Complex Class 332 332 Programming Exercises 341 Answers to Chapter Questions 342 19 : Floating Point 343 Floating-Point Format 343 Floating Addition/Subtraction 344 Multiplication 345 Division 346 Overflow and Underflow 346 Roundoff Error 347 Accuracy 347 Minimizing Roundoff Error 348 Determining Accuracy 348 Precision and Speed 350 Power Series 351 Programming Exercises 352 20: Advanced Pointers 355 Pointers, Structures, and Classes 355 delete Operator 358 Linked List 359 Ordered Linked Lists 362 Double-linked List 365 Trees 368 Printing a Tree 373 The Rest of the Program 373 Data Structures for a Chess Program 377 Programming Exercises 378 378 Answers to Chapter Questions 379 21: Advanced Classes 381 Derived Classes 381 Virtual Functions 387 Page xii Virtual Classes 393 Function Hiding in Derived Classes 395 Constructors and Destructors in Derived Classes 396 Summary 398 Programming Exercises 399 Answers to Chapter Questions 399 V: Other Language Features 401 22: Exceptions 403 Stack Exceptions 405 Runtime Library Exceptions 410 Programming Exercises 410 23: Modular Programming 413 Modules 413 Public and Private 414 The extern Modifier 414 Headers 416 The Body of the Module 418 A Program to Use Infinite Arrays 418 The Makefile for Multiple Files 420 Using the Infinite Array 424 424 Dividing a Task into Modules 429 Module Division Example: Text Editor 430 Compiler Construction 431 Spread sheet 432 Module Design Guidelines 433 Programming Exercises 434 24: Templates 435 What Is a Template? 435 Templates: The Hard Way 435 Function Specialization 439 Class Templates 440 Class Specialization 442 Implementation Difficulties 442 Page xiii Summary 445 Programming Exercises 445 25: Portability Problems 447 Modularity 447 Word Size 448 Byte-Order Problem 448 Alignment Problem 449 NULL-Pointer Problem 450 Filename Problems 451 File Types 452 452 Summary 452 Answers to Chapter Questions 453 26: Putting It All Together 455 Requirements 455 Code Design 457 Coding 459 Functional Description 459 Testing 463 Revisions 464 A Final Warning 464 Program Files 464 Programming Exercises 483 27: From C to C++ 485 Overview 485 K&R-Style Functions 485 struct 486 malloc and free 486 Turning Structures into Classes 488 ssetjmp and longjmp 489 Summary 491 Programming Exercise 491 Page xiv 28. C++'s Dustier Corners 493 do/while 493 493 goto 493 The ?:Construct 495 The Comma Operator 495 Overloading the ( )Operator 495 Pointers to Members 496 Vampire Features 497 Answers to Chapter Questions 498 29: Programming Adages 499 General 499 Design 500 Declarations 500 switch Statement 500 Preprocessor 500 Style 501 Compiling 501 The Ten Commandments for C++ Programmers 501 Final Note 502 Answers to Chapter Questions 503 VI: Appendixes 505 A: ASCII Table 507 B: Ranges 511 C: Operator Precedence Rules 513 D: Computing sine Using a Power Series 515 Glossary 521 Index 543 Page xv Preface This book is devoted to practical C++ programming. It teaches you not only the mechanics of the language, but also style and debugging. The entire life cycle of a program is discussed, including conception, design, writing, debugging, release, documentation, maintenance, and revision. Style is emphasized. Creating a good program involves more than just typing code. It is an art in which writing and programming skills blend to form a masterpiece. A well-written program not only functions correctly, but also is simple and easy to understand. Comments allow programmers to include descriptive text in their programs. Clearly written, well-commented programs are highly prized. A program should be as simple as possible. Avoid the use of clever tricks. Cleverness and complexity can kill programs. This book stresses simple, practical rules. For example, the 15 operator-precedence rules in C++ can be simplified to 2: 1. Multiply and divide before you add and subtract. 2. Put parentheses around everything else. Consider two programs. One was written by a clever programmer, using all the tricks.