C delivers a dependable, powerful base for programming and functions as a stepping stone on which to expand your expertise and learn extra programming languages. Written by veteran For Dummies author Dan Gookin, this straightforward-but-fun newcomer’s guide covers the principles of using C and slowly walks you through more complex topics such as pointers, linked lists, document I/O, and debugging. With a distinctive focus on the topic of an Integrated Development Environment, it provides you a good comprehension of computer programming generally as you learn how to program with C.
Encourages one to slowly improve your knowledge and comprehension of C, with each chapter building away from the previous one frees you with a good base of knowledge the C language so it’s possible to take on bigger programming jobs, learn new programming languages that are popular, and handle new subjects with confidence Contains over 100 sample programs with code which are adaptable for your own endeavors Beginning Programming with C For Dummies presumes no prior programming language expertise and enables you become capable and comfortable with the essentials of C very quickly. It begins by assuming you know little to nothing about programming, and it ends by covering a few of the advanced C surgeries. To program in C, then you require a computer.
This Beginning Programming with C for Dummies book makes no assumptions regarding the pc you pick: It may be a Windows PC, a Macintosh, or even a Linux program. Central to all programs, as well as programming in this novel, is to install and utilize the Code::Blocks integrated development environment, or IDE. Steps to do this are extended in Chapter 1. Nothing has been introduced without a complete explanation first, though because of the nature of programming, so I have created several exceptions; they are carefully mentioned in text. The book flows from front to rear, and that’s the way you can read this publication.
Download FileSteven Holzner, the author of Quantum Physics for Dummies, born in 1957, on 2nd of September. He graduated from MIT and got his PhD at Cornell. He remained faculty member in both the universities. He give lectures on Java. He is running a software house, teaching week-long to hundreds of students on Java programming.
DMCA Disclaimer: This site complies with DMCA Digital Copyright Laws. Please bear in mind that we do not own copyrights to these books. We’re sharing this material with our audience ONLY for educational purpose. We highly encourage our visitors to purchase original books from the respected publishers. If someone with copyrights wants us to remove this content, please contact us immediately.All books on the cibook.net are free and NOT HOSTED ON OUR WEBSITE. If you feel that we have violated your copyrights, then please contact us immediately (click here).
Amazon.com: C For Dummies (681): Dan Gookin: Books. Of concise technical writing, spend fifteen bucks to download Coronado's C tutorial: [.]. C++ is an object-oriented programming language commonly adopted by would-be programmers. This book explores the basic development concepts and techniques of C++ and explains the “how” and “why” of C++ programming from the ground up. You’ll discover what goes into creating a program, as. About the Author Stephen R. Davis lives near Dallas, Texas. He has written numerous books including C++ For Dummies and C++ Weekend Crash Course. Stephen works for L-3 Communications in Homeland Security and is studying for a PhD in Geospatial Information Sciences at University of Texas at Dallas. 01_617977-ffirs.indd iii 7/6/10 11:36 PM. If you visit Dan Gookin's LinkedIn Page (he's the author of C for Dummies) then you'll see the. It is also available as free pdf on the following link. 01 570684 FM.qxd 3/31/04 2:50 PM Page v About the Author Dan Gookin has been writing about technology for 20 years. He has contributed articles to numerous high-tech magazines and written more than 90 books.
For Dummies Books Pdf
DUMmIES
‰
5TH
EDITION
by Stephen Randy Davis
C++ FOR
DUMmIES
‰
5TH
EDITION
by Stephen Randy Davis
C++ For Dummies®, 5th Edition Published by Wiley Publishing, Inc. 111 River Street Hoboken, NJ 07030-5774 Copyright © 2004 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, e-mail: [email protected] Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REP RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CRE ATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CON TAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FUR THER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFOR MATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Control Number: 2004102365 ISBN: 0-7645-6852-3 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 5B/SW/QU/QU/IN
About the Author
Stephen R. Davis lives with his wife and son near Dallas, Texas. He and his family have written numerous books including C++ For Dummies and C++ Weekend Crash Course. Stephen works for L-3 Communications.
Dedication To my friends and family, who help me be the best Dummy I can be.
Author’s Acknowledgments I find it very strange that only a single name appears on the cover of any book, but especially a book like this. In reality, many people contribute to the creation of a For Dummies book. From the beginning, editorial director Mary Corder and my agent, Claudette Moore, were involved in guiding and molding the book’s content. During the development of the five editions of this book, I found myself hip-deep in edits, corrections, and suggestions from a group of project editors, copyeditors, and technical reviewers — this book would have been a poorer work but for their involvement. And nothing would have made it into print without the aid of the person who coordinated the first and second editions of the project, Suzanne Thomas. Nevertheless, one name does appear on the cover and that name must take responsibility for any inaccuracies in the text. I also have to thank my wife, Jenny, and son, Kinsey, for their patience and devotion. I hope we manage to strike a reasonable balance. Finally, a summary of the animal activity around my house. For those of you who have not read any of my other books, I should warn you that this has become a regular feature of my For Dummies books. My two dogs, Scooter and Trude, continue to do well, although Trude is all but blind now. Our two mini-Rex rabbits, Beavis and Butt-head, passed on to the big meadow in the sky after living in our front yard for almost a year and a half. If you would like to contact me concerning C++ programming, semi-blind dogs, or free-roaming rabbits, feel free to drop me a line at [email protected]
Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/. Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development
Production
Project Editor: Linda Morris Acquisitions Editor: Katie Feltman Copy Editor: Melba Hopper
Project Coordinator: Adrienne Martinez Layout and Graphics: Amanda Carter, Andrea Dahl, Denny Hager, Michael Kruzil, Lynsey Osborn, Jacque Schneider
Editorial Manager: Leah Cameron
Proofreaders: Andy Hollandbeck, Carl Pierce, Dwight Ramsey, TECHBOOKS Production Services
Permissions Editor: Laura Moss
Indexer: TECHBOOKS Production Services
Media Development Specialist: Travis Silvers
Special Help: Barry Childs-Helton
Technical Editor: Wiley-Dreamtech India Pvt Ltd
Media Development Manager: Laura VanWinkle Media Development Supervisor: Richard Graves Editorial Assistant: Amanda Foxworth Cartoons: Rich Tennant, www.the5thwave.com
Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary C. Corder, Editorial Director Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services
Table of Contents
Introduction ..................................................................1 What’s in This Book .........................................................................................1 What’s on the CD..............................................................................................2 What Is C++?......................................................................................................2 Conventions Used in This Book .....................................................................2 How This Book Is Organized...........................................................................3 And There’s More.............................................................................................4 Part I: Introduction to C++ Programming ......................................................4 Part II: Becoming a Functional C++ Programmer .........................................4 Part III: Introduction to Classes......................................................................5 Part IV: Inheritance ..........................................................................................5 Part V: Optional Features ................................................................................5 Part VI: The Part of Tens .................................................................................5 Icons Used in This Book..................................................................................6 Where to Go from Here....................................................................................6
Part I: Introduction to C++ Programming ........................7 Chapter 1: Writing Your First C++ Program . . . . . . . . . . . . . . . . . . . . . . . .9 Grasping C++ Concepts .................................................................................10 What’s a program?................................................................................10 How do I program? ...............................................................................11 Installing Dev-C++...........................................................................................12 Setting the options ...............................................................................15 Creating Your First C++ Program..................................................................16 Entering the C++ code..........................................................................17 Building your program.........................................................................18 Executing Your Program................................................................................20 Dev-C++ is not Windows ......................................................................21 Dev-C++ help .........................................................................................21 Reviewing the Annotated Program ..............................................................21 Examining the framework for all C++ programs ...............................22 Clarifying source code with comments .............................................22 Basing programs on C++ statements .................................................23 Writing declarations.............................................................................24 Generating output ................................................................................25
vi
C++ For Dummies, 5th Edition Calculating Expressions ................................................................................25 Storing the results of expression........................................................26 Examining the remainder of Conversion.cpp ...................................26
Chapter 2: Declaring Variables Constantly . . . . . . . . . . . . . . . . . . . . . . .27 Declaring Variables ........................................................................................27 Declaring Different Types of Variables ........................................................28 Reviewing the limitations of integers in C++.....................................29 Solving the truncation problem..........................................................30 Looking at the limits of floating-point numbers ...............................31 Declaring Variable Types...............................................................................33 Types of constants ...............................................................................34 Special characters ................................................................................35 Are These Calculations Really Logical?.......................................................36 Mixed Mode Expressions ..............................................................................36
Chapter 3: Performing Mathematical Operations . . . . . . . . . . . . . . . . .39 Performing Simple Binary Arithmetic .........................................................40 Decomposing Expressions ............................................................................41 Determining the Order of Operations .........................................................42 Performing Unary Operations ......................................................................43 Using Assignment Operators........................................................................45
Chapter 4: Performing Logical Operations . . . . . . . . . . . . . . . . . . . . . . .47 Why Mess with Logical Operations?............................................................47 Using the Simple Logical Operators ............................................................48 Storing logical values ...........................................................................49 Using logical int variables ...................................................................51 Be careful performing logical operations
on floating-point variables...............................................................51 Expressing Binary Numbers .........................................................................53 The decimal number system ..............................................................54 Other number systems ........................................................................54 The binary number system.................................................................54 Performing Bitwise Logical Operations.......................................................56 The single bit operators ......................................................................57 Using the bitwise operators ................................................................58 A simple test .........................................................................................59 Do something logical with logical calculations ................................60
Chapter 5: Controlling Program Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . .61 Controlling Program Flow with the Branch Commands ...........................61 Executing Loops in a Program......................................................................63 Looping while a condition is true.......................................................64 Using the autoincrement/autodecrement feature............................65 Using the for loop.................................................................................67
Table of Contents Avoiding the dreaded infinite loop.....................................................69 Applying special loop controls ...........................................................70 Nesting Control Commands..........................................................................73 Switching to a Different Subject? .................................................................74
Part II: Becoming a Functional C++ Programmer...........77 Chapter 6: Creating Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79 Writing and Using a Function .......................................................................79 Defining the sumSequence( ) function...............................................81 Calling the function sumSequence( ) .................................................82 Divide and conquer ..............................................................................82 Understanding the Details of Functions......................................................83 Understanding simple functions ........................................................84 Understanding functions with arguments.........................................85 Overloading Function Names .......................................................................87 Defining Function Prototypes.......................................................................89 Variable Storage Types ..................................................................................91 Including Include Files...................................................................................91
Chapter 7: Storing Sequences in Arrays . . . . . . . . . . . . . . . . . . . . . . . . .93 Considering the Need for Arrays .................................................................93 Using an array .......................................................................................95 Initializing an array...............................................................................98 Accessing too far into an array...........................................................99 Using arrays ..........................................................................................99 Defining and using arrays of arrays .................................................100 Using Arrays of Characters.........................................................................100 Creating an array of characters........................................................100 Creating a string of characters .........................................................101 Manipulating Strings with Character.........................................................103 String-ing Along Variables ...........................................................................106
Chapter 8: Taking a First Look at C++ Pointers . . . . . . . . . . . . . . . . . .109 Variable Size..................................................................................................109 What’s in an Address? .................................................................................110 Address Operators.......................................................................................111 Using Pointer Variables ...............................................................................112 Comparing pointers and houses ......................................................114 Using different types of pointers......................................................114 Passing Pointers to Functions ....................................................................117 Passing by value .................................................................................117 Passing pointer values.......................................................................118 Passing by reference ..........................................................................119
vii
viii
C++ For Dummies, 5th Edition Making Use of a Block of Memory Called the Heap .................................119 Limiting scope ....................................................................................120 Examining the scope problem ..........................................................121 Providing a solution using the heap ................................................122
Chapter 9: Taking a Second Look at C++ Pointers . . . . . . . . . . . . . . . .125 Defining Operations on Pointer Variables.................................................125 Re-examining arrays in light of pointer variables ..........................126 Applying operators to the address of an array ..............................128 Expanding pointer operations to a string .......................................129 Justifying pointer-based string manipulation.................................131 Applying operators to pointer types other than char...................131 Contrasting a pointer with an array.................................................132 Declaring and Using Arrays of Pointers ....................................................133 Utilizing arrays of character strings ................................................134 Accessing the arguments to main( ).................................................136
Chapter 10: Debugging C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Identifying Types of Errors .........................................................................139 Choosing the WRITE Technique for the Problem ....................................140 Catching bug #1 ..................................................................................142 Catching bug #2 ..................................................................................143 Calling for the Debugger..............................................................................146 Defining the debugger........................................................................147 Finding commonalities among us.....................................................147 Running a test program .....................................................................148 Single-stepping through a program..................................................149
Part III: Introduction to Classes..................................155 Chapter 11: Examining Object-Oriented Programming . . . . . . . . . . .157 Abstracting Microwave Ovens ...................................................................157 Preparing functional nachos .............................................................158 Preparing object-oriented nachos....................................................159 Classifying Microwave Ovens .....................................................................159 Why Classify?................................................................................................160
Chapter 12: Adding Class to C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161 Introducing the Class...................................................................................161 The Format of a Class ..................................................................................162 Accessing the Members of a Class.............................................................163
Table of Contents Chapter 13: Making Classes Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167 Activating Our Objects ................................................................................168 Simulating real-world objects ...........................................................168 Why bother with member functions? ..............................................169 Adding a Member Function.........................................................................169 Creating a member function .............................................................170 Naming class members......................................................................171 Calling a Member Function .........................................................................171 Accessing a member function...........................................................172 Accessing other members from a member function .....................174 Scope Resolution (And I Don’t Mean How Well
Your Microscope Works) .........................................................................175 Defining a Member Function in the Class .................................................177 Keeping a Member Function After Class ...................................................179 Overloading Member Functions.................................................................181
Chapter 14: Point and Stare at Objects . . . . . . . . . . . . . . . . . . . . . . . . .183 Defining Arrays of and Pointers to Simple Things ...................................183 Declaring Arrays of Objects........................................................................184 Declaring Pointers to Objects.....................................................................185 Dereferencing an object pointer.......................................................186 Pointing toward arrow pointers .......................................................187 Passing Objects to Functions .....................................................................187 Calling a function with an object value ...........................................188 Calling a function with an object pointer ........................................189 Calling a function by using the reference operator .......................191 Why Bother with Either Pointers or References? ....................................192 Returning to the Heap .................................................................................192 Comparing Pointers to References ............................................................193 Why Not Use References Rather Than Pointers?.....................................193 Linking Up with Linked Lists ......................................................................195 Performing other operations on a linked list..................................196 Hooking up with a LinkedListData program ...................................197 A Ray of Hope: A List of Containers Linked to the C++ Library .............200
Chapter 15: Protecting Members: Do Not Disturb . . . . . . . . . . . . . . . .201 Protecting Members ....................................................................................201 Why you need protected members..................................................201 Discovering how protected members work....................................202 Making an Argument for Using Protected Members................................204 Protecting the internal state of the class ........................................204 Using a class with a limited interface ..............................................205 Giving Non-Member Functions Access to Protected Members..............205
ix
x
C++ For Dummies, 5th Edition Chapter 16: “Why Do You Build Me Up,
Just to Tear Me Down, Baby?” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .209 Creating Objects...........................................................................................209 Using Constructors ......................................................................................210 Why you need constructors..............................................................210 Making constructors work ................................................................212 Dissecting a Destructor ...............................................................................217 Why you need the destructor...........................................................217 Working with destructors..................................................................217
Chapter 17: Making Constructive Arguments . . . . . . . . . . . . . . . . . . . .221 Outfitting Constructors with Arguments ..................................................221 Justifying constructors......................................................................222 Using a constructor............................................................................222 Placing Too Many Demands on the Carpenter: Overloading the Constructor..................................................................223 Defaulting Default Constructors.................................................................227 Constructing Class Members......................................................................228 Constructing a complex data member ............................................228 Constructing a constant data member ............................................232 Constructing the Order of Construction ...................................................233 Local objects construct in order ......................................................234 Static objects construct only once ..................................................234 All global objects construct before main( ) ....................................235 Global objects construct in no particular order ............................235 Members construct in the order in which they are declared.......236 Destructors destruct in the reverse order
of the constructors.........................................................................237
Chapter 18: Copying the Copy Copy Copy Constructor . . . . . . . . . . . .239 Copying an Object........................................................................................239 Why you need the copy constructor ...............................................239 Using the copy constructor ..............................................................240 The Automatic Copy Constructor..............................................................242 Creating Shallow Copies versus Deep Copies ..........................................244 It’s a Long Way to Temporaries ..................................................................248 Avoiding temporaries, permanently ................................................249 Referring to the copy constructor’s referential argument ............250
Chapter 19: Static Members: Can Fabric Softener Help? . . . . . . . . . .251 Defining a Static Member ............................................................................251 Why you need static members .........................................................251 Using static members ........................................................................252 Referencing static data members.....................................................253 Uses for static data members ...........................................................255
Table of Contents Declaring Static Member Functions...........................................................255 What Is This About, Anyway?.....................................................................258
Part IV: Inheritance...................................................259 Chapter 20: Inheriting a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261 Do I Need My Inheritance? ..........................................................................262 How Does a Class Inherit?...........................................................................263 Using a subclass .................................................................................265 Constructing a subclass ....................................................................265 Destructing a subclass.......................................................................267 Having a HAS_A Relationship .....................................................................267
Chapter 21: Examining Virtual Member Functions:
Are They for Real? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .269 Why You Need Polymorphism....................................................................272 How Polymorphism Works .........................................................................274 When Is a Virtual Function Not?.................................................................276 Considering Virtual Considerations ..........................................................277
Chapter 22: Factoring Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279 Factoring .......................................................................................................279 Implementing Abstract Classes..................................................................284 Describing the abstract class concept ............................................286 Making an honest class out of an abstract class............................287 Passing abstract classes....................................................................289 Declaring pure virtual functions — is it really necessary? ...........290 Factoring C++ Source Code .........................................................................291 Dividing the program — Student......................................................292 Defining a namespace ........................................................................293 Implementing Student........................................................................294 Dividing the program — GraduateStudent .....................................295 Implementing an application ............................................................296 Project file ...........................................................................................298 Creating a project file under Dev-C++ ..............................................298
Part V: Optional Features...........................................303 Chapter 23: A New Assignment Operator,
Should You Decide to Accept It . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .305 Comparing Operators with Functions .......................................................305 Inserting a New Operator............................................................................306
xi
xii
C++ For Dummies, 5th Edition Creating Shallow Copies Is a Deep Problem .............................................307 Overloading the Assignment Operator .....................................................308 Protecting the Escape Hatch ......................................................................311
Chapter 24: Using Stream I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .313 How Stream I/O Works.................................................................................313 The fstream Subclasses...............................................................................315 Reading Directly from a Stream..................................................................320 What’s Up with endl? ...................................................................................322 Using the strstream Subclasses .................................................................322 Manipulating Manipulators.........................................................................325
Chapter 25: Handling Errors — Exceptions . . . . . . . . . . . . . . . . . . . . .329 Justifying a New Error Mechanism?...........................................................331 Examining the Exception Mechanism........................................................332 What Kinds of Things Can I Throw? ..........................................................335
Chapter 26: Inheriting Multiple Inheritance . . . . . . . . . . . . . . . . . . . . .339 Describing the Multiple Inheritance Mechanism .....................................339 Straightening Out Inheritance Ambiguities ..............................................341 Adding Virtual Inheritance..........................................................................342 Constructing the Objects of Multiple Inheritance ...................................349 Voicing a Contrary Opinion ........................................................................349
Chapter 27: Tempting C++ Templates . . . . . . . . . . . . . . . . . . . . . . . . . . .351 Generalizing a Function into a Template...................................................353 Template Classes..........................................................................................355 Do I Really Need Template Classes? .........................................................358 Tips for Using Templates ............................................................................361
Chapter 28: Standardizing on the Standard Template Library . . . . . .363 The string Container....................................................................................364 The list Containers.......................................................................................366 Iterators.........................................................................................................368 Using Maps....................................................................................................371
Part VI: The Part of Tens............................................375 Chapter 29: Ten Ways to Avoid Adding Bugs to Your Program . . . . .377 Enabling All Warnings and Error Messages ..............................................377 Insisting on Clean Compiles........................................................................378
Table of Contents Adopting a Clear and Consistent Coding Style.........................................379 Limiting the Visibility ..................................................................................379 Commenting Your Code While You Write It ..............................................381 Single-Stepping Every Path at Least Once ................................................381 Avoid Overloading Operators.....................................................................382 Heap Handling ..............................................................................................382 Using Exceptions to Handle Errors............................................................382 Avoiding Multiple Inheritance ....................................................................383
Chapter 30: The Ten Most Important Optional Features
of Dev-C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385 Customize Editor Settings to Your Taste...................................................385 Highlight Matching Braces/Parentheses ...................................................386 Enable Exception Handling .........................................................................387 Include Debugging Information (Sometimes)...........................................387 Create a Project File .....................................................................................388 Customize the Help Menu ...........................................................................388 Reset Breakpoints after Editing the File....................................................388 Avoid Illegal Filenames ................................................................................389 Include #include Files in Your Project .......................................................389 Executing the Profiler ..................................................................................389
Appendix: About the CD .............................................393 System Requirements ..................................................................................393 Using the CD with Microsoft Windows......................................................394 Using the CD with Linux ..............................................................................395 What You’ll Find ...........................................................................................396 Development tools .............................................................................396 Program source code.........................................................................397 If You’ve Got Problems (Of the CD Kind) ..................................................397
Bonus Chapters on the CD-ROM! ..................................CD
Bonus Chapter 1: A Functional Budget Program . . . . . . . . . . . . . . . .BC1 BUDGET1 ......................................................................................................BC1
BUDGET2 ......................................................................................................BC7
BUDGET3 ....................................................................................................BC16
Implementing a linked list module ................................................BC17
Taking savings and checking into account...................................BC19
The linked list classes.....................................................................BC26
Assessing the budget ......................................................................BC28
xiii
xiv
C++ For Dummies, 5th Edition BUDGET4 ....................................................................................................BC28
Implementing linked list as a template class ...............................BC29
It’s easy to con-template.................................................................BC31
Balancing the template budget......................................................BC37
BUDGET5 ....................................................................................................BC37
Listing containers ............................................................................BC38
Making a list of the accounts .........................................................BC43
Bonus Chapter 2: Using Visual C++.NET . . . . . . . . . . . . . . . . . . . . . .BC45 Building a Project ......................................................................................BC45
Adding an Existing Program to an Existing Project ..............................BC47
Creating a New Program Project .............................................................BC49
Index ........................................................................407
Introduction
W
elcome to C++ For Dummies, 5th Edition. Think of this book as C++: Reader’s Digest Edition, bringing you everything you need to know without the boring stuff.
What’s in This Book
C++ For Dummies is an introduction to the C++ language. C++ For Dummies starts from the beginning (where else?) and works its way from early concepts and through more sophisticated techniques. It doesn’t assume that you have any prior knowledge, at least, not of programming. C++ For Dummies is rife with examples. Every concept is documented in numer ous snippets and several complete programs. Unlike other C++ programming books, C++ For Dummies considers the “why” just as important as the “how.” The features of C++ are like pieces of a jigsaw puzzle. Rather than just present the features, I think it’s important that you understand how they fit together. If you don’t understand why a particular feature is in the language, you won’t truly understand how it works. After you finish this book, you’ll be able to write a reasonable C++ program, and, just as important, you’ll understand why and how it works. C++ For Dummies can also be used as a reference: If you want to understand what’s going on with all the template stuff, just flip to Chapter 27, and you’re there. Each chapter contains necessary references to other earlier chapters in case you don’t read the chapters in sequence. C++ For Dummies is not operating- or system-specific. It is just as useful to Unix or Linux programmers as it is to Windows-based developers. C++ For Dummies doesn’t cover Windows or .NET programming. You have to master C++ before you can move on to Windows and .NET programming.
2
C++ For Dummies, 5th Edition
What’s on the CD
The CD-ROM included with C++ For Dummies contains the source code for the examples in this book. This can spare you considerable typing. Your computer can’t execute these or any other C++ program directly. You have to run your C++ programs through a C++ development environment, which spits out an executable program. (Don’t worry, this procedure is explained in Chapter 1.) The programs in C++ For Dummies are compatible with any standard C++ envi ronment, but don’t worry if you don’t already own one. A full-featured C++ envi ronment known as Dev-C++ is contained on the enclosed CD-ROM. You can use this tool to write your own C++ programs as well as explore the programs from the book. No worries if you already own Visual Studio.NET. Some people need an intro duction to C++ before going into the many features offered by .NET. C++ For Dummies is just as happy with Visual Studio as it is with its own Dev-C++. C++ For Dummies does not contain Visual Studio.NET. However, the programs in the book have been tested for compatibility with the industry standard “unman aged C++” portion of Visual Studio.NET.
What Is C++?
C++ is an object-oriented, low-level ANSI and ISO standard programming lan guage. As a low-level language similar to and compatible with its predecessor C, C++ can generate very efficient, very fast programs. As an object-oriented language, C++ has the power and extensibility to write large-scale programs. C++ is one of the most popular programming languages for all types of programs. Most of the programs you use on your PC every day are written in C++. C++ has been certified as a 99.9 percent pure standard. This makes it a portable language. There is a C++ compiler for every major operating system, and they all support the same C++ language. (Some operating systems support exten sions to the basic language, but all support the C++ core.)
Conventions Used in This Book
When I describe a message or information that you see onscreen, it appears like this:
Introduction Hi mom!
In addition, code listings appear as follows: // some program void main() { ... }
If you are entering these programs by hand, you must enter the text exactly as shown with one exception: The number of spaces is not critical, so don’t worry if you enter one too many or one too few spaces. C++ words are usually based on English words with similar meanings. This can make reading a sentence containing both English and C++ difficult to make out without a little help. To help out, C++ commands and function names appear in a different font like this. In addition, function names are always followed by an open and closed parenthesis like myFavoriteFunction(). The argu ments to the function are left off except when there’s a specific need to make them easier to read. It’s a lot easier to say: “this is myFavoriteFunction()” than “this is myFavoriteFunction(int, float).” Sometimes, the book directs you to use specific keyboard commands. For exam ple, when the text instructs you to press Ctrl+C, it means that you should hold down the Ctrl key while pressing the C key and then release both together. Don’t type the plus sign. Sometimes, I’ll tell you to use menu commands, such as File➪Open. This nota tion means to use the keyboard or mouse to open the File menu and then choose the Open option. Finally, both Dev-C++ and Visual Studio.NET define function keys for certain common operations — unfortunately, they don’t use the same function keys. To avoid confusion, I rarely use function keys in the book — I couldn’t have kept the two straight anyway.
How This Book Is Organized Each new feature is introduced by answering the following three questions: 0001 What is this new feature?
0001 Why was it introduced into the language?
0001 How does it work?
3
4
C++ For Dummies, 5th Edition Small pieces of code are sprinkled liberally throughout the chapters. Each demonstrates some newly introduced feature or highlights some brilliant point I’m making. These snippets may not be complete and certainly don’t do any thing meaningful. However, every concept is demonstrated in at least one functional program. Note: A good programmer doesn’t let lines of code extend too far because it makes them hard to read. I have inserted newlines appropriately to limit my programs to the width of the book page.
And There’s More
A real-world program can take up lots of pages. However, seeing such a pro gram is an important didactic tool for any reader. I have included a series of programs along with an explanation of how these programs work on the enclosed CD-ROM. I use one simple example program that I call BUDGET. This program starts life as a simple, functionally-oriented BUDGET1. This program maintains a set of simple checking and savings accounts. The reader is encouraged to review this program at the end of Part II. The subsequent version, BUDGET2, adds the object-oriented concepts presented in Part III. The examples work their way using ever more features of the language, culminating with BUDGET5, which you should review after you master all the chapters in the book. The BUDGET programs can be found on the book’s CD-ROM. For a complete overview of the CD-ROM’s contents, see this book’s Appendix.
Part I: Introduction to C++ Programming
Part I starts you on your journey. You begin by examining what it means to write a computer program. From there, you step through the syntax of the language (the meaning of the C++ commands).
Part II: Becoming a Functional C++ Programmer In this part, you expand upon your newly gained knowledge of the basic com mands of C++ by adding the capability to bundle sections of C++ code into mod ules and reusing these modules in programs.
Introduction In this section, I also introduce that most dreaded of all topics, the C++ pointer. If you don’t know what that means, don’t worry — you’ll find out soon enough.
Part III: Introduction to Classes
The plot thickens in this part. Part III begins the discussion of object-oriented programming. Object-oriented programming is really the reason for the exis tence of C++. Take the OO features out of C++, and you’re left with its prede cessor language, C. I discuss things such as classes, constructors, destructors, and making nachos (I’m not kidding, by the way). Don’t worry if you don’t know what these concepts are (except for nachos — if you don’t know what nachos are, we’re in big trouble).
Part IV: Inheritance
Inheritance is where object-oriented programming really comes into its own. Understanding this most important concept is the key to effective C++ pro gramming and the goal of Part IV. There’s no going back now — after you’ve completed this part, you can call yourself an Object-Oriented Programmer, First Class.
Part V: Optional Features
By the time you get to Part V, you know all you need to program effectively in C++. I touch on the remaining features of the language. Features such as file input/output, error-handling constructs, and templates are left to this part.
Part VI: The Part of Tens
What For Dummies book would be complete without The Part of Tens? Chap ter 29 shows you the top ten best ways to avoid introducing bugs into your programs, bugs that you would otherwise have to ferret out on your own. Chapter 30 takes you through the most important tools and options in the Dev-C++ environment. Although Dev-C++ is not part of the C++ language, under standing these options enhances your programming experience.
5
6
C++ For Dummies, 5th Edition
Icons Used in This Book
This is technical stuff that you can skip on the first reading.
Tips highlight a point that can save you a lot of time and effort.
This icon alerts you to examples and software that appear on this book’s CD-ROM.
Remember this. It’s important.
Remember this, too. This one can sneak up on you when you least expect it and generate one of those really hard-to-find bugs.
Where to Go from Here
Finding out about a programming language is not a spectator sport. I’ll try to make it as painless as possible, but you have to power up the ol’ PC and get down to some serious programming. Limber up the fingers, break the spine on the book so that it lies flat next to the keyboard (and so that you can’t take it back to the bookstore), and dive in.
Part I
Introduction to C++ Programming
B
In this part . . .
oth the newest, hottest flight simulator and the simplest yet most powerful accounting programs use the same basic building blocks. In this part, you dis cover the basic features you need to write your killer application.
Chapter 1
Writing Your First C++ Program In This Chapter 0001 Finding out about C++ 0001 Installing Dev-CPP from the accompanying CD-ROM 0001 Creating your first C++ program 0001 Executing your program
O
kay, so here we are: No one here but just you and me. Nothing left to do but get started. Might as well lay out a few fundamental concepts.
A computer is an amazingly fast but incredibly stupid machine. A computer can do anything you tell it (within reason), but it does exactly what it’s told — nothing more and nothing less. Perhaps unfortunately for us, computers don’t understand any reasonable human language — they don’t speak English either. Okay, I know what you’re going to say: “I’ve seen computers that could understand English.” What you really saw was a computer executing a program that could meaningfully under stand English. (I’m still a little unclear on this computer-understanding-language concept, but then I don’t know that my son understands my advice, either, so I’ll let it slide.) Computers understand a language variously known as computer language or machine language. It’s possible but extremely difficult for humans to speak machine language. Therefore, computers and humans have agreed to sort of meet in the middle, using intermediate languages such as C++. Humans can speak C++ (sort of), and C++ is converted into machine language for the com puter to understand.
10
Part I: Introduction to C++ Programming
Grasping C++ Concepts
In the early 1970s, a consortium of really clever people worked on a computer system called Multix. The goal of Multix was to give all houses inexpensive computer access to graphics, e-mail, stock data, pornography (just kidding), whatever. Of course, this was a completely crazy idea at the time, and the entire concept failed. A small team of engineers working for Bell Labs decided to save some portion of Multix in a very small, lightweight operating system that they dubbed Unix (Un-ix, the single task version of Mult-ix, get it?). Unfortunately for these engineers, they didn’t have one large machine but a number of smaller machines, each from a different manufacturer. The standard development tricks of the day were all machine-dependent — they would have to rewrite the same program for each of the available machines. Instead, these engineers invented a small, powerful language named C. C caught on like wildfire. Eventually, however, new programming techniques (most notably object-oriented programming) left the C programming language behind. Not to be outdone, the engineering community added equivalent new features to the C language. The result was called C++. The C++ language consists of two basic elements: 0002 Semantics: This is a vocabulary of commands that humans can under stand and that can be converted into machine language, fairly easily. and 0002 Syntax: This is a language structure (or grammar) that allows humans to combine these C++ commands into a program that actually does some thing (well, maybe does something). Think of the semantics as the building blocks of your C++ program and the syntax as the correct way to put them together.
What’s a program?
A C++ program is a text file containing a sequence of C++ commands put together according to the laws of C++ grammar. This text file is known as the source file (probably because it’s the source of all frustration). A C++ source file carries the extension .CPP just as a Microsoft Word file ends in .DOC or an MS-DOS (remember that?) batch file ends in .BAT. The concept extension .CPP is just a convention.
Chapter 1: Writing Your First C++ Program The point of programming in C++ is to write a sequence of commands that can be converted into a machine-language program that actually does what we want done. The resulting machine-executable files carry the extension .EXE. The act of creating an executable program from a C++ program is called compiling or building (the subtle difference between the two is described in Chapter 22). That sounds easy enough — so what’s the big deal? Keep going.
How do I program? To write a program, you need two specialized computer programs. One (an editor) is what you use to write your code as you build your .CPP source file. The other (a compiler) converts your source file into a machine-executable .EXE file that carries out your real-world commands (open spreadsheet, make rude noise, deflect incoming asteroid, whatever). Nowadays, tool developers generally combine compiler and editor into a single package — a development environment. After you finish entering the commands that make up your program, you need only click a button to create the exe cutable file. The most popular of all C++ environments is a Microsoft product, Visual C++.NET (pronounced “Visual-C-plus-plus-DOT-net”). All programs in this book compile and execute with Visual C++.NET; however, many of you may not already own Visual C++.NET — and at $250 bucks a pop, street price, this may be a problem. Fortunately, there are public-domain C++ environments. We use one of them in this book — the Dev-CPP environment. A recent version of Dev-CPP envi ronment is included on CD-ROM enclosed at the back of this book (or you can download the absolutely most recent version off the Web at www.bloodshed. net). You can download quite a range of public-domain programs from the Internet. Some of these programs, however, are not free — you’re encouraged — or required — to pay some (usually small) fee. You don’t have to pay to use DevC++, but you can contribute to the cause if you like. See the Web site for details. I have tested the programs in this book with Dev-C++ version 4.9.8.0; they should work with other versions as well. You can check out my Web site at www.stephendavis.com for a list of any problems that may arise with future versions of Dev-C++ or Windows. Dev-C++ is not some bug-ridden, limited edition C++ compiler from some flyby-night group of developers. Dev-C++ is a full-fledged C++ environment. DevC++ supports the entire C++ language and executes all the programs in this book (and any other C++ book) just fine, thank you.
11
12
Part I: Introduction to C++ Programming Dev-C++ does generate Windows-compatible 32-bit programs, but it does not easily support creating programs that have the classic Windows look. If you want to do that, you’ll have to break open the wallet and go for a commercial package like Visual Studio.NET. Having said that, I strongly recommend that you work through the examples in this book first to learn C++ before you tackle Windows development. They are two separate things and (for the sake of sanity) should remain so in your mind. Follow the steps in the next section to install Dev-C++ and build your first C++ program. This program’s task is to convert a temperature value entered by the user from degrees Celsius to degrees Fahrenheit. The programs in this book are compatible with Visual C++.NET and the C++ section of Visual Studio.NET (which are essentially the same thing). Use the documentation in the Visual C++ .NET for instructions on installing C++. True, the error messages generated by Visual C++.NET are different (and often just as difficult to decipher), but the territory will seem mysteriously familiar. Even though you’re using a different songbook, you shouldn’t have much trouble following the tune.
Installing Dev-C++
The CD-ROM that accompanies this book includes the most recent version of the Dev-C++ environment at the time of this writing. The Dev-C++ environment comes in an easy-to-install, compressed executable file. This executable file is contained in the DevCPP directory on the accom panying CD-ROM. Here’s the rundown on installing the environment: 1. Navigate to and double-click the file devcpp4980.exe, or (in Windows) click Start➪Run. • Double-clicking the file installs the environment automatically. (Note that 4.9.8.0, the version number, will be different on any newer ver sion of Dev-C++ you downloaded off the Web.) • If you clicked Start➪Run, type x:devcppdevcpp4980 in the Run window that appears, where x is the letter designation for your CD-ROM drive (normally D but perhaps E — if one doesn’t work, try the other). Dev-C++ begins with a warning (shown in Figure 1-1) that you’d better uninstall any older version of Dev-C++ you may have hanging around, and then reboot and start over. (Starting an installation with a threat is an inauspicious way to begin a relationship, but everything gets better from here.)
Chapter 1: Writing Your First C++ Program
Figure 1-1: You must uninstall earlier versions of Dev-C++ before you begin the installation process.
2. If you don’t have to uninstall an old version of Dev-C++, skip to Step 4; if you do have to uninstall, abort the current installation process by closing the Run window. Don’t get upset if you’ve never even heard of Dev-C++ and you still get the warning message. It’s just a reminder. 3. Okay, if you’re on this step, you’re uninstalling: Open the Dev-CPP folder and double-click the Uninstall.exe file there. The uninstall program does its thing, preparing the way for the new instal lation; the End User Legal Agreement (commonly known as the EULA) appears. 4. Read the EULA and then click OK if you can live with its provisions. Nope, the package really won’t install itself if you don’t accept. Assuming you do click OK, Dev-C++ opens the window shown in Figure 1-2 and offers you some installation options. The defaults are innocuous, with two exceptions: • You must leave the Mingw compiler system. . . option enabled. • The Associate C and C++ Files to Dev-C++ option means that doubleclicking a .CPP file automatically opens Dev-C++ rather than some other program (such as Visual C++ .NET, for example). It is possible, but difficult, to undo this association. Don’t check this option if you also have Visual Studio.NET installed. DevC++ and Visual Studio.NET coexist peacefully on the same machine, but what Visual Studio has done, let no man cast assunder. You can still open your .CPP files with Dev-C++ by right-clicking on the file and selecting Open With. Personally, I prefer to use this option, even with Visual Studio.NET installed. It doesn’t cause any problems, and Dev-C++ starts a lot faster than Visual Studio.
13
14
Part I: Introduction to C++ Programming
Figure 1-2: The default installation options should be acceptable to most users.
5. Click the Next button. The installation program asks where you want it to install Dev-C++, using a message like that shown in Figure 1-3.
Figure 1-3: The default location for the Dev-C++ environment is provided.
6. Accept the default directory, c:Dev-CPP. Don’t install Dev-C++ in the directory Program Files with all the other executables. That’s because Dev-C++ doesn’t do well with directories that contain spaces in their names. I haven’t experimented much along these lines, but I believe you can use any other directory name without any special characters other than ‘_’. It’s safer just to accept the default. 7. Make sure you have enough room for the program, wherever you decide to put it. The Dev-C++ environment uses only a paltry 45MB, but it’s always good practice to check. 8. Click Install. At first, nothing seems to happen. Then Dev-C++ gets going, copying a whole passel of files to the Dev-CPP directory — putting absolutely noth ing in the Windows home directory. Figure 1-4 displays the eventual result.
Chapter 1: Writing Your First C++ Program
Figure 1-4: The DevC++ installation process unzips a large number of mostly small files.
While the installation is going on, Dev-C++ presents a window that asks whether you want to install for all users once it’s done copying files onto your hard drive. That question boils down to this: If someone else logs on to your computer, do you want her or him to be able to execute DevC++? (The answer is “Yes” in my case.) 9. Choose whether you want to install for all users, and then click the Close button to complete installation of the package. Dev-C++ starts immediately, so you can set its options properly for your needs. (Yep, there’s more work to do. But you knew that. Read on.)
Setting the options
As you probably know if you’ve spent more than a coffee break’s worth of time installing software, setting options is a procedure unto itself. In this case, DevC++ has two options that must be set before you can use it. Set ’em as follows: 1. Choose Tools➪Compiler Options. You can change these settings at any time, but now is as good as any. 2. Choose the Settings tab. 3. Choose Code Generation from the menu on the left. Make sure that the Enable Exception Handling is enabled, as shown in Figure 1-5. (If it isn’t, click on the option box to display the two choices and select Yes.) 4. Choose Linker and make sure the Generate Debugging Information option is enabled. Figure 1-6 shows you what to look for.
15
16
Part I: Introduction to C++ Programming
Figure 1-5: The Enable Exception Handling option must be enabled.
Figure 1-6: The Generate Debugging Information option must be enabled.
5. Choose OK. Installation is now complete! (Your options are saved automatically.)
Creating Your First C++ Program In this section, you create your first C++ program. You first enter the C++ code into a file called CONVERT.CPP, and then convert the C++ code into an exe cutable program.
Chapter 1: Writing Your First C++ Program
Entering the C++ code
The first step to creating any C++ program is to enter C++ instructions using a text editor. The Dev-C++ user interface is built around a program editor specifi cally designed to create C++ programs. 1. Click Start➪Programs➪Bloodshed Dev-C++➪Dev-C++ to start up the Dev-C++ tool. The Dev-C++ interface looks fundamentally like that of any other Win dows program — perhaps a little clunkier, but a Windows application nonetheless. This is a lot of clicking. My personal preference is to create a shortcut on the desktop. To create a shortcut, double-click My Computer. Now double-click the Local Disk (C:). Finally, double-click Dev-CPP — whew! Right-click the file devcpp.exe and choose Create Shortcut from the drop down menu. Drag the Shortcut to devcpp.exe file onto your desktop (or some other easily accessible place). From now on, you can just double-click the shortcut to start Dev-C++. 2. Choose File➪New➪Source File. Dev-C++ opens a blank window wherein you get to enter your new code. Don’t worry if you find yourself wishing you knew what to enter right now — that’s why you bought this book. 3. Enter the following program exactly as written. Don’t worry too much about indentation or spacing — it isn’t critical whether a given line is indented two or three spaces, or whether there are one or two spaces between two words. C++ is case sensitive, how ever, so you need to make sure everything is lowercase. You can cheat and copy the Conversion.cpp file contained on the enclosed CD-ROM in directory CPP_ProgramsChap01. // // Program to convert temperature from Celsius degree // units into Fahrenheit degree units: // Fahrenheit = Celsius * (212 - 32)/100 + 32 // #include
17
18
Part I: Introduction to C++ Programming // enter the temperature in Celsius int celsius; cout << “Enter the temperature in Celsius:”; cin >> celsius; // calculate conversion factor for Celsius // to Fahrenheit int factor; factor = 212 - 32; // use conversion factor to convert Celsius // into Fahrenheit values int fahrenheit; fahrenheit = factor * celsius/100 + 32; // output the results (followed by a NewLine) cout << “Fahrenheit value is:”; cout << fahrenheit << endl; // wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
4. Choose Save As under the File menu. Then type in the program name and press Enter. I know that it may not seem all that exciting, but you’ve just created your first C++ program! For purposes of this book, I created a folder CPP_Programs. Within this, I created Chap01. Finally, I saved the program with the name Conversion. cpp. Note that Dev-C++ won’t work properly with directory names that contain spaces. (It doesn’t have a problem with names longer than eight characters in length — thank goodness!)
Building your program
After you’ve saved your Conversion.cpp C++ source file to disk, it’s time to generate the executable machine instructions. To build your Conversion.cpp program, you choose Execute➪Compile from the menu or press F9 — or you can even click that cute little icon with four colored squares on the menu bar (use the Tool Tips to see which one I’m talk ing about). In response, Dev-C++ opens a compiling window. Nothing will happen at first (sshh . . . it’s thinking). After a second or two, Dev-C++ seems to take off, compiling your program with gusto. If all goes well, a window like that shown in Figure 1-7 appears.
Chapter 1: Writing Your First C++ Program
Figure 1-7: The user is rewarded with a simple Done message if his program is error free.
Dev-C++ generates a message if it finds any type of error in your C++ program — and coding errors are about as common as snow in Alaska. You’ll undoubtedly encounter numerous warnings and error messages, probably even when enter ing the simple Conversion.cpp. To demonstrate the error-reporting process, let’s change Line 17 from cin >> celsius; to cin >>> celsius;. This seems an innocent enough offense — forgivable to you and me perhaps, but not to C++. Dev-C++ opens a Compiler tab, as shown in Figure 1-8. The mes sage parse error before ‘> is perhaps a little terse, but descriptive. To get rid of the message, remove the extra > and recompile.
Figure 1-8: Bad little programs generate error messages in the Compiler window.
19
20
Part I: Introduction to C++ Programming
Why is C++ so picky? In the example given here, C++ could tell right away — and without a doubt — that I had screwed up. However, if C++ can figure out what I did wrong, why doesn’t it just fix the prob lem and go on? The answer is simple but profound. C++ thinks that I mistyped the >> symbol, but it may be mistaken. What could have been a mistyped command may actually be some other, com pletely unrelated error. Had the compiler simply
corrected the problem, C++ would have masked the real problem. Finding an error buried in a program that builds without complaining is difficult and timeconsuming. It’s far better to let the compiler find the error for you if at all possible. Generating a compiler error is a waste of the computer’s time — forcing me to find a mistake that C++ could have caught is a waste of my time. Guess which one I vote for?
The term parse means to convert the C++ commands into something that the machine-code-generating part of the process can work with. There was once a language that tried to fix simple mistakes like this for you. From my personal experience, I can tell you it was a waste of time — because (except for very simple cases) the compiler was almost always wrong. At least it warned me of the problem so I could fix it myself.
Executing Your Program
It’s now time to execute your new creation . . . that is, to run your program. You will run the CONVERT.EXE program file and give it input to see how well it works. To execute the Conversion program, click Execute➪Run or press Ctrl+F10. (I have no idea how they selected function keys. I would think that an action as common as executing a program would warrant its own function key — something without a Control or Shift key to hold down — but maybe that’s just me.) A window opens immediately, requesting a temperature in Celsius. Enter a known temperature, such as 100 degrees. After you press Enter, the program returns with the equivalent temperature of 212 degrees Fahrenheit as follows: Enter the temperature in Celsius:100 Fahrenheit value is:212 Press any key to continue . . .
Chapter 1: Writing Your First C++ Program The message Press any key gives you the opportunity to read what you’ve entered before it goes away. Press Enter, and the window (along with its con tents) disappears. Congratulations! You just entered, built, and executed your first C++ program.
Dev-C++ is not Windows
Notice that Dev-C++ is not truly intended for developing Windows programs. In theory, you can write a Windows application by using Dev-C++, but it isn’t easy. (That’s so much easier in Visual Studio.NET.) Windows programs show the user a very visually oriented output, all nicely arranged in onscreen windows. Convesion.exe is a 32-bit program that exe cutes under Windows, but it’s not a “Windows” program in the visual sense. If you don’t know what 32-bit program means, don’t worry about it. As I said earlier, this book isn’t about writing Windows programs. The C++ programs you write in this book have a command line interface executing within an MS DOS box. Budding Windows programmers shouldn’t despair — you didn’t waste your money. Learning C++ is a prerequisite to writing Windows programs. I think that they should be mastered separately: C++ first, Windows second.
Dev-C++ help
Dev-C++ provides a Help menu item. Choose Help followed by Help on Dev C++ to open up a typical Windows help box. Help is provided on various aspects of the Dev-C++ development package but not much else. Noticeably lacking is help on the C++ language itself. Click a topic of interest to display help.
Reviewing the Annotated Program
Entering data in someone else’s program is about as exciting as watching some one else drive a car. You really need to get behind the wheel itself. Programs are a bit like cars as well. All cars are basically the same with small differences and additions — OK, French cars are a lot different than other cars, but the point is still valid. Cars follow the same basic pattern — steering wheel in front of you, seat below you, roof above you and stuff like that.
21
22
Part I: Introduction to C++ Programming Similarly, all C++ programs follow a common pattern. This pattern is already present in this very first program. We can review the Conversion program by looking for the elements that are common to all programs.
Examining the framework for all C++ programs Every C++ program you write for this book uses the same basic framework, which looks a lot like this: // // Template - provides a template to be used as the starting // point // // the following include files define the majority of // functions that any given program will need #include
Without going into all the boring details, execution begins with the code con tained in the open and closed braces immediately following the line begin ning main(). I have copied this code into a file called Template.cpp located in the main CPP_Programs folder on the enclosed CD-ROM.
Clarifying source code with comments
The first few lines in Conversion.cpp appear to be freeform text. Either this code was meant for human eyes or C++ is a lot smarter than I give it credit for. These first six lines are known as comments. Comments are the programmer’s
Chapter 1: Writing Your First C++ Program explanation of what he or she is doing or thinking when writing a particular code segment. The compiler ignores comments. Programmers (good program mers, anyway) don’t. A C++ comment begins with a double slash (//) and ends with a newline. You can put any character you want in a comment. A comment may be as long as you want, but it’s customary to keep comment lines to no more than 80 char acters across. Back in the old days — “old” is relative here — screens were limited to 80 characters in width. Some printers still default to 80 characters across when printing text. These days, keeping a single line to under 80 char acters is just a good practical idea (easier to read, less likely to cause eye strain, the usual). A newline was known as a carriage return back in the days of typewriters — when the act of entering characters into a machine was called typing and not keyboarding. A newline is the character that terminates a command line. C++ allows a second form of comment in which everything appearing after a /* and before a */ is ignored; however, this form of comment isn’t normally used in C++ anymore. (Later in this book, I describe the one case in which this type of comment is applied.) It may seem odd to have a command in C++ (or any other programming lan guage) that’s specifically ignored by the computer. However, all computer lan guages have some version of the comment. It’s critical that the programmer explain what was going through her mind when she wrote the code. A programmer’s thoughts may not be obvious to the next colleague who picks up her program and tries to use it or modify it. In fact, the programmer herself may forget what her program meant if she looks at it months after writing the original code and has left no clue.
Basing programs on C++ statements
All C++ programs are based on what are known as C++ statements. This sec tion reviews the statements that make up the program framework used by the Conversion.cpp program. A statement is a single set of commands. All statements other than comments end with a semicolon. (There’s a reason that comments don’t end with a semicolon, but it’s obscure. To my mind, comments should end in semicolons as well, for consistency’s sake. Why nobody asked me about that remains a mystery.)
23
24
Part I: Introduction to C++ Programming Program execution begins with the first C++ statement after the open brace and continues through the listing, one statement at a time. As you look through the program, you can see that spaces, tabs, and newlines appear throughout the program. In fact, I place a newline after every state ment in this program. These characters are collectively known as white space because you can’t see them on the monitor. You may add white space anywhere you like in your program to enhance readability — except in the middle of a word: See wha t I mean?
Although C++ may ignore white space, it doesn’t ignore case. In fact, it’s case sensitive to the point of obsession. The variable fullspeed and the variable FullSpeed have nothing to do with each other. While the command int may be understood completely, C++ has no idea what INT means.
Writing declarations
The line int nCelsius; is a declaration statement. A declaration is a state ment that defines a variable. A variable is a “holding tank” for a value of some type. A variable contains a value, such as a number or a character. The term variable stems from algebra formulae of the following type: x = 10 y = 3 * x
In the second expression, y is set equal to 3 times x, but what is x? The vari able x acts as a holding tank for a value. In this case, the value of x is 10, but we could have just as well set the value of x to 20 or 30 or –1. The second for mula makes sense no matter what the value of x. In algebra, you’re allowed to begin with a statement, such as x = 10. In C++, the programmer must first define the variable x before she can use it. In C++, a variable has a type and a name. The variable defined on Line 11 is called celsius and declared to hold an integer. (Why they couldn’t have just said integer instead of int, I’ll never know. It’s just one of those things you learn to live with.)
Chapter 1: Writing Your First C++ Program The name of a variable has no particular significance to C++. A variable must begin with the letters A through Z or a through z. All subsequent characters must be a letter, a digit 0 through 9 or an underscore (_). Variable names can be as long as you want to make them. It’s convention that variable names begin with a lowercase letter. Each new word within a variable begins with a capital letter, as in myVariable. Try to make variable names short but descriptive. Avoid names such as x because x has no particular meaning. A variable name such as lengthOfLine Segment is much more descriptive.
Generating output
The lines beginning with cout and cin are known as input/output statements, often contracted to I/O statements. (Like all engineers, programmers love con tractions and acronyms.) The first I/O statement says output the phrase Enter the temperature in Celsius to cout (pronounced “see-out”). cout is the name of the standard C++ output device. In this case, the standard C++ output device is your monitor. The next line is exactly the opposite. It says, in effect, Extract a value from the C++ input device and store it in the integer variable celsius. The C++ input device is normally the keyboard. What we’ve got here is the C++ analog to the algebra formula x = 10 just mentioned. For the remainder of the program, the value of celsius is whatever the user enters there.
Calculating Expressions
All but the most basic programs perform calculations of one type or another. In C++, an expression is a statement that performs a calculation. Said another way, an expression is a statement that has a value. An operator is a command that generates a value. For example, in the Conversion example program — specifically in the two lines marked as a calculation expression — the program declares a vari able factor and then assigns it the value resulting from a calculation. This par ticular command calculates the difference of 212 and 32; the operator is the minus sign (–), and the expression is 212–32.
25
26
Part I: Introduction to C++ Programming
Storing the results of expression
The spoken language can be very ambiguous. The term equals is one of those ambiguities. The word equals can mean that two things have the same value as in “5 cents equals a nickel.” Equals can also imply assignment, as in math when you say that “y equals 3 times x.” To avoid ambiguity, C++ programmers call the assignment operator, which says (in effect), Store the results of the expression to the right of the equal sign in the variable to the left. Programmers say that “factor is assigned the value 212 minus 32.” Never say “factor is equal to 212 minus 32.” You’ll hear this from some lazy types, but you and I know better.
Examining the remainder of Conversion.cpp The second expression in Conversion.cpp presents a slightly more compli cated expression than the first. This expression uses the same mathematical symbols: * for multiplication, / for division and, + for addition. In this case, how ever, the calculation is performed on variables and not simply on constants. The value contained in the variable called factor (calculated immediately prior, by the way) is multiplied by the value contained in celsius (which was input from the keyboard). The result is divided by 100 and summed with 32. The result of the total expression is assigned to the integer variable fahrenheit. The final two commands output the string Fahrenheit value is: to the display, followed by the value of fahrenheit — and all so fast that the user scarcely knows it’s going on.
Chapter 2
Declaring Variables Constantly In This Chapter 0001 Declaring variables 0001 Declaring different types of variables 0001 Using floating-point variables 0001 Declaring and using other variable types
T
he most fundamental of all concepts in C++ is the variable — a variable is like a small box. You can store things in the box for later use, particularly numbers. The concept of a variable is borrowed from mathematics. A state ment such as x = 1
stores the value 1 in the variable x. From that point forward, the mathemati cian can use the variable x in place of the constant 1 — until she changes the value of x to something else. Variables work the same way in C++. You can make the assignment x = 1;
From that point forward in the program, until the value of x is changed, any references to x are the same as referencing 1. That is, the value of x is 1. Unfortunately, C++ has a few more concerns about variables than the mathe matician does. This chapter deals with the care and feeding of variables in C++.
Declaring Variables
C++ saves numeric values in small storage boxes known as variables. Mathe maticians throw variables around with abandon. A mathematician might (for example) write down something like the following:
28
Part I: Introduction to C++ Programming (x + 2) = y / 2 x + 4 = y solve for x and y
Any reader who’s had algebra realizes right off that the mathematician has introduced the variables x and y. But C++ isn’t that smart (computers may be fast, but they’re stupid). You have to announce each variable to C++ before you can use it. You have to say something soothing like this: int x; x = 10; int y; y = 5;
These lines of code declare that a variable x exists, that it is of type int, and that a variable y of type int also exists. (The next section discusses vari able types.) You can declare variables (almost) anywhere you want in your program — as long as you declare the variable before you use it.
Declaring Different Types of Variables
If you’re on friendly terms with math (hey, aren’t we all?), you probably think of a variable in mathematics as an amorphous box capable of holding what ever you might choose to store in it. You might easily write something like the following: x x x x
= = = =
1 2.3 “this is a sentence” Texas
Alas, C++ is not that flexible. (On the other hand, C++ can do things that people can’t do, such as add a billion numbers or so in a second, so let’s not get too uppity.) To C++, there are different types of variables just as there are different types of storage bins. Some storage bins are so small that they can only handle a single number. It takes a larger bin to handle a sentence. Of course, no bin is large enough to hold Texas (maybe Rhode Island or Delaware). You have to tell C++ what size bin you need before you can use a C++ variable. In addition, different types of variables have different properties. So far, you have only seen the int type of variable in this chapter:
Chapter 2: Declaring Variables Constantly int x; x = 1;
The variable type int is the C++ equivalent of an integer — a number that has no fractional part. (Integers are also known as counting numbers or whole numbers.) Integers are great for most calculations. You can make it up through most (if not all) of elementary school with integers. It isn’t until you reach age 11 or so that they start mucking up the waters with fractions. The same is true in C++: More than 90 percent of all variables in C++ are declared to be of type int. Unfortunately, int variables don’t always work properly in a program. If (for example) you worked through the temperature-conversion program in Chap ter 1, the program has a potential problem — it can only handle integer tem peratures — whole numbers that don’t have a fractional part. This limitation of using only integers doesn’t affect daily use because it isn’t likely that some one (other than a meteorologist) would get all excited about entering a frac tional temperature (such as 10.5 degrees). The lurking problem is not at all obvious: The conversion program lops off the fractional portion of tempera tures that it calculates, and just keeps going without complaint. This can result in a lapse of accuracy that can be serious — for example, you wouldn’t want to come up a half mile short of the runway on your next airplane trip due to a navigational round-off.
Reviewing the limitations of integers in C++ The int variable type is the C++ version of an integer. int variables suffer the same limitations as their counting-number integer equivalents in math do.
Integer round-off Consider the problem of calculating the average of three numbers. Given three int variables — nValue1, nValue2, and nValue3 — an equation for calculat ing the average is int nAverage; int nValue1; int nValue2; int nValue3; nAverage =(nValue1 + nValue2 + nValue3) / 3;
Because all three values are integers, the sum is assumed to be an integer. Given the values 1, 2, and 2, the sum is 5. Divide that by 3, and you get 12⁄ 3, or 1.666. Given that all three variables nValue1, nValue2, and nValue3 are inte gers, the sum is also assumed to be an integer. The result of the division is also an integer. The resulting value of nAverage is unreasonable but logical: 1.
29
30
Part I: Introduction to C++ Programming Lopping off the fractional part of a number is called truncation, or rounding off. For many applications, truncation isn’t a big deal. Some folks might con sider its results reasonable (not mathematicians or bookies, of course), but integer truncation can create math mayhem in computer programs. Consider the following equivalent formulation: int nAverage; int nValue1; int nValue2; int nValue3; nAverage = nValue1/3 + nValue2/3 + nValue3/3;
Plugging in the same 1, 2, and 2 values, the resulting value of nAverage is (talk about logical-but-unreasonable) 0. To see how this can occur, consider that 13 truncates to 0, 23 truncates to 0, and 23 truncates to 0. The sum of 0, 0, and 0 is zero. (Sort of like that old song: “Nothing from nothing leaves nothing, ya gotta be something . . .”) You can see that integer truncation can be completely unacceptable.
Limited range A second problem with the int variable type is its limited range. A normal int variable can store a maximum value of 2,147,483,647 and a minimum value of –2,147,483,648 — roughly from positive 2 billion to negative 2 billion, for a total range of about 4 billion. Two billion is a very large number: plenty big enough for most uses. But it’s not large enough for some applications — for example, computer technology. In fact, your computer probably executes faster than 2 gigahertz, depending upon how old your computer is. (Giga is the prefix meaning billion.) A single strand of communications fiber — the kind that’s been strung from one end of the country to the other — can handle way more than 2 billion bits per second. C++ offers a little help by allowing you declare an integer to be unsigned, mean ing that it cannot be negative. An unsigned int value type can represent a number from 0 to 4,294,967,295, should the need arise for some unimaginable reason. You can declare a variable simply unsigned. The int is implied.
Solving the truncation problem The limitations of int variables can be unacceptable in some applications. Fortunately, C++ understands decimal numbers. A decimal number can have a nonzero fractional part. (Mathematicians also call those real numbers.) Decimal numbers avoid many of the limitations of int type integers. Notice that a decimal number “can have” a nonzero fractional part. In C++, the number 1.0 is just as much a decimal number as 1.5. The equivalent integer is written simply as 1. Decimals numbers can also be negative, like –2.3.
Chapter 2: Declaring Variables Constantly When you declare variables in C++ that are decimal numbers, you identify them as double precision floating-point values. (Yes, there is such a critter as a “single precision floating-point variable,” but stick with me here.) The term floating-point means the decimal point is allowed to float back and forth, iden tifying as many “decimal places” as necessary to express the value. Floatingpoint variables are declared in the same way as int variables: double dValue1;
From this point forward, the variable dValue1 is declared to be a double. Once declared, you cannot change the type of a variable. dValue1 is now a double and will be a double for the remainder of its natural instructions. To see how floating-point numbers fix the truncation problem inherent with integers, con vert all the int variables to double. Here’s what you get: double dValue; dValue = 1.0/3.0 + 2.0/3.0 + 2.0/3.0;
is equivalent to dValue = 0.333... + 0.666... + 0.666...;
which results in the value dValue = 1.666...;
I have written the value 1.6666 . . . as if the number of trailing 6s goes on forever. This is (not necessarily) the case. There’s a limit to the number of digits of accuracy of a double variable — but it’s a lot more than I can keep track of. The programs IntAverage and FloatAverage are available on the enclosed CD in the CPP_ProgramsChap02 directory to demonstrate this averaging example.
Looking at the limits of
floating-point numbers
Although floating-point variables can solve many calculation problems such as truncation, they have some limitations themselves — in effect, the reverse of those associated with integer variables. double variables can’t be used as counting numbers, they’re more difficult for the computer to handle, and they also suffer from round-off error (though not nearly to the same degree as int variables).
31
32
Part I: Introduction to C++ Programming Counting You cannot use floating-point variables in applications where counting is impor tant. This includes C++ constructs, which requires counting ability. C++ can’t verify which whole number value is meant by a given floating-point number. For example, it’s clear that 1.0 is 1. But what about 0.9 or 1.1? Should these also be considered as 1? C++ simply avoids the problem by insisting on using int values when counting is involved.
Calculation speed Historically, a computer processor can process integer arithmetic quicker than it can floating-point arithmetic. Thus, while a processor can add 1 million inte ger numbers in a given amount of time, the same processor may be able to perform only 200,000 floating-point calculations during the same period. (Not surprisingly, I couldn’t even get around to reading the first value.) Calculation speed is becoming less of a problem as microprocessors increase their capabilities. Most modern processors contain special calculation cir cuitry for performing floating-point calculations almost as fast as integer calculations.
Loss of accuracy Floating-point variables cannot solve all computational problems. Floatingpoint variables have a limited precision of about 6 digits — an extra-economy size, double-strength version of float can handle some 15 significant digits with room left over for lunch. To evaluate the problem, consider that 13 is expressed as 0.333 . . . in a con tinuing sequence. The concept of an infinite series makes sense in math, but not to a computer. The computer has a finite accuracy. Average 1, 2, and 2 (for example), and you get 1.666667. C++ can correct for many forms of round-off error. For example, in output, C++ can determine that instead of 0.999999, that the user really meant 1. In other cases, even C++ cannot correct for round-off error.
Not-so-limited range Although the double data type has a range much larger than that of an inte ger, it’s still limited. The maximum value for an int is a skosh more than 2 bil lion. The maximum value of a double variable is roughly 10 to the 38th power. That’s 1 followed by 38 zeroes; it eats 2 billion for breakfast. (It’s even more than the national debt, at least at the time of this writing.) Only the first 13 digits or so have any meaning; the remaining 25 digits suffer from floating-point round-off error.
Chapter 2: Declaring Variables Constantly
Declaring Variable Types
So far this chapter has been trumpeting that variables must be declared and that they must be assigned a type. Fortunately (ta-dah!), C++ provides a num ber of different variable types. See Table 2-1 for a list of variables, their advan tages, and limitations.
Table 2-1
C++ Variables
Variable
Example
Purpose
int
1
A simple counting number, either positive or negative.
unsigned int
1U
A counting number that’s only non-negative.
long
10L
A potentially larger version of int. There is no difference between long and int with Dev-C++ and Microsoft Visual C++.NET.
unsigned long
10UL
A nonnegative long integer.
float
1.0F
A single precision real number. This smaller version takes less memory than a double but has less accuracy and a smaller range.
double
1.0
A standard floating-point variable.
char
‘c’
A single char variable stores a single alpha betic or digital character. Not suitable for arithmetic.
string
“this is a string”
A string of characters forms a sentence or phrase.
bool
true
The only other value is false. No I mean, it’s really false. Logically false. Not “false” as in fake or ersatz or . . . never mind.
It may seem odd that the standard floating length variable is called double while the “off size” is float. In days gone by, memory was an expensive asset — you could reap significant space savings by using a float variable. This is no longer the case. That, combined with the fact that modern processors perform double precision calculations at the same speed as float, makes the double the default. Bigger is better, after all.
33
34
Part I: Introduction to C++ Programming The following statement declares a variable lVariable as type long and sets it equal to the value 1, while dVariable is a double set to the value 1.0: // declare a variable and set it to 1 long lVariable; lVariable = 1; // declare a variable of type double and set it to 1.0 double dVariable; dVariable = 1.0;
You can declare a variable and initialize it in the same statement: int nVariable = 1;
// declare a variable and // initialize it to 1
Although such declarations are common, the only benefit to initializing a vari able in the declaration is that it saves typing. A char variable can hold a single character; a string (which isn’t really a vari able but works like one for most purposes) holds a string of characters. Thus, ‘C’ is a char that contains the character C, whereas “C” is a string with one character in it. A rough analogy is that a ‘C’ corresponds to a nail in your hand, whereas “C” corresponds to a nail gun with one nail left in the magazine. (Chap ter 9 describes strings in detail.) If an application requires a string, you’ve gotta provide one, even if the string contains only a single character. Providing nothing but the character just won’t do the job.
Types of constants
A constant is an explicit number or character (such as 1, 0.5, or ‘c’) that doesn’t change. As with variables, every constant has a type. In an expression such as n = 1; (for example), the constant 1 is an int. To make 1 a long integer, write the statement as n = 1L;. The analogy is as follows: 1 represents a single ball in the bed of a pickup truck, whereas 1L is a single ball in the bed of a dump truck. The ball is the same, but the capacity of its container is much larger. Following the int to long comparison, 1.0 represents the value 1, but in a floating-point container. Notice, however, that the default for floating-point constants is double. Thus, 1.0 is a double number and not a float. true is a constant of type bool. However, “true” (note the quotation marks)
is a string of characters that spell out the word true. In addition, in keeping with C++’s attention to case, true is a constant, but TRUE has no meaning.
Chapter 2: Declaring Variables Constantly
Special characters
You can store any printable character you want in a char or string vari able. You can also store a set of non-printable characters that is used as character constants. See Table 2-2 for a description of these important nonprintable characters.
Table 2-2
Special Characters
Character Constant
Action
‘n’
newline
‘t’
tab
‘0’
null
‘’
backslash
You have already seen the newline character at the end of strings. This char acter breaks a string and puts the parts on separate lines. A newline charac ter may appear anywhere within a string. For example, “This is line 1nThis is line 2”
appears on the output as This is line 1 This is line 2
Similarly, the t tab character moves output to the next tab position. (This position can vary, depending on the type of computer you’re using to run the program.) Because the backslash character is used to signify special charac ters, a character pair for the backslash itself is required. The character pair represents the backslash.
C++ collision with file names Windows uses the backslash character to sep arate folder names in the path to a file. (This is a remnant of MS-DOS that Windows has not been able to shake.) Thus, RootFolderA File represents File within FolderA, which is a subdirectory of Root.
Unfortunately, MS-DOS’s use of backslash con flicts with the use of backslash to indicate an escape character in C++. The character is a backslash in C++. The MS-DOS path Root FolderAFile is represented in C++ string as RootFolderAFile.
35
36
Part I: Introduction to C++ Programming
Are These Calculations Really Logical?
C++ provides a logical variable called bool. The type bool comes from Boolean, the last name of the inventor of the logical calculus. There are two values for a boolean variable: true and false. There are actually calculations that result in the value bool. For example, “x is equal to y” is either true or false.
Mixed Mode Expressions
C++ allows you to mix variable types in a single expression. That is, you are allowed to add an integer with a double precision floating-point value. In the following expression, for example, nValue1 is allowed to be an int: // in the following expression the value of nValue1 // is converted into a double before performing the // assignment int nValue1 = 1; nValue1 + 1.0;
An expression in which the two operands are not the same type is called a mixed-mode expression. Mixed-mode expressions generate a value whose type is equal to the more capable of the two operands. In this case, nValue1 is con verted to a double before the calculation proceeds. Similarly, an expression of one type may be assigned to a variable of a different type, as in the following statement: // in the following assignment, the whole // number part of fVariable is stored into nVariable double dVariable = 1.0; int nVariable; nVariable = dVariable;
You can lose precision or range if the variable on the left side of the assignment is smaller. In the previous example, C++ truncates the value of dVariable before storing it in nVariable. Converting a larger value type into a smaller value type is called demotion, whereas converting values in the opposite direction is known as promotion. Programmers say that the value of int variable nVariable1 is promoted to a double as expressions such as the following: int nVariable1 = 1; double dVariable = nVariable1;
Chapter 2: Declaring Variables Constantly
Naming conventions You may have noticed that the name of each variable begins with a special character that seems to have nothing to do with the name. These special characters are shown in the fol lowing table. You can immediately recognize dVariable as a variable of type double by using this convention. Character
Type
n
int
l
long
f
float
d
double
c
character
sz
string
These leading characters help the programmer keep track of the variable type. Thus, you can immediately identify the following as a mixedmode assignment of a long variable to an int variable: nVariable = lVariable;
These leading characters have no significance to C++. You don’t need to adopt any naming scheme at all if you don’t want to. Here’s what you get: double myVariable; int someIntValue; double nThisDoesntEvenMatch;
I used this first-letter-naming convention in this chapter to simplify the discussion; many pro grammers use this naming scheme all the time.
Mixed-mode expressions are not a good idea. Avoid forcing C++ to do your conversions for you.
37
38
Part I: Introduction to C++ Programming
Chapter 3
Performing Mathematical
Operations
In This Chapter 0001 Defining mathematical operators in C++ 0001 Using the C++ mathematical operators 0001 Identifying expressions 0001 Increasing clarity with special mathematical operators
A
mathematician uses more than just the variables described in Chap ter 2. A mathematician must do something with those variables: She can add them together, subtract them, multiply them, and perform an almost end less list of other operations. C++ offers the same set of basic operations: C++ programs can multiply, add, divide, and so forth. Programs have to be able to perform these operations in order to get anything done. What good is an insurance program if it can’t cal culate how much you’re supposed to (over) pay? C++ operations look like the arithmetic operations you would perform on a piece of paper, except you have to declare any variables before you can use them (as detailed in Chapter 2): int var1; int var2 = 1; var1 = 2 * var2;
Two variables, var1 and var2, are declared. var2 is initialized to 1. var1 is assigned the value resulting from the calculation two times the value of var2. This chapter describes the complete set of C++ mathematical operators.
40
Part I: Introduction to C++ Programming
Performing Simple Binary Arithmetic
A binary operator is one that has two arguments. If you can say var1 op var2, op must be a binary operator. The most common binary operators are the simple operations you performed in grade school. The binary operators are flagged in Table 3-1.
Table 3-1
Mathematical Operators in Order of Precedence
Precedence
Operator
Meaning
1
+ (unary)
Effectively does nothing
1
- (unary)
Returns the negative of its argument
2
++ (unary)
Increment
2
-- (unary)
Decrement
3
* (binary)
Multiplication
3
/ (binary)
Division
3
% (binary)
Modulo
4
+ (binary)
Addition
4
- (binary)
Subtraction
5
=, *=,%=,+=,-= (special)
Assignment types
Multiplication, division, modulus, addition, and subtraction are the operators used to perform arithmetic. In practice, they work just like the familiar arith metic operations as well. For example, using the binary operator for division with a float variable looks like this: float var = 133 / 12;
Each of the binary operators has the conventional meaning that you studied in grammar school — with one exception. You may not have encountered modulus in your studies. The modulus operator (%) works much like division, except it produces the remainder after division instead of the quotient. For example, 4 goes into 15 three times with a remainder of 3. Expressed in C++ terms, 15 modulus 4 is 3. int var = 15 % 4; // var is initialized to 3
Chapter 3: Performing Mathematical Operations Because programmers are always trying to impress nonprogrammers with the simplest things, C++ programmers define modulus as follows: IntValue % IntDivisor
This expression is equal to IntValue - (IntValue / IntDivisor) * IntDivisor
Try it out on this example: 15 % 4 is equal to 15 - (15/4) * 4 15 - 3 * 4 15 - 12 3
Modulus is not defined for floating-point variable because it depends on the round-off error inherent in integers. (I discuss round-off errors in Chapter 2.)
Decomposing Expressions The most common type of statement in C++ is the expression. An expression is a C++ statement with a value. Every expression has a type (such as int, double, char, and so on). A statement involving any mathematical operator is an expression since all these operators return a value. For example, 1 + 2 is an expression whose value is 3 and type is int. (Remember that constants without decimal points are ints.) Expressions can be complex or extremely simple. In fact, the statement 1 is an expression because it has a value (1) and a type (int). There are five expres sions in the following statement: z = x * y + w;
The expressions are x * y + w x * y x y w
41
42
Part I: Introduction to C++ Programming An unusual aspect of C++ is that an expression is a complete statement. Thus, the following is a legal C++ statement: 1;
The type of the expression 1 is int.
Determining the Order of Operations
All operators perform some defined function. In addition, every operator has a precedence — a specified place in the order in which the expressions are evaluated. Consider, for example, how precedence affects solving the follow ing problem: int var = 2 * 3 + 1;
If the addition is performed before the multiplication, the value of the expres sion is 2 times 4 or 8. If the multiplication is performed first, the value is 6 + 1 or 7. The precedence of the operators determines who goes first. Table 3-1 shows that multiplication has higher precedence than addition, so the result is 7. (The concept of precedence is also present in arithmetic. C++ adheres to the common arithmetic precedence.) So what happens when we use two operators of the same precedence in the same expression? Well, it looks like this: int var = 8 / 4 / 2;
But is this 8 divided by 2 or 4, or is it 2 divided by 2 or 1? When operators of the same precedence appear in the same expression, they are evaluated from left to right (the same rule applied in arithmetic). Thus, the answer is 8 divided by 4, which is 2 divided by 2 (which is 1). The expression x / 100 + 32
divides x by 100 before adding 32. But what if the programmer wanted to divide x by 100 plus 32? The programmer can change the precedence by bundling expressions together in parentheses (shades of algebra!), as follows: x/(100 + 32)
Chapter 3: Performing Mathematical Operations This expression has the same effect as dividing x by 132. The original expression x / 100 + 32
is identical to the expression (x/100) + 32
In a given expression, C++ normally performs multiplication and division before addition or subtraction. Multiplication and division have higher precedence than addition and subtraction. In summary: Precedence refers to the order in which operators are evaluated. An operator with higher precedence is executed first. You can override the precedence of an operator by using parentheses.
Performing Unary Operations
Arithmetic binary operators — those operators that take two arguments — are familiar to a lot of us from school days. You’ve probably been doing binary operations since the first grade in school. But consider the unary operators, which take a single argument (for example, –a). Many unary operations are not so well known. The unary mathematical operators are plus, plus-plus, minus, and minus-minus (respectively, +, –, ++, and – –). Thus int var1 = 10; int var2 = -var1;
The latter expression uses the minus unary operator (–) to calculate the value negative 10. The minus operator changes the sign of its argument. Positive numbers become negative and vice versa. The plus operator does not change the sign of its argument. It wouldn’t be weird to say the plus operator has no effect at all. The ++ and the – – operators might be new to you. These operators (respec tively) add one to their arguments or subtract one from their arguments, so they’re known (also respectively) as the increment and decrement operators.
43
44
Part I: Introduction to C++ Programming Because they’re dependent upon numbers that can be counted, they’re lim ited to non-floating-point variables. For example, the value of var after exe cuting the following expression is 11. int var = 10; var++;
// initalize var // now increment it // value of var is now 11
The increment and decrement operators are peculiar in that both come in two flavors: a prefix version and a postfix version (known as pre-increment and post-increment, respectively). Consider, for example, the increment operator (the decrement works in exactly the same way). Suppose that the variable n has the value 5. Both ++n and n++ increment n to the value 6. The difference between the two is that the value of ++n in an expression is 6 while the value of n++ is 5. The following example illustrates this difference: // declare three integer variables int n1, n2, n3; // the value of both n1 and n2 is 6 n1 = 5; n2 = ++n1; // the value of n1 is 6 but the value of n3 is 5 n1 = 5; n3 = n1++;
Thus n2 is given the value of n1 after n1 has been incremented (using the pre-increment operator), whereas n3 gets the value of n1 before it is incre mented using the post-increment operator.
Why define a separate increment operator? The authors of C++ noted that programmers add 1 more than any other constant. To provide some convenience, a special add 1 instruction was added to the language. In addition, most present-day computer proces sors have an increment instruction that is faster
than the addition instruction. Back when C++ was created, however — with microprocessors being what they were — saving a few instruc tions was a big deal.
Chapter 3: Performing Mathematical Operations
Using Assignment Operators
An assignment operator is a binary operator that changes the value of its left argument. The equal sign (=), a simple assignment operator, is an absolute necessity in any programming language. This operator puts the value of the right-hand argument into the left argument. The other assignment operators are odd enough that they seem to be someone’s whim. The creators of C++ noticed that assignments often follow the form of variable = variable # constant
where # is some binary operator. Thus, to increment an integer operator by 2, the programmer might write nVariable = nVariable + 2;
This expression says, “add two to the value of nVariable and store the results back into nVariable.” Doing so changes the value of nVariable to 2 more than it was. It’s common to see the same variable on both the right and left side of an assignment. Because the same variable appears on both sides of the = sign, the same Fathers of the C++ Republic decided to create a version of the assignment operator in which a binary operator is attached. This says, in effect, “Thou shalt perform whatever operation on a variable and store the results right back into the same variable.” Every binary operator has one of these nifty assignment versions. Thus, the assignment just given could have been written this way: nVariable = nVariable + 2; nVariable += 2;
Here the first line says (being very explicit now) “Take the value of nVariable, add 2, and store the results back into nVariable.” The line is a second form if the same expression, saying (a bit more abruptly), “Add 2 to the value of nVariable.” Other than assignment itself, these assignment operators are not used all that often. However, as odd as they might look, sometimes they can actually make the resulting program easier to read.
45
46
Part I: Introduction to C++ Programming
Chapter 4
Performing Logical Operations In This Chapter 0001 Using sometimes-illogical logical operators 0001 Defining logical variables 0001 Operating with bitwise logical operators logically, a bit at a time
T
he most common statement in C++ is the expression. Most expressions involve the arithmetic operators such as addition (+), subtraction (–) and multiplication (*). This chapter describes these types of expressions. There is a whole other class of operators known as the logical operators. In comparison with the arithmetic operators, most people don’t think nearly as much about operations. It isn’t that people don’t deal with logical operations — after all, people compute AND and OR constantly. I won’t eat cereal unless the bowl contains cereal AND the bowl has milk in it AND the cereal is coated with sugar (lots of sugar). I’ll have a Scotch IF it’s single-malt AND someone else paid for it. People use such logical operations all the time, it’s just that they don’t write them down as machine instructions (or think of them in that light). Logical operators fall into two types. The AND and OR operators are what I will call simple logical operators. There is a second type of logical operator that people don’t use in their daily business — the bitwise operator — that’s unique to the computer world. We’ll start with the simple and sneak up on the bitwise here.
Why Mess with Logical Operations?
C++ programs have to make decisions. A program that can’t make decisions is of limited use. The temperature-conversion program laid out in Chapter 1 is about as complex you can get without some type of decision-making. Invariably a computer program gets to the point where it has to figure out situations such as “Do this if the a variable is less than some value, do that other thing if it’s not.” That’s what makes a computer appear to be intelligent — that it can make
48
Part I: Introduction to C++ Programming decisions. (By the same token, that same property makes a computer look really stupid when the program makes the wrong decision.) Making deci sions, right or wrong, requires the use of logical operators.
Using the Simple Logical Operators The simple logical operators, shown in Table 4-1, evaluate to true or false.
Table 4-1
Simple Operators Representing Daily Logic
Operator
Meaning
Equality; true if the left-hand argument has the same value as the right
!=
Inequality; opposite of equality
>, <
Greater than, less than; true if the left-hand argument is greater than or less than the right-hand argument
>=, <=
Greater than or equal to, less than or equal to; true if either > or is true, OR either < or is true
&&
AND; true if both the left-and right-hand arguments are true
||
OR; true if either the left-or the right-hand argument is true
!
NOT; true if its argument is false
The first six entries in Table 4-1 are comparison operators. The equality opera tor is used to compare two numbers. For example, the following is true if the value of n is 0, and is false otherwise: n 0;
Looks can be deceiving. Don’t confuse the equality operator () with the assignment operator (=). Not only is this a common mistake, but it’s a mis take that the C++ compiler generally cannot catch — that makes it more than twice as bad. n = 0;
// programmer meant to say n 0
The greater-than (>) and less-than (<) operators are similarly common in everyday life. The following expression logical comparison is true:
Chapter 4: Performing Logical Operations int n1 = 1; int n2 = 2; n1 < n2;
It’s easy to forget which operator is “greater than” and which is “less than.” Just remember that the operator is true if the arrow points to the smaller of the two. You may think that n1 is greater than or less than n2; however, this ignores the possibility that n1 and n2 are equal. The greater-than-or-equal-to opera tor (<=) and the less-than-or-equal-to operator (>=) include that bit of mathe matical nuance. They are similar to the less-than and greater-than operators, with one major exception: They include equality; the other operators don’t. The && (AND) and || (OR) can combine with the other logic operators, like this: // true if n2 is greater than n1 but n2 smaller than n3 // (this is the most common way determining that n2 is in // the range of n1 to n3, exclusive) (n1 < n2) && (n2 < n3);
Storing logical values The result of a logical operation can be assigned to a variable of type bool: int n1 = 1; int n2 = 2; bool b; b = (n1 n2);
This expression highlights the difference between the assignment operator = and the comparison operator . The expression says, “Compare the vari ables n1 and n2. Store the results of this comparison in the variable b.” The assignment operators are about as low down on the precedence totem pole as you can get. The equality operator is executed before the assignment. The parentheses are not required — so the following is an equally valid form of logical confusion: b = n1 n2; // compare n1 with n2; generate a true if n1 // if n1 has the same value as n2, false if not // store the result, true or false, in b
Whoa. Better look at that again. Note the difference between the operators.
49
50
Part I: Introduction to C++ Programming The following program demonstrates the use of a bool variable: // BoolTest - compare variables input from the // keyboard and store the results off // into a logical variable #include
“The statement, “ << nArg1 “ equals “ << nArg2 “ is “ << b endl;
// wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
The first line cout.setf() makes sure that our bool variable b is output as “true” or “false”. The next section explains why this is necessary. The program inputs two values from the keyboard and displays the result of the equality comparison: Input value 1: 5 Input value 2: 5 The statement, 5 equals 5 is true Press any key to continue . . .
Chapter 4: Performing Logical Operations The special value endl inserts a newline. The difference between the value endl and the character ‘n’ as described in Chapter 2 is subtle and explained in Chapter 24.
Using logical int variables
C++ hasn’t always had a bool type variable. Back in the old days (before that guy on TV kept walking around saying “Can you hear me now?”), C++ used int variables to store logical values. A value of 0 was considered false and all other values true. By the same token, a logical operator generated a 0 for false and a 1 for true. (Thus, 0 was false while 10 > 5 returned a 1.) C++ retains a high degree of compatibility between bool and int in order to support the older programs that still have that quirk. You get completely different output from the BitTest program if you remove the line cout. setf(cout.boolalpha): Input value 1: 5 Input value 2: 5 The statement, 5 equals 5 is 1 Press any key to continue . . .
Variables of type int and bool can be mixed in expressions as well. For exam ple, Dev-C++ allows the following bizarre statement without batting an eyelid: int n; n = nArg1 nArg2;
Continue to use type bool to hold logical values despite this wart that modern C++ inherits from its forefathers. Other compilers may not be as forgiving.
Be careful performing logical operations on floating-point variables Real numbers are those numbers that can have a fractional part. Because of this, real numbers cannot be counting numbers. That is, you can say the first (1st), second (2nd), third, fourth, and so on because the relationship of 1, 2, and 3 are known exactly. It does not make sense to speak of the 4.5th number in a sequence. (This brings to mind the number between the fourth and fifth, but it has no real meaning.) Similarly the C++ type float, which is the C++ representation, is not a count ing number. Even worse (unlike a real number), a floating-point number can’t have an infinite number of digits beyond the decimal point if a computer is
51
52
Part I: Introduction to C++ Programming going to make any use of it. Because of this limitation, be careful when you use comparison operators on floating-point numbers. Consider the following example: float f1 = 10.0; float f2 = f1 / 3; f1 (f2 * 3.0);
// are these two equal?
The comparison in the preceding example is not necessarily true. A floatingpoint variable cannot hold an unlimited number of significant digits. Thus, f2 is not equal to the number we’d call “three-and-a-third,” but rather to 3.3333..., stopping after some number of decimal places. A float variable supports about 6 digits of accuracy while a double sup ports 13 digits. I say “about” because the computer is likely to generate a number like 3.3333347 due to vagaries in floating point calculations. Now, in pure math, the number of threes after the decimal point is infinite — but no computer built can handle infinity. So, after multiplying 3.3333 by 3, you get 9.9999 instead of the 10 you’d get if you multiplied “three-and-a-third” — in effect, a round-off error. Such small differences may be unnoticeable to a person, but not to the computer. Equality means exactly that — exact equality. Modern processors are very sophisticated in performing such calculations. The processor may, in fact, accommodate the round-off error, but from inside C++, you can’t predict exactly what any given processor will do. Problems can arise even in a straightforward calculation, such as the following: float f1 = 10.0; float f2 = 100 % 30; f1 f2;
// are these two equal?
Theoretically, f1 and f2 should be equal (after you apply that percentlike operator that Chapter 3 identifies as modulus). There doesn’t appear to be any problem with round off. So far. But you can’t be sure — you have no idea how the computer that eventually runs your program is going to represent floating-point numbers internally. To flatly claim that there’s no round-off error lurking here makes unwarranted assumptions about CPU internals. The safer comparison is as follows: float float float (f1 -
f1 = 10.0; f2 = f1 / 3; f3 = f2 * 3.0; f3) < 0.0001 && (f3 - f1) < 0.0001;
Chapter 4: Performing Logical Operations This comparison is true if f1 and f3 are within some small delta from each other, which should still be true even if you take some small round-off error into account.
Short circuits and C++ The& & and || perform what is called short-circuit evaluation. Consider the following: condition1 && condition2
If condition1 is not true, the result is not true, no matter what the value of condition2. (For example, condition2 could be true or false without changing the result.) The same situation occurs in the following: condition1 || condition2
If condition1 is true, the result is true, no matter what the value of condition2. To save time, C++ (wisely) cuts to the chase and evaluates condition1 first. C++ does not evaluate condition2 if condition1 is false (in the case of & &) or condition1 is true (in the case of ||). This is known as short circuit evaluation.
Expressing Binary Numbers
C++ variables are stored internally as so-called binary numbers. Binary num bers are stored as a sequence of 1 and 0 values known as bits. Most of the time, you don’t really need to deal with which particular bits you use to rep resent numbers. Sometimes, however, it’s actually practical and convenient to tinker with numbers at the bit level — so C++ provides a set of operators for that purpose. Fortunately, you won’t have to deal too often with C++ variables at the bit level, so it’s pretty safe to consider the remainder of this chapter a Deep Techie excursion. The so-called bitwise logical operators operate on their arguments at the bit level. To understand how they work, let’s first examine how computers store variables.
53
54
Part I: Introduction to C++ Programming
The decimal number system
The numbers we’ve been familiar with from the time we could first count on our fingers are known as decimal numbers because they’re based on the number 10. (Coincidence? I don’t think so . . .) In general, the programmer expresses C++ variables as decimal numbers. Thus you could specify the value of var as (say) 123 — but consider the implications. A number such as 123 refers to 1 * 100 + 2 * 10 + 3 * 1. Each of these base numbers — 100, 10, and 1 — are powers of 10. 123 = 1 * 100 + 2 * 10 + 3 * 1
Expressed in a slightly different (but equivalent) way, 123 looks like this: 123 = 1 * 102 + 2 * 101 + 3 * 100
Remember that any number to the zero power is 1.
Other number systems Well, okay, using 10 as the basis (or base) of our counting system probably stems from those 10 human fingers, the original counting tools. An alterna tive base for a counting system could just as easily have been 20 (maybe the inventor of base 10 had shoes on at the time). If our numbering scheme had been invented by dogs, it might well be based on 8 (one digit of each paw is out of sight on the back part of the leg). Mathemat ically, such an octal system would have worked just as well: 12310 = 1 * 82 + 7 * 81 + 3 * 80 = 1738
The small 10 and 8 here refer to the numbering system, 10 for decimal (base 10) and 8 for octal (base 8). A counting system may use any positive base.
The binary number system
Computers have essentially two fingers. (Maybe that’s why computers are so stupid: without an opposing thumb, they can’t grasp anything. And then again, maybe not.) Computers prefer counting using base 2. The number 12310 would be expressed this way:
Chapter 4: Performing Logical Operations 12310 = 0*128 + 1*64 + 1*32 + 1*16 + 1*8 + 0*4 +1*2 + 1*1 = 011110112
Computer convention expresses binary numbers by using 4, 8, 16, 32 or even 64 binary digits even if the leading digits are zero. This is also because of the way computers are built internally. Because the term digit refers to a multiple of ten, a binary digit is called a bit (an abbreviation of binary digit). Eight bits make up a byte. (Calling a binary digit a byte-it didn’t seem like a good idea.) A short word is two bytes; a long word is four bytes. With such a small base, you have to use a large number of bits to express numbers. Human beings don’t want the hassle of using an expression such as 011110112 to express such a mundane value as 12310. Programmers prefer to express numbers by using an even number of bits. The octal system — which is based on 3 bits — has been almost completely replaced by the hexadeci mal system, which is based on 4-bit digits. Hexadecimal uses the same digits for the numbers 0 through 9. For the digits between 9 and 16, hexadecimal uses the first six letters of the alphabet: A for 10, B for 11, etc. Thus, 12310 becomes 7B16, like this: 123 = 7 * 161 + B (i.e. 11) * 160 = 7B16
Programmers prefer to express hexadecimal numbers in 2, 4, or 8 hexadeci mal digits even when the leading digit in each case is 0. Finally, who wants to express a hexadecimal number such as 7B16 by using a subscript? Terminals don’t even support subscripts. Even on a word proces sor such as the one I’m using now, it’s a drag to change fonts to and from sub script mode just to type two lousy digits. Therefore, programmers (no fools they) use the convention of beginning a hexadecimal number with a 0x. (Why? Well, the reason for such a strange convention goes back to the early days of C, in a galaxy far, far, away . . . never mind.) Thus, 7B becomes 0x7B. Using this convention, the hexadecimal number 0x7B is equal to 123 decimal while 0x123 hexadecimal is equal to 291 decimal. You can use all the mathematical operators on hexadecimal numbers, in the same way you’d apply them to decimal numbers. (Well, okay, most of us can’t perform a multiplication such as 0xC * 0xE in our heads, but that has more to do with the multiplication tables we learned in school than it has to do with any limitation in the number system.)
55
56
Part I: Introduction to C++ Programming
Roman numeral expressions On a historical note, I should mention that some numbering systems actually hinder computa tions. The Roman numeral system is a (so to speak) classic example that greatly hindered the development of math. Adding two Roman numerals isn’t too difficult: XIX + XXVI = XLV Think this one out: a) IX + VI: The I after the V cancels out the I before the X so the result is V carry the X.
b) X + XX: Plus the carry X is XXXX, which is expressed as XL. Subtraction is only slightly more difficult. Ah, but multiplying two Roman numerals all but requires a bachelor’s degree in mathematics. (You end up with rules like X promotes the digits on the right by 1 letter so that X –* IV becomes XL.) Division practically required a Ph.D., and higher operations such as integration would have been completely impossible. Love those Arabic numerals . . .
Performing Bitwise Logical Operations
All C++ numbers can be expressed in binary form. Binary numbers use only the digits 1 and 0 to represent a value. The following Table 4-2 defines the set of operations that work on numbers one bit at a time, hence the term bitwise operators.
Table 4-2
Bitwise Operators
Operator
Function
~
NOT: Toggle each bit from 1 to 0 and from 0 to 1
&
AND each bit of the left-hand argument with that on the right
|
OR each bit of the left-hand argument with that on the right
^
XOR (exclusive OR) each bit of the left-hand argument with that on the right
Bitwise operations can potentially store a lot of information in a small amount of memory. There are a lot of traits in the world that have only two (or, at most, four) possibilities — that are either this way or that way. You are either married or you’re not (you might be divorced but you are still not currently
Chapter 4: Performing Logical Operations married). You are either male or female (at least that’s what my driver’s license says). In C++, you can store each of these traits in a single bit — in this way, you can pack 32 separate properties into a single 32-bit int. In addition, bit operations can be extremely fast. There is no performance penalty paid for that 32-to-1 saving. Even though memory is cheap these days, it’s not unlimited. Sometimes, when you’re storing large amounts of data, this ability to pack a whole lot of properties into a single word is a big advantage.
The single bit operators
The bitwise operators — AND (&), OR (|) and NOT (~) — perform logic oper ations on single bits. If you consider 0 to be false and 1 to be true (it doesn’t have to be this way, but it’s a common convention), you can say things like the following for the NOT operator: NOT 1 (true) is 0 (false) NOT 0 (false) is 1 (true)
The AND operator is defined as following: 1 (true) AND 1 (true) is 1 (true) 1 (true) AND 0 (false) is 0 (false)
It’s a similar situation for the OR operator: 1 (true) OR 0 (false) is 1 (true) 0 (false) OR 0 (false) is 0 (false)
The definition of the AND operator appears in Table 4-3.
Table 4-3
Truth Table for the AND Operator
AND
1
0
1
1
0
0
0
0
You read this table as the column corresponding to the value of one of the arguments while the row corresponds to the other. Thus, 1 & 0 is 0. (Column 1
57
58
Part I: Introduction to C++ Programming and row 0.) The only combination that returns anything other than 0 is 1 & 1. (This is known as a truth table.) Similarly, the truth table for the OR operator is shown in Table 4-4.
Table 4-4
Truth Table for the OR Operator
XOR
1
0
1
1
1
0
1
0
One other logical operation that is not so commonly used in day-to-day living is the OR ELSE operator commonly contracted to XOR. XOR is true if either argument is true but not if both are true. The truth table for XOR is shown in Table 4-5.
Table 4-5
Truth Table for the XOR Operator
XOR
1
0
1
0
1
0
1
0
Armed with these single bit operators, we can take on the C++ bitwise logical operations.
Using the bitwise operators
The bitwise operators operate on each bit separately. The bitwise operators are used much like any other binary arithmetic operator. The NOT operator is the easiest to understand. To NOT a number is to NOT each bit that makes up that number (and to a programmer, that sentence makes perfect sense — honest). Consider this example: ~01102 (0x6) 10012 (0x9)
Thus we say that ~0x6 equals 0x9.
The following calculation demonstrates the & operator:
Chapter 4: Performing Logical Operations 01102 & 00112 00102
Beginning with the most significant bit, 0 AND 0 is 0. In the next bit, 1 AND 0 is 0. In bit 3, 1 AND 1 is 1. In the least significant bit, 0 AND 1 is 0. The same calculation can be performed in hexadecimal by first converting the number in binary, performing the operation and then converting the result back. 0x6 & 0x3 0x2
01102 & 00112 00102
In shorthand, we say that 0x6 & 0x3 equals 0x2. (Try this test: What is the value of 0x6 | 0x3? Get this in 7 seconds, and you can give yourself 7 pats on the back.)
A simple test
The following program illustrates the bitwise operators in action. The pro gram initializes two variables and outputs the result of ANDing, ORing, and XORing them. // BitTest - initialize two variables and output the // results of applying the ~,& , | and ^ // operations #include
59
60
Part I: Introduction to C++ Programming cout cout cout cout
<< << << <<
“Arg1 “Arg2 “~nArg1 “~nArg2
= = = =
0x” 0x” 0x” 0x”
<< << << <<
nArg1 << “n”; nArg2 << “n”; ~nArg1 << “n”; ~nArg2 << “n”;
// now the binary operators cout << “nArg1 & nArg2 = 0x” << (nArg1 & nArg2) << “n”; cout << “nArg1 | nArg2 = 0x” << (nArg1 | nArg2) << “n”; cout << “nArg1 ^ nArg2 = 0x” << (nArg1 ^ nArg2) << “n”; // wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
The first expression in our program, cout.setf(ios::hex), sets the output format from the default decimal to hexadecimal (you’ll have to trust me for now that it works). The remainder of the program is straightforward. The program assigns nArg1 the test value 0x1234 and nArg2 the value 0x00ff. The program then out puts all combinations of bitwise calculations. The process looks like this: Arg1 Arg2 ~nArg1 ~nArg2 nArg1 & nArg2 nArg1 | nArg2 nArg1 ^ nArg2 Press any key
= 0x1234 = 0xff = 0xffffedcb = 0xffffff00 = 0x34 = 0x12ff = 0x12cb to continue . . .
Do something logical with logical calculations Running through simple and bitwise logical calculations in your head at par ties is fun (well, okay, for some of us), but a program has to make actual, prac tical use of these values to make them worth the trouble. Coming right up: Chapter 5 demonstrates how logical calculations are used to control program flow.
Chapter 5
Controlling Program Flow In This Chapter 0001 Controlling the flow through the program 0001 Executing a group of statements repetitively 0001 Avoiding infinite loops
T
he simple programs that appear in Chapters 1 through 4 process a fixed number of inputs, output the result of that calculation, and quit. However, these programs lack any form of flow control. They cannot make tests of any sort. Computer programs are all about making decisions. If the user presses a key, the computer responds to the command. For example, if the user presses Ctrl+C, the computer copies the currently selected area to the Clipboard. If the user moves the mouse, the pointer moves on the screen. If the user clicks the right mouse button with the Windows key depressed, the computer crashes. The list goes on and on. Programs that don’t make decisions are necessarily pretty boring. Flow-control commands allow the program to decide what action to take, based on the results of the C++ logical operations performed (see Chapter 4). There are basically three types of flow-control statements: the branch, the loop, and the switch.
Controlling Program Flow with the Branch Commands The simplest form of flow control is the branch statement. This instruction allows the program to decide which of two paths to take through C++ instruc tions, based on the results of a logical expression (see Chapter 4 for a descrip tion of logical expressions).
62
Part I: Introduction to C++ Programming In C++, the branch statement is implemented using the if statement: if (m > n) { // Path 1 // ...instructions to be executed if // m is greater than n } else { // Path 2 // ...instructions to be executed if not }
First, the logical expression m > n is evaluated. If the result of the expression is true, control passes down the path marked Path 1 in the previous snip pet. If the expression is false, control passes to Path 2. The else clause is optional. If it is not present, C++ acts as if it is present but empty. Actually, the braces are optional (sort of) if there’s only one statement to exe cute as part of the if. If you lose the braces, however, it’s embarrassingly easy to make a mistake that the C++ compiler can’t catch. The braces serve as a guide marker; it’s much safer to include ’em. (If your friends try to entice you into not using braces, “Just say No.”) The following program demonstrates the if statement (note all the lovely braces): // BranchDemo - input two numbers. Go down one path of the // program if the first argument is greater than // the first or the other path if not #include
Chapter 5: Controlling Program Flow { cout << “Argument 1 is greater than argument 2” << endl; } else { cout << “Argument 1 is not greater than argument 2” << endl; } // wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
Here the program reads two integers from the keyboard and compares them. If the expression “arg1 is greater than arg2” is true, control flows to the output statement cout << “Argument 1 is greater than argument 2”. If arg1 is not greater than arg2, control flows to the else clause where the statement cout << “Argument 1 is not greater than argument 2n” is executed. Here’s what that operation looks like: Enter arg1: 5 Enter arg2: 6 Argument 1 is not greater than argument 2 Press any key to continue . . .
Executing Loops in a Program
Branch statements allow you to control the flow of a program’s execution from one path of a program or another. This is a big improvement, but still not enough to write full-strength programs. Consider the problem of updating the computer display. On the typical PC display, 1 million pixels are drawn to update the entire display. A program that can’t execute the same code repetitively would need to include the same set of instructions over and over 1,000 times. What we really need is a way for the computer to execute the same sequence of instructions thousands and millions of times. Executing the same command multiple times requires some type of looping statements.
63
64
Part I: Introduction to C++ Programming
Looping while a condition is true
The simplest form of looping statement is the while loop. Here’s what the while loop looks like: while(condition) { // ... repeatedly executed as long as condition is true }
The condition is tested. This condition could be if var > 10 or if var1 var2 or anything else you might think of. If it is true, the state ments within the braces are executed. Upon encountering the closed brace, C++ returns control to the beginning, and the process starts over. The effect is that the C++ code within the braces is executed repeatedly as long as the condition is true. (Kind of reminds me of how I get to walk around the yard with my dog until she . . . well, until we’re done.) If the condition were true the first time, what would make it be false in the future? Consider the following example program: // WhileDemo - input a loop count. Loop while // outputting astring arg number of times. #include
WhileDemo begins by retrieving a loop count from the user, which it stores in the variable loopCount. The program then executes a while loop. The while first tests loopCount. If loopCount is greater than zero, the program enters
Chapter 5: Controlling Program Flow the body of the loop (the body is the code between the braces) where it decre ments loopCount by 1 and outputs the result to the display. The program then returns to the top of the loop to test whether loopCount is still positive. When executed, the program WhileDemo outputs the results shown in this next snippet. Here I entered a loop count of 5. The result is that the program loops 5 times, each time outputting a countdown. Enter loopCount: 5 Only 4 loops to go Only 3 loops to go Only 2 loops to go Only 1 loops to go Only 0 loops to go Press any key to continue . . .
If the user enters a negative loop count, the program skips the loop entirely. That’s because the specified condition is never true, so control never enters the loop. In addition, if the user enters a very large number, the program loops for a long time before completing. A separate, less frequently used version of the while loop known as the do . . . while appears identical except the condition isn’t tested until the bottom of the loop: do { // ...the inside of the loop } while (condition);
Because the condition isn’t tested until the end, the body of the do . . . while is always executed at least once.
The condition is only checked at the beginning of the while loop or at the end of the do . . . while loop. Even if the condition ceases to be true at some time during the execution of the loop, control does not exit the loop until the condition is retested.
Using the autoincrement/ autodecrement feature Programmers very often use the autoincrement ++ or the autodecrement -operators with loops that count something. Notice, from the following snip pet extracted from the WhileDemo example, that the program decrements the loop count by using assignment and subtraction statements, like this:
65
66
Part I: Introduction to C++ Programming // now loop that many times while (loopCount > 0) { loopCount = loopCount - 1; cout << “Only “ << loopCount << “ loops to gon”; }
A more compact version uses the autodecrement feature, which does what you may well imagine: while (loopCount > 0) { loopCount--; cout << “Only “ << loopCount << “ loops to gon”; }
The logic in this version is the same as in the original. The only difference is the way that loopCount is decremented. Because the autodecrement both decrements its argument and returns its value, the decrement operation can actually be combined with the while loop. In particular, the following version is the smallest loop yet. while (loopCount-- > 0) { cout << “Only “ << loopCount << “ loops to gon”; }
Believe it or not, the loopcount— > 0 is the version that most C++ program mers would use. It’s not that C++ programmers like being cute (although they do). In fact, the more compact version (which embeds the autoincrement or autodecrement feature in the logical comparison) is easier to read, especially as you gain experience. Both loopCount— and —loopCount expressions decrement loopCount. The former expression, however, returns the value of loopCount before being decremented; the latter expression does so after being decremented. How often should the autodecrement version of WhileDemo execute when the user enters a loop count of 1? If you use the pre-decrement version, the value of —loopCount is 0, and the body of the loop is never entered. With the postdecrement version, the value of loopCount— is 1, and control enters the loop. Beware thinking that the version of the program with the autodecrement command executes faster (since it contains fewer statements). It probably executes exactly the same. Modern compilers are pretty good at getting the number of machine-language instructions down to a minimum, no matter which of the decrement instructions shown here you actually use.
Chapter 5: Controlling Program Flow
Using the for loop
The most common form of loop is the for loop. The for loop is preferred over the more basic while loop because it’s generally easier to read (there’s really no other advantage). The for loop has the following format: for (initialization; conditional; increment) { // ...body of the loop }
Execution of the for loop begins with the initialization clause, which got its name because it’s normally where counting variables are initialized. The ini tialization clause is only executed once when the for loop is first encountered. Execution continues with the conditional clause. This clause works a lot like the while loop: as long as the conditional clause is true, the for loop con tinues to execute. After the code in the body of the loop finishes executing, control passes to the increment clause before returning to check the conditional clause — thereby repeating the process. The increment clause normally houses the autoincrement or autodecrement statements used to update the counting variables. The following while loop is equivalent to the for loop: { initialization; while(conditional) { { // ...body of the loop } increment; } }
All three clauses are optional. If the initialization or increment clauses are missing, C++ ignores them. If the conditional clause is missing, C++ performs the for loop forever (or until something else passes control outside the loop). The for loop is best understood by example. The following ForDemo program is nothing more than the WhileDemo converted to use the for loop construct:
67
68
Part I: Introduction to C++ Programming // ForDemo1 - input a loop count. Loop while // outputting astring arg number of times. #include
The program reads a value from the keyboard into the variable loopCount. The for starts out comparing loopCount to zero. Control passes into the for loop if loopCount is greater than zero. Once inside the for loop, the pro gram decrements loopCount and displays the result. That done, the program returns to the for loop control. Control skips to the next line after the for loop as soon as loopCount has been decremented to zero. All three sections of a for loop may be empty. An empty initialization or increment section does nothing. An empty comparison section is treated like a comparison that returns true. This for loop has two small problems. First, it’s destructive — not in the sense of what my puppy does to a slipper, but in the sense that it changes the value of loopCount, “destroying” the original value. Second, this for loop counts “backward” from large values down to smaller values. These two problems are addressed if you add a dedicated counting variable to the for loop. Here’s what it looks like: // ForDemo2 - input a loop count. Loop while // outputting astring arg number of times. #include
Chapter 5: Controlling Program Flow #include
This modified version of WhileDemo loops the same as it did before. Instead of modifying the value of loopCount, however, this ForDemo2 version uses a counter variable. Control begins by declaring a variable and initializing it to the value contained in loopCount. It then checks the variable i to make sure that it is positive. If so, the program executes the output statement, decrements i and starts over. When declared within the initialization portion of the for loop, the index variable is only known within the for loop itself. Nerdy C++ programmers say that the scope of the variable is the for loop. In the example just given, the variable i is not accessible from the return statement because that state ment is not within the loop. Note, however, that not all compilers are strict about sticking to this rule. The Dev-C++ compiler (for example) generates a warning if you use i outside the for loop — but it uses the variable anyway.
Avoiding the dreaded infinite loop
An infinite loop is an execution path that continues forever. An infinite loop occurs any time the condition that would otherwise terminate the loop can’t occur — usually the result of a coding error. Consider the following minor variation of the earlier loop:
69
70
Part I: Introduction to C++ Programming while (loopCount > 0) { cout << “Only “ << loopCount << “ loops to gon”; }
The programmer forgot to decrement the variable loopCount as in the loop example below. The result is a loop counter that never changes. The test con dition is either always false or always true. The program executes in a neverending (infinite) loop. I realize that nothing’s infinite. Eventually the power will fail, the computer will break, Microsoft will go bankrupt, and dogs will sleep with cats. . . . Either the loop will stop executing, or you won’t care anymore. You can create an infinite loop in many more ways than shown here, most of which are much more difficult to spot than this one.
Applying special loop controls
C++ defines two special flow-control commands known as break and continue. Sometimes the condition for terminating the loop occurs at neither the beginning nor the end of the loop, but in the middle. Consider a program that accumulates numbers of values entered by the user. The loop terminates when the user enters a negative number. The challenge with this problem is that the program can’t exit the loop until the user has entered a value, but must exit before the value is added to the sum. For these cases, C++ defines the break command. When encountered, the break causes control to exit the current loop immediately. Control passes from the break statement to the statement immediately following the closed brace at the end of the loop. The format of the break commands is as follows: while(condition) // break works equally well in for loop { if (some other condition) { break; // exit the loop } } // control passes here when the // program encounters the break
Armed with this new break command, my solution to the accumulator prob lem appears as the program BreakDemo.
Chapter 5: Controlling Program Flow // BreakDemo - input a series of numbers. // Continue to accumulate the sum // of these numbers until the user // enters a negative number. #include
After explaining the rules to the user (entering a negative number to termi nate, and so on), the program enters what looks like an infinite for loop.
71
72
Part I: Introduction to C++ Programming Once within the loop, BreakDemo retrieves a number from the keyboard. Only after the program has read a number can it test to see whether the number it just read matches the exit criteria. If the input number is negative, control passes to the break, causing the program to exit the loop. If the input number is not negative, control skips over the break command to the expression that sums the new value into the accumulator. After the program exits the loop, it outputs the accumulated value and then exits. When performing an operation on a variable repeatedly in a loop, make sure that the variable is initialized properly before entering the loop. In this case, the program zeros accumulator before entering the loop where value is added to it. The result of an example run appears as follows: This program sums values entered by the user Terminate the loop by entering a negative number Enter next number: 1 Enter next number: 2 Enter next number: 3 Enter next number: -1 The total is 6 Press any key to continue . . .
The continue command is used less frequently. When the program encoun ters the continue command, it immediately moves back to the top of the loop. The rest of the statements in the loop are ignored for the current iteration. The following example snippet ignores negative numbers that the user might input. Only a zero terminates this version (the complete program appears on the CD-ROM as ContinueDemo): while(true) // this while() has the same effect as for(;;) { // input a value cout << “Input a value:”; cin >> value; // if the value is negative... if (value < 0) { // ...output an error message... cout << “Negative numbers are not allowedn”; // ...and go back to the top of the loop continue; } // ...continue to process input like normal }
Chapter 5: Controlling Program Flow
Nesting Control Commands
Return to our PC-screen-repaint problem. Surely it must need a loop struc ture of some type to write each pixel from left to right on a single line. (Do Middle Eastern terminals scan from right to left? I have no idea.) What about repeatedly repainting each scan line from top to bottom? (Do PC screens in Australia scan from bottom to top? Beats me.) For this particular task, you need to include the left-to-right scan loop within the top-to-bottom scan loop. A loop command within another loop is known as a nested loop. As an exam ple, you can modify the BreakDemo program into a program that accumulates any number of sequences. In this NestedDemo program, the inner loop sums numbers entered from the keyboard until the user enters a negative number. The outer loop continues accumulating sequences until the sum is 0. Here’s what it looks like: // NestedDemo - input a series of numbers. // Continue to accumulate the sum // of these numbers until the user // enters a 0. Repeat the process // until the sum is 0. #include
73
74
Part I: Introduction to C++ Programming cout << “Enter next number: “; cin >> value; // if it’s negative... if (value < 0) { // ...then exit break; } // ...otherwise add the number to the // accumulator accumulator = accumulator + value; } // output the accumulated result... cout << “The total for this sequence is “ << accumulator << endl << endl; // ...and start over with a new sequence // if the accumulated sequence was not zero } while (accumulator != 0); // we’re about to quit cout << “Thank you” << endl; // wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
Switching to a Different Subject?
One last control statement is useful in a limited number of cases. The switch statement resembles a compound if statement by including a number of dif ferent possibilities rather than a single test: switch(expression) { case c1: // go here if the expression c1 break; case c2: // go here if expression c2 break; default: // go here if there is no match }
Chapter 5: Controlling Program Flow The value of expression must be an integer (int, long, or char). The case values c1, c2, and c3 must be constants. When the switch statement is encountered, the expression is evaluated and compared to the various case constants. Control branches to the case that matches. If none of the cases match, control passes to the default clause. Consider the following example code snippet: int choice; cout << “Enter a 1, 2 or 3:”; cin >> choice; switch(choice) { case 1: // do “1” processing break; case 2: // do “2” processing break; case 3: // do “3” processing break; default: cout << “You didn’t enter a 1, 2 or 3n”; }
Once again, the switch statement has an equivalent, in this case multiple if statements; however, when there are more than two or three cases, the switch structure is easier to understand. The break statements are necessary to exit the switch command. Without the break statements, control falls through from one case to the next. (Look out below!)
75
76
Part I: Introduction to C++ Programming
Part II
Becoming a Functional C++ Programmer
I
In this part . . .
t’s one thing to perform operations such as addition and multiplication — even when we’re logical (AND and OR or other operations). It’s another thing to write real programs. This section introduces the features neces sary to make the leap into programmerdom. You’ll find the program BUDGET1 on the enclosed CD-ROM. This largish program demonstrates the concepts of functional programming. You may want to visit this pro gram and its documentation once you’ve mastered func tional programming concepts.
Chapter 6
Creating Functions In This Chapter 0001 Writing functions 0001 Passing data to functions 0001 Naming functions with different arguments 0001 Creating function prototypes 0001 Working with include files
T
he programs developed in prior chapters have been small enough that they can be easily read as a single unit. Larger, real-world programs can be many thousands (or millions!) of lines long. Developers need to break up these monster programs into smaller chunks that are easier to conceive, develop, and maintain. C++ allows programmers to divide their code into exactly such chunks (known as functions). As long as a function has a simple description and a well-defined interface to the outside world, it can be written and debugged without worrying about the code that surrounds it. This divide-and-conquer approach reduces the difficulty of creating a work ing program of significant size. This is a simple form of encapsulation — see Chapter 15 for more details on encapsulation.
Writing and Using a Function
Functions are best understood by example. This section starts with the example program FunctionDemo, which simplifies the NestedDemo program I discussed in Chapter 5 by defining a function to contain part of the logic. Then this section explains how the function is defined and how it is invoked, using FunctionDemo as a pattern for understanding both the problem and the solution.
80
Part II: Becoming a Functional C++ Programmer The NestedDemo program in Chapter 5 contains an inner loop (which accu mulates a sequence of numbers) surrounded by an outer loop (which repeats the process until the user quits). Separating the two loops would simplify the program by allowing the reader to concentrate on each loop independently. The following FunctionDemo program shows how NestedDemo can be simpli fied by creating the function sumSequence(). Function names are normally written with a set of parentheses immediately following the term, like this: // FunctionDemo - demonstrate the use of functions // by breaking the inner loop of the // NestedDemo program off into its own // function #include
Chapter 6: Creating Functions cout << << << << << <<
“This program sums multiple seriesn” “of numbers. Terminate each sequencen” “by entering a negative number.n” “Terminate the series by entering twon” “negative numbers in a rown” endl;
// accumulate sequences of numbers... int accumulatedValue; for(;;) { // sum a sequence of numbers entered from // the keyboard cout << “Enter next sequence” << endl; accumulatedValue = sumSequence(); // terminate the loop if sumSequence() returns // a zero if (accumulatedValue 0) { break; } // now output the accumulated result cout << “The total is “ << accumulatedValue << “n” << endl; } cout << “Thank you” << endl; // wait until user is ready before terminating program // to allow the user to see the program results system(“PAUSE”); return 0; }
Defining the sumSequence() function
The statement int sumSequence(void) begins the definition of the sumSequence() function. The block of code contained in the braces is the function body. The function sumSequence() accumulates a sequence of values entered from the keyboard. This code section is identical to that found in the inner loop of NestedDemo.
81
82
Part II: Becoming a Functional C++ Programmer
Calling the function sumSequence()
Let’s concentrate on the main program contained in the braces following main(). This section of code looks similar to the outer loop in NestedDemo. The main difference is the expression accumulatedValue = sumSequence(); that appears where the inner loop would have been. The sumSequence() statement invokes the function of that name. A value returned by the function is stored in the variable accumulatedValue. Then this value is displayed. The main program continues to loop until sumSequence() returns a sum of zero, which indicates that the user has finished calculating sums.
Divide and conquer
The FunctionDemo program has split the outer loop in main() from the inner loop into a function sumSequence(). This division wasn’t arbitrary: sumSequence() performs a separate role — worth considering by itself — apart from the control features within FunctionDemo. A good function is easy to describe. You shouldn’t have to use more than a single sentence, with a minimum of such words as and, or, unless, or but. For example, here’s a simple, straightforward definition: “The function sumSequence accumulates a sequence of integer values entered by the user.” This definition is concise and clear. It’s a world away from the ContinueDemo program description: “sums a sequence of positive values AND generates an error if the user enters a negative number AND displays the sum AND starts over again until the user enters two zero-length sums.” The output of a sample run of this program appears much like that generated by the NestedDemo program, as follows: This program sums multiple series of numbers. Terminate each sequence by entering a negative number. Terminate the series by entering two negative numbers in a row Enter next sequence Enter next number: 1 Enter next number: 2
Chapter 6: Creating Functions Enter next number: 3 Enter next number: -1 The total is 6 Enter next sequence Enter next number: 1 Enter next number: 2 Enter next number: -1 The total is 3 Enter Enter Thank Press
next sequence next number: -1 you any key to continue . . .
Understanding the Details of Functions
Functions are so fundamental to creating C++ programs that getting a handle on the details of defining, creating, and testing them is critical. Armed with the example FunctionDemo program, consider the following definition of function: A function is a logically separated block of C++ code. The function construct has the following form:
Chapter 27: Tempting C++ Templates float maximum(float, float);
// creates an instance of // maximum
float
C++ can’t compile a template function until the template is expanded into a real function. If your template function has compile errors, you probably won’t know it until you instantiate the template function.
Template Classes
C++ also allows the programmer to define template classes. A template class follows the same principle of using a conventional class definition with a placeholder for some unknown support classes. For example, the following TemplateVector program creates a vector for any class that the user provides (a vector is a type of container in which the objects are stored in a row; an array is the classic vector example). // TemplateVector - implement a vector that uses a template // type #include