0
(0)
Book Cover

C++ All-In-One Desk Reference for Dummies – Read Now and Download Mobi

Comments

Product Description

Here’s the easy way to learn how to use C++

C++, developed by Bjarne Stroustrup at Bell Labs, is one of the most widely used programming languages, with close to four million C++ programmers and growing. C++’s popularity has earned it a spot as part of the Standard Library.

Fully updated for the new C++ 2009 standard, C++ All-in-One for Dummies, 2nd Edition compiles seven books into one. This guidebook covers key topics like an introduction to C++, understanding objects and classes, fixing problems, advanced programming, reading and writing files, advanced C++, and building applications with Microsoft MFC. If you’re a C++ newbie, start with Book I. But if you’re experienced with C++, simply jump in anywhere to learn more! This all-in-one reference helps you learn to:

  • Use C++ for Windows, Mac, and Linux by using the CodeBlocks compiler
  • Understand object-oriented programming
  • Use various diagrams to design your programs
  • Recognize how local variables are stored
  • Use packages, notes, and tags effectively
  • Make a class persistent
  • Handle constructors and destructors

With over 25,000 sold of the previous bestselling edition, this second edition with a bonus CD makes C++ easier to understand. It’s a perfect introduction for new programmers and guide for advanced programmers.

Note: CD-ROM/DVD and other supplementary materials are not included as part of eBook file.

From the Back Cover

C++ is the “in” language!

Find out why, andhow to use it, right here

C++ is fast, powerful, and fully compiled — three great reasons why it’s #1. There are more reasons, and in this guide you discover them as you dig in and really learn to use C++. Each handy minibook covers what you need to know about a key aspect of C++. If you’re a C++ newbie, start with Book I; experienced folks can jump in anywhere to learn more!

  • One size fits most — see how to use C++ for Windows, Mac, and Linux, using the CodeBlocks compiler

  • Explore objects and classes — understand object-oriented programming and how to use various diagrams to design your programs

  • Banish bugs — learn to use a debugger and how the CodeBlocks debugger ferrets out problems in your applications

  • Reading and writing — Minibook V covers it all, including stream programming

  • Advance to the Library — understand how to create your own templates and build a full set of libraries for your own use

Open the book and find:

  • Tips on managing arrays of data

  • What to do with constructors and destructors

  • How local variables are stored

  • What packages, notes, and tags are for

  • Secrets of architecting the Standard Library

  • The difference between deque and vector

  • How to make a class persistent

  • Where to obtain the free Visual Studio Express

Bonus CD Includes:

  • All source code from the examples used in the book

  • CodeBlocks compiler

Please see the CD appendix for details and complete system requirements.

Author
John Paul Mueller, Jeff Cogswell

Rights
NONE

Language
en

Published
2009-01-02

ISBN
9780470317358

Buy on Amazon Read Now

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.


C++ All-in-One For Dummies®, 2nd Edition

Table of Contents

Introduction
No Experience Necessary
Great for Advanced Folks, Too!
For All Computers
Conventions
Organization
Icons Galore
What’s Next?
Book I: Introducing C++
Book I: Chapter 1: Creating a First C++ Program
Creating a Project
Understanding projects
Defining your first project
Building and executing your first application
Typing the Code
Starting with Main
Showing Information
Doing some math
Tabbing your output
Let Your Program Run Away
Book I: Chapter 2: Storing Data in C++
Putting Your Data Places: Variables
Creating an integer variable
Declaring multiple variables
Changing values
Setting one variable equal to another
Initializing a variable
Creating a great name for yourself
Manipulating Integer Variables
Adding integer variables
Subtracting integer variables
Multiplying integer variables
Dividing integer variables
Characters
Null character
Nonprintable and other cool characters
Strings
Getting a part of a string
Changing part of a string
Adding onto a string
Adding two strings
Deciding between Conditional Operators
Telling the Truth with Boolean Variables
Reading from the Console
Book I: Chapter 3: Directing Your C++ Program Flow
Doing This or Doing That
Evaluating Conditions in C++
Finding the right C++ operators
Combining multiple evaluations
Including Evaluations in C++ Conditional Statements
Deciding what if and also what else
Going further with the else and if
Repeating Actions with Statements That Loop
Looping situations
Looping for
Looping while
Doing while
Breaking and continuing
Nesting loops
Book I: Chapter 4: Dividing Your Work with Functions
Dividing Your Work
Calling a Function
Passing a variable
Passing multiple variables
Writing Your Own Functions
Multiple parameters or no parameters
Returning nothing
Keeping your variables local
Forward references and function prototypes
Writing two versions of the same function
Calling All String Functions
Understanding main
Book I: Chapter 5: Dividing Between Source-Code Files
Creating Multiple Source Files
Multiple source files in CodeBlocks
Multiple source files in other compilers
Creating multiple files
Sharing with Header Files
Adding the header only once
Using brackets or quotes
Sharing Variables Among Source Files
Using the Mysterious Header Wrappers
Book I: Chapter 6: Referring to Your Data through Pointers
Heaping and Stacking the Variables
Getting a variable’s address
Changing a variable by using a pointer
Pointing at a string
Pointing to something else
Tips on pointer variables
Dynamically Allocating with new
Using new
Using an initializer
Making new strings
Freeing Pointers
Passing Pointer Variables to Functions
Changing variable values with pointers
Modifying string parameters
Returning Pointer Variables from Functions
Returning a Pointer as a Nonpointer
Passing by Reference
Remembering the Rules
Book I: Chapter 7: Working with Classes
Understanding Objects and Classes
Classifying classes and objects
Describing member functions and data
Implementing a class
Separating member function code
The parts of a class
Working with a Class
Accessing members
Using classes and pointers
Passing objects to functions
Using const parameters in functions
Using the this pointer
Overloading member functions
Starting and Ending with Constructors and Destructors
Starting with constructors
Ending with destructors
Sampling constructors and destructors
Adding parameters to constructors
Building Hierarchies of Classes
Creating a hierarchy in C++
Understanding types of inheritance
Book I: Chapter 8: Using Advanced C++ Features
Filling Your Code with Comments
Converting Types
Reading from the Console
Understanding Preprocessor Directives
Using Constants
Using Switch Statements
Supercharging enums with Classes
Working with Random Numbers
Storing Data in Arrays
Declaring and accessing an array
Arrays of pointers
Passing arrays to functions
Adding and subtracting pointers
Book II: Understanding Objects and Classes
Book II: Chapter 1: Planning and Building Objects
Recognizing Objects
Observing the mailboxes class
Observing the mailbox class
Finding other objects
Encapsulating Objects
Building Hierarchies
Establishing a hierarchy
Protecting members when inheriting
Overriding member functions
Specializing with polymorphism
Getting abstract about things
Discovering Classes
Engineering your software
Finding those pesky classes
Book II: Chapter 2: Describing Your Program with UML
Moving Up to UML
Modeling with UML
Diagramming and designing with UML
Building with UML and the Unified Process
Speaking iteratively
Phasing in and out
The inception phase
The elaboration phase
The construction phase
The transition phase
Moving Forward with UML
Book II: Chapter 3: Structuring Your Classes with UML
Drawing Classes
Mapping classes with UML
Inheriting in UML
Aggregating and composing classes
Building Components
Deploying the Software
Book II: Chapter 4: Demonstrating Behavior with UML
Drawing Objects
Casing Out the Use Cases
Expanding use cases
Matching use cases and requirements
Sequence Diagrams
Notating sequence diagrams
Looping and comparing in sequence diagrams
Collaboration Diagrams
Activity Diagrams
State Diagrams
Book II: Chapter 5: Modeling Your Programs with UML
Using UML Goodies
Packaging your symbols
Notating your diagrams
Tagging your symbols
Free to Be UML
C++ and UML
Drawing enumerations
Including static members
Parameterizing classes with templates
Book II: Chapter 6: Building with Design Patterns
Introducing a Simple Pattern: the Singleton
Watching an Instance with an Observer
Observers and the Standard C++ Library
Automatically adding an observer
Mediating with a Pattern
Book III: Fixing Problems
Book III: Chapter 1: Dealing with Bugs
It’s Not a Bug. It’s a Feature!
Make Your Programming Features Look Like Features
Anticipating (Almost) Everything
Avoiding Mistakes, Plain and Simple
Book III: Chapter 2: Debugging a Program
Programming with Debuggers
Running the debugger
Recognizing the parts of the CodeBlocks debugger
Debugging with Different Tools
Standard debuggers
Book III: Chapter 3: Stopping and Inspecting Your Code
Setting and Disabling Breakpoints
Setting a breakpoint in CodeBlocks
Enabling and disabling breakpoints
Watching, Inspecting, and Changing Variables
Watching the local variables
Watching other variables
Book III: Chapter 4: Traveling About the Stack
Stacking Your Data
Moving about the stack
Storing local variables
Debugging with Advanced Features
Viewing threads
Tracing through assembly code
Book IV: Advanced Programming
Book IV: Chapter 1: Working with Arrays, Pointers, and References
Building Up Arrays
Declaring arrays
Arrays and pointers
Using multidimensional arrays
Arrays and command-line parameters
Allocating an array on the heap
Storing arrays of pointers and arrays of arrays
Building constant arrays
Pointing with Pointers
Becoming horribly complex
Pointers to functions
Pointing a variable to a member function
Pointing to static member functions
Referring to References
Reference variables
Returning a reference from a function
Book IV: Chapter 2: Creating Data Structures
Working with Data
The great variable roundup
Expressing variables from either side
Casting a spell on your data
Casting safely with C++
Dynamically casting with dynamic_cast
Statically casting with static_cast
Structuring Your Data
Structures as component data types
Equating structures
Returning compound data types
Naming Your Space
Using variables and part of a namespace
Book IV: Chapter 3: Constructors, Destructors, and Exceptions
Constructing and Destructing Objects
Overloading constructors
Initializing members
Adding a default constructor
Functional constructors
Calling one constructor from another
Copying instances with copy constructors
When constructors go bad: failable constructors?
Destroying your instances
Virtually inheriting destructors
Programming the Exceptions to the Rule
Throwing direct instances
Catching any exception
Rethrowing an exception
Book IV: Chapter 4: Advanced Class Usage
Inherently Inheriting Correctly
Morphing your inheritance
Adjusting access
Returning something different, virtually speaking
Multiple inheritance
Virtual inheritance
Friend classes and functions
Using Classes and Types within Classes
Nesting a class
Types within classes
Book IV: Chapter 5: Creating Classes with Templates
Templatizing a Class
Separating a template from the function code
Including static members in a template
Parameterizing a Template
Putting different types in the parameter
Including multiple parameters
Typedefing a Template
Deriving Templates
Deriving classes from a class template
Deriving a class template from a class
Deriving a class template from a class template
Templatizing a Function
Overloading and function templates
Templatizing a member function
Book IV: Chapter 6: Programming with the Standard Library
Architecting the Standard Library
Containing Your Classes
Storing in a vector
Mapping your data
Containing instances, pointers, or references
Comparing instances
Iterating through a container
A map of pairs in your hand
The Great Container Showdown
Associating and storing with a set
Unionizing and intersecting sets
Listing with list
Stacking the deque
Waiting in line with stacks and queues
Copying Containers
Book V: Reading and Writing Files
Book V: Chapter 1: Filing Information with the Streams Library
Seeing a Need for Streams
Programming with the Streams Library
Getting the right header file
Opening a file
Handling Errors When Opening a File
Flagging the ios Flags
Book V: Chapter 2: Writing with Output Streams
Inserting with the << Operator
Formatting Your Output
Formatting with flags
Specifying a precision
Setting the width and creating fields
Book V: Chapter 3: Reading with Input Streams
Extracting with Operators
Encountering the End of File
Reading Various Types
Reading Formatted Input
Book V: Chapter 4: Building Directories and Contents
Manipulating Directories
Creating a directory
Deleting a directory
Getting the Contents of a Directory
Copying Files
Moving and Renaming Files and Directories
Book V: Chapter 5: Streaming Your Own Classes
Streaming a Class for Text Formatting
Manipulating a Stream
What’s a manipulator?
Writing your own manipulator
Book VI: Advanced C++
Book VI: Chapter 1: Exploring the Standard Library Further
Considering the Standard Library Categories
Containers
Iterators
Algorithms
Functors
Utilities
Adaptors
Allocators
Parsing Strings Using a Hash
Obtaining Information Using a Random Access Iterator
Locating Values Using the Find Algorithm
Using the Random Number Generator
Performing Comparisons Using min and max
Working with Temporary Buffers
Book VI: Chapter 2: Building Original Templates
Deciding When to Create a Template
Defining the Elements of a Good Template
Creating a Basic Math Template
Building a Structure Template
Developing a Class Template
Considering Template Specialization
Creating a Template Library
Defining the library project
Configuring the library project
Coding the library
Using Your Template Library
Book VI: Chapter 3: Investigating Boost
Understanding Boost
Boost features
Licensing
Paid support
Obtaining and Installing Boost for CodeBlocks
Unpacking Boost
Building the libraries
Building the Boost tools
Using Boost Jam
Using Boost Build
Using Regression
Using Inspect
Understanding BoostBook
Using QuickBook
Using bcp
Using Wave
Building Your First Boost Application Using Date Time
Book VI: Chapter 4: Boosting up a Step
Parsing Strings Using RegEx
Adding the RegEx library
Creating the RegEx code
Breaking Strings into Tokens Using Tokenizer
Performing Numeric Conversion
Creating Improved Loops Using Foreach
Accessing the Operating System Using Filesystem
Book VII: Building Applications with Microsoft MFC
Book VII: Chapter 1: Working with the Visual C++ 2008 IDE and Projects
Understanding the Project Types
Creating a New Win32 Console Application
Defining the project
Adding code
Running the application
Writing Code Faster
Obtaining coding help
Working with IntelliSense
Viewing Your Project in Solution Explorer
Using the Standard Toolbars
Changing Application Properties
Modifying the IDE Appearance
Changing toolbars and menus
Modifying windows
Book VII: Chapter 2: Creating an MFC Dialog Box Project
Understanding the MFC Dialog Box Project
Creating the MFC Dialog Box Project
Adding Components and Controls
Adding the component or control
Creating variables to use in your code
Defining methods to react to control events
Defining the Dialog Box Code
Understanding the Essential Windows
Working with Class View
Modifying the Toolbox
Book VII: Chapter 3: Creating an MFC SDI Project
Understanding the MFC SDI Project
Creating the MFC SDI Project
Understanding the Document/View Architecture
Adding Code to Your SDI Project
An overview of the essential application files
Locating Microsoft specified suggested changes
Making resource changes
Considering the help file
Registering and unregistering the application
Seeing the Text Editor Project in Action
Book VII: Chapter 4: Using the Visual C++ 2008 Debugger
A Quick Look at the Error Application
Starting Your Application in Debugging Mode
Creating the proper build
Setting breakpoints
Viewing your breakpoints
Starting the debugger
Working with the Debugging Windows
Viewing the focus variables using the Autos window
Viewing all of the variables in a methodusing the Locals window
Screening specific variables usingthe Watch 1 window
Working with the Call Stack window
Book VII: Chapter 5: Analyzing Your Visual C++ 2008 Code
Using Performance Wizard
Profiling the Code
Book VII: Appendix A: Automating Your Programs with Makefiles
Using rules that depend on other rules
Making specific items
Depending on multiple files
Compiling and linking with make
Cleaning up and making it all
Using macros
Getting the most out of Makefiles
Book VII: Appendix B: About the CD
CodeBlocks Compiler
Author-created material

C++ All-in-One For Dummies®, 2nd Edition

by John Paul Mueller and Jeff Cogswell

C++ All-in-One For Dummies®, 2nd Edition
Published by
Wiley Publishing, Inc.
111 River St.
Hoboken, NJ 07030-5774
www.wiley.com
Copyright © 2009 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 Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
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, Making Everything Easier, 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 representations 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 created or extended by sales or promotional materials. The advice and strategies contained 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 further information does not mean that the author or the publisher endorses the information 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, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
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: 2009932710
ISBN: 978-0-470-31735-8
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1

About the Authors

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 83 books and over 300 articles to date. The topics range from networking to artificial intelligence and from database management to heads-down programming. Some of his current books include a C# design and development guide and a complete reference for LINQ. John also writes about areas other than programming, such as Exchange Server. His technical editing skills have helped more than 63 authors refine the content of their manuscripts. John has provided technical editing services to both Data Based Advisor and Coast Compute magazines. He’s also contributed articles to the following magazines: CIO.com, DevSource, InformIT, Informant, DevX, SQL Server Professional, Visual C++ Developer, Hard Core Visual Basic, asp.netPRO, Software Test and Performance, and Visual Basic Developer.
When John isn’t working at the computer, he enjoys spending time in his workshop crafting wood projects or making candles. On any given afternoon, you can find him working at a lathe or putting the finishing touches on a bookcase. He also likes making glycerin soap, which comes in handy for gift baskets. You can reach John on the Internet at [email protected]. John is also setting up a Web site and blog at http://www.johnmuellerbooks.com/. Feel free to look and make suggestions on how he can improve it.
Jeff Cogswell is an experienced teacher, writer, and software engineer. He worked 15 years as a professional programmer and software engineer before leaving that field to write and edit full time. He is currently a senior editor with Ziff Davis Enterprise, writing and editing for DevSource.com and eWEEK.com. His skills include C++ as well as several other languages and platforms, such as C# and ASP.NET. In his spare time he enjoys traveling, playing the guitar, and photography.

Dedication

This book is dedicated to Dr. Michael Shonfeld and Nurse Barb McPherson, two special people who may not always get the thanks they deserve. Thank you so much for your help in returning my beautiful wife to me!
— John Paul Mueller
To my wife Angie, and my son Dylan, with love.
— Jeff Cogswell

Authors’ Acknowledgments

I really appreciate Jeff having the confidence to work with me on this book. We’ve known each other for quite some time now and I always enjoy working with him.
Russ Mullen deserves thanks for his technical edit of this book. He added greatly to the accuracy and depth of the material that you see here. I appreciated the time he devoted to checking my code for accuracy. As I wrote this book, I also spent a good deal of time bouncing ideas off Russ, who is a valuable aid to any author.
Matt Wagner, my agent, deserves credit for helping me get the contract in the first place and taking care of all the details that most authors don’t consider. I always appreciate his assistance. It’s good to know that someone wants to help. Matt also helped me through an extremely difficult time in my life — this book is a tribute to the perseverance of us both.
A number of people read all or part of this book to help me refine the approach, test the examples, and generally provide input that every reader wishes they could have. These unpaid volunteers helped in ways too numerous to mention here. I especially appreciate the efforts of Eva Beattie, Osvaldo Téllez Almirall, and all the others who provided input on C++. I'd like to thank each person who wrote me with an idea by name, but there are simply too many.
Finally, I would like to thank Katie Feltman, Susan Pink, Blair Pottenger, and the rest of the editorial and production staff for their assistance in bringing this book to print. It’s always nice to work with such a great group of professionals.
— John Paul Mueller
I first want to thank John Mueller for taking up such a difficult task and writing the second edition of this book, as well as his wife, Rebecca, for staying strong. Also, another book brings another big thanks to my agent and friend, Margot Hutchison, for the usual great work. And special thanks to Katie Feltman and editors Susan Pink and Blair Pottenger for their meticulous work in making this project reality. Finally, thanks to my wife Angie and my son Dylan for supporting me in all my projects.
— Jeff Cogswell

Publisher’s Acknowledgments

We’re proud of this book; please send us your comments through our online registration form located at http://dummies.custhelp.com. For other comments, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002
Some of the people who helped bring this book to market include the following:
Acquisitions, Editorial, and Media Development
Project Editor: Susan Pink (Previous Edition: Pat O’Brien)
Acquisitions Editor: Katie Feltman
Copy Editor: Susan Pink (Previous Edition: Diana Conover, Barry Childs-Helton)
Technical Editor: Russ Mullen
Editorial Manager: Jodi Jensen
Media Development Project Manager: Laura Moss-Hollister
Media Development Assistant Project Manager: Jenny Swisher
Media Development Associate Producer: Shawn Patrick
Sr. Editorial Assistant: Cherie Case
Cartoons: Rich Tennant (www.the5thwave.com)
Composition Services
Project Coordinator: Kristie Rees
Layout and Graphics: Carl Byers, Ronald Terry
Proofreaders: David Faust, Amanda Graham, John Greenough, Christine Sabooni
Indexer: Broccoli Information Management
Publishing and Editorial for Technology Dummies
Richard Swadley, Vice President and Executive Group Publisher
Andy Cummings, Vice President and Publisher
Mary Bednarek, Executive Acquisitions Director
Mary C. Corder, Editorial Director
Publishing for Consumer Dummies
Diane Graves Steele, Vice President and Publisher
Composition Services
Debbie Stailey, Director of Composition Services

Introduction

C++ is the language of the millennium. Why is C++ so popular?
♦ It’s powerful. You can write almost any program in it.
♦ It’s fast, and it’s fully compiled. That’s a good thing.
♦ It’s easy to use — if you have this book.
♦ It’s object-oriented. If you’re not sure what that is, don’t worry. You can find out about it by reading this very book you’re holding.
♦ It’s portable. Versions are available for nearly every computer.
♦ It’s standardized. The American National Standards Institute and the International Standards Organization both approve an official version.
♦ It’s popular. More people are using C++ because so many other people use it.
Sure, some people criticize C++. But most of these people don’t truly understand C++ or are just having a bad day. Or both.

No Experience Necessary

This book is not a big rant about C++. Rather, it’s a hands-on, roll-up-your-sleeves book, where you will truly learn C++.
At the very beginning, we start you out from square one. We don’t assume any programming experience whatsoever. Everybody has to start somewhere. You can start here. Not to brag, but you are in the hands of highly successful C++ users who have shown thousands of people how to program, many of whom started out from square one.

Great for Advanced Folks, Too!

You already know C++? This book is great for you, too, because although we start discussing C++ from the beginning, we go all the way through it.
Want to know how to derive a nontemplatized class from a class template? Check out Minibook IV, Chapter 5.
Want to see how to create an observer pattern in C++? See Minibook II, Chapter 6.
Want to find out the difference between deque and vector in the C++ Standard Library? Look at Minibook IV, Chapter 6.
Want to know how to make a class persistent? Minibook V, Chapter 5.
Want to know about the Boost library, the library that has added more to the Standard Template Library (STL) than just about any other source? Check out Minibook VI, Chapters 3 and 4. If you use C++ and don’t use Boost, you’re really missing out!

For All Computers

Although one of the minibooks in C++ All-in-For Dummies, 2nd Edition is devoted to Microsoft-specific topics (Minibook VII on Visual Studio 6.0 and MFC), the rest of the book is for C++ in general. C++ is now standardized, and you can use the information in this book for many different platforms. We wrote the samples on Microsoft Windows. But for most samples, we used a compiler called CodeBlocks that runs on almost every computer (Windows, Linux, and Macintosh). It doesn’t matter which computer you’re using!
All the code in this book, except that in Minibook VII, has been tested on both Windows and Linux. (Don’t let the Windows screenshots fool you; CodeBlocks works great on just about any platform.) Even though we didn’t have a Macintosh available for testing at the time of writing, we’re sure that the examples will also work fine in the Macintosh environment if you use the CodeBlocks compiler as described in the book.

Conventions

As a guy who is about to head off to a convention, we thought it would be appropriate to share with you some tidbits about the conventions in this book. However, this time we’re talking about the text format.
♦ When you see something in monofont, it’s a computer word that you type into the computer or read on a computer screen. If we discuss a computer term but it’s not a word that you type into the computer, it is in the usual font. You also see monofont for URLs and e-mail addresses.
♦ When you see something in bold, you can type it into the computer.
♦ When you see a word in italics, it’s new and we explain its meaning.
♦ When code is on a single line, it looks like this:

MyClass.IsCool();

♦ When code appears on multiple lines, it looks like this:
MyClass.IsCool();

AndSo.IsYours();

♦ Lengthy program listings have a header and a listing number. These are entire programs you can type, and they should run as-is. However, you save time and effort by using the code supplied as part of the book’s CD. The CD also contains a full copy of the Windows version of CodeBlocks.

Organization

This book is divided into seven minibooks. Each one covers a separate, broad topic, with chapters devoted to individual subtopics.
You can either read this book cover to cover or you can look topics up and treat the book as a reference guide — whichever works best for you. Keep it on your shelf and have it ready to grab when you need to look something up. Here are the seven minibooks and what they cover:
Minibook I, Introducing C++: Here, we start at the very beginning, showing you all you need to know to get up and running with C++. This is also the minibook that gets you started with CodeBlocks. If you don’t have a copy of CodeBlocks installed on your system, you definitely want to start by reviewing Chapter 1.
Minibook II, Understanding Objects and Classes: In this minibook, we present all the latest information about object-oriented programming and how to use various diagrams to design your programs. Advanced readers should especially appreciate this minibook because we cover such topics as UML and design patterns. But beginners should be able to understand it, too, and find out how to get up to speed with the best software engineering ideas around.
Minibook III, Fixing Problems: Here, we show you how to debug your programs by using a special program called a debugger. If you’re a beginner, this minibook gets you started on fixing the problems in your code. If you’re advanced, you can appreciate how we use the debugger supplied with CodeBlocks to locate any problems your application might have.
Minibook IV, Advanced Programming: In this minibook, we move through advanced C++ topics. After reading Minibook IV, the beginners become intermediate or advanced programmers, and the intermediate and advanced programmers can master the C++ language.
Minibook V, Reading and Writing Files: Yes, this entire minibook is devoted to the issues of reading and writing files. In this book, we cover stream programming, which is a special way C++ treats files.
Minibook VI, Advanced C++: This advanced minibook includes two chapters each on STL (Standard Template Library) and Boost. The STL chapters describe some of the advanced classes not used in other areas of the book and help you create your own templates. The Boost library chapters describe all the tools found in Boost, show how to build a full set of libraries for your own use, and then provide an overview of some interesting Boost capabilities. You really miss out on a lot if you don’t at least visit this minibook after you build your programming skills.
Minibook VII, Building Applications with Microsoft MFC: Many, many people use the native code capabilities of Microsoft Visual C++. In this minibook, we show you how to create workspaces and projects in Visual Studio 2008. We then show you how to write software for Windows by using Microsoft Foundation Classes. This minibook doesn’t include any discussion of Microsoft’s latest offering for C++ developers, the .NET Framework.

Icons Galore

Hey, what would a For Dummies book be without all the great icons? These are the second best part, next to the cartoons. Here’s what they mean:
We have lots of experience as both C++ programmers and instructors, and so we pass on tidbits here and there to help you along.
This icon identifies things you may want to remember to do when you’re programming.
These icons can save you a lot of headaches. They’re suggestions to help keep you from really messing up — the way that we probably already did. You won’t cause the computer to explode if you skip these, but you’ll sleep better knowing you won’t accidentally lose all your code or overwrite a file.
Computer people often search for extra knowledge, even when it may not be necessary. These Technical Stuff paragraphs are fascinating information, primarily to cover your serious curiosity.

What’s Next?

If you want to e-mail us, please do! We have special e-mail addresses for you:
[email protected]
[email protected]
We both get a lot of e-mail from readers, so we can’t always reply, nor can we promise to have a quick-and-easy answer. Please don’t be offended if you don’t hear back. You can check out our Web sites, www.jeffcogswell.com and http://www.johnmuellerbooks.com/.
Jeff has a newsletter that dishes out tips and tricks for C++ programmers. Send an e-mail to [email protected], and you’ll get back an e-mail on how to subscribe. We think that you’ll be pleased with the information. Oh yes, and it’s free.
In the pages that follow you will see just how easy it is to program in C++. When you finish this book you will have a full mastery of the language!
Book I
Introducing C++

Contents at a Glance

Chapter 1: Creating a First C++ Program

Creating a Project

Typing the Code

Starting with Main

Showing Information

Let Your Program Run Away

Chapter 2: Storing Data in C++

Putting Your Data Places: Variables

Manipulating Integer Variables

Characters

Strings

Deciding between Conditional Operators

Telling the Truth with Boolean Variables

Reading from the Console

Chapter 3: Directing Your C++ Program Flow

Doing This or Doing That

Evaluating Conditions in C++

Including Evaluations in C++ Conditional Statements

Repeating Actions with Statements That Loop

Chapter 4: Dividing Your Work with Functions

Dividing Your Work

Calling a Function

Writing Your Own Functions

Calling All String Functions

Understanding main

Chapter 5: Dividing Between Source-Code Files

Creating Multiple Source Files

Sharing with Header Files

Sharing Variables Among Source Files

Using the Mysterious Header Wrappers

Chapter 6: Referring to Your Data through Pointers

Heaping and Stacking the Variables

Dynamically Allocating with new

Freeing Pointers

Passing Pointer Variables to Functions

Returning Pointer Variables from Functions

Returning a Pointer as a Nonpointer

Passing by Reference

Remembering the Rules

Chapter 7: Working with Classes

Understanding Objects and Classes

Working with a Class

Starting and Ending with Constructors and Destructors

Building Hierarchies of Classes

Chapter 8: Using Advanced C++ Features

Filling Your Code with Comments

Converting Types

Reading from the Console

Understanding Preprocessor Directives

Using Constants

Using Switch Statements

Supercharging enums with Classes

Working with Random Numbers

Storing Data in Arrays

Chapter 1: Creating a First C++ Program

In This Chapter
Organizing your programs into projects
Typing code into the code editor
Writing a program that writes to the screen
Doing basic math
Running your program
It’s your lucky day. You have decided to learn the most popular programming language on the planet. From the biggest skyscrapers housing huge Fortune-500 companies all the way down to the garages with the self-starting kids grinding out the next generation of software, people are using C++. Yes, there are other languages, but more programmers use C++ than any other language. In this chapter, you start right out writing a C++ program.
For this chapter we use CodeBlocks, a full-featured system for easily creating C++ code — and it’s free! You don’t need to spend hundreds of dollars to get up and running. Instead, you can install it right from the CD-ROM that came with this book. However, you’re not limited to using CodeBlocks. Several other tools are available to you, but in this chapter we suggest working with CodeBlocks because it’s easy to use. In fact, you may find you like it so well that you wind up almost neglecting the other tools.
We assume that you have already installed CodeBlocks. If you have not, you can find instructions in Appendix B.

Creating a Project

Creating a computer program is usually a bigger job than you’d want to organize in your head. Program code is saved in files much like the documents in a word processor. But programs often have more than one source-code file. At big companies in big buildings in big cities, some programs are really big — hundreds of source-code files for just one program.
Understanding projects
Projects can contain a lot of source code. To keep all that source code together, programmers use a file that manages it all called a project. Projects have a few key elements:
♦ A set of source-code files
♦ (Optionally) Resource information such as icons and sound files
♦ A description of how to compile (build) the application
♦ Integrated Development Environment (IDE) settings that tell how to set up the editor you use to write the application
♦ Some general descriptions of the program being built, such as its name and what type of program it is
By type of program, we don’t mean “word processor” or “really cool earth-shattering software,” even if that’s what your program is. We use type to mean your program’s overall relationship with other programs:
♦ Does this program run by itself?
♦ Does this program add to or extend the functionalities of another program (such as Microsoft Excel)?
♦ Does this program serve as a library (a bunch of code that you make available to another program)?
All this information, along with your source-code files, represents a project.
In the CodeBlocks tool, you create a new project each time you start work on a new program. You provide a little information about the program you’re working on, and then you begin writing your code. All the code for your program goes in one place — stored in the project.
This book presents a lot of sample programs, so you may want to create a directory (or folder) on your hard drive to house all the programs you create as you work through this book. Call it MyProjects, or something specific like CPPAllInOne, or whatever you prefer.
Defining your first project
To create a new project in CodeBlocks, start CodeBlocks and choose File⇒New⇒Project or click Create a New Project on the Start Here page that appears when you start the program. A dialog box appears, as shown in Figure 1-1.

 Figure 1-1:  The New from Template dialog box lets you select a new project type.

When you create a project in CodeBlocks, you choose from a list of several types of programs. They’re shown as icons in the New from Template dialog box. The following list shows some program types:
Win32 GUI Project: This is a standard Windows program that includes, well, a window. You know the kind; it usually has a menu across the top and something inside it that you can either click or type into.
Console Application: This is a program that gets a paltry Console window instead of a regular Windows window. Console refers to a window with a command prompt (folks who recall the old days before Windows call it a DOS box). You can remember this because you may have to “console it” for being just a boring DOS-type text window with a prompt.
Static library: A static library is a set of C++ code that you use later in another project. It’s like making a really great marinade that you won’t use up today. You’ll use some of it tomorrow and some of it after that. Same with a C++ library.
Dynamic Link Library: A Dynamic Link Library (DLL) is kind of like a static library except it stays separated from the main program and gets its own file with a .DLL extension.
Programmers have a bad habit of dropping DLLs in your c:\windows\system or c:\windows\system32 directory when you probably don’t really want them there. That’s why you’ve likely heard of DLLs before.
Empty project: A blank project that’s as clean as a blank sheet of white typing paper, ready for you to fill ’er up.
What about all of those other projects?
CodeBlocks supports a host of other application types. This book doesn’t discuss them because they won’t add to your initial understanding of C++ programming. However, these other projects are valuable in the right environment. For example, the GIMP Tool Kit Plus (GTK+) Project relies on a graphical user interface designed for the X Windowing system (see more at http://www.gtk.org/).
You’ll find that CodeBlocks uses a considerable number of acronyms and abbreviations for project and resource names without defining any of them. We define all the acronyms that we employ on first use in the book. However, some of these acronyms and abbreviations go on and on. For example, you might wonder about the GIMP part of the GTK+ definition. GIMP stands for GNU Image Manipulation Program. Of course, now you need to know GNU, which stands for Gnu’s Not Unix. Okay, now that we’ve exhausted that bit of fun, if you ever do run across an interesting acronym or abbreviation, you can always get it defined for you on the Acronym Finder Web site (http://www.acronymfinder.com/). The bottom line is that you need to research both projects and resources before you use them.
Frankly, it’s kind of a pain to use an empty project, because you have to tweak and set a bunch of things. So we never use this option.
For the samples in this chapter, create a Console Application. Follow these steps:
1. In the New from Template dialog box, click the Console Application icon found in the Projects tab. Click Go.
You see the Welcome page of the Console Application wizard.
2. Click Next.
The wizard asks which language you want to use.
3. Highlight C++ and click Next.
You see a list of project-related questions, as shown in Figure 1-2. These questions define project basics, such as the project name.
4. Type a name for your project in the Project Title field.
The example uses SayHello as the project title. Notice that the wizard automatically starts creating an entry for you in the Project Filename field.

 Figure 1-2:  Provide the name of your project for CodeBlocks.

5. Type a location for your project in the Folder to Create Project In field.
The example uses FirstProject as the folder name. You can also click the ellipses button next to the Folder to Create Project In field to use the Browse for Folder dialog box to locate the folder you want to use. Notice that the wizard completes the entry in the Project Filename field.
If you made a folder to house all the programs for this book (as suggested in the “Understanding projects” section of the chapter), put your FirstProject folder in the folder for the book. Make sure you’re inside the folder you just created.
6. (Optional) Type a project filename in the Project Filename field.
7. Click Next.
You see the compiler settings shown in Figure 1-3. Most of the projects in this book use the default compiler settings. However, if you look at the Compiler drop-down list, you see that CodeBlocks supports a number of compilers and you can add more to it. The other settings control the creation and location of a Debug version (the version you use for finding problems in your code) and a Release version (the version that you send to a customer) of the application.
8. Change any required compiler settings and click Finish.
The wizard creates the application for you. It then displays the CodeBlocks IDE shown in Figure 1-4 with the project loaded.

 Figure 1-3:  Tell CodeBlocks where to place the Debug and Release versions of your application.

 Figure 1-4:  Use the CodeBlocks IDE to interact with your project.

The project window is organized side by side:
♦ The left side is an Explorer view (called a tree view), which represents your project. At the top of the tree view is a workspace — the essential unit of a project. Below the workspace is the name of your project. Underneath that are the components of your project. In this case, only one component exists so far: the source-code file whose filename is main.cpp. Remember that to program in C++, you enter code into a source-code file; this file, called main.cpp, is such a file for your SayHello project.
♦ The right side (which actually takes up about three-quarters of the screen) is the source-code file itself.
This part works much like a word processor or an e-mail editor, and you can type the code into the window. You notice that you already have some code there — a sort of starter code that came into being when you chose Console Application and created the project.
♦ At the bottom of the display are a number of status windows. The Code::Blocks window tells you how the wizard created your application. Don’t worry about these windows for right now. You see them in action as the book progresses.
Building and executing your first application
Okay, it’s time to work with your first application. Use the following steps to save the file, build the program (make it into an executable that Windows can use), and execute the program.
1. Save the code file by choosing FileSave Everything.
Saving the files ensures you have a good copy on disk should something go wrong. For example, you could completely crash the IDE if your application does the wrong thing.
2. Choose BuildBuild or press Ctrl+F9.
This action creates the executable file. Building the code converts words you understand into code that Windows understands. Notice that CodeBlocks automatically selects the Build Log window for you and you see the steps that CodeBlocks takes to create your application. At the end of the process, you should see 0 Errors, 0 Warnings as the output.
3. Choose BuildRun or press Ctrl+F10.
An output window like the one shown in Figure 1-5 opens and you see your first program execute.
4. Press Enter to stop program execution.
The program window disappears and you see the CodeBlocks IDE again.
Well that wasn’t interesting, was it? But that’s okay! The program starts out in a basic situation: We have a console window, and then when the program is finished doing whatever it must do, it shows the message Press any key to continue — and when you do so, the program ends.

 Figure 1-5:  Execute your first program.

Typing the Code

The right-hand 75 percent or so of the CodeBlocks window is called the code editor; it’s where you type and change your code. Of all the tasks we just mentioned, the nearest equivalent to using the CodeBlocks code editor is composing an e-mail message.
Word movement and selection actions look a bit strange on the screen. They ignore some characters, such as braces — the curly characters { and }. (We recently added this to our “Mysteries of Life” on the refrigerator.)
The code editor works like the editor in an e-mail message. You can
♦ Type code.
♦ Move the cursor with the arrow keys (up, down, left, right) to the position where you want to type. The cursor is the little blinking vertical bar that shows where your text goes when you type. Some folks call it a caret or an insertion point.
♦ Click where you want to type. Use the mouse to point where you want to type, then click the mouse button. The cursor jumps to the spot where you click.
♦ Select text to delete or change. You can select text in either of two ways:
• Point with the mouse at the first or last character you want to select; then hold down the mouse button while you drag the mouse.
• Move the cursor to the first or last character you want to select; then hold down the Shift key while you press the arrow keys.
♦ Scroll the text up and down (vertically) or left and right (horizontally) with the scrollbars. The scrollbars work only when there is more text than you can see in the window, just like most other places in the Windows and Macintosh worlds. You can scroll up and down (if there’s enough text in the editor) by using Ctrl+↑ and Ctrl+↓ key combinations.
♦ Scrolling changes only what you see. You must use the mouse or the arrow keys to select what you see.
After you play around a bit with the editor, you can use Table 1-1 to do a few of your favorite tasks. (Of course, if you’re new to programming, you may not know yet whether these are your favorites — but they will be soon. Trust me.)

  
Table 1-1 Navigation and Edit Commands
  

Command

  

Keystroke or Action

  

Cursor movement

  

↑, ↓, ←, or →, Home, End

  

Moving from word to word

  

Ctrl+← or Ctrl+→

  

Selecting with the mouse

  

Click the mouse in the text, and while the mouse button is down, drag the mouse

  

Selecting with the cursor

  

Shift+↑, Shift+↓, Shift+←, or Shift+→

  

Selecting the next word

  

Shift+Ctrl+→

  

Selecting the previous word

  

Shift+Ctrl+←

  

Selecting everything

  

Ctrl+A

  

Going to the top

  

Ctrl+Home

  

Going to the bottom

  

Ctrl+End

Starting with Main

When a computer runs code, it does so in a step-by-step, line-by-line manner. But your code is organized into pieces, and one of these pieces is called the main function, or simply main. main is the part that runs first. main tells the computer which other parts of the program you want to use. main is the head honcho, the big boss.
How does the computer know what is main? You type lines of code between the brace characters, { and }. Here is the default program that CodeBlocks produces when you create a Console Application project.
int main()
{
cout << “Hello world!” << endl;
return 0;
}
The word main is required, and it tells the computer where main is. You might also see main shown as:
int main(int argc, char *argv[])
Don’t worry about the words around main for now. You discover what these words mean later in the chapter. For now, all you need to know is that every C++ program has a main function.
The computer performs the code line by line. If a line is blank, the computer just goes to the next line. When you write lines of code, you are instructing the computer to do something (which is why some people refer to lines of code as instructions).

Showing Information

Ready to type some code and try it out? Let’s do it! This code will open the famous console window and write some words to it.
First, make sure that you still have the CodeBlocks tool open and the SayHello project open, as in this chapter’s preceding examples. If not, follow these steps:
1. Start CodeBlocks if it’s not already running.
You see a Start page for the CodeBlocks IDE.
2. Click the SayHello.cbp project found in the Recent Projects list.
CodeBlocks opens the project for you.
If the main.cpp code isn’t showing in the right 75 percent of the window, click main.cpp in the tree view on the left. It will immediately open. (If you don’t see the tree view, click the little tab at the top that says Projects; it’s next to a tab that says Symbols.)
Follow these steps carefully. Make sure that you type everything exactly as given here:
1. Position the cursor on the line with the opening brace.
In this case, that’s line 6. You can see the line number on the left side of the code editor.
2. Press the Enter key.
The cursor should be in the fifth column. If it isn’t — if it stays in the first column — then press the spacebar four times.
3. Type the following line of code exactly as it appears here.
Put no spaces between the two less-than (<) symbols. Make sure that you remember the final semicolon at the end. Here’s the line:
cout << “Hello, I am your computer talking.” << endl;
4. Delete the line of code that looks like this:
cout << “Hello world!” << endl;
In the end, your code will look like the following example (the new line that you typed is shown here in bold):
#include <iostream>
using namespace std;
int main()
{
cout << “Hello, I am your computer talking.” << endl;
return 0;
}
If you don’t type your code correctly, the computer can tell you. This step compiles the program: the computer makes sure that what you wrote is okay and then translates it into a runnable program. (Don’t worry too much about what that means. For now just think of it as making sure that your program is okay. Appendix A gives you the whole story about compiling.)
To find out whether your program is good to go, choose Build⇒Build.
If all is well, you see a window in the lower-left of the main CodeBlocks window with the really happy message, 0 errors, 0 warnings. A message like You rock! might be nicer, but 0 errors, 0 warnings ain’t all that bad, we guess.
If you didn’t type the line correctly, all is not lost because the computer will tell you what you did wrong. In this case, you will see something like what is shown in Figure 1-6. A list with columns appears at the bottom of your screen.

 Figure 1-6:  CodeBlocks tells you about errors in your program.

♦ The leftmost column shows the name of the file where the error was. In this case the error was in main.cpp, the only file we were working on.
♦ The second column shows the line number of the problem (in this case, 7).
♦ The third column of the list makes a basic attempt to tell us what we did wrong, like this:
error: ‘couts’ was not declared in this scope
When the compiler doesn’t recognize a word, it says that the word is not declared. In other words, the compiler doesn’t know what couts is. (The word should be cout.)
If we want to see the problem, we can point at the error report line and double-click. The bad line appears in the code editor, with a little red box next to the line. The line is also highlighted. As soon as we press an arrow key, the highlight vanishes.
Thus, if we press the key a few times and get to the word couts and then delete the letter s, we can try again. If we choose Build⇒Build, this time we see the happy message 0 errors, 0 warnings. Excellent!
No errors means that the program is good enough to run. So run it!
Choose Build⇒Run. A console appears with text that looks like this:
Hello, I am your computer talking.
Process returned 0 (0x0) execution time : 0.015 s
Press any key to continue.
See what happened? There is now a message that says, Hello, I am your computer talking. Apparently the thing you typed caused that message to appear. (Go ahead and press Enter to close the console.)
And in fact, that’s exactly what happened. That’s how you make a message appear on the console screen. The steps look like this:
1. Type cout.
Although cout looks like it’s pronounced “cowt,” most programmers say “see-out.” Think of it as shorthand for console output. (But don’t type console output in its place, because the compiler won’t accept that.)
2. After the word cout, type a space and then type two less-than signs (make sure to leave that one space before them).
These less-than signs just mean, the thing that follows is going to appear on the console. The thing that follows, you will notice, is in double quotes. That’s the way the computer knows where it starts and ends. The words and stuff inside these double quotes is called a string because it’s a bunch of letters strung together. (I’m not making this up.) The computer knows where the string starts because there’s a double quote, and it knows where the string ends because there’s a double quote. The computer doesn’t display these two sets of double quotes when the program runs.
Then some weirdness follows. There’s another set of less-than signs, which means you want to write more to the console. But what follows? It’s endl. Notice this is not in quotes. Therefore we are not saying that we want the strange barely pronounceable word “endl” to appear on the screen. Instead, we’re using a special notation that tells the computer that we want to start fresh on the next line. And if you look at the output, you’ll notice that the words that follow (the message about pressing the any key) are, indeed, on the next line. Note that endl is pronounced “end-el.”
So that’s not so bad after all. Let us recap:
♦ The word cout means you want to write to the console.
♦ The << symbols together (with no space between them!) mean the thing that follows is what you want to write.
♦ After the << symbol, you tell the computer what you want to write. It can either be a string of letters, symbols, and other characters (all inside quotes), or it can be the word endl.
♦ You can put multiple items in a row and have them appear on the console that way, provided you start the line with cout and precede each item with the << symbols.
Oh, and if you have a sharp eye, you may notice one more thing we haven’t mentioned yet: we included a semicolon at the end of the line. In C++, every line must end with a semicolon. That’s just the way it’s done.
Statements in C++ end with a semicolon.
It’s not quite accurate to say that every line must end with a semicolon. You can break any line into multiple lines. The computer doesn’t mind. We could just as easily have written our line as the following two lines:
cout << “Hello, I am your computer talking.”
<< endl;
This is fine, provided that you don’t split any individual word (such as cout and endl), or the << symbols, or the string. In effect, anyplace you have a space occurring “naturally” in the code (for example, between I and am), you can start a new line if you want. Then, when the whole statement is finished, you end with a semicolon. Think of the semicolon as a signal to the computer that the old statement is finished.
Doing some math
You can get the computer to do some math for you; you can use the same cout approach we described in the preceding section, and you throw in some numbers and arithmetic symbols.
Although addition uses the familiar plus sign (+) and subtraction uses the familiar minus (–) sign, multiplication and division use symbols you might not be familiar with. To multiply, you use the asterisk (*); to divide, you use the forward-slash (/).
Table 1-2 shows the math symbols.

  
Table 1-2 Math Symbols
  

Symbol

  

Function

  

+

  

Addition (plus)

  

  

Subtraction (minus)

  

*

  

Multiplication (times)

  

/

  

Division (divided by)

Yep, it’s now math-with-weird-symbols time. Continue with the source code you already have. Click somewhere on the line you typed — you know, the one that looks like this:
cout << “Hello, I am your computer talking.” << endl;
Press End so the cursor moves to the end of the line. Then press Enter so you can start a new line in between the cout line and the line that starts with the word return.
Whenever you want to insert a line between two other lines, the easiest way to get it right is to go to the first of those two lines, press End, and then press Enter. This will insert a new blank line in the right place.
After you press Enter, you will notice that something happened: The cursor is not at the start of the newly inserted line; instead, there are four spaces and it’s indented flush with the other lines. That’s not a mistake. Believe it or not, it’s a serious lifesaver. Well, okay, maybe not a lifesaver, but it’s almost as good as those little candies that everybody loves. The reason is that often you indent your code (this particular code is indented four spaces); if you’re typing lots of code, it’s a bummer to have to type four spaces (or press the Tab key) every time you start a new line. So CodeBlocks considerately (and automatically) does the indentation for you.
If, for some reason, your code didn’t automatically indent and the cursor is loitering at the beginning of the line, the auto-indent feature is not turned on. It should be on by default, but if it isn’t, here’s how to turn it on:
1. Choose SettingsEditor Options.
The Configure Editor dialog box appears.
2. Make sure that the Tab Indents check box is selected, then click OK.
3. Once back in the code, press Backspace to delete your new line, then try pressing Enter again.
Behold! The code automatically indents.
4. After your new blank line appears and indents itself, type the following:
cout << 5 + 10 << endl;
The beginning and the end of this line are just like those of the line you typed earlier. The difference is the middle — instead of typing a string, you type a math problem: 5 plus 10. Note that we put spaces around the 5, around the +, and around the 10 — but not between the 1 and 0. If you put a space there, the computer gets confused (it doesn’t know that you meant to write a single two-digit number). When you’re finished, your code should look like the following code snippet (here the new line you typed is shown in bold):
#include <iostream>
using namespace std;
int main()
{
cout << “Hello, I am your computer talking.” << endl;
cout << 5 + 10 << endl;
return 0;
}
5. Save your work by choosing FileSave Everything.
Instead of choosing File⇒Save Everything, you can recognize that the only thing that changed is the source-code file you’re currently working on. If you see the blinking cursor in the code editor, you know that the code editor is active. If not, click somewhere in your code to activate the editor. When you see the blinking cursor, press Ctrl+S. This saves your file.
In the computer world, there’s an adage that goes something like this: “Save early, save often.” Get in the habit of pressing Ctrl+S every so often. You won’t wear out your hard drive, and the keyboard is pretty durable. Every time we type a few lines of code, we press Ctrl+S. Before we compile, we press Ctrl+S. When we’re feeling paranoid that the last Ctrl+S didn’t stick, we press Ctrl+S. When we’re stuck at a traffic light, we press Ctrl+S.
Now you can tell the computer to compile your code. If you haven’t saved it, do so now by pressing Ctrl+S. Then choose Build⇒Build. If you typed everything correctly, you should see the magical message 0 errors, 0 warnings appear in the Build Log window. But if not, don’t worry; you can easily fix it. Look at your code and find the difference between the line we wrote earlier and your code. Here it is again, just for safe measure:
cout << 5 + 10 << endl;
There is a space after cout, a space after <<, a space after 5, a space after +, a space after 10, and a space after <<. And there is a semicolon at the end. Make sure that these are all correct.
Then when you successfully compile and see the happy message 0 errors, 0 warnings, you are ready to run your program. Choose Build⇒Run.
A console window opens, and you should see the following:
Hello, I am your computer talking.
15
Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.
Notice the second line is the answer to the math problem 10 + 5. That means the computer knows how to do math, more or less correctly. (Okay, it had better be correct, or we’re going to demand a refund from our teachers.)
Ordering the operations
If you want, you can play around with some more complicated problems. For example, you can try something like this:
cout << 5 + 10 / 2 * 3 + 25 << endl;
What do you think the answer will be? The answer depends on computer rules for the order in which it performs math problems. These are called orders of operation. Multiplication and division take precedence over addition and subtraction. Therefore, the computer does all the multiplication and division first from left to right; then it does the addition and subtraction from left to right. Figure 1-7 shows the order in which the computer does this particular math problem.
Going overboard
The computer actually has various limits, including when it comes to math. If you try something like this
cout << 8762547892451 * 10 / 2 * 3 + 25 << endl;

 Figure 1-7:  The computer likes to use orders of operation.

an error message shows up in the error window when you try to compile:
error: integer constant is too large for “long” type
This message is bad. The reason is that you’ve gone beyond the limits of what this style of math enables you to do. So be careful.
You can also go too big when you run your program — and (unfortunately) you won’t know it. For example, the line
cout << 12345 * 12345 * 12345 * 12345 * 12345 << endl;
will compile correctly — but (aieee!) shows the following result:
253233049
Nope, it’s not correct. Not even a good guess. So the moral here is mainly to use the approach to coding shown in this section only when you’re using basic math and don’t have to juggle really big numbers. If you’re getting over five or six digits, you’re getting into too-big territory.
The greatest positive number you can use is 2,147,483,647. The greatest negative number is –2,147,483,647. However, if you’re willing to stick to only positive numbers and 0, the computer can make some adjustments inside and handle a higher positive number. In that case, your numbers can range from 0 to 4,294,967,295.
Pairing the parentheses
If you want to get around the order in which the computer does its math, you can add parentheses. For example, if you use the following line, the computer does the final operation (+) before it does the others:
cout << 5 + 10 / 2 * (3 + 25) << endl;
Whereas previously, without the parentheses, this thing came out to be 45, now it comes out to be 145. First the computer does the 3 + 25 to get 28. Then it begins with the multiplication and division, from left to right. So it takes 10 / 2 to get 5, then multiples that by (3 + 25), or 28, to get 140. Then it starts with the addition and subtraction from left to right. So it adds 5 to this to get the final number, 145.
Tabbing your output
Just as you can write a string of letters and numbers to the console, you can also write a tab. For example, take the following line from your program
cout << “Hello, I am your computer talking.” << endl;
and change it to the line shown in bold in the following code:
#include <iostream>
using namespace std;
int main()
{
cout << “Hello\tI am your computer talking.” << endl;
return 0;
}
In the preceding code, we replaced the comma and space with a backslash and then a lowercase t. (We also removed the extra line about math, just in case you tried the math things from the preceding section.) But when you compile and run this program (remember to compile it first!), it won’t print exactly what’s in the double quotes. Here’s what you see:
Hello I am your computer talking.
The extra space in the displayed line is a tab space, just as if you had pressed the Tab key while typing this. (Is that slick, or what?)
There’s a complication to using the backslash: You can’t just type a backslash or a double quote and expect to see it on the screen. A couple of workarounds will show the actual characters:
♦ Really want to display a backslash, not a special character? Use a backslash followed by another backslash. (Yes, it’s bizarre.) The compiler treats only the first backslash as special. When a string has two backslashes in a row, the compiler treats the second backslash as, well, a backslash.
For example, the following line of code has two backslashes:
cout << “\\tabc” << endl;
The following text shows up at the console:
\tabc
♦ If a string starts with a double quote and ends with a double quote, how in the world would you actually print a double quote? Type a backslash, then a double quote, as in the following code:
cout << “Backslash and double quote equal \” in C++.” << endl;
When that code runs in a program, you see this on the screen:

Backslash and double quote equal “ in C++.

C++ programmers use the term escape-sequence to refer to any special character in a string that starts with a backslash. This is an outdated bit of vocabulary — maybe not as old as “methinks,” but it does date back to the original C language of the 1970s. Back then, you made special characters appear on console screens by first pressing the Esc key.

Let Your Program Run Away

The word execute refers to running your program, but you need to compile (or build using the CodeBlocks terminology) the program before you run it. The compilation process transforms your program into an executable file. An executable file is a special type of file that contains a program that you can run on your computer. When you run your word processor program, you run an executable file containing the word processor program.
After the computer compiles (builds) your program, it performs a step called linking. People often refer to these two steps together as simply compiling. Indeed, in this book, we often use the term to mean both steps together. If you’re curious about what goes on here, take a look at Appendix A. It has a section devoted to the compiling and linking processes.
Whenever you want to run your program, you first compile it, and then you run it. If you make more changes to your program, you must compile it again before running it. Otherwise, the executable file won’t have your changes.
Because you almost always use Build and Run in sequence, the kind people who built CodeBlocks included a special menu item called Build and Run on the Build menu. The computer first compiles your code, then it immediately runs the program if there are no errors. If there are errors, the compiler doesn’t run the program, and the errors are reported as usual.
We almost always use the Build and Run option, rather than clicking Build and then Run separately.
Sometimes the old-fashioned approach is more efficient: When we compile and run our programs, we use shortcut keys. It takes a bit of extra time to grab the mouse, move the pointer to a menu, and so on. Instead, we press F9 to compile.
Table 1-3 lists keyboard shortcuts for compiling.

  
Table 1-3 Keyboard Shortcuts for Compiling and Running
  

Action

  

Keyboard Shortcut

  

Build

  

Ctrl+F9

  

Run

  

Ctrl+F10

  

Build and run

  

F9

Chapter 2: Storing Data in C++

In This Chapter
Using storage bins called variables
Working with integer variables
Using character variables
Manipulating strings
Using Boolean variables
Using conditional operators
Reading from the console
We all love to store things away. Our closets are a perfect example of a place to store things. We have boxes in there that we have not opened in years. Perhaps we inadvertently created a time capsule. Or just a fire hazard. When you program a computer, you can also store things away. Most people know that computers have two kinds of memory: memory inside the chips and memory in the hard drive. But most people use the term memory in reference to the memory chips; the other is just referred to as the hard drive. When you type a business letter in a word processor, the letter is stored in the memory. After you choose File⇒Save, the letter gets stored to the hard drive, but as long as you still have it open in the word processor, it’s generally still in memory.
The best way to think of memory is as a set of storage bins, much like the ones in the closet that we are afraid of. When you write a computer program, you reserve some storage bins, and you give each storage bin a name. You also say what type of thing can go inside the storage bin. The technical term for such a storage bin is a variable.
In this chapter, we show you how you can use these storage bins in your programs.
The programs in this and the remaining chapters work with the free compiler included on this book’s CD-ROM. You can also use any other compiler, such as the C++ compiler supplied with Visual Studio. In this chapter, we’re assuming that (by now) you know how to use the compiler of your choice. Chapter 1 shows you how to use CodeBlocks; to find out more about CodeBlocks see Appendix B.

Putting Your Data Places: Variables

When you write a program, you specify that you want to make use of one or more storage bins called variables. You can put different kinds of things in these storage bins. The difference with these computer storage bins and those in your closet, however, is that each computer storage bin can hold only one thing at a time.
You can put many different types of things into your variables, too. For example, you can put numbers in a storage bin, or you can put a string in a storage bin. Minibook I, Chapter 1 advises that a string is simply a bunch of letters, numbers, or other characters all strung together. As for numbers, they can either be integers (which are positive whole numbers, negative whole numbers, and 0) or they can be numbers with a decimal point, such as 3.11 or 10.0, which (for various reasons) are called floating-point numbers.
The term floating-point number means a number that has a decimal point and something to the right of the decimal point (even if it’s just a 0). When you see the term floating point, you can remember what it means by the word point in its name. Think of decimal point.
If you are already familiar with the term variable from other fields, be careful that you do not apply their definitions here. Although similar, some significant differences are involved. For example, in algebra, a variable represents an unknown quantity, and you can solve for a variable. But in programming, it’s simpler than that: A variable is simply a storage bin with an associated name.
Creating an integer variable
In your C++ program, you can easily write a line of code that creates a variable. Although what you’re doing at that point is just writing code (and the variable won’t actually get created until you run the program), people often refer to this process as creating a variable. When we are working with another programmer that we like, we will often say, “We’ll go ahead and make a variable.” What we’re really doing is writing code that tells the computer to go ahead and make the variable. And of course, the computer won’t actually make the variable until the program runs. If, on the other hand, we’re working with a programmer we don’t like, we probably won’t say anything at all.
A variable has three aspects, as shown in Table 2-1.

  
Table 2-1 A Variable Has Three Aspects
  

Aspect

  

What It Means

  

Name

  

The name you use in your program to refer to the variable

  

Type

  

The type of information that the variable can hold

  

Value

  

The actual thing that the storage bin holds

The following list describes the items in Table 2-1 in more detail.
Name: Each variable must have a name. In your program, you refer to the variable by this name. For example, you may have a variable called count, and you may have a variable called LastName. Or you could have a variable called MisterGates.
Type: When you create a variable, you must specify the type of information the variable can hold. For example, one variable may hold an integer, and another variable may hold a single character. After you pick a type for the variable in your program, you can put only things of that type into the variable.
Value: At any given moment, a variable holds a single value. For example, an integer variable might hold the number 10, and a character variable might hold the character a. In your program, you can store something in a variable, and later you can store something else in the variable. When you store something else, the variable forgets what was previously inside it. So in this sense, you can think of a computer as having a one-track mind.
The code in Listing 2-1 demonstrates how to create a variable. This is a full program that you can run.
Listing 2-1: Creating a Variable
#include <iostream>
using namespace std;
int main()
{
int mynumber;
mynumber = 10;
cout << mynumber << endl;
return 0;
}
Take a careful look at Listing 2-1. Remember that the computer starts with the code inside the braces that follow the word main, and it performs the code line-by-line.
The first line inside main looks like this:
int mynumber;
When you declare a variable, the first thing you specify is the type of thing the variable can hold. Here, we used the word int. This word is the C++ word for integer. Thus, the variable that we’re declaring can hold an integer. Next is the name of the variable. This variable is called mynumber. Then a semicolon ends the variable declaration.
Notice that, in this line, we have covered two of the three aspects of variables; we have given the variable a name, and we have told the computer what type of thing we want the variable to hold. The order seems a little odd; in C++, we first say the type and then the name. That’s just the way it’s done in C++, and a good reason stands behind it, which you can read about in “Declaring multiple variables,” later in this chapter.
The next line looks like this:
mynumber = 10;
This puts something in the variable. It puts the number 10 in it. Because we already said that the variable can hold an integer, we’re allowed to put in a 10, because it is an integer. If we had tried to put something other than an integer in it, the compiler would have given us an error. The compiler makes sure that we put into a variable only the type of thing that we said we would. It’s good at keeping us in line. And of course, you noticed that the statement ends with a semicolon. In C++, every statement ends with a semicolon.
To put something in a variable, you type the variable’s name, an equals sign (surrounded by optional spaces), and the value. You then end the line with a semicolon. This line of code is called an assignment. Or you can say that you are setting the variable to the value.
The next line is this:
cout << mynumber << endl;
Minibook I, Chapter 1 describes what this line does. It’s a cout statement, which means that it writes something on the console. As you can probably guess, this code tells the computer to write the value of mynumber on the console. It does not write the string mynumber. Rather, it writes whatever happens to be stored in the storage bin. The previous line of code put a 10 in the storage bin, and so this line will print a 10 on the console. When you run the program, you see this:
10
Think of it like this: When you type the variable’s name, you are accessing the variable. The exception to this is when the variable’s name appears to the left of an equals sign. In that case, you are setting the variable.
You can do two things with a variable:
Set the variable: You can set a variable, which means that you can put something inside the storage bin.
Retrieve the value: You can get back the value that is inside the variable. When you do so, the value stays inside it; you are not, so to speak, taking it out.
When you retrieve the value that is in a variable, you are not removing it from the variable. The value is still inside the variable.
Declaring multiple variables
Many years ago, when we first learned the original C programming language (which was the language that served as the predecessor to C++), we thought it odd that we had to first say the type of the variable and then the name. But this actually works out well, because it makes declaring multiple variables of the same type easy. If we want to declare three integer variables in a row, we can do it all in one shot, like this:
int tom, dick, harry;
This statement declares three separate variables. The first is called tom; the second is called dick; and the third is called harry. Each of these three variables holds an integer. We have not put anything in any of them, so we may follow that with some code to stuff each of them full with a number. For example, this code puts the number 10 in tom, the number 20 in dick, and the number 3254 in harry.
tom = 10;
dick = 20;
harry = 3254;
When you run your programs, the computer executes the statements in the order that they appear in your code. Therefore, in the preceding code, the computer first creates the three storage bins. Then it puts a 10 inside tom. (Now doesn’t that sound yummy.) Next, dick will get a 20. And finally, harry will consume a 3254.
Changing values
Although a variable can only hold one thing at a time, you can still change what the variable holds. After you put something else in a variable, it forgets what it originally had. So when people accuse us of being forgetful, we can just say, “Yes, but you should see that computer we work with all day long!”
You put something new in the variable in the same way you originally put something in it.
Look closely at Listing 2-2. Notice that the first part of the program is just like Listing 2-1. But then we added two more lines (shown in bold) that look pretty much like the previous two: The first one sticks something (20) in the same variable as before, and the next one writes it out to the console.
Listing 2-2: Changing a Variable
#include <iostream>
using namespace std;
int main()
{
int mynumber;
mynumber = 10;
cout << mynumber << endl;
mynumber = 20;
cout << mynumber << endl;
return 0;
}
As before, the line where we put something new in the variable follows the same format: There’s an equals sign, with the variable on the left and the new value on the right. As described earlier in this chapter, this statement is an assignment statement.
When you see a single equals sign by itself, the item on the left side is the variable or item that receives the information that is on the right side.
Setting one variable equal to another
Because you can do only two direct things with variables — put something in and retrieve the value — setting one variable equal to another is a simple process of retrieving the value of one variable and putting it in the other. This process is often referred to as copying the variable from one to another.
For example, if you have two integer variables, say start and finish, and you want to copy the value of start into finish, you would use a line of code like the following.
finish = start;
Although we said copy the value of start into finish, notice that the first thing we typed was finish, and then the equals sign, and then start. Don’t let the language confuse you. The left side of the equals sign is what receives the value; it is an assignment statement.
When you copy the value of one variable to another the two variables must be the same type. You cannot, for instance, copy the value from a string variable into an integer variable. If you try, the compiler issues an error message and stops.
After the computer runs this copy statement, the two variables hold the same thing. Listing 2-3 is an example of copying one variable to another.
Listing 2-3: Copying a Value from One Variable to Another
#include <iostream>
using namespace std;
int main()
{
int start = 50;
int finish;
finish = start;
cout << finish << endl;
return 0;
}
Initializing a variable
When you create a variable, it starts out as an empty storage bin. Before it can be of much use, you need to put something in it.
If you try to retrieve the contents of a variable before you actually put anything in it, you end up with what computer people fondly call unpredictable results. What they really mean to say is, don’t do this because who knows what’s in it. It’s kind of like if you go in the attic and you discover the former owners left a big, ominous box. Do you really want to look inside it? With variables, the problem you run into is that the computer memory has something stored in that particular place where the variable now sits, and that stored item is probably just some number left over from something else. But you can’t know in advance what it is. So always make sure that you place a value inside a variable before you try to retrieve its contents, a process called initializing the variable.
You can initialize a variable in two ways. The first way is by declaring the variable and then assigning something into it, which takes two lines of code:
int mynumber;
mynumber = 153;
MyThis and MyThat
As you progress through your computer programming life (which is, we hope, in addition to your life as a millionaire), you are likely to notice that, for some reason, some computer programmers seem to favor variable names that start with the word My. Other computer programmers despise this practice and completely distance themselves from it. We have seen such computer identifiers as MyClass, MyNumber, MyHeight, MyName, MyCar, MyWhatASurprise, MyLar, MyStro, and MyOpic. Personally, we have no problem using names that start with My, especially in training exercises.
But the other way is a bit quicker. It looks like this:
int mynumber = 153;
This method combines both worlds into one neat little package that is available for you to use whenever you want. You see us initializing variables both ways in this book, depending on how we feel at the moment.
Creating a great name for yourself
Every variable needs to have a name. But what names can you use? Although you are free to use names such as Fred or Zanzibar or Supercount1000M, there are limits to what you are allowed to use.
Although most C++ code is in lowercase, you are free to use uppercase letters in your variable names. However, C++ distinguishes between the two. Therefore, if you have a variable called count, you cannot access it later in your program by calling it Count with a capital C. The compiler treats the two names as two different variables, which makes C++ case sensitive. But on the other hand, please don’t use two separate variables in the same program, one called count and one called Count. Although the compiler doesn’t mind, the mere humans that may have to read your code or work on it later might get confused.
Here are the rules you need to follow when creating a variable name:
Characters: You can use any uppercase letter, lowercase letter, number, or underscore in your variable names. Other symbols (such as spaces or the ones above the number keys on your keyboard) are not allowed in variable names. The only catches are that
• The first character cannot be a number.
• The variable name cannot consist of only numbers.
Length: Most compilers these days allow you to have as many characters in the variable name as you want. Just to be sure, and to prove we’re easily amused, in CodeBlocks we successfully created a variable with a name that was over 1000 characters in length. However, we wouldn’t want to have to type that thing over and over. Instead, we recommend keeping your variable names long enough to make sense but short enough that you can type them easily. Most people prefer anywhere from five to ten characters or so.
Examples of acceptable variable names include Count, current_name, address_1000, and LookupAmount. Table 2-2 lists some variable names that are not allowed.

Table 2-2 Examples of Bad Variable Names
  

Bad Variable Name

  

Why It’s Not Allowed

  

12345

  

It has only numbers (plus it starts with a number, which is wrong as well).

  

A&B

  

The only special character allowed is the underscore, _. The & (ampersand) is not allowed.

  

1abc

  

A variable name cannot start with a number.

Manipulating Integer Variables

Just like your friends, integer variables can be manipulated. But in this case, manipulation means simply that you can do arithmetic. You can easily do the usual addition, subtraction, multiplication, and division.
In Minibook I, Chapter 1, we introduced the characters that you use for the arithmetic operations. They are
♦ + for addition
♦ - for subtraction
♦ * for multiplication
♦ / for division
You can, however, perform another operation with integers, and it has to do with remainders and division. The idea is that if you divide, for example, 16 by 3, the answer in whole numbers is 5 remainder 1. Another way of saying this is that 16 doesn’t divide by 3 evenly, but 3 goes into 16 five times, leaving a remainder of 1. This remainder is sometimes called a modulus. Computer people actually have an important reason for calling it modulus rather than remainder, and that’s because people in the computer field like to use confusing terms.
When working with integer variables, remember the two basic things that you can do with variables: You can put something in a variable, and you can retrieve it from a variable. Therefore, when working with an integer variable, the idea is that you can retrieve the contents, do some arithmetic on it, and then print the answer or store it back into the same variable or another variable.
Adding integer variables
If you want to add two integer variables, use the + symbol. You can take the result and either print it or put it back into a variable.
The following example adds two variables (start and time) and then prints the answer to the console. The addition operation is shown in bold.
#include <iostream>
using namespace std;
int main()
{
int start;
int time;
start = 37;
time = 22;
cout << start + time << endl;
return 0;
}
This code starts with two integer variables called start and time. It then sets start to 37, and time to 22. Finally, it adds the two variables (to get 59) and prints the results.
In this example, however, the computer doesn’t actually do anything with the final sum, 59, except print it. If you want to use this value later, you can save it in its own variable. The following code demonstrates this; the storage operation is shown in bold:
#include <iostream>
using namespace std;
int main()
{
int start;
int time;
int total;
start = 37;
time = 22;
total = start + time;
cout << total << endl;
return 0;
}
In this code, we declared the integer variable total along with the others. Then, after we stored 37 in start and 22 in time, we added the two and saved the total in the variable called total. Then we finally printed the value stored in total.
You can also add numbers themselves to variables. The following line adds 5 to start and prints the result.
cout << start + 5 << endl;
Or, you can save the value back in another variable, as in the following fragment:
total = start + 5;
cout << total << endl;
This adds 5 to start and saves the new value in total.
When you use such code as total = start + 5;, although you are adding 5 to start, you are not actually changing the value stored in start. The start variable itself remains the same as it was before this statement runs. Rather, the computer figures out the result of start + 5 and saves that value inside total. Thus, total is the only variable that changes here.
Now here’s where things get a little tricky in the logical arena. This might seem a strange at first, but you can actually do something like this:
total = total + 5;
If you have taken some math courses, you might find this statement a little bizarre, just like the math courses themselves. But remember, total is a variable in computer programming, and that definition is a bit different from in the math world.
This statement really just means we’re going to add 5 to the value stored in total, and we’ll take the value we get back and store it back in total. In other words, total will now be 5 greater than it was to begin with.
The following code shows this in action:
#include <iostream>
using namespace std;
int main()
{
int total;
total = 12;
cout << total << endl;
total = total + 5;
cout << total << endl;
return 0;
}
When you run this program, you see the following output on the console:
12
17
Notice what took place. First, we put the value 12 inside total and printed the value to the console. Then we added 5 to total, stored that back in total, and printed the new value of total to the console.
Now it’s no big secret that we computer people are lazy. After all, why would we own computers if we weren’t? And so the great makers of the C++ language gave us a bit of a shortcut for adding a value to a variable and storing it back in the variable. The line
total = total + 5;
is the same as
total += 5;
We computer folks also have a special way of pronouncing +=. We say plus equal. So for this line, we would say, total plus equal five.
Think of the total += 5 notation as simply a shortcut for total = total + 5;.
You can also use the += notation with other variables. For example, if you want to add the value in time to the value in total and store it back in total, you can either do this
total = total + time;
or you can use this shortcut:
total += time;
If you are adding just 1 to a variable, you can use an even shorter shortcut. It looks like this:
total++;
This is the same as total = total + 1;.
Table 2-3 summarizes the different things that you can do that involve the addition of variables.

Table 2-3 Doing Things with Addition
  

What You Can Do

  

Sample Statement

  

Add two variables

  

cout << start + time << endl;

  

Add a variable and a number

  

cout << start + 5 << endl;

  

Add two variables and save the result in a variable

  

total = start + time;

  

Add a variable and a number and save the result in a variable

  

total = start + 5;

  

Add a number to what’s already in a variable

  

total = total + 5;

  

Add a number to what’s already in a variable by using a shortcut

  

total += 5;

  

Add a variable to what’s already in a variable

  

total = total + time;

  

Add a variable to what’s already in a variable by using a shortcut

  

total += time;

  

Add 1 to a variable

  

total++;

Subtracting integer variables
Everything you can do involving addition of integer variables you can also do with subtraction. For example, you can subtract two variables, as shown in Listing 2-4.
And now the answer to The Great Question
In C++, as well as in the original C language upon which C++ is based, the operator ++ adds 1 to a variable. So this finally brings us to a point where we can answer The Great Question: Where did the name C++ come from? When the guy who originally designed C++, Bjarne Stroustrup, needed a name for his language, he decided to look into its roots for the answer. He had based the language on C; and in C, to add 1 to something, you use the ++ operator. And because he felt that he added only 1 thing to the language, he decided to call the new language C++. Okay, that’s not quite true; he actually added a great deal to the language. But that entire great deal can be thought of as just one thing made of lots of smaller things. What did he add? The main thing of those smaller things is the capability to do object-oriented programming. That’s something we cover in the next chapter. And by the way, the originator of C++, Mr. Stroustrup, is still alive and still doing work for the language at AT&T. You can see his Web page at www.research.att.com/~bs/.
Listing 2-4: Subtracting Two Variables
#include <iostream>
using namespace std;
int main()
{
int final;
int time;
final = 28;
time = 18;
cout << final - time << endl;
return 0;
}
When this program runs, the console shows the number 10, which is 28 – 18. Remember that, as with addition, the value of neither final nor time actually changed. The computer just figured out the difference and printed the answer on the console without modifying either variable.
You can also subtract a number from a variable, and (as before) you still aren’t actually changing the value of the variable, as in the following example:
cout << final - 5 << endl;
You can subtract one variable from another and save the result in a third variable:
start = final - time;
And you can change the value in a variable by using subtraction, as in the following four sample lines of code. This first subtracts time from start and saves it back in start:
final = final - time;
Or you can do the same thing by using the shortcut notation:
final -= time;
Or you can do the same thing with a number:
final = final - 12;
And (as before) you can alternatively do the same thing with a shortcut:
final -= 12;
Finally, as with addition, you have a shortcut to a shortcut. If you want to just subtract one, you can simply use two minus signs, as in
final--;
This is pronounced, minus minus.
Multiplying integer variables
To do multiplication in C++, you use the asterisk (*) symbol. Like addition and subtraction, you can multiply two variables, or you can multiply a variable by a number. You can take the result and either print it or save it in a variable.
For example, you can multiply two variables and print the results to the console with the following:
cout << length * width << endl;
Or you can multiply a variable by a number as in this:
cout << length * 5 << endl;
And as with addition and subtraction, you can multiply two variables and save the result in a third variable:
area = length * width;
And you can use multiplication to modify a variable’s value, as in the following:
total = total * multiplier;
or to use the shortcut
total *= multiplier;
And (as before) you can do the same with just a number
total = total * 25;
or
total *= 25;
Dividing integer variables
Although addition, subtraction, and multiplication are pretty straightforward with integer variables, division is a bit trickier. The chief reason is that, with whole numbers, sometimes you just can’t divide evenly. It’s like trying to divide 21 tortilla chips evenly between 5 people. You just can’t do it. Either somebody will feel cheated, or everyone will get 4, and 1 chip will be left over for everyone to fight over. Of course, you could break every chip into 5 pieces, and then each person gets 1/5 of each chip, but then you’re no longer working with whole numbers — just a bunch of crumbs.
If we use a calculator and type 21 divided by 5, we get 4.2, which is not a whole number. If we want to stick to whole numbers, we have to use the notion of a remainder. In the case of 21 divided by 5, the remainder is 1, as we figured out with the tortilla chips. The reason is that the highest multiple of 5 in 21 is 20 (since 5 times 4 is 20), and 1 is left over. That lonely 1 is the remainder.
So in terms of strictly whole numbers, the answer to 21 divided by 5 is 4 remainder 1. And that’s how the computer does arithmetic with integers: It gets two different answers: The quotient and the remainder. In math terms, the main answer (in our example, 4) is called the quotient. And what’s left over is the remainder.
Because two different answers to a division problem may occur, C++ uses two different operators for figuring these two different answers.
To find the quotient, use the slash (/). Think of this as the usual division operator, because when you deal with numbers that divide evenly, this operator gives you the correct answer. Thus, 10 / 2 gives you 5 as you would expect. Further, most people just call this the division operator, anyway.
To find the remainder, use the percent sign (%). This is often called the modulus operator.
The sample program in Listing 2-5 takes two numbers and prints their quotient and remainder. Then it does it again for another pair of numbers. The first pair has no remainder, but the second pair does.
Listing 2-5: Finding Quotients and Remainders
#include <iostream>
using namespace std;
int main()
{
int first, second;
cout << “Dividing 28 by 14.” << endl;
first = 28;
second = 14;
cout << “Quotient “ << first / second << endl;
cout << “Remainder “ << first % second << endl;
cout << “Dividing 32 by 6.” << endl;
first = 32;
second = 6;
cout << “Quotient “ << first / second << endl;
cout << “Remainder “ << first % second << endl;
return 0;
}
When you run this program, you see the following output:
Dividing 28 by 14.
2
0
Dividing 32 by 6.
5
2
Notice, in Listing 2-5, that we used a couple new tricks in addition to (or divided by?) the division tricks. For one, we combined our variable declarations of first and second variables into one statement. A comma separates the variable names, and we wrote the type (int) only once. Next, we combined the output of strings and numbers into a single cout statement. We did this for four of the cout statements. That’s acceptable, as long as you string them together with the << signs between each of them.
You can do all the usual goodies with both the division (/) and remainder (%) operators. For example, you can store the quotient in another variable, as you can with the remainder:
myQuotient = first / second;
myRemainder = first % second;
And you have shortcuts available, as well:
int first = 30;
first /= 5;
cout << first << endl;
In this case, first becomes 6, because 30 / 5 is 6.
int first = 33;
first %= 5;
cout << first << endl;
And in this case, first becomes 3, because the remainder of 33 divided by 6 is 3.

Characters

Another type of variable you can have is a character variable. A character variable can hold a single — just one — character. A character is anything that can be typed, such as the letters of the alphabet, the digits, and the other symbols you see on the computer keyboard.
To use a character variable, you use the type name char. To initialize a character variable, you put your character inside single quotes. (If you use double quotes, the compiler issues an error message.) The following is an example of a character:
char ch;
ch = ‘a’;
cout << ch << endl;
The character variable here is called ch. We initialized it to the character a, which, you notice, is surrounded by single quotes. We then printed it by using cout.
Null character
One important character in the programming world is the null character. Deep down inside the computer’s memory, the computer stores each character by using a number, and the null character’s number is 0. There’s nothing to actually see with the null character; we can’t draw a picture of it in this book for you to hang on your wall. (Bummer.) All we can do is describe it. Yes, every once in a while computer people have to become philosophers. But the null character is important because it is often used to signify the end of something. Not the end of the world or anything big like that, but the end of some data.
To notate the null character in C++, use \0, as in
char mychar = ‘\0’;
Nonprintable and other cool characters
In addition to the null character, several other cool characters are available, some that have a look to them and can be printed and some that do not and cannot. The null character is an example of a nonprintable character. You can try to print one, but you will get either a blank space or nothing at all, depending on the compiler.
But some characters are special in that they do something when you print, but you can’t type them directly. One example is the newline character. A newline character symbolizes the start of a new line of text. In all cases, the computer places the insertion point, the place where it adds new characters, on the next line. If you are printing some text to the console and then you print a newline character, any text that follows will be on the next line. Most compilers these days start the text at the far left of the next line (column 1), but some compilers start the text in the next column on the next line, as in the following output. In this case, the text appears on the next line, but it starts at column 4, rather than at the far left (column 1).
abc
def
What is that symbol?
Never known to turn down the chance to invent a new word, computer people have come up with names for characters that may not always match the names you know. You’ve already heard the use of the word dot for a period when surfing the Internet. And for some characters that already have multiple names, computer folks may use one name and not the other. And sometimes, just to throw you off, they use the usual name for something. The following are some of the names of symbols that computer people like to use:
. dot (but not period or decimal point)
@ at
& ampersand (but not and)
# pound (but not number sign)
! bang, but most people still say exclamation point
~ tilde
% percent
*star (not asterisk)
( left paren or left parenthesis
) right paren or right parenthesis
[ left square bracket or left bracket
] right square bracket or right bracket
== equal-equal (not double equal)
++ plus-plus (not double plus)
– – minus-minus (not double minus)
/ forward slash
\ backslash
{ left brace or left curly brace or open brace
} right brace or right curly brace or close brace
^ caret, but a few people say hat (for real — no joke here!)
“ double quote
Here, we printed abc, then a newline, and then def. Notice that the def continued in the same position it would have been had it been on the first line. For the compilers that we use in this book, however, printing abc, then a newline, and finally def results in this output:
abc
def
But to accommodate the fact that some other compilers sometimes treat a newline as just that (start a new line but don’t go anywhere else), the creators of the computers gave us another special character: the carriage return. (Can you hear the crowd say, “ooooh!”?)
The carriage return places the insertion point at the start of the line, but not on a new line. (Which means that if you use just a carriage return on a computer expecting both a carriage return and a newline, you’ll overwrite what’s already on the line.) That’s true with pretty much every C++ compiler.
In Minibook I, Chapter 1, we describe the tab character and other characters that start with a backslash. These are individual characters, and you can have them inside a character variable, as in the following, which prints the letter a, then a tab, and then the letter b. Notice that, to get the tab character to go into the character variable, we had to use the \ then a t.
char ch = ‘\t’;
cout << “a” << ch << “b” << endl;
In Minibook II, Chapter 1, we mention that to put a double quote inside a string, you needed to precede the double quote with a backslash so the computer won’t think that the double quote is the end of the string. But because a character is surrounded by single quotes, you don’t need to do this: You can just put a double quote inside the character, as in the following.
char ch = ‘“‘;
Of course, now that raises an important question: What about single quotes? This time you do have to use the backslash:
char ch = ‘\’’;
And finally, to put a backslash inside a character, you use two backslashes:
char ch = ‘\\’;
When the compiler sees a backslash inside a string or a character, it treats the backslash as special and looks at whatever follows it. If you have something like ‘\’ with no other character inside the single quotes following it, the compiler thinks the final quote is to be combined with the backslash. And then it moves forward, expecting a single quote to follow, representing the end. Because a single quote doesn’t appear, the compiler gets confused and issues an error. Compilers are easily confused. Kind of gives you more respect for the human brain.

Strings

If any single computer word has become so common in programming that most computer people forget that it’s a computer word, it would be string. Minibook I, Chapter 1 introduces strings and what they are, and it gives examples of them. In short, a string is simply a set of characters strung together. The compiler knows the start and end of a string in your code based on the location of the double quotes.
You can create a variable that can hold a string. The type you use is string. The example program in Listing 2-6 shows you how to use a string variable.
Delimiters limit de tokens
When you read an English sentence, you can tell where one word starts and one word ends by looking at the spaces and the punctuation. The same is true in a computer program. Words are normally separated by spaces, but other characters also denote the beginning and end of a word. With a string, this character is the double quote. Such word dividers are called delimiters (pronounced dee-LIM-it-ers). And just to make sure we stay confused, computer people use the word token to mean the individual words in a program that are set apart by delimiters. However, you won’t hear us use that term again in this book, as we prefer the word word.
Listing 2-6: Using the string Type to Create a String Variable
#include <iostream>
using namespace std;
int main()
{
string mystring;
mystring = “Hello there”;
cout << mystring << endl;
return 0;
}
When you run this program, the string Hello there appears on the console. The first line inside main creates a string variable called mystring. The second line initializes it to “Hello there”. The third line prints the string to the console.
Getting a part of a string
Accessing the individual characters within a string is easy. Take a look at Listing 2-7.
Listing 2-7: Using Brackets to Access Individual Characters in a String
#include <iostream>
using namespace std;
int main()
{
string mystring;
mystring = “abcdef”;
cout << mystring[2] << endl;
return 0;
}
Those strange # lines
Now for those strange-looking lines that start with a # symbol. In Minibook I, Chapter 5, we talk about how you can divide your code into multiple pieces, each in its own source file. That is a powerful way to create large software programs, because different people can work on the different parts at the same time. But to do so, somehow each file must know what the other files can do. And the way you tell the files about the other files is by putting a line toward the top of your file that looks like this:
#include <string>
This line means that your program is making use of another file somewhere, and that file has a filename of string. Inside that other file is a bunch of C++ code that essentially gives your program the ability to understand strings. To see this file in CodeBlocks, right-click the filename and choose Open Include File: <filename> from the context menu. The line
#include <iostream>
gives your program the ability to write to the console, among other things. And finally, the line
#include <stdlib.h>
provides some general C++ features that you aren’t yet using. As you progress through C++, you discover more lines that you can include at the top of your program, each starting with #include and each giving your program more features and capabilities. We use many of these throughout this book. Now how is that for a teaser?
Notice that the seventh line, the cout line, has the word mystring followed by a 2 inside brackets. When you run this program, here’s what you see:
c
That’s it, just a letter c, hanging out all by itself. The 2 inside brackets means that you want to take the second character of the string and only that character. But wait! Is c the second character? Our eyes may deceive us, but it looks to us like that’s the third character. What gives?
Turns out, C++ starts numbering the positions inside the string at 0. So for this string, mystring[0] is the first character, which happens to be a. And so really mystring[2] gets the third character. Yes, life gets confusing when trying to hold conversations with programmers, because sometimes they use the phrase the third character to really mean the third position; but sometimes they use it to mean what’s really the fourth position. But to those people, the fourth position is actually the fifth position, which is actually the sixth position. Life among computer programmers can be confusing. In general, in this book, we use fourth position to really mean the fourth position, which you access through mystring[3]. (The number inside brackets is called an index.)
A string is made of characters. Thus, a single character within a string has the type char. This means that you can do something like this:
string mystring;
mystring = “abcdef”;
char mychar = mystring[2];
cout << mychar << endl;
In the preceding example, mychar is a variable of type char. The mystring[2] expression returns an item of type char. Thus, the assignment is valid. When you run this, you once again see the single character in the third position:
c
Changing part of a string
Using the bracket notation, you can also change a character inside a string. The following code, for example, changes the second character in the string (that is, the one with index 1) from a c to a q:
string x = “abcdef”;
x[1] = ‘q’;
cout << x << endl;
This code writes the string aqcdef to the console.
Adding onto a string
Any good writer can keep adding more and more letters to a page. And the same is true with the string type: You can easily add to it. The following lines of code use the += operator, which was also used in adding numbers. What do you think this code will do?
string mystring;
mystring = “Hi “;
mystring += “there”;
cout << mystring << endl;
The first line declares the string mystring. The second line initializes it to “Hi ”. But what does the third line do? The third line uses the += operator, which appends something to the string, in this case “there”. Thus, after this line runs, the string called mystring contains the string “Hi there”, and that’s what appears on the console when the cout line runs. The fancy programmer term for adding something to a string is concatenation.
You can also do something similar with characters. The following code snippet takes a string and adds a single character onto it:
string mystring;
mystring = “abcdef”;
mystring += ‘g’;
cout << mystring << endl;
This code creates a string with “abcdef”, and then adds a ‘g’ character on to the end to get “abcdefg”. Then it writes the full “abcdefg” to the console.
Adding two strings
You can take two strings and add them together by using a + sign just as you can do with integers. The final result is a string that is simply the two strings pushed together side by side. For example, the following code adds first to second to get a string called third.
string first = “hello “;
string second = “there”;
string third = first + second;
cout << third << endl;
This code prints the value of third, which is simply the two strings pushed together, in other words, “hello there”. (Notice the string called first has a space at its end, which is inside quotes and, therefore, part of the string.)
You can also add a string constant (that is, an actual string in your program surrounded by quotes) to an existing string variable, as in the following.
string first = “hello “;
string third = first + “there”;
cout << third << endl;
You may be tempted to try to add two string constants together, like so:
string bigstring = “hello “ + “there”;
cout << bigstring << endl;
Unfortunately, this won’t work. The reason is that (deep down inside its heart) the compiler just wants to believe that a string constant and a string are fundamentally different. But really, you don’t have a good reason to do this, because you could accomplish the same thing with this code:
string bigstring = “hello there”;
cout << bigstring << endl;
You can do a lot more with strings. But first, you need to understand something called a function. If you’re curious about functions, read Minibook I, Chapter 4, where we cover all the nitty-gritty details.

Deciding between Conditional Operators

One of the most important features of computers, besides allowing you to surf the Web and allowing telemarketers to dial your telephone automatically while you’re eating, is the capability to make comparisons. Although this topic may not seem like a big deal, computer technology did not start to take off until the engineers realized that computers could become much more powerful if they could test a situation and do one task or another task, depending on the situation.
You can use many ways to write a C++ program that can make decisions; see Minibook I, Chapter 3, for a discussion about this topic. But one way that is quite handy is through the use of the conditional operator.
Think about this process: If two integer variables are equal, set a string variable to the string “equal”. Otherwise, set it to the string “not equal”.
In other words, suppose we have two integer variables, called first and second. first has the value 10 in it, and second has the value 20 in it. We also have a string variable called result. Now, to follow the little process that we just described: Are the two variables equal? No, they are not, so we set result to the string “not equal”.
Now we do this in C++. Look carefully at the following code. First, we are going to declare our variables first, second, and result:
int first = 10;
int second = 20;
string result;
So far, so good. Notice that we didn’t yet initialize the string variable result. But now, we’re going to write a single line of code that performs the process we just described. First, look the following over, and see whether you can figure out what it is doing. Look carefully at the variables and what they may do, based on the process we described earlier. Then we explain what the code does.
result = (first == second) ? “equal” : “not equal”;
This is probably one of the more bizarre looking lines of C++ code you’ll see in this book. First, we’ll tell you what it means. Then we’ll break it into parts to show you why it means what it does.
In English, this means result will get “equal” if first is equal to second; otherwise it will get “not equal”.
So now, break it into two parts. A single equals sign indicates that the left side, result, receives what is on the right side. So we need to figure out that crazy business on the right side:
(first == second) ? “equal” : “not equal”
When you see this strange setup, consider the question mark to be the divider. The stuff on the left of the question mark is usually put in parentheses, as shown in the following:
(first == second)
This actually compares first to second and determines whether they are equal. Yes, the code shows two equals signs. In C++, that’s how you test whether two things are equal.
Now the part on the right of the question mark:
“equal” : “not equal”
This is, itself, two pieces divided by a colon. This means that if first is indeed equal to second, result gets the string “equal”. Otherwise, it gets the string “not equal”.
So take a look at the whole thing one more time:
result = (first == second) ? “equal” : “not equal”;
And once again, consider what it means: If first is equal to second, result gets “equal”; otherwise, it gets “not equal”.
Remember that the storage bin on the left side of the single equals sign receives what is on the right side. The right side is an expression, which comes out to be a string of either “equal” or “not equal”.
Now here’s the whole program in Listing 2-8.
Listing 2-8: Using the Conditional Operator to Do Comparisons
#include <iostream>
using namespace std;
int main()
{
int first = 10;
int second = 20;
string result;
result = first == second ? “equal” : “not equal”;
cout << result << endl;
return 0;
}
Boolean variables and conditional operators
You can use Boolean variables with conditional operators. In a conditional operator such as
result = (first == second) ? “equal” : “not equal”;
the item (first == second) actually works out to be a Boolean value, either true or false. Therefore, you can break this code up into several lines. We know: Breaking something into several lines seems a little backwards. The reason for breaking code into lines is that sometimes, when you are programming, you may have an expression that is extremely complex, much more complex than first == second. As you grow in your C++ programming ability, you start to build more complex expressions, and then you start to realize just how complex they can become. And often, breaking expressions into multiple smaller pieces is more manageable.
To break this example into multiple lines, you can do the following:
bool isequal;
isequal = (first == second);
result = isequal ? “equal” : “not equal”;
The first line declares a Boolean variable called isequal. The second line sets this to the value first == second. In other words, if first is equal to second, then isequal gets the value true. Otherwise, isequal gets the value false. In the third line, result gets the value “equal” if isequal is true; or result gets the value “not equal” if isequal is false.
The reason that this code works is that the item on the left side of the question mark is a Boolean expression, which is just a fancy way of saying that the code requires a Boolean value. Therefore, you can throw in a Boolean variable if you prefer, because a Boolean variable holds a Boolean value.

Telling the Truth with Boolean Variables

In addition to integers and strings, another type in C++ can be pretty useful. This type is called a Boolean variable. Whereas an integer variable is a storage bin that can hold any integer value, a Boolean variable can hold only one of two different values, a true or a false. Boolean values take their name from George Boole, the father of Boolean logic (you can read about him at http://en.wikipedia.org/wiki/George_Boole).
The type name for a Boolean variable is bool. Therefore, to declare a Boolean variable, you use a statement like this:
bool finished;
This declares a Boolean variable called finished. Then, you can either put a true or a false in this variable, as in the following:
finished = true;
or
finished = false;
When you print the value of a Boolean variable by using code like the following
cout << finished << endl;
you see either a 1 for true or a 0 for false. The reason is that, deep down inside, the computer stores a 1 to represent true and a 0 to represent false.

Reading from the Console

Throughout this chapter and the preceding chapter, we have given many examples of how to write information to the console. But just writing information is sort of like holding a conversation where one person does all the talking and no listening. Getting some feedback from the users of your programs would be nice. Fortunately, getting feedback is easy in C++.
Writing to the console involves the use of cout in a form like this:
cout << “hi there” << endl;
Reading from the console (that is, getting a response from the user of your program) uses the cin (pronounced see-in, as in, “When I see out the door, I’m a-seein’ the mountain from here”) object. Next, instead of using the goofy looking << operator, you use the equally but backwardly goofy > operator.
The << operator is often called an insertion operator because you are writing to (or inserting into) a stream, which is nothing more than a bunch of characters going out somewhere. In the case of cout, those characters are going out to the console. The >> operator, on the other hand, is often called the extraction operator. The idea here is that you are extracting stuff from the stream. In the case of cin, you are pulling letters from the stream that the user is, in a sense, sending into your program through the console.
Listing 2-9 shows how you can read a string from the console.
Listing 2-9: Using the Conditional Operator to Make Comparisons
#include <iostream>
using namespace std;
int main()
{
string name;
cout << “Type your name: “;
cin >> name;
cout << “Your name is “ << name << endl;
return 0;
}
When you run this code, you see the console ask you to type your name, then it stops. That’s because it’s waiting for your input. Notice that the insertion point appears immediately after “Type your name:”. That’s because the first cout statement lacks the usual endl. It’s normal to leave the insertion point, the cursor, on the same line as the question to avoid confusing the user. Type a name, such as Fred, without spaces and press Enter. The console then looks like this:
Type your name: Fred
Your name is Fred
The first line is the line you typed (or whatever name you chose to go by), and the second line is what appears after you press Enter.
Notice what happened: When you typed a word and pressed Enter, the computer placed that word in the name variable, which is a string. Then you were able to print it to the console by using cout.
You can also read integers, as in the following code:
int x;
cin >> x;
cout << “Your favorite number is “ << x << endl;
This sample code reads a single integer into the variable x and then prints it to the console.
By default, cin reads in characters from the console based on spaces. If you put spaces in your entry, only the first word gets read. cin reads the second word the next time the program encounters a cin >>.

Chapter 3: Directing Your C++ Program Flow

In This Chapter
Comparing numbers and evaluating other conditions
Doing things based on a comparison
Repeating code a certain number of times
Repeating code while certain things are true
Repeating code that repeats code that . . . well, you get the idea
As you program in C++, many times you need to present the computer with a choice, allowing it to do one thing for one situation and something else in another situation. For example, you may have a program that asks for a user’s password. If the password is correct, the program continues; but if the password is incorrect, the program asks the user to reenter the password. After some number of times, usually three, the program performs yet another task when the user enters the incorrect password. Such situations are called conditions. In the case of the password, the condition is whether the password matches.
You may also encounter situations where you want several lines of code to run over and over. These are called loops, and you can specify conditions under which the loop runs. For example, you may want to check the password only three times; and if the user fails to enter it correctly on the third time you may bar access to the system. This would be a loop, and the loop would run under the condition that a counter has not exceeded the value of 3.
In this chapter, we take you through different ways to evaluate conditions within your programs and cause different sections of code to run based on those conditions. We talk about how you can use C++ commands called if statements, which are very similar to what-if situations in real life. And we show you how to use other C++ statements (such as do-while) to performs loops (repeating the same program sections a number of times).
To make the explanations clear, this chapter gives you real-world examples that you can feel free to incorporate into your life. The examples usually refer to groups of friends and how you can get money from them. So, you see, the benefits of this chapter are twofold: you find out how to program by using conditions and loops, and you find out how to make money off your unsuspecting friends.

Doing This or Doing That

As you go through life, you’re always faced with decisions. For example, when you bought this book, you faced the following decision: Should I buy this really great For Dummies book where I’m sure to find out just what I need to know, or should I buy some other book?
When you are faced with a decision, you usually have options that offer different results — say plan A and plan B. Making a decision really means making a choice that results in the execution of either plan A or plan B. For example, if you approach a stoplight that just turned yellow, you must either slam on the brakes or nail the accelerator. If you slam on the brakes, the car will stop just in time (you hope). If you nail the accelerator, the car will speed up, and you’ll go sailing through the intersection just before the stoplight turns red (right?). The choice is this: Should I press the brake or the accelerator? And the plan looks like this:
If I press the brake, I will stop just in time.
If I press the accelerator, I will speed through the intersection.
Computers are faced with making decisions too, although their decisions are usually a little less exciting and, we hope, don’t yield the possibility of police interaction. And computer decisions are usually simpler in nature. That is, a computer’s decisions usually focus around such issues as comparing numbers and strings of characters. For example, you may be writing a computer program for a bank where the user of your program (that is, the bank customer) has a choice of plan A: Making a Deposit or plan B: Receiving a Cash Withdrawal. If the user chooses to make a deposit your program adds to the balance the amount of the deposit. If the user chooses to make a withdrawal, your program instead subtracts the withdrawal amount from the balance.
In C++, decisions usually take the form of an if statement, which is code that starts with the if keyword followed by a condition, which is often a numerical condition wherein two numbers are compared, and then two blocks of code appear: one that runs if the condition is satisfied and one that runs if it is not.

Evaluating Conditions in C++

Most decisions that the computer makes are based on conditions evaluated by comparing either two numbers or two characters. For numerical comparisons, you may compare a variable to a number, as in the following statement:
x > 10
This comparison evaluates whether the variable x is greater than the number 10. If x is indeed greater than 10, the computer sees this condition as true. If x is not greater than 10, the computer sees the condition as not true.
We often use the word satisfied with conditions. For the condition x > 10, if x really is greater than 10, we say that the condition is satisfied. It’s kind of like, “We’re satisfied if our IRS tax refund is five figures.” For this, if the condition is x > 9999, and if we really did get that much money back from Uncle Sam, the condition is satisfied (and so are we).
For character comparisons, you may compare if two characters are equal or not, as in the following statement:
mychar == ‘A’
This comparison evaluates whether mychar contains the letter A. Notice that you use two equals signs, not just one. Using just one equals sign would assign the value A to mychar.
To test whether the character is not equal to something, you use the somewhat cryptic-looking != operator. Think of the ! as meaning not, as in:
mychar != ‘X’
Finding the right C++ operators
Each statement in the previous section uses an operator to specify what comparison to make between the numbers or the strings. Table 3-1 shows you the types of operators available in C++ and the comparisons that they help you make in your programs.

  
Table 3-1 Evaluating Numerical Conditions
  

Operator

  

What It Means

  

<

  

Less than

  

<=

  

Less than or equal to

  

>

  

Greater than

  

>=

  

Greater than or equal to

  

==

  

Equal to

  

!=

  

Not equal to

Some operators in this table — and how you use them — can be a bit annoying or downright frightening. The following list gives examples:
♦ The operator that tests for equality is two equals signs. It looks like this:
x == 10
When the computer finds this statement, it checks whether x equals 10.
If you put just one equals sign in your statements, most C++ compilers will not give you an error — though a statement like x = 10 is not really a condition! Instead, x = 10 is an assignment, setting the variable x to 10. When code contains such a statement, the result of the evaluation is always the same, regardless of what value x has.
♦ The operator that tests for inequality is an exclamation mark followed by an equals sign. For the condition x != 10, the condition evaluates as true only if x is not equal to 10 (x is equal to something other than 10).
♦ When you’re testing for greater than or less than conditions, the condition x > 10 is not true if x is 10. The condition x > 10 is true only if x is actually greater than, but not equal to, 10. To also test for x being equal to 10, you have two choices:
• If you’re working with integers, you can test whether x > 9. In that case, the condition is true if x is 10, or 11, or 12, and so on.
• You can use the greater-than-or-equal-to operator to x >= 10. This condition also is true if x is 10, 11, and so on.
To test for all numbers greater than or equal to 10, the condition x > 9 works only if you’re working with integers. If you’re working with floating-point numbers (refer to Minibook I, Chapter 2, for information on the types of numbers you can work with in C++), the statement x > 9 won’t work like you want. The number 9.1 is greater than 9, and it’s not greater than or equal to 10. So if you really want greater than or equal to and you’re not working with integers, use the >= operator.
Combining multiple evaluations
When you make evaluations for program decisions, you may have more than one condition to evaluate. For example, you might say, “If I get a million dollars, or if I decide to go into debt up to my eyeballs, then I will buy that Lamborghini.” In this case, you would buy the car under two conditions, and either can be true. Combining conditions like this is called an or situation: If this is true or if that is true, something happens.
To evaluate two conditions together in C++, you write them in the same statement and separate them with the or symbol (||), which looks like two vertical bars. Other programming languages get to use the actual word or, but C++ uses the strange, unpronounceable symbol that we call The Operator Previously Known as Or. The following statement shows it performing live:
(i < 10 || i > 100)
This condition is not of much use. If you use the or operator (||), accidentally ending up with a condition that is always true is easy. For example, the condition (x < 100 || x > 0) is always going to be true. When x is -50, it’s less than 100, so the condition is true. When x is 500, it’s greater than 0, so it’s true.
In addition to an or situation, you can have something like this: “If I get a million dollars and I really feel bold, then I will buy a Lamborghini.” Notice that we’re using the word and: In this case, you will do it only if both situations are true. (Remember that with or, you will do it if either situation is true.) In C++, the and operator is two ampersands, &&. This makes more sense than the or operator, because the & symbol is often associated with the word and. The and comparison in C++ looks like the following:
(i > 10 && i < 100)
This example checks whether a number is both more than 10 and less than 100. That would mean the number is in the range 11 through 99.
Combining conditions by using the && and || operators is a use of logical operators.
To determine if a number is within a certain range, you can use the and operator (&&), as we did earlier in this chapter.
With the and operator, accidentally creating a condition that is never true is easy. For example, the condition (x < 10 && x > 100) will never be true. No single number can be both less than 10 and simultaneously greater than 100.

Including Evaluations in C++ Conditional Statements

Computers, like humans, evaluate conditions and use the results of the evaluations as input for making a decision. For humans, the decision usually involves alternative plans of action, and the same is true for computers. The computer needs to know what to do if a condition is true and what to do if a condition is not true. To decide a plan of action based on a condition that your program evaluates, you use an if statement, which looks like this:
if (x > 10)
{
cout << “Yuppers, it’s greater than 10!” << endl;
}
This translates into English as: If x is greater than 10, write the message “Yuppers, it’s greater than 10!”
In an if statement, the part inside the parentheses is called either the test or the condition. We usually apply condition to this part of the if statement and use the word test as a verb, as in “I will test whether x is greater than 10.”
In C++, the condition for an if statement always goes inside parentheses. If you forget the parentheses, you get a compile error.
You can also have multiple plans of action. The idea is simply that if a condition is true, you will do plan A. Otherwise, you will do plan B. This is called an if-else block, which we discuss in the next section.
Deciding what if and also what else
When you are writing the code for a comparison, usually you want to tell the computer to do something if the condition is true and to do something else if the condition is not true. For example, you may say, “If I’m really hungry I will buy the Biggiesupersizemondohungryperson french fries with my meal for an extra nickel; otherwise, I’ll go with the small.” In the English language, you will often see this kind of logic with the otherwise word: If such-and-such is true, I will do this; otherwise, I will do that.
In C++, you use the else keyword for the otherwise situation. It looks like the following:
#include <iostream>
using namespace std;
int main()
{
int i;
cout << “Type any number: “;
cin >> i;
if (i > 10)
{
cout << “It’s greater than 10.” << endl;
}
else
{
cout << “It’s not greater than 10.” << endl;
}
return 0;
}
In this code, you test whether a number is greater than 10. If it is, you print one message. If it is not, you print a different message. Notice how the two blocks of code are distinct. The first block immediately follows the if statement; it’s the code that runs if the condition is true. The next block is preceded by an else keyword, and it runs if the condition is not true.
Think carefully about your else situation when dealing with numbers. If you are testing whether a number is greater than 10, for instance, and it turns out that the number is not greater than 10, the tendency of most people is to assume it must, therefore, be less than 10. But that’s not true. The number 10 itself is not greater than 10, but it’s not less than 10 either. So the opposite of greater than 10 is simply not greater than 10. If you need to test the full range of numbers using a simple if statement, create an if statement that uses either >= or <= (see Table 3-1 for a listing of operators).
Going further with the else and if
When you are working with comparisons, you often have multiple comparisons going on. For example, you may say, “If I go to Mars, I will look for a cool red rock; otherwise, if I go to the moon, I will jump up really high; otherwise, I will just look around wherever I end up, but I hope there will be air.”
This type of sentence has several ifs in it; and in C++, the sentence looks like the following:
#include <iostream>
using namespace std;
int main()
{
int i;
cout << “Type any number: “;
cin >> i;
if (i > 10)
{
cout << “It’s greater than 10.” << endl;
}
else if (i == 10)
{
cout << “It’s equal to 10” << endl;
}
else
{
cout << “It’s less than 10.” << endl;
}
return 0;
}
Here you can see how we have several different conditions, and only one can be true. The computer first checks to see if i is greater than 10. If i is greater, the computer prints a message saying that i is greater than 10. But if not, the computer checks to see whether i equals 10. If so, the computer prints a message saying that i is equal to 10. Finally, the computer assumes that i must be less than 10, and it prints a message accordingly. Notice, for the final else statement, we didn’t put a condition (and, in fact, you cannot have a condition with else statements). But because the other conditions failed, we know that i must be less than 10 by our careful logic.
Be careful when you are thinking through such if statements. You could have a situation where more than one condition could occur. For example, you may have something like this:
#include <iostream>
using namespace std;
int main()
{
int i;
cout << “Type any number: “;
cin >> i;
if (i > 100)
{
cout << “It’s greater than 100.” << endl;
}
else if (i > 10)
{
cout << “It’s greater than 10” << endl;
}
else
{
cout <<
“It’s neither greater than 100 nor greater than 10.”
<< endl;
}
return 0;
}
Think about what would happen if i is the number 150. The first condition, i > 100, is true. But so is the second condition, i > 10. 150 is greater than 100, and 150 is also greater than 10. So which block will the computer do? Or will it do both blocks?
The computer only does the first condition that is satisfied. Thus, when i is 150, the computer prints the message “It’s greater than 100.” It does not print the other messages. In fact, the computer doesn’t even bother checking the other conditions at that point. It just continues with the program.

Repeating Actions with Statements That Loop

Suppose that you’re writing a program that needs to add all the numbers from 1 to 100. For example, you may want to know how much money you will get if you tell 100 people, “give me one dollar more than the person to your left.” With a mastery of copy and paste, you could do something like this
int x = 1;
x = x + 2;
x = x + 3;
x = x + 4;
and so on until you get to x = x + 100. As you can see, this code could take a long time to type, and you would probably find it a tad frustrating, too, no matter how quickly you can choose the Edit⇒Paste command (or press Ctrl+V). Fortunately, the great founders of the computer world recognized that not every programmer is a virtuoso at the piano with flying fingers and that programs often need to do the same thing over and over. Thus, they gave us a really great tool called a for loop. A for loop does the same piece of code over and over for a certain number of times. And that’s just what you wanted to do in this example.
Looping situations
Several types of loops are available, and next you’ll see how they work. Which type of loop you use depends on the situation. We’ve already mentioned the first type, called a for loop. The idea behind a for loop is to have a counter variable that either increases or decreases, and the loop runs as long as the counter variable satisfies a particular condition. For example, the counter variable might start at 0, and the loop runs as long as the counter is less than 10. The counter variable increments each time the loop runs, and after the counter variable is not less than 10, the loop stops.
But another way to loop is to simplify the logic a bit and say, “I want this loop to run as long as some condition is true.” This is called a while loop, and you simply specify a condition under which the loop continues to run. When the condition is true, the loop keeps running. After the condition is no longer true, the loop stops.
Finally, there’s a slight modification to the while loop called a do-while loop. The do-while loop is used to handle one particular situation that could arise. When you have a while loop, if the condition is not true when everything starts, the computer will skip over the code in the while loop and not even bother executing it. But sometimes you may have a situation where you would want the code to always execute at least once. In that case, you can use a do-while loop.
Table 3-2 shows the types of loops. In the sections that follow, we show you how to use these types of loops.

  
Table 3-2 Choosing Your Loops
  

Type of Loop

  

Appearance

  

for

  

for (x=0; x<10; x++) { }

  

while

  

while (x < 10) { }

  

do-while

  

do { } while (x < 10)

The following list describes the situations under which you may want these loops.
♦ for loop: Use the for loop when you have a counter variable and you want to loop while the counter variable increases or decreases over a range.
♦ while loop: Use the while loop when you have a condition under which you want your code to run.
♦ do-while loop: Use the do-while loop when you have a condition under which you want your code to run, and you want to ensure that the loop always runs at least once, even if the condition is not satisfied.
Looping for
To use a for loop, you use the for keyword and follow it with a set of parentheses that contains information regarding the number of times the for loop executes.
For example, when adding the numbers from 1 to 100, you would want a variable that starts with the number 1; then you would add 1 to x, increase the variable to 2, and add the next number to x again over and over. The common part here that doesn’t change each time is the “add it to x” part, and the part that changes is the variable, called a counter variable.
The counter variable, therefore, starts at 1 and goes through 100. Does it include 100? Yes. And with each iteration, you would add 1 to the counter variable. Your for statement would look like this:
for (i = 1; i <=100; i++)
This statement means that the counter variable, i, starts at 1, and the loop runs over and over while i is less than or equal to 100. After each iteration, the counter variable increments by 1 due to the i++ statement.
The following list shows the different portions inside the parentheses of the for loop:
♦ The first portion is the initializer. You use it to set up the counter variable.
♦ The second portion is the condition under which the loop continues to run.
♦ The third portion is the finalizer. In it, you specify what happens after each cycle of the loop.
Three items are inside the for loop, and you separate them with semicolons. If you try to use commas, your code will not compile.
Now this code we just showed you doesn’t do anything for each iteration other than add one to i. To tell the computer the work to do with each iteration, follow the for statement with a set of braces containing the statements you want to execute with each iteration. Thus, to add the counter variable to x, you would do this:
for (i = 1; i <=100; i++)
{
x += i;
}
This would add i to x with each loop. Of course, we didn’t start x out with anything in particular, so we should probably include that, too. Here’s the final thing, complete with the way to write the final value of x to the console after the loop is finished:
#include <iostream>
using namespace std;
int main()
{
int x = 0;
int i;
for (i = 1; i <= 100; i++)
{
x += i;
}
cout << x << endl;
return 0;
}
Notice a few things about this block of code. First, we declared both variables that we’re working with, x and i. Second, the for statement initializes the counter variable, specifies the condition under which it continues running, and tells what to do after each iteration. In this example, the for loop starts with i = 1, and it runs as long as i is less than or equal to 100. For each iteration, the computer adds the value of the counter to x; the process that adds the value to x is the code inside the braces. Finally, the computer adds 1 to x, which we specified as the third item inside the parentheses. The computer does this part, adding 1 to x, only after it finishes the stuff inside the braces.
Meddling with the middle condition
The middle portion of the for statement specifies a condition under which to continue doing the stuff inside the for loop. In the case of the preceding example, the condition is i <= 100, which means the stuff inside the braces continues to run as long as i is less than or equal to 100.
If you’re familiar with other computer languages, the middle condition specifies a condition under which to continue the loop, not a condition under which to terminate the loop. Other languages will say do this until such-and-such is true, but that is not the case in C++.
In our example, we want the loop to iterate for the special case where i is 100, which still satisfies the condition i <= 100. If we had instead said i < 100, the loop would not have executed for the case where i is 100. The loop would have stopped short of the final iteration. In other words, the computer would only add the numbers 1 through 99. And if our friends are gathering money for us, we would be cheated out of that final $100. And, by golly, that could make the difference between whether we pay rent this month or not.
The question of when the loop stops can get kind of confusing. If we had gone crazy (but can we really go crazy since we’re crazy to begin with?) and said that we wanted to add the numbers 1 up to but not including 100, we would have wanted a condition such as i < 100. If we had just said up to 100, it would not have been clear exactly which we wanted to do, include the 100 or not. If that had been the case and you were writing the program for us, you would want to ask us for clarification. (Unless we’re the 100th friend, in which case we may get out of paying our dues.)
In the example we’ve been using, the condition i <= 100 and the condition i < 101 have essentially the same meaning. If our condition were i < 101, the program would operate the same. But the only reason that’s true is because we’re working with integers counting up to and including 100. If we were instead adding, for instance, floating-point numbers, and we incremented the counter by 0.1 after each iteration, these two conditions (i <= 100 and i < 101) wouldn’t be the same. With i <=100, we would get up to 99.5, 99.6, 99.7, 99.8, 99.9, and finally 100, after which we would stop. But i < 101 would also include 100.1, 100.2, up to and including 100.9. You can see they are not the same.
Going backwards
If you need to count backwards, you can do that with a for loop as well. For example, you may be counting down the number of days left before you get to quit your job because you learned C++ programming and are moving on to an awesome new job. Or you may be writing a program that can manipulate that cool countdown timer they show when the Space Shuttle launches. Counting up just isn’t always the right action. It would be a bummer if every day were one day longer before you get to quit your job and move to an island. Sometimes counting backwards is best.
To count backwards, you set up the three portions of the for loop. The first is the initial setup, the second is the condition under which it continues to run, and the third is the action after each iteration. For the first portion, you set the counter to the starting value, the top number. For the condition, you check whether the number continues to be greater than or equal to the final number. And for the third portion, you decrement the counter instead of increment it. Thus, you would have this:
for (i=10; i>=5; i--)
This starts the counter variable i at 10. After each iteration, i becomes 1 less, and thus it moves to 9, then 8, then 7, and so on. And this process continues as long as i is at least 5. Thus, i will count 10, 9, 8, 7, 6, 5. The whole program might look like this:
#include <iostream>
using namespace std;
int main()
{
int i;
for (i=10; i>=5; i--)
{
cout << i << endl;
}
return 0;
}
When you run this code, you see the following output.
10
9
8
7
6
5
Incrementing one step at a time
In our example, we declared the counter variable before the for loop. However, you can actually declare the counter variable inside the loop, as in for (int i = 0; i <= 100; i++). The end result is identical to declaring the counter variable beforehand. You must declare the variable each time you use it in a loop, as shown in the following example:
int x = 0;
for (int i = 0; i <= 100; i++)
{
x += i;
}
for (int i = 200; i <= 300; i++)
{
x += i;
}
In our earlier example under “Going backwards,” we were working with integers, and after each iteration we added 1 to the counter variable. But we can do other things with each iteration. We already hinted that we could work with floating-point numbers and add 0.1 with each iteration. To do this, we can use a program like the following:
#include <iostream>
using namespace std;
int main()
{
double x = 0.0;
double i;
for (i = 0.0; i <= 100.0; i+=0.1)
{
x += i;
}
cout << x << endl;
return 0;
}
Now notice the third item in the for statement, i += 0.1. Remember that this item is the same as i = i + 0.1. Therefore, this third item is a complete statement. A common mistake is to instead include just a partial statement, as in i + 0.1. Unfortunately, some compilers allow that to get through with only a warning. C++ is notorious for letting you do things that really don’t make a whole lot of sense, but newer compilers tend to fix these errors.
Yes, it’s true: The entire statement i = i + 1 is considered to have a side effect. In medicine, a side effect is some extra little goodie you get when you take a pill the doctor prescribes. For example, to cure your headache with a medicine, one side effect may be that you get severe abdominal pains — not something you really want. But in computers, a side effect can be something that you may want. In this case, we want the counter to get incremented. The partial statement i + 0.1 just returns a value and doesn’t put it anywhere; that is, the partial statement doesn’t change the value of i — it has no side effects. (If you try this at home by replacing one of the for loops in the earlier examples with just i + 0.1, your loop will run forever until you manually stop the program. The reason for this action is that the counter always stays put right where it started, and it never increments. Thus the condition i <= 100 will always be satisfied.)
The final portion of the for statement must be a complete statement in itself. If the statement simply evaluates to something, it will not be used in your for loop. In that case, your for loop can run forever unless you stop it.
Getting sneaky (and too complicated)
If you need multiple counter variables, the for loop can handle it. Each portion of the for statement can have multiple items in it, separated by commas. For example, the following line of code uses two counter variables. Look carefully at it because it’s a bit confusing. In fact, we’re going to say a little something about that shortly.
for (i = 0, j=10; i <= 5, j <=20; i++, j=j+2)
{
cout << i << “ “ << j << endl;
x += i + j;
}
To understand this, look at each portion separately. The first portion starts the loop. Here, the code creates two counters, i and ji starts at 0, and j starts at 10.
So far, easy enough. The second portion says that the loop will run as long as the following two conditions are true: i must be less than or equal to 5, and j must be less than or equal to 20.
Again, not too bad. The final portion says what must happen at the end of each iteration: i is incremented by 1, and j is incremented by 2.
And thus you have two counter variables. And it’s not too bad, except . . . imagine if we did something like this instead:
for (i = 0, j=20; i <= 5, j >= 10 ; i++, j=j-2)
{
cout << i << “ “ << j << endl;
x += i + j;
}
If you look carefully, you’ll notice that aside from i, j starts out at 20, the loop runs as long as j is at least 10, and that with each iteration, 2 is subtracted from j. In other words, j is counting down by 2s from 20 to 10.
But i is counting up from 0 to 5. Thus, we have two loops: one counting up and one counting down. (Does it seem to you that just maybe we’re starting to make this a little confusing?)
But wait, there’s more. If you think this is confusing, take a look at the following gem, which we took great pride in putting together:
for (i=0, j=10; i<=5, j <=20 ; i++, j=j+2, cout<<i+j, x+=i+j)
{
}
If you type this, you can see that it does do something. But can you tell what it does just by looking at it? Probably not. (If you can, that’s probably not a good thing either.) The truth is, this kind of code is just too complicated. Best to stick to simpler code. Although you may know what this code means, your coworkers will only get frustrated trying to decode it. And if you just write code for fun at home, six months from now — when you go back and look at this code — you might have trouble figuring it out yourself!
Putting too much inside the for statement itself is easy to do. In fact, if you’re really clever, you can put almost everything inside the for loop and leave nothing but an empty pair of braces, as we did in our preceding example. But remember, just because your code is clever doesn’t mean that what you did was the best way to do it. Instead, sticking to the common practice of using only one variable in the for statement is a good idea (as is not using multiple statements within each portion).
Keeping your programs clear so that other people can figure out what you were trying to do when you wrote the code is always a good idea. Some people seem to think that if they keep their programs complicated, they’re guaranteeing themselves job security. Oddly, all the people we know like that tend to leave their jobs and have trouble getting good references. (Imagine that!)
You may recall that with the ++, you can have both i++ and ++i. The first is called a post-increment and the second is called a pre-increment. You may be tempted to try something like this: for (int i = 0; i <= 5; ++i). Although that looks cool and some people actually prefer it, the truth is that it doesn’t change anything. The ++i still takes place at the end of the loop, not at the beginning as you might hope. To me, that setup just makes code confusing, so we use i++ in our for loops, and we avoid ++i.
Looping while
Often, you find that for loops only work so well. Sometimes, you don’t want a counter variable; you just want to run a loop over and over as long as a certain situation is true. Then, after that situation is no longer the case, you want to stop the loop.
For example, instead of saying that you’ll have 100 people line up and each will give you one more dollar than the person to his or her left, you may say that you will continue accepting money like this as long as they’re willing to give it.
In this case, you can see that the condition under which the thing continues to operate is the “as long as they’re willing to give it.”
To do this in C++, you use a while statement. The while keyword is followed by a set of parentheses containing the condition under which the program is to continue running the loop. Whereas the for statement’s parentheses include three portions that show how to change the counter variable, the while statement’s parentheses contain only a condition.
For example, you may have
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 10)
{
cout << i << endl;
i++;
}
cout << “All Finished!” << endl;
return 0;
}
This code runs while i is less than or equal to 10. Thus, the output of this program is
0
1
2
3
4
5
6
7
8
9
10
All Finished!
The while loop is handy if you don’t have a particular number of times you need the loop to run. For example, let’s consider a situation where your application is reading data from the Internet. Unless you control the Internet data source, you won’t know how much data it can provide. (There are many other situations where you don’t know how much data to read, but Internet applications commonly experience this problem.) Using a while loop, the code can continue reading data until your application has read it all. The Internet data source can simply stream the data to your application until the data transfer is complete.
Often, for this kind of situation, we make a Boolean variable called done, and we start it out as false. My while statement is simply
while (!done)
This translates easily to English as while not done do the following. Then, inside the while loop, when the situation happens that we know the loop must finish (such as the Internet data source has no more data to read), we set
done = true;
For example, the following would do this sort of process:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
bool done = false;
while (!done)
{
cout << i << endl;
i++;
if (i == 10)
done = true;
}
cout << “All Finished!” << endl;
return 0;
}
In the case of the Internet data example, after you encounter no more data, you would set done to true. In the case of your friends giving you money, after one of them refuses, you would set done to true.
If you have worked in other languages, you may have come across the notion of while loops always executing at least once. This is not the case in C++. If the condition in the while statement evaluates to false, the while loop will not execute at all.
Doing while
The while statement has a cousin in the family called the do-while statement. A loop of this form is very similar to the while loop, but with an interesting little catch: The while statement goes at the end. It looks like this:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
do
{
cout << i << endl;
i++;
}
while (i <= 10);
cout << “All Finished!” << endl;
return 0;
}
Notice here that the loop starts with the do keyword, then the material for the loop follows inside braces, and finally the while statement comes at the end. The idea is that you’re telling the computer do this while such-and-such is true, where this is the stuff inside braces and the such-and-such is the condition inside parentheses.
The do-while loop has one important caveat: Unlike the while loop, the do-while loop always runs at least once. In other words, even if the condition isn’t satisfied the first time you run the loop, it runs anyway. That can be a problem sometimes, and if you don’t want that behavior, you should consider using a while loop instead of a do-while loop.
Breaking and continuing
Sometimes, you may write a program that includes a loop that does more than just add numbers. You may find that you want the loop to end under a certain condition that’s separate. Or you may want the loop to suddenly skip out of the current loop and continue with the next item in the loop. When you stop a loop and continue with the code after the loop, you use a break statement. When you quit the current cycle of the loop and continue with the next cycle, you use a continue statement. The next sections show you how to do this.
Breaking
For example, you may be writing a program that reads data over the Internet, and the loop runs for the amount of data that’s supposed to come. But midway through the process, you may encounter some data that has an error in it, and you may want to get out of the for loop immediately.
C++ includes a handy little statement that can rescue you in such a situation. The statement is called break. Now nothing actually breaks, and it seems a bit frightening to write a program that instructs the computer to break. But this use of the term break is more like in break out of prison than break the computer. But instead of breaking out of prison, it breaks you out the loop. This can be any kind of loop — a for loop, a while loop, or a do-while loop.
The following code demonstrates this. This sample actually just checks for the special case of i being 5. We could have accomplished the same thing by simply changing the end condition of our for loop, but at least it shows you how the break statement works.
#include <iostream>
using namespace std;
int main()
{
int i;
for (i=0; i<10; i++)
{
cout << i << “ “;
if (i == 5)
{
break;
}
cout << i * 2 << endl;
}
cout << “All Finished!” << endl;
return 0;
}
In the preceding code, the first line inside the for loop, cout << i << “ “;, runs when i is 5. But the final line in the for loop, cout << i * 2 << endl;, does not run when i is 5 because we told it to break out of the loop between the two cout statements.
Also notice that when you break out of the loop, the program does not quit. It continues with the statements that follow the loop. In this case, it still prints the message, “All Finished!”.
You can actually leave the second portion of the for statement (the condition) empty by just putting a blank between the spaces. Then, to get out of the loop, you can use a break statement. However, doing this makes for messy code. And treat messy code like a messy house: Although sometimes we don’t mind, the truth is that most people really don’t care for a messy house. And you really don’t want other people to see your messy house — or your messy code. Yes, as a programmer, sometimes being a little self-conscious is a good thing.
Continuing
In addition to the times when you may need to break out of your loop for a special situation, you can also cause the loop to end its current iteration; but instead of breaking out of it, the loop resumes with the next iteration.
For example, you may be, again, reading data from over the Internet, and you are doing this by looping a specified number of times. In the middle of the loop, you may encounter some bad data. But instead of quitting out of the loop, you may want to just ignore the current piece of bad data and then continue reading more data.
To do this trick, you use a C++ statement called continue. The continue statement means end the current iteration but continue running the loop with the next iteration.
The following code is a slightly modified version of the previous example in the section called “Breaking.” When the loop gets to 5, it doesn’t do the second cout line. But instead of breaking out of the loop, it continues with 6, then 7, and so on until the loop finishes on its own.
#include <iostream>
using namespace std;
int main()
{
int i;
for (i=0; i<10; i++)
{
cout << i << “ “;
if (i == 5)
{
cout << endl;
continue;
}
cout << i * 2 << endl;
}
cout << “All Finished!” << endl;
return 0;
}
Nesting loops
Many times, you need to work with more than one loop. For example, you may have several groups of friends, and you want to bilk the individual friends of each group for all you can get. You may host a party for the first group of friends and make them each give you as much money as they have. Then, the next week, you may hold another party with a different group of friends. You would do this for each group of friends. Oh wait, we just said the word for, so that’s probably what we’re onto with this.
We could draw out the logic like this:
For each group of friends,
for each person in that group
bilk the friend for all he or she is worth
This is called a nested loop. But if you do this, don’t be surprised if this is the last time your friends visit your nest.
A nested loop simply means a loop inside a loop. Because computers aren’t good at making friends, although they can be used to bilk people, we’ll use an example that’s a bit nicer: Suppose you want to multiply each of the numbers 1 through 10 by 1 and print the answer of each multiplication, and then you want to multiply each of the numbers 1 through 10 by 2 and print the answer of each multiplication, and so on, up to a multiplier of 10. Your C++ code would look like the following.
#include <iostream>
using namespace std;
int main()
{
int x,y;
for (x = 1; x <= 10; x++)
{
cout << “Products of “ << x <<endl;
for (y = 1; y <= 10; y++)
{
cout << x * y << endl;
}
cout << endl;
}
return 0;
}
In this example, we simply have a loop inside a loop. The inner loop can make use of the counter variable from the outer loop. Beyond that, nothing is magical or bizarre about this kind of thing. It’s just a loop inside a loop. And yes, you can have a loop inside a loop inside a loop inside a loop. You can also have any loop inside any other loop, like a while loop inside a for loop.
And notice that we have stuff going on outside the inner loop, but inside the outer loop. That is, we have a cout calls before and after the inner loop. You can do this; your inner loop need not be the only thing inside the outer loop.
Although you can certainly have a loop inside a loop inside a loop inside a loop, the deeper you get, the more potentially confusing your code can become. It’s like the dozens of big cities in America that are promising to build an outer loop. Eventually, that outer loop won’t be big enough, so the cities have to build yet another and another. That’s kind of a frightening prospect, so try not to get carried away with nesting.
If you put a break statement or a continue statement inside a nested loop, the statement applies to the innermost loop it sits in. For example, the following code contains three loops: an outer loop, a middle loop, and an inner loop. The break statement applies to the middle loop.
#include <iostream>
using namespace std;
int main()
{
int x,y,z;
for (x = 1; x <= 3; x++)
{
for (y = 1; y < 3; y++)
{
if (y == 2)
break;
for (z = 1; z < 3; z++)
{
cout << x << “ “ << y;
cout << “ “ << z << endl;
}
}
}
return 0;
}
You can see that when y is 2, the for loop with the y in it breaks. But the outer loop continues to run with the next iteration.

Chapter 4: Dividing Your Work with Functions

In This Chapter
Calling a function
Passing things, such as variables
Writing your own great functions
Fun with strings
Manipulating main
People generally agree that most projects throughout life are easier when you divide them into smaller, more manageable tasks. That’s also the case with computer programming. If you break your code into smaller pieces, it becomes more manageable.
C++ provides many ways to divide code into smaller portions. One way is through the use of what are called functions. A function is a set of lines of code that performs a particular job.
In this chapter, we show you what functions are and how you can use them to make your programming job easier.

Dividing Your Work

If you have a big job to do that doesn’t involve a computer, you can divide your work in many ways. Over the years of studying process management, people have pretty much narrowed division of a job down to two ways: using nouns and using verbs.
Yes, that’s right. Back to good old English class, where we all learned about nouns and verbs. The idea is this: Suppose that we’re going to go out back and build a flying saucer. We can approach the designing of the flying saucer in two ways.
First, we could just draw up a plan of attack, listing all the steps to build the flying saucer from start to finish. That would, of course, be a lot of steps. But to simplify it, we could instead list all the major tasks without getting into the details. It might go something like this:
1. Build the outer shell.
2. Build and attach the engine.
That’s it. Only two steps. But when you hire a couple dozen people to do the grunt work for you while you focus on your daytrading, would that be enough for them to go on? No, probably not. Instead, you could take these two tasks and divide them into smaller tasks. For example, Step 2 might look like this:
2a. Build the antigravity lifter.
2b. Build the thruster.
2c. Connect the lifter to the thruster to form the final engine.
2d. Attach the engine to the outer shell.
That’s a little better; it has more detail. But, it still needs more. How do we do the Build the antigravity lifter part? That’s easy, but it requires more detail, as in the following:
2aa. Unearth the antigravity particles from the ground.
2ab. Compress them tightly into a superatomizing conductor.
2ac. Surround with coils.
2ad. Connect 9-volt battery clip to the coils.
And, of course, each of these requires even more detail. Eventually, after you have planned the whole thing, you will have many, many steps, but they will be organized into a hierarchy of sorts, as shown in Figure 4-1. In this drawing, the three dots represent places where other steps go, but we chose to leave them off so the diagram could fit on the page.
This type of design is called a top-down design. The idea is that you start at the uppermost step of your design (in this case, Build flying saucer) and continue to break the steps into more and more detailed steps until you have something manageable. For many years, this was how computer programming was taught.

 Figure 4-1:  A process can be divided into a hierarchy.

Although this process works, people have found a slightly better way. First, before breaking the steps (which are the verbs), you divide the thing you’re building into parts (the nouns). In this case, we kind of did that already in the first two steps. But instead of calling them steps, we call them objects: One object is the outer shell, and one object is the engine. This way, two different factories can work on these in sort of a division of labor. Of course, the factories would have to coordinate their activities; otherwise, the two parts may not fit together when they’re ready to go. And before figuring out exactly how to build each of these objects, it would be a good idea to describe each object: What it does, its features, its dimensions, and so on. Then, when we finally have all that done, we can list the exact features and their details. And finally, we can divide the work with each person designing or building a different part.
As you can see, this second approach makes more sense. And that’s the way programmers divide their computer programs. But at the bottom of each method is something in common: The methods are made of several little processes. These processes are called functions. When you write a computer program, after you divide your job into smaller things called objects, you eventually start giving these objects behaviors. And to code these behaviors, you do just as we did in the first approach: You break them into manageable parts, again, called functions. In computer programming terms, a function is simply a small set of code that performs a specific task. But it’s more than that: Think of a function as a machine. You can put one or more things into the machine; it processes them, and then it spits out a single answer, if anything at all. One of the most valuable diagrams we have seen draws a function in this manner, like a machine, as shown in Figure 4-2.

 Figure 4-2:  You can think of a function as a machine.

This machine (or function) has three main parts:
Inputs: The function can receive data through its inputs. These data elements can be numbers, strings, or any other type. When you create such a machine, you can have as many inputs as you want (or even zero if necessary).
Processor: The processor is the function itself. In terms of C++, this is actually a set of code lines.
Output: A function can return something when it has finished doing its thing. In C++, this is in the form of numbers, strings, or any other type.
To make all this clear, try out the code in Listing 4-1. (Don’t forget the second line, #include <math.h>, which gives you some math capabilities.)
Listing 4-1: Seeing a Function in Action
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
cout << fabs(-10.5) << endl;
cout << fabs(10.5) << endl;
return 0;
}
When you run this program, you see the following output:
10.5
10.5
In this code, you used a function or machine called fabs (usually pronounced ef-abs for floating-point absolute). This function takes a number as input and returns as output the absolute value of the number. Remember that the absolute value of a number is simply the positive version of the number. The absolute value, for example, of –5 is simply 5. The absolute value of 12 is still 12. An absolute value is always positive. And the absolute value of 0 is 0. (The reason for the f before the name abs is that it uses floating-point numbers, which are simply numbers with decimal points.)
So the first line inside main calls fabs for the value –10.5. The cout then takes the output of this function (that is, the result) and prints it to the console.
Then the second line does the same thing again, except it takes the absolute value of the number 10.5.
And where is the processor for this function? It’s not in your code; it’s in another file, and the following line ensures that your program can use this function:
#include <math.h>
You have seen functions in many places. If you use a calculator and enter a number and press the square root button, the calculator runs a function that calculates the square root.
But functions can be more sophisticated than just working with numbers. Consider this carefully: When you are using a word processor and you highlight a word and do a spelling check on the word, the program calls a function that handles the spelling check. This function does something like the following:
This is a function to check the spelling of a single word.
Inputs: A single word.
Look up the word
If the word is not found
Find some suggestions.
Open a dialog box through which you (the user)
can change the word by either typing a new word
or picking one of the selections, or just leaving
it the same.
If you made a change,
Return the new spelling.
Otherwise
Return nothing.
Otherwise
Return nothing
Notice how we grouped the if statements with indentations. The final otherwise goes with the first if statement because its indentation matches that of the if statement.
So that’s a function that performs a spelling check. But consider this: When you do not highlight a word but run the spelling checker, the spelling checker runs for the whole document. That’s another function. Here it is.
This is a function to check the spelling of the entire document
For each word in the document
Check the spelling of the single word
How does the computer do the step inside the for loop, Check the spelling of the single word? It calls the function we described earlier. This process is called code reuse. We have no reason to rewrite the entire function again if we already have it somewhere else. And that’s the beauty of functions.

Calling a Function

When you run the code in a function, computer people say you are calling the function. And just like every good person, a good function has a name. When you call a function, you do so by name.
Often, when we’re writing a program and write code to call a function, we will say that We are calling a function. This is just partly computerspeak, and partly a strange disorder in which we computer programmers start to relate just a little too much with the computer.
To call a function, you type its name and then a set of parentheses. Inside the parentheses, you list the items you want to send to the inputs of the function. The term we use here is pass, as in you pass the values to the function.
For example, if you want to call the fabs function, you type the name, fabs, an open parenthesis, the number you want to pass to it, and then a close parenthesis, as in the following:
fabs(-10.5)
But by itself, this does not do anything. The fabs function returns a value — the absolute value of –10.5, which comes out to be 10.5 — and you probably want to do something with that value. You could, for example, print it to the console:
cout << fabs(-10.5) << endl;
Or you could store it away in another variable. But there’s a catch. Before you can do that, you need to know the type the function returns. Just as with variables, function return values have a type. In this case, the type is a special type called double. The double type is a floating-point type that can hold many digits in a single number. To save the result of fabs, you need to have a variable of type double. The code in Listing 4-2 does this.
Listing 4-2: Seeing Another Function in Action
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double mynumber;
mynumber = fabs(-23.87);
cout << mynumber << endl;
return 0;
}
This code declares a double variable called mynumber. Then it calls fabs, passing it –23.87, and returning the value into mynumber. Next it prints the value in mynumber out to the console.
When you run this program you see the following, which is the absolute value of –23.87.
23.87
Passing a variable
You can also pass the value of a variable into a function. The code in Listing 4-3 creates two variables; one is passed into the function, and the other receives the results of the function.
Listing 4-3: Seeing Yet Another Function in Action
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double start;
double finish;
start = -253.895;
finish = fabs(start);
cout << finish << endl;
return 0;
}
(We separated the parts of the code with blank lines to make it a little easier to follow.) This code first creates two variables; the first is called start, and the second is called finish. It then initializes start with a value of –253.895. Next, it calls fabs, passing it the value of start. It saves the return value in the finish variable, and it finally prints the value in finish. When it runs, you see the following appear on the console:
253.895
Saving a function result to a variable is useful if you need to use the result several times over. For example, if you need the absolute value of –253.895 for whatever reason and then a few lines later you need it again, you have a choice: You can either call fabs(-253.895) each time or you can call it once, save it in a variable, and then use the variable each time you need it. The advantage to saving it in a variable is that if you later, for example, say, “Oh wait! I didn’t just want the absolute value! I wanted the negative of the absolute value!” you only have to change one line of code — the line where it calls fabs. If, instead, you had called fabs several times, you would have had to change it every time you called it. And by the way, in case you’re curious about how to take the negative of the absolute value and store it in a variable, you just throw a minus sign in front of it, like so:
finish = -fabs(start);
Passing multiple variables
Some functions like to have all sorts of goodies thrown their way, such as multiple parameters. As with functions that take a single value, you put the values inside a single set of parentheses. Because you have multiple values, you separate them with commas. Listing 4-4 uses a function called pow to calculate the third power of 10. (That is, it calculates 10 times 10 times 10. Yes, POW!). Make sure that you include the math.h line in the includes section so that you can use the pow function.
Listing 4-4: Seeing Yet One More Function in Action
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double number = 10.0;
double exponent = 3.0;
cout << pow(number, exponent) << endl;
return 0;
}
When you run the program, you see 10 to the third power, which is 1,000:
1000
You can also pass a mixture of variables and numbers, or just numbers. The following code snippet also calculates the third power of 10 but passes an actual number, 3.0, for the power.
double number = 10.0;
cout << pow(number, 3.0) << endl;
Or you can pass only numbers:
cout << pow(10.0, 3.0) << endl;

Writing Your Own Functions

And now the fun begins! Calling functions is great, but you get real power (ooh!) when you write your own specialized functions. Before writing a function, remember the parts: the inputs, the main code or processor, and the single output (or no output). The inputs, however, are actually called parameters, and the output is called a return value.
Listing 4-5 shows both a custom function and code in main that calls the custom function. (The function goes outside main — before it, in fact.)
Listing 4-5: Writing Your Very Own Function
#include <iostream>
using namespace std;
int AddOne(int start)
{
int newnumber;
newnumber = start + 1;
return newnumber;
}
int main()
{
int testnumber;
int result;
testnumber = 20;
result = AddOne(testnumber);
cout << result << endl;
return 0;
}
After you get all this typed in and your fingers are feeling nice and exercised, go ahead and run it. Because there’s a good bit of code, you may get some compiler errors at first; look carefully at the lines with the errors and find the difference between your code and what’s here in the book.
After you run it, you see
21
Now before we explain the code for the function, we’ll save the fun for last. Take a look at these three lines of main:
testnumber = 20;
result = AddOne(testnumber);
cout << result << endl;
You can probably put together some facts and determine what the function does. First, we called it AddOne, which is a pretty good indication in itself. Second, when you ran the program, the number 21 appear on the console, which is one more than the value in testnumber; it added one. And that, in fact, is what the function does. It’s amazing what computers can do these days.
When you write your own functions, try to choose a name that makes sense and describes what the function does. Writing a function and calling it something like process or TheFunction is easy, but those names do not accurately describe the function.
So now take a look at the function itself. First, here are a few high-level observations about it:
Position: The function appears before main. Because of the way the compiler works, it must know about a function before you call it. And thus, we put it before main. (You can do this in another way, which we discuss in “Forward references and function prototypes,” later in this chapter.)
Format: The function starts with a line that seems to describe the function (which we explain later in this section), and then it has an open brace and, later, a closing brace.
Code: The function has code in it that is just like the type of code you could put inside a main.
After noting these high-level things, take a look at the code inside the function. The first part of it looks like this:
int newnumber;
newnumber = start + 1;
So far, this is pretty straightforward. It declares an integer variable called newnumber. Then it initializes it to start plus one. But what is start? That’s one of the inputs.
Finally, this line is at the end of the function, before the closing brace:
return newnumber;
This is the output of the function, or the return value. When you want to return something from a function, you just put the word return and then indicate what you want to return. From the preceding two lines, you can see that newnumber is one more than the number passed into the function. So this line returns the newnumber. Thus, we have covered all three parts: We have taken the input or parameter; we have processed it by creating a variable and adding one to the parameter; and we have returned the output, which is one more than the parameter.
But what is the parameter? It’s called start. And where did that come from? Here’s the very first line of the function:
int AddOne(int start)
The stuff in parentheses is the list of parameters. Notice that it looks just like a variable declaration; it’s the word int (the type, or integer) followed by a variable name, start. That’s the parameter — the input — to the function, and you can access this parameter throughout the function by simply using a variable called start.
We think that’s rather ingenious, if we do say so ourselves. Okay, so we didn’t invent it, but nevertheless, we think it’s ingenious: You can use the input to the function as a variable itself.
And so, if down in main we had written
result = AddOne(25);
then throughout the function, the value of start would be 25.
But if we had written
result = AddOne(152);
then throughout the function, the value of start would be 152.
But here’s the really great thing about functions. Or, at least, one of the loads of really great things about functions! We can call the function several times over. In the same main, we can have the following lines
cout << AddOne(100) << endl;
cout << AddOne(200) << endl;
cout << AddOne(300) << endl;
which would result in this output:
101
201
301
Arguing over parameters
Technically, the term parameter refers strictly to the inputs to the function, from the function’s perspective. When you call the function, the things you place in parentheses in the call line are not called parameters; rather, they are called arguments. Thus, in the following function header the variables first and last are parameters. But in the following call to this function
ConnectNames(“Bill”, “Murray”)
the strings “Bill” and “Murray” are arguments of the call.
In the first call to AddOne, the value of start would be 100. During the second call, the value would be 200, and during the third call, it would be 300.
Now take another look at the header:
int AddOne(int start)
The word AddOne is the name of the function, as you probably figured out already. And that leaves that thing at the beginning, the int. That’s the type of the return value. The final line in the function before the closing brace is
return newnumber;
The variable newnumber inside the function is an integer. And the return type is integer. That’s no accident: As we’ve all heard before, friends don’t let friends return something other than the type specified in the function header. The two must match in type. And further, take a look at this line from inside main:
result = AddOne(testnumber);
What type is the result variable? It’s also an integer. All three match. Again, no accident. You can copy one thing to another (in this case the function’s return value to the variable called result) only if they match in type. And here, they do. They’re both integers.
And notice one more thing about the function header: It has no semicolon after it. This is one of the places you do not put a semicolon. If you do, the compiler gets horribly confused. The CodeBlocks compiler shows an error that says, “error: expected unqualified-id before ‘{‘ token.”
Here’s a recap of some of the rules we just mentioned regarding functions:
Header line: The header line starts with a value for the return type, the name of the function, and the list of parameters.
Parameters: The parameters are written like variable declarations, and indeed, you can use them as variables inside the function.
Return type: Whatever you return from the function must match in type with the type you specified in your function header.
More on format: The function header does not have a semicolon after it.
Even more on format: After the function header, you use an open brace. The function ends with a closing brace. The final brace tells the compiler where the function ends.
Finally, ponder this line of code for a moment:
testnumber = AddOne(testnumber);
This takes the value stored inside testnumber, passes it into AddOne, and gets back a new number. It then takes that new number and stores it back into testnumber. Thus, testnumber’s value changes based on the results of the function AddOne.
Multiple parameters or no parameters
You don’t need to write your functions with only one parameter each. You can have several parameters, or you can have none at all. It may seem a little strange that you would want a function — a machine — that takes no inputs. But you may run into lots of cases where this may be a good idea. Here are some ideas:
Day function: This would be a function that figures out the day and returns it as a string, as in “Monday” or “Tuesday”.
Number-of-users function: This could be a function that figures out the current number of users logged into a Web-server computer.
Current font function: This function would be in a text editor program (such as Notepad) and would return a string containing the current font name, such as “Arial”.
Editing time function: This function would return the amount of time you have been using the word processor program.
Username function: If you are logged onto a computer, this function would give back your username as a string, such as “Elisha”.
All the functions in this list have something in common: They look something up. Because no parameters are in the code, for the functions to process some information, they have to go out and get it themselves. It’s like sending people out into the woods to find food but not giving them any tools: It’s totally up to them to do it, and all you can do is sit back and watch and wait for your yummy surprise.
If a function takes no parameters, you write the function header as you would for one that takes parameters, and you include the parentheses; you just don’t put anything in the parentheses, as Listing 4-6 shows. So if nothing good is going in, there really can be something good coming back out, at least in the case of a function with no parameters.
Listing 4-6: Taking No Parameters
#include <iostream>
using namespace std;
string Username()
{
return “Elisha”;
}
int main()
{
cout << Username() << endl;
return 0;
}
When you run Listing 4-6, you see the following output:
Elisha
Your function can also take multiple parameters. Listing 4-7 shows this. Notice that the function, ConnectNames, takes the two strings as parameters and combines them, along with a space in the middle. Notice also that the function uses the two strings as variables.
Listing 4-7: Taking Multiple Parameters
#include <iostream>
using namespace std;
string ConnectNames(string first, string last)
{
return first + “ “ + last;
}
int main()
{
cout << ConnectNames(“Richard”, “Nixon”) << endl;
return 0;
}
In the function header in Listing 4-7, we had to put the type name string for each parameter. If we only listed it for the first, we would get a compile error. (Okay, we admit it — we did forget it, and that’s how we remembered to tell you. But that shows that even experienced programmers came make mistakes. Occasionally.)
Now here are some points about this code:
♦ We didn’t create variables for the two names in main. Instead, we just typed them as string constants (that is, as actual strings surrounded by quotes).
♦ You can do calculations and figuring right inside the return statement. That saves the extra work of creating a variable. In the function, we could have created a return variable of type string, set it to first + + last, and then returned that variable, as in the following code:
string result = first + “ “ + last;
return result;
But instead, we chose to do it all on one line, as in this:
return first + “ “ + last;
Although you can save yourself the work of creating an extra variable and just put the whole expression in the return statement, sometimes this is a bad thing. If the expression is really long like the following
return (mynumber * 100 + somethingelse / 200) *
(yetanother + 400 / mynumber) / (mynumber + evenmore);
then it can get just a tad complicated. Breaking it into variables, such as this, is best:
double a = mynumber * 100 + somethingelse / 200;
double b = yetanother + 400 / mynumber;
double c = mynumber + evenmore;
return a * b / c;
Returning nothing
In the preceding section, “Multiple parameters or no parameters,” we presented a list of functions that take no parameters; these functions go and bring back something, whether it’s a number, a string, or some other type of food.
One such example gets the username of the computer you’re logged into. But what if you are the great computer guru, and you are writing the program that actually logs somebody in? In that case, your program doesn’t ask the computer what the username is — your program tells the computer what the username is, by golly!
In that case, your program would call a function, like SetUsername, and pass the new username. And would this function return anything? It could; it could return the name back, or it could return a message saying that the username is not valid or something like that. Or, it may not return anything at all.
Take a look at the case where a function doesn’t return anything at all. In C++, the way you state that the function doesn’t return anything is by using the word void as the return type in the function header. Listing 4-8 shows this.
Listing 4-8: Returning Nothing at All
#include <iostream>
using namespace std;
void SetUsername(string newname)
{
cout << “New user is “ << newname << endl;
}
int main()
{
SetUsername(“Harold”);
return 0;
}
When you run the program, you see
New user is Harold
Notice the function header: It starts with the word void, which means that it returns nothing at all. It’s like in outer space: There’s just a big void with nothing there, and nothing is returned, except for static from the alien airwaves, but we won’t go there. Also notice that, because this function does not return anything, there is no return statement.
Now, of course, this function really doesn’t do a whole lot other than print the new username to the console, but that’s okay; it shows you how you can write a function that does not return anything.
A function of return type void returns nothing at all.
Do not try to return something in a function that has a return type of void. Void means the function returns nothing at all. If you try to put a return statement in your function, you get a compile error.
Keeping your variables local
Everybody likes to have their own stuff, and functions are no exception. When you create a variable inside the code for a function, that variable will be known only to that particular function. When you create such variables, they are called local variables, and people say that they are local to that particular function. (Well, computer people say that, anyway.)
For example, consider the following code:
#include <iostream>
using namespace std;
void PrintName(string first, string last)
{
string fullname = first + “ “ + last;
cout << fullname << endl;
}
int main()
{
PrintName(“Thomas”, “Jefferson”);
return 0;
}
Notice in the PrintName function that we declared a variable called fullname. We then use that variable in the second line in that function, the one starting with cout. But we cannot use the variable inside main. If we try to, as in the following code, we would get a compile error:
int main()
{
PrintName(“Thomas”, “Jefferson”);
cout << fullname << endl;
return 0;
}
However, we can declare a variable called fullname inside main, as in the following code. But, if we do that, this fullname is local only to main, while the other variable, also called fullname, is local only to the PrintName function. In other words, each function has its own variable; they just happen to share the same name. But they are two separate variables.
int main()
{
string fullname = “Abraham Lincoln”;
PrintName(“Thomas”, “Jefferson”);
cout << fullname << endl;
return 0;
}
When two functions declare variables by the same name, they are two separate variables. If you store a value inside one of them, the other function will not know about it. The other function only knows about its own variable by that name. Think of it the way two people could each have a storage bin in the closet labeled “tools.” If Sally puts a hammer in her bin labeled “tools” and Hal opens another bin also labeled “tools” at his house, he won’t see the very same hammer in Sally’s bin, will he? We hope not, or something is seriously awry in the universe. With variables it works the same way.
If you use the same variable name in two different functions, forgetting that you’re working with two different variables is very easy. Only do this if you’re sure that no confusion can occur.
If you use the same variable name in two different functions (such as a counter variable called index, which you use in a for loop), matching the case is usually a good idea. Don’t use count in one function, and Count in another. Although you can certainly do that, you may find yourself typing the name wrong when you need it. But that won’t cause you to access the other one. (You can’t because it’s in a different function.) Instead, you get a compile error, and you have to go back and fix it. Being consistent is a timesaver.
Forward references and function prototypes
In all the examples in this chapter, we have put the code for any function we write above the code for main. The reason is that the compiler scans through the code from start to finish. If it has not encountered a function yet but sees a call to it, it won’t know what it’s seeing, and it issues a good old compile error.
Such an error can be especially frustrating and could cause you to spend hours yelling at your computer (or, if you’re like us, running to the refrigerator and getting something sweet and fattening). Nothing is more frustrating than looking at your program, being told by the compiler it’s wrong, yet knowing it’s right because you know you wrote the function.
You can, however, put your functions after main; or you can even use this method to put your functions in other source-code files (something we talk about in Minibook I, Chapter 5).
What you can do is include a function prototype. A function prototype is nothing more than a copy of the function header. But instead of following it with an open brace and then the code for the function, you follow the function header with a semicolon and are finished. A function prototype, for example, looks like this:
void PrintName(string first, string last);
Then you actually write the full function (header, code, and all) later. The full function can even be later than main or later than any place that makes calls to it.
Notice that this looks just like the first line of a function. In fact, we cheated! To write it, we simply copied the first line of the original function we wrote and added a semicolon.
So where would you use this fellow? Take a look at Listing 4-9.
Listing 4-9: Using a Function Prototype
#include <iostream>
using namespace std;
void PrintName(string first, string last);
int main()
{
PrintName(“Thomas”, “Jefferson”);
return 0;
}
void PrintName(string first, string last)
{
string fullname = first + “ “ + last;
cout << fullname << endl;
}
Notice, in this listing, that we have the function header copied above main and ending with a semicolon. Then we have main. Finally we have the function itself (again, with the header but no semicolon this time). Thus, the function comes after main.
“Whoop-de-do,” we can hear you saying. The function comes after. But why bother when now we have to type the function header twice?
But rest assured, dear readers, that this step is useful. If you have a source code file with, say, 20 functions, and these functions all make various calls to each other, it could be difficult to carefully order them so that each function calls only functions that are above it in the source code file. Instead, most programmers put the functions in some logical order (or maybe not), but they don’t worry much about the calling order. Then they have all the function prototypes toward the top of the source code file, as we did earlier in Listing 4-9.
When you type a function prototype, many people say that you are specifying a forward reference. This phrase simply means that you are providing a reference to something that happens later. It’s not a big deal, and it mainly comes from some of the older programming languages. But some people use the jargon, and we hope that if you hear that phrase, it will trigger happy memories of this book.
Writing two versions of the same function
There may be times when you want to write two versions of the same function, the only difference being that they take different parameter types. For example, you may want a function called Combine. One version takes two strings and puts the two strings together, but with a space in the middle. It then prints the resulting string to the console. Another version takes two numbers, adds them, and writes all three numbers — the first two and the sum — to the console.
The first version would look like this:
void Combine(string first, string second)
{
cout << first << “ “ << second << endl;
}
There’s nothing magical or particularly special about this function. It’s called Combine; it takes two strings as parameters; it does not return anything. The code for the function prints the two strings with a space between them.
Now the second version looks like this:
void Combine(int first, int second)
{
int sum = first + second;
cout << first << “ “ << second << “ “ << sum << endl;
}
Again, nothing spectacular here. The function name is Combine, and it does not return anything. But this version takes two integers, not two strings, as parameters. The code is also different from the previous code in that it first figures the sum of the two and then it prints the different numbers.
Well this is all fine and dandy, but can you have two functions by the same name like this? Yup! Listing 4-10 shows the entire code. Both functions are present in the listing.
Listing 4-10: Writing Two Versions of a Function
#include <iostream>
using namespace std;
void Combine(string first, string second)
{
cout << first << “ “ << second << endl;
}
void Combine(int first, int second)
{
int sum = first + second;
cout << first << “ “ << second << “ “ << sum << endl;
}
int main()
{
Combine(“David”,”Letterman”);
Combine(15,20);
return 0;
}
Note in main that we called each function. How did we specify which one we want? By simply passing the right types. Take a close look at the first call:
Combine(“David”,”Letterman”);
This call includes two strings. so the compiler knows to use the first version, which takes two strings. Now look at the second function call:
Combine(15,20);
This call takes two integers, so the compiler knows to use the second version of the function.
This process of writing two versions of the same function is called overloading the function. Normally, overloading is a bad thing, like when we go to a nice restaurant and overload our stomachs. But here it’s a good thing and even useful.
When you overload a function, the parameters must differ. For example, the functions can take the same type of information but use a different number of parameters. Of course, the previous example shows that the parameters can also vary by type. You can also have different return types, but they must differ by more than just the return type.

Calling All String Functions

To get the most out of strings, you need to make use of some special functions that cater to the strings. However, using these functions is a little different from the other functions used so far in the chapter. Instead of just calling the function, you type first the variable name that holds the string, then a period (or dot, as the netheads prefer to call it), and then the function name along with any parameters (arguments, if any purists are reading).
The reason you code string functions differently is because you’re making use of some object-oriented programming features. Minibook I, Chapter 7 describes in detail how these types of functions (called member functions) work.
One function that you can use is called insert. You can use this function if you want to insert more characters into another string. For example, if you have the string “Something interesting and bizarre” and you insert the string “seriously ” (with a space at the end) into the middle of it starting at index 10, you’ll get the string “Something seriously interesting and bizarre”.
When you work with strings, the first character is the 0th index, and the second character is the 1st index, and so on.
The following lines of code perform an insert by using the insert function:
string words = “Something interesting and bizarre”;
words.insert(10, “seriously “);
The first of these lines simply creates a string called words and stuffs it full with the phrase “Something interesting and bizarre”. The second line does the insert. Notice the strange way of calling the function: You first specify the variable name, words, and then a dot, and then the function name, insert. Next, you follow it with the parameters in parentheses, as usual. For this function, the first parameter is the index where you want to insert the string. The second parameter is the actual string you are going to insert.
After these two lines run, the string variable called words contains the string “Something seriously interesting and bizarre”.
You can also erase parts of a string by using a similar function called, believe it or not, erase. Although computer folks like to obfuscate through their parlance (that is, confuse people through choices of words!), they do occasionally break down and pick names that actually make sense.
The following line of code erases from the string called words 16 characters starting with the 20th index:
words.erase(19,16);
Consequently, if the variable called words contains the string “Something seriously interesting and bizarre”, after this line runs, it will contain “Something seriously bizarre”.
Another useful function is replace. This function replaces a certain part of the string with another string. To use this, you specify where in the string you want to start the replacement and how many characters you want to replace. Then you specify the string you want to replace the old, worn-out parts with.
So, for example, if your string is “Something seriously bizarre” and you want to replace the word “thing” with the string “body”, you would tell replace to start at index 4, and replace 5 characters with the word “body”. To do this, you would enter:
words.replace(4, 5, “body”);
Notice the number of characters you replace does not have to be the same as the length of the new string. If the string starts out with “Something seriously bizarre”, after this replace statement runs, the string will contain “Somebody seriously bizarre”. But the string will not actually contain somebody who is seriously bizarre; it contains just the string.
Listing 4-11 shows all these functions working together.
Listing 4-11: Operating on Strings
#include <iostream>
using namespace std;
int main()
{
string words = “Something interesting and bizarre”;
cout << words << endl;
words.insert(10, “seriously “);
cout << words << endl;
words.erase(19,16);
cout << words << endl;
words.replace(4, 5, “body”);
cout << words << endl;
return 0;
}
When you run this program, you see the following output:
Something interesting and bizarre
Something seriously interesting and bizarre
Something seriously bizarre
Somebody seriously bizarre
The first line is the original string. The second line is the result of the insert function. The third line is the result of the erase function. And the final line is the result of the replace function.

Understanding main

All the programs so far have had a main. This main is actually a function. Notice its header, which is followed by code inside braces:
int main()
You can see that this is definitely a function header: It starts out with a return type, then the function name, main. This is just one form of the main function — the form that CodeBlocks uses by default. However, you may decide that you want to give users the ability to provide input when they type the name of your program at the console. In this case, you use this alternative form of the main function that includes two parameters.
int main(int argc, char *argv[])
Who, what, where, and why return?
The main function header starts with the type int. This means the function main returns something. But what? And to whom? And why and when and all those w words?
The result of main is sometimes used by the computer to return error messages if the program, for some reason, didn’t work or didn’t do what it was supposed to do. But here’s the inside scoop: Outputting a return value just doesn’t work — at least, not in the graphical environment that most of you use.
It’s true. For many computers, particularly Windows computers, the return value is of very little use to anybody. The return type is specifically designed to work with batch files (files with a BAT extension that originally appeared as part of DOS, or Disk Operating System). Consequently, unless you plan to work with batch files (and many people still do), just return 0.
On some high-powered Unix systems, the return value of main is used. Some of these systems running so-called mission-critical applications (a fancy word that means the computer programmers feel like what they’re doing is important to the safety of the universe) do indeed use the return values from main. These computers may run hundreds of programs. If one of these programs returns something other than 0, another program detects this and notifies somebody (usually by sending the poor sap a page in the middle of the night). When you’re still learning C++, you’re not likely to need to return things other than 0, but if you’re lucky enough to be working for a company that builds applications vital to the well-being of the universe, you may want to find out from your teammates if you do, in fact, need to return something other than 0.
So what about those seriously bizarre looking parameters in main? The first is reasonably straightforward; it’s an integer variable with the goofy name argv, which sounds like something Scooby-Doo would say. But what about that second goofiness? To understand the second, you need to know that these two parameters are actually used as command-line parameters. When you run a program, especially from the command prompt, you type the name of the program and press Enter. But before pressing Enter, you can follow the program name with other words. Many of the commands you use in Unix and in the Windows command-line tool (also known as DOS) have a program name and then various parameters. For example, on Unix you could type the following command to copy the file called myfile to a new file called yourfile:
cp myfile yourfile
On Windows, you could type the following command to copy the file called myfile to a new file called yourfile:
copy myfile yourfile
When you run such a command, you are actually running a program called copy. The program takes two command-line parameters, in this case “myfile” and “yourfile” and passes these two strings into the main function as parameters.
For the main function, the first parameter in the header is argc, pronounced arg-SEE, which represents the number of command-line parameters. In the case of the copy or cp command (see the two preceding lines of code), you have two (“myfile” and “yourfile”), so argc would be 2.
The second parameter in the main function is the cryptic-looking char *argv[]. The name of the variable is called argv, and it is pronounced arg-VEE. Minibook I, Chapter 8, deals with a topic called an array. An array is a sequence of variables stored under one name. The argv variable is one such animal. To access the individual variables stored under the single umbrella known as argv, you do something like this:
cout << argv[0] << endl;
cout << argv[1] << endl;
(In the preceding example, you’re using brackets as you did similarly with accessing the individual characters in a string.)
In the case of the two command-line parameters myfile and yourfile, these two lines of code would print the lines
myfile
yourfile
You can access the command-line parameters using a for loop. Listing 4-12 shows how.
Listing 4-12: Accessing the Command-Line Parameters
#include <iostream>
#include <stdlib.h>
int main(int argc, char *argv[])
{
for (int index=0; index < argc; index++)
{
cout << argv[index] << endl;
}
return 0;
}
When we run this program from the prompt using the following command-line parameters
CommandLineParameters Command Line Parameters
we see the following output:
c:\CommandLineParameters Command Line Parameters
CommandLineParameters
Command
Line
Parameters
The first item in the argv list is always the name of the program.

Chapter 5: Dividing Between Source-Code Files

In This Chapter
Creating multiple source-code files
Creating header files
Sharing variables among source files
Making use of the mysterious header wrappers
Just as you can divide your work into functions, you can also divide your work into multiple source-code files. The main reason to do so is, simply, to help keep your project more manageable. Also, with multiple source-code files, you can have several people working on a single project, each working on a different source-code file at the same time. The goal, of course, is to make sure that your coworkers work on the harder parts that are more grueling and no fun while you get all the credit.
The key to multiple source files is knowing where to break the source code into pieces. Like anything else, if you break the source code in the wrong place, it will, well, break.
In this chapter, we show you how to divide your source code into multiple files (and in all the right places). The examples we give use CodeBlocks; however, we also provide a few Makefile tips if you’re using other tools.

Creating Multiple Source Files

In this section, we talk about how to create multiple source-code files, first for CodeBlocks and then for other compilers. This process is far simpler in CodeBlocks, and we highly recommend that approach.
When you create a second source-code file, this code becomes part of your project. And when you compile, the compiler compiles all the source-code files in your project, assuming that you have changed them since the last time you compiled. You can put your functions in separate source-code files, and they can call each other. In this way, they all work together in the single program. In the section “Sharing with Header Files,” later in this chapter, we talk about how you can have a function call another function in a different source file.
You cannot break a single function up and put it into two source files. That would be quite painful for the little fellow, and certainly not a good programming practice either because it simply wouldn’t compile. The compiler requires that your functions stay in one piece in a single source file.
Multiple source files in CodeBlocks
If you’re using CodeBlocks, cutting your program into multiple source-code files is as easy as cutting a cake. The following steps show you how to perform this task:
1. Choose FileNewFile.
You see the New from Template dialog box shown in Figure 5-1. Notice that you can choose from a header, source code, or an empty file. Normally, you’ll choose either the C/C++ Header or C/C++ Source option. The Empty File option is for non-source files, such as a text file used as a ReadMe.

 Figure 5-1:  The New from Template dialog box lets you select a new file type.

2. Highlight the template you want to use and click Go.
You see a wizard associated with the particular file you’ve chosen.
3. Click Next to get past the initial Welcome page.
If you chose the Empty File template, skip to Step 5. When using the C/C++ Header or C/C++ Source templates, you see a language selection page.
4. Highlight the language you want to use — either C or C++ — and click Next.
The wizard asks what you want to call the file, where you want to store it, and which builds should use the file, as shown in Figure 5-2.

 Figure 5-2:  Provide the file information required by the wizard.

5. Type a path and filename for the file in the Filename with Full Path field.
You must provide a full path, even if you want the file in the current folder. Click the ellipses to display a Select Filename dialog box where you can choose the location of the file. The default path shown in the Select Filename dialog box is the current folder.
6. Check the individual builds that should use the file.
As an alternative, you can click All to add the file to all builds.
7. Click Finish.
The wizard adds the new file to your project. CodeBlocks automatically opens the file so you can begin editing it. You also see the file you added in the Management window, as shown in Figure 5-3. In this case, you see both the source files and a header file. Notice that the source files appear in dark type, while the header file appears in gray type. This shows that the source files are compiled to create the project and the header file isn’t. The “Sharing with Header Files” section of the chapter discusses how the compiler works with header files in more detail.

 Figure 5-3:  The Management window displays the files used to compile the project.

If you add a file to CodeBlocks that you really don’t need, right-click the file in the Management window and choose Remove File from Project from the context menu. The file will disappear from the project but still appear in the directory in which you created it. If you later decide that you really do want that file, right-click the project entry in the Management window, choose Add Files from the context menu, and select the file you want to add back into the project using the options in the Add Files to Project dialog box.
If CodeBlocks doesn’t automatically open the file you added, you can open it by double-clicking its name in the tree. When you do, an additional tab appears at the top of your source-code files. These tabs represent the different files that are open. You can click a tab to have that file’s code appear in the source-code window. When you click another tab, the window shows the source for that file, instead. And, thankfully, it remembers any changes you make if you switch to another tab. So you can bounce all around the screen and switch all you want, and the computer shouldn’t get confused.
After you have multiple files in your project, you can put some of your source in one file and some in another. But before you do, you may want to read some of the other sections in this chapter because we explain how to properly divide your source code without it ending up like cake that got smooshed while you were trying to cut it.
Multiple source files in other compilers
If you’re using CodeBlocks, you don’t really need to read this section because CodeBlocks mucks around with the Makefile for you automatically. Life is good. If you want to see how CodeBlocks performs this task, look at the .depend file for your project, such as MultipleSourceFiles.depend. The .depend file is simple XML, so you can view it with any XML-capable application (including Internet Explorer or Firefox). Otherwise, you’ll want to read this section.
To add source-code files to other compilers, you need to modify the Makefile, and you need to understand Makefile rules and the compile rocess. Yuck. (Makefiles are described in Appendix A.) Many ways to modify a Makefile are available. If you use implicit rules, you probably just need to add the name of the file to the list of source files. If you use a separate rule for each file, you need to add another rule for this new file. In that case, you may still have a list of all source-code files or a list of all object files (which are just the source-code filenames with either an .o or .obj extension), in which case you’ll have to make another entry.
For example, you may have separate rules for each source file, as in the following:
main.o: main.cpp
$(CC) -c main.cpp -o main.o $(CFLAGS)
In this case, you need to add another line similar to this one for your new file. If your new file is orangegoo.cpp, your new rule will look like this:
orangegoo.o: orangegoo.cpp
$(CC) -c orangegoo.cpp -o orangegoo.o $(CFLAGS)
Note that you must indent the second line by using a tab. If you use spaces, it may not work properly.
You probably also have a rule listing the object files. Remember that it will likely be the object files and not the source files, because the object files are the temporary things that the compiler generates — or makes. Thus, you may have a macro such as this:
OBJ = main.o orangegoo.o
This macro would be listed in the rule for the final executable file. That way, when you make the executable file, the make utility first sees whether these two .o files are up-to-date. If not, make first makes these two .o files, based on the rules you supplied earlier. Nice and simple; too bad Makefiles are so ugly.
Creating multiple files
Before two source files can work together, they must somehow find out about each other. Just because they’re both sitting on the computer doesn’t mean that they know about each other. Computers are kind of goofy about that sort of thing. So to get two source files to finally open up and get to know each other, you need to tell each of them about what’s in the other file.
When you write a function, normally the function must appear before any calls to it appear within the same source file. That’s because of the way the compiler goes through the code: If it encounters a call to a function but has not yet heard of that function, it issues an error. But the way around this is to use a function prototype. A function prototype is simply the header line from a function, ending with a semicolon, as in the following:
void BigDog(int KibblesCount);
Later in the source file is the actual function, with this header line duplicated. But instead of a semicolon, the function would have an open brace, the function code, and a closing brace, as in the following:
void BigDog(int KibblesCount)
{
cout << “I’m a lucky dog” << endl;
cout << “I have “ << KibblesCount << “ pieces of food” << endl;
}
So after the function prototype, you can call the function whether the function code itself is before or after the call.
For the compiler to understand a function call, all it needs at the point the code makes the call is a function prototype. It’s up to the linker to determine whether that function really exists.
Because the function call only needs a function prototype, you can put the function itself in another source-code file. You could, therefore, have two separate source-code files, as in the following example. The first source-code file, main.cpp, is shown in Listing 5-1. The second source-code file, mystuff.cpp, is shown in Listing 5-2.
Listing 5-1: Calling a Function with Only a Prototype
#include <iostream>
using namespace std;
void BigDog(int KibblesCount);
int main()
{
BigDog(3);
return 0;
}
Listing 5-2: Using a Function from a Separate File
#include <iostream>
using namespace std;
void BigDog(int KibblesCount)
{
cout << “I’m a lucky dog” << endl;
cout << “I have “ << KibblesCount << “ pieces of food” << endl;
}
A quick overview of namespaces
The using namespace std; line in Listing 5-2 tells the compiler to use a specific namespace, std. A namespace is a grouping of classes and functions. The std, or standard, namespace contains a host of useful classes and functions, such as string. If you don’t include this declaration, you need to preface every use of the classes or functions found in std by typing std::<class or function>. For example, to use a string you need to type std::string. Because this is a painful way to write code, you add the using namespace std; line.
In Listings 5-1 and 5-2, we broke the function away from the prototype. When you compile these two files together as a single program (either by pressing F9 in CodeBlocks or by using the methods described in the “Multiple source files in other compilers” section, earlier in this chapter), they all fit together nicely. You can then run the program, and you see this somewhat interesting output:
I’m a lucky dog
I have 3 pieces of food
Notice also that we had to put the same #include lines at the start of the mystuff.cpp file. That’s because mystuff.cpp uses cout, and to use cout, it needs the #include <iostream> line.

Sharing with Header Files

Breaking source code apart into multiple files is easy, but soon you may run into a problem. If you have a function, say, SafeCracker, and this function is extremely useful and is likely to be called many times from within several other source-code files, you would need a prototype for SafeCracker in every file that calls it. The prototype may look like this:
string SafeCracker(int SafeID);
But instead of putting this line in every file that uses the function, we know of an easier way. (We computer people are always looking for the easier way so we can finally retire.) Simply put this line inside its own file, called a header file, and give the filename an .h or an .hpp extension. (It’s your choice which extension you use, because it really doesn’t matter; we usually just go with .h.) For example, we might save the line string SafeCracker (int SafeID); in a file called safestuff.h.
Then, instead of typing the header line at the start of each file that needs the function, you type
#include “safestuff.h”
You would then have three source-code files, which we have shown in Listings 5-3, 5-4, and 5-5. The first is main.cpp, which calls the function. The second is safestuff.h, which contains the function prototype. The third is safestuff.cpp, which contains the actual code for the function whose prototype appears in the header file. Lots of files, but now the code is broken into manageable pieces. Also, make sure that you save all three of these files in the same directory.
Listing 5-3: Including the Header File in the main File
#include <iostream>
#include “safestuff.h”
using namespace std;
int main()
{
cout << “Surprise, surprise!” << endl;
cout << “The combination is (once again)” << endl;
cout << SafeCracker(12) << endl;
return 0;
}
Listing 5-4: Containing the Function Prototype in the Header File
using namespace std;
#ifndef SAFESTUFF_H_INCLUDED
#define SAFESTUFF_H_INCLUDED
string SafeCracker(int SafeID);
#endif // SAFESTUFF_H_INCLUDED
Listing 5-5: Containing the Actual Function Code
#include <iostream>
using namespace std;
string SafeCracker(int SafeID)
{
return “13-26-16”;
}
Before you compile this program, however, we need to give you a couple pointers. First, the compiler does not compile the header file into a separate .o or .obj file. With the program in Listings 5-3 through 5-5, the compiler compiles only two files: main.cpp and mystuff.cpp. Instead of compiling the header file, when it reads through the main.cpp file and gets to the #include line for the header file, it temporarily switches over and reads that file, pretending that it’s still reading the same main.cpp file. As it continues, it compiles everything as if it’s all part of the main.cpp file. And if you include this header file in other source-code files, it does the same thing again for those source files.
To get this code to compile, remember the following rules:
♦ Makefiles: If you are using a compiler where you have to handle your own Makefiles, do not add a rule for compiling the header files, which usually start with .hpp or .h. Only compile the source files, which usually start with .cpp or .cc.
♦ Visual C++: Although we’ve said very little so far about Microsoft Visual C++ (VC++), if you use VC++, do not add header files to your project. Only add source files. VC++ will keep a listing of the header files in a tree called dependencies, but you don’t add them yourself.
♦ CodeBlocks: What could be easier? You just make the files, and CodeBlocks handles all the file connectivity for you. Nothing to worry about. The header and source files all show in the project list, and CodeBlocks also handles the details of which ones need to be compiled.
After you follow these rules, you can go ahead and compile and run the code in Listings 5-3 through 5-5. When you run the program, you see the following output:
Surprise, surprise!
The combination is (once again)
13-26-16
If you have a source file containing some functions, creating a header file that contains the associated function prototypes is generally a good practice. Then you can name the header file the same as the source file, except with a different extension. We did this in Listings 5-4 and 5-5: We named the header file safestuff.h, and the source file safestuff.cpp.
Instead of saying header file, some people prefer to say include file. We usually say header file because, to us, include is usually a verb, and it gets kind of awkward to say something like this: “We’re pretty sure that we included the include file, but if we didn’t include the correct include file, would you please include us in your meeting; and in the discussion, we will be sure to include a few questions about how to include the proper include file. Then you can include an answer to our inclusions about the inclusions of an include file.” It’s just difficult to say, you know? So we say header file.
Adding the header only once
CodeBlocks includes several lines in the header file by default. These lines create a symbol that tells the compiler whether a header file is already included in the source file so that the compiler doesn’t add it twice. Adding a header twice is an error because then you’d define the forward reference for a function twice. Here is what you see when you initially create a header file with CodeBlocks:
#ifndef SAFESTUFF_H_INCLUDED
#define SAFESTUFF_H_INCLUDED
#endif // SAFESTUFF_H_INCLUDED
When you type the header code into CodeBlocks, type it between the #define SAFESTUFF_H_INCLUDED and #endif // SAFESTUFF_H_INCLUDED lines. The “Using the Mysterious Header Wrappers” section of the chapter describes these automatic entries in detail.
Using brackets or quotes
You may have noticed something about the code in Listing 5-3. When we included the safestuff.h file, we did not put it inside brackets as we did in the other #include lines. Instead, we put it inside quotes:
#include “safestuff.h”
That’s because programmers for years have been fighting over the rules of where exactly on the hard drive to put the header files. Do you put them in the same directory or folder as your project? Or do you put them in a special directory all by themselves? Or do you just put them out in the back yard to dry out?
Regardless of where you put your header files, here is the rule for when to use quotes and when to use brackets: The compiler looks in several directories to find include files. And it can, possibly, look in the same directory as the source file. If you use angled brackets (that is, less-than and greater-than signs), as in #include <string>, the compiler does not look in the same directory as the source file. But if you use double quotes, as in #include “safestuff.h”, the compiler first looks in the same directory as the source file. And if the compiler doesn’t find the header file there, it looks in the remaining directories, as it would with angle brackets.
Some people always like to use double quotes. That way, whether the header file is in the same file as the source file or not, the compiler should find it.
Most professional programmers today always use angle brackets. This forces programmers to put their header files in a common area. With really big projects, programmers like to have a directory dedicated to source files and another directory dedicated to header files. No header file is ever in the same directory as the source file.
For small projects, some people like to lump all the source and header files into a single directory. These people typically use angle brackets around system header files (such as #include <string>) and double quotes around their own header files. In the projects in this book, we generally follow this rule. The header files that we write are in the same directory as the source files, and we use double quotes for #include lines of our own files and angle brackets for the #include lines of system headers.
If you follow the same approach that we use here, you immediately know whether the #include line refers to one of your own header files or another header file. If it refers to your own, it has double quotes.
If you start working on a large C++ project, you will probably find that project managers use the rule of always using angle brackets. For large projects, this is typically the best policy.
If you try to compile and you get a No such file or directory error on the #include line, it’s probably because you put the header file in a source file directory but used angle brackets instead of double quotes. Try switching that line to double quotes.

Sharing Variables Among Source Files

When you declare a variable inside a function, it remains local to the function. But you may want functions to share a single variable: One function may store something, and another may read its contents and write it to the console. To do this, declare the variable outside a function. That works until you try to share a variable between multiple source files. If you’re not careful, the source files end up with a separate copy of the variable. Within a single source file, the variable can be shared between functions but not between source files. That could be confusing.
There’s a trick to making this work. Declare the variable inside one and only one of the source files. Then, you declare it again inside one (and only one) header file, but you precede it with the word extern, as in extern int DoubleCheeseburgers;.
Listings 5-6, 5-7, and 5-8 demonstrate the use of a single variable that is shared between multiple source files.
Listing 5-6: Making Use of a Global Variable
#include <iostream>
#include “sharealike.h”
using namespace std;
int main()
{
DoubleCheeseburgers = 20;
EatAtJoes();
return 0;
}
Listing 5-7: Using a Header File to Declare a Global Variable
#ifndef SHAREALIKE_H_INCLUDED
#define SHAREALIKE_H_INCLUDED
extern int DoubleCheeseburgers;
void EatAtJoes();
#endif // SHAREALIKE_H_INCLUDED
Listing 5-8: Declaring the Actual Storage for the Global Variable
#include <iostream>
#include “sharealike.h”
using namespace std;
int DoubleCheeseburgers;
void EatAtJoes() {
cout << “How many cheeseburgers today?” << endl;
cout << DoubleCheeseburgers << endl;
}
Be careful when you do this; getting it exactly right is very tricky. You declare the variable once inside the header file, but you must remember the word extern. That tells the various files, “This variable is declared elsewhere, but here’s its name and type so you can use it.” Then you declare the variable in one of the source files, without the word extern; this creates the actual storage bin for the variable. Finally, you include the header file in each of your source files that use the global variable.
When you share a variable among multiple source files, it is a global variable. A variable used by a single function is called a local variable. If you share a variable between functions within a single source file but not between multiple source files, people call this a global variable or a global variable that is local to the source file.
Use the word extern in your header file when using a global variable. If you forget to do that, you give each source file its own variable that happens to have the same name.

Using the Mysterious Header Wrappers

When you include a header file, you usually only want to include it once per source file. But that can create a problem: Suppose we have a huge software project, and several header files include another of our header files, called superheader.h. If we include all these other header files, how can we be sure to pick up the superheader.h file only once?
The answer looks strange but does the trick. We start each header file with these lines:
#ifndef SHAREALIKE_H
#define SHAREALIKE_H
#endif
Depending on which C++ IDE you use, your editor may add these lines automatically, just as CodeBlocks does. In this case, you type the header file content between the #define SHAREALIKE_H and #endif lines. However, if your IDE doesn’t add the lines automatically, be sure to add them so your code looks like the code in Listing 5-7. Otherwise, the compiler may spout errors that you may not recognize immediately.
These header wrappers, as they are often called, ensure that the code in the header gets processed only once per source-code file each time you compile. The wrappers use special lines called preprocessor directives. Basically, the second line defines something that is sort of like a variable but is used only during compilation; this something is called a symbol. The symbol is called SHAREALIKE_H, and we picked it by taking the filename, making it all caps, and replacing the dot with an underscore.
The first line checks to see whether this symbol has been defined. If not, it proceeds with the lines of code that follow. The next line goes ahead and defines the symbol, so now it’s actually defined for later. Then the compiler does all the rest of the lines in the file. Finally, the last line, #endif, simply finishes the very first line.
Now consider what could happen if you include this same file twice, as in
#include “sharealike.h”
#include “sharealike.h”
(That can happen indirectly if you include two different files that each include sharealike.h.) The second time the compiler goes through sharealike.h, it sees the first line, which checks to see whether the SHAREALIKE_H symbol is defined. But this time it is! So instead of going through all the lines again, the compiler skips to the #endif line at the very end of the file. Thus, your header file gets processed only once per source-code file. Tricky, no? And confusing? Yes, a bit. So remember the following rule.
When you create a header file, be sure to put the header wrappers around it.You can use any symbol name you like, provided it uses only letters, numbers,and underscores and doesn’t start with a number, and provided it’s not already a variable name in your source or a C++ word. But most people base their choice on some variation of the filename itself, such as MYFILE_H or MYFILE_H_ or even _MYFILE_H_.

Chapter 6: Referring to Your Data through Pointers

In This Chapter
Using two types of memory: the stack and heap
Accessing variable addresses through pointers
Creating variables on the heap by using the new keyword
Taking pointers as parameters and returning pointers
Modifying variables the easy way
Where do you live? Don’t say it out loud because thousands of people are reading this book, and you don’t want them all to know. So just think about your address. Most places have some sort of address so the mail service will know where to deliver your packages and the cable guy can show up sometime between now and 5:00 next Thursday. (So make sure that you’re there.)
Other things have addresses too. For example, a big corporation in an office building likely has all its cubes numbered. And offices in buildings usually have numbers; and apartments normally have numbers, too.
Now suppose someone named Sam works in office number 180. Last week, however, Sam got booted out the door for spending too much time surfing the Web. Now Sally gets first dibs on office number 180, even though she’s not taking over Sam’s position. Sam moved out; Sally moved in. Same office — different person staying there.
The computer’s memory works similarly. Every little part of the computer’s memory is associated with a number that represents its location, or address. In this chapter, we show you that after you determine the address of a variable stored in memory, you can do powerful things with it, which gives you the tools to create powerful programs.
If any single topic in C++ programming is most important, it is the notion of pointers. Therefore, if you want to become a millionaire, read this chapter. Okay, so it may not make you a millionaire, but suggesting it could give you the incentive to master this chapter. Then you can become an ace programmer and make lots of money.

Heaping and Stacking the Variables

C++ programs use two kinds of memory: heap and stack. The heap is a common area of memory that your program allocates — that is, sets aside — for the different functions in your program to use. Global variables go in this heap.
Whenever your program calls a function, however, the function gets its own little private area of memory storage in an area of memory known as a stack. The reason that this is called a stack is because it’s treated like a stack of papers: You can put something on the stack, and you can take something off, but you can’t put anything in the middle or take anything from the middle. The computer uses this stack to keep track of all your function calls.
For example, suppose you have a function called GoFishing. The function GoFishing calls StopAndBuyBait, which then calls PayForBait, which calls GetOutCreditCard, which calls UseFakeCreditCard. How can the computer keep track of all this mess? It uses the stack metaphor. First it saves the original function, GoFishing. Then when that function calls StopAndBuyBait, the computer remembers that function by putting it on top of GoFishing — not in the same storage bin, but in one on top of the preceding item so that the preceding item is still there. Then, when that function calls PayForBait, the computer once again remembers that function by putting it on top of StopAndBuyBait, and so on, until it has all the items piled one on top of the other, with UseFakeCreditCard on the top and GoFishing on the bottom. This process pushes items onto the top of the stack.
Next, when the computer is finished with UseFakeCreditCard, it pops off the top of the stack. What it picks up is the place it left off before calling UseFakeCreditCard, which happens to be GetOutCreditCard. And when that function is finished, once again the computer pops the top off the stack to find PayForBait. And, as before, that’s where it left off last. It continues this until it gets all the way back to the beginning, which was GoFishing.
Every position in memory has a number associated with it. When your program starts, the computer sets aside a large chunk of memory and then works closely with the microprocessor itself to assign a bunch of numbers to the memory. Your program’s variables and your program’s code goes in this memory. And consider this: If your program sits in memory, each function sits in a particular place in memory, a place with a number or address associated with it. In other words, each function has an address.
Each function and each variable in your program has a place where it resides in memory. That place has a number associated with it. Therefore, each function and each variable has an address.
Placing a hex on C++
Sooner or later in your computer programming, you will encounter a strange way of notating numbers on the computer. This strange way is called hexadecimal, or sometimes just hex. In C++, you can recognize a hex number because it starts with the characters 0x. These characters aren’t actually part of the number; they just notate it in the same way double quotes denote a string. Whereas our usual decimal numbers consist of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9, a hex number consists of these digits plus six more: A, B, C, D, E, and F. That makes a total of 16 digits. (Yes, we know, the letters A through F are not digits. But in hex, they are considered digits.) A good way to picture counting with regular decimal numbers is by using the odometer in a car, which (if you’re honest) only goes forward, not backward. It starts out with 00000000 (assuming eight digits, which is a lot). The rightmost digit runs from 0 through 9, over and over. When any digit reaches 9 and all digits to the right of that are nine, the next digit to the left goes up by 1. For example, when you reach 00000999, the next digit to the left goes up by 1 as each 9 goes back to 0, to get 00001000.
With hex numbers, you count this same way, except instead of stopping at 9 to loop back, you then go to A, then B, and then up to F. And then you loop back. So the first 17 hex numbers are, using eight digits, 00000000, 00000001, 00000002, 00000003, 00000004, 00000005, 00000006, 00000007, 00000008, 00000009, 0000000A, 0000000B, 0000000C, 0000000D, 0000000E, 0000000F, 00000010. Notice when we hit F toward the end there, we wrapped around again, adding 1 to the next digit to the left. When working with hex numbers, you may see such numbers as 0xAAAA0000 and 0X0000A3FF. (We included the 0x for C++ notation.) And incidentally, 1 more than each of these is 0xAAAA0001 and 0x0000A400.
The stack where the computer keeps track of the function calls is just a bunch of memory, too. What the computer considers the top of the stack is really the next position in memory. And the way the computer puts a function on the stack is by putting on the stack the address of where the computer left off in the preceding function.
When the computer calls one of your functions, not only does it save the address of the return location on the stack, it also reserves some space on the stack for your local variables.
This means that your variables can live in two places:
Heap: The heap is a common area in memory where you can store global variables.
Stack: The stack is the area where the computer stores both the information about the functions being called and the local variables for those functions.
A stack is an example of all sorts of wonderful things called data structures. Computer programmers have a tendency to try to model things from real life on the computer. A stack of papers apparently wasn’t good enough for the computer folk; they wanted to be able to do the same type of thing with their data in the computer, and they called this thing a stack. They have come up with many types of data structures, including a similar one called a queue: With a queue, you put data in one end and take it out the other. It’s like putting sheets of paper on top but taking them only from the bottom. You experience a queue when you wait in line at a store. The people are forming a queue, and some even call a line of people a queue.
Every hex number has a decimal equivalent. When you make a list showing decimal numbers side by side with hex numbers, you see, for example, that 0x0000001F is next to the decimal number 31. Thus, these two numbers represent the same quantity of items, such as apples. Remember that when you want to buy some apples: “I would like to buy one-ef apples.”
Looks can be deceiving. The hex number 10 represents the same number of apples as the decimal number 16. That’s why it’s a good idea to use the 0x notation. Thus instead of hex 10, we would write 0x10, making it clear that we’re not talking about a decimal number.
Converting between hexadecimal and decimal
If you want to convert between hex and decimal, you can use the calculator program that comes with Windows. However, you need to make sure it’s running in scientific mode. To turn on this mode, choose View⇒Scientific (if it’s not already chosen). When you do, you will see the calculator magically transform into a much bigger, more powerful calculator.
To convert a hex number to decimal, click the Hex option in the upper left. Then type the hex number by using the number keys and the letters A through F, such as FB1263. (You don’t need to type the zeros at the beginning, such as 00FB1263 — they won’t show up — nor do you type the 0x used in C++.) After you finish typing it all in, click the Dec option, which is next to the Hex option. The calculator instantly transforms this beautiful hex thing into an equally beautiful thing — a decimal number! In this case, you see 16454243. You can go the other way, too: If you have a decimal number, such as 16454243, you can click the Hex option to convert it to hex. If you convert 16454243 to hex, you get back FB1263, which is what you started with.
You can convert words, too (if you’re bored). The hex number and disco group ABBA is 43962 in decimal. And the hex number FADE is 64222. And Jeff’s house, which he calls hex number FACADE, is 16435934. Have fun!
You can represent hex numbers by using either uppercase or lowercase letters. However, do not mix cases within a single number. Don’t use 0xABab0000. Instead use either 0xabab0000 or 0xABAB0000.
Getting a variable’s address
Because every variable lives somewhere in memory, every variable has an address. If you have a function that declares an integer variable called NumberOfPotholes, then when your program calls this function, the computer will allocate space for NumberOfPotholes somewhere in memory.
If you want to take the address of (which is computerspeak for find the address of) the variable NumberOfPotholes, you simply throw an ampersand, &, in front of it.
Listing 6-1 shows an example of taking the address of a variable and printing it.
Listing 6-1: Using the & Character to Take the Address of a Variable
#include <iostream>
using namespace std;
int main()
{
int NumberOfPotholes = 532587;
cout << &NumberOfPotholes << endl;
return 0;
}
When you run this program, a hexadecimal number appears on the console. This may or may not match ours, and it may or may not be the same each time you run the program. The result depends on exactly how the computer allocated your variable for you and the order in which it did things. This could be very different between versions of compilers. When we run Listing 6-1, we see
0x22ff74
The output you see from this program is the address of the variable called NumberOfPotholes. In other words, that number is the hex version of the place where the NumberOfPotholes variable is stored in memory. The output is not the contents of the variable or the contents of the variable converted to hex; rather, it’s the address of the variable converted to hex.
A pointer example
Suppose NumberOfPotholes contains the number 5000. That means the computer stores the number 5000 somewhere in memory. When you take the address of NumberOf Potholes, you are taking the address of the memory where you can find the number 5000.
And so, when you set
ptr = &NumberOfPotholes;
ptr points to a memory location that contains the number 5000.
That output is not very useful, unless you want to sound like a computer techie. You could walk around announcing that the variable lives at 0x22ff74, but that’s not going to get you very far in life. (It may get you some interesting looks, though, which may be worth it.) But when you take that address, you can use it for other purposes. For example, you can use it to modify the variable itself by using what are called pointer variables. A pointer variable is just like any other variable except that it stores the address of another variable.
To declare a pointer variable, you need to specify the type of variable it will point to. Then you precede the variable’s name with an asterisk, as in the following:
int *ptr;
This declares a variable that points to an integer. In other words, it can contain the address of an integer variable. And how do you grab the address of an integer variable? Easy! By using the & notation! Thus, you can do something like this:
ptr = &NumberOfPotholes;
This puts the address of the variable NumberOfPotholes in the ptr variable. Remember that ptr doesn’t hold the number of potholes; rather, it holds the address of the variable called NumberofPotholes.
You specify the type of a pointer by the type of item it points to. If a pointer variable points to an integer, its type is pointer to integer. In C++ notation, its type is int * (with a space between them) or int* (no space); you are allowed to enter it with or without a space. If a pointer variable points to a string, then its type is pointer to string, and notation for this type is string *.
The ptr variable holds an address, but what’s at that address? That address is the location in memory of the storage bin known as NumberOfPotholes. Right at that spot in memory is the data stored in NumberOfPotholes.
Think this pointer concept through carefully. If you have to, read this section over a few times until it’s in your head. Then meditate on it. Wake up in the night thinking about it. Call strangers on the telephone and chitchat about it. But the more you understand pointers, the better off your programming career will be — and the more likely you will make a million dollars.
Changing a variable by using a pointer
After you have a pointer variable holding another variable’s address, you can use the pointer to access the information in the other variable. That means that we have two ways to get to the information in a variable: We can use the variable name itself (such as NumberOfPotholes) or we can use the pointer variable that points to it.
If we want to store the number 6087 in NumberOfPotholes, we could do this:
NumberOfPotholes = 6087;
Or we could use the pointer. To use the pointer, we first declare it as follows.
ptr = &NumberOfPotholes;
Then, to change NumberOfPotholes, we don’t just assign a value to it. Instead, we throw an asterisk in front of it, like so:
*ptr = 6087;
If ptr points to NumberOfPotholes, these two lines of code will have the same effect: Both will change the value to 6087. This process of sticking the asterisk before a pointer variable is called dereferencing the pointer. By the time you’re finished with this book, you will know gobs of words that nobody else does. (And your newly enriched vocabulary makes talking on the telephone difficult at first.)
Take a look at Listing 6-2, which demonstrates all this.
Listing 6-2: Modifying the Original Variable with a Pointer Variable
#include <iostream>
using namespace std;
int main()
{
int NumberOfPotholes;
int *ptr;
ptr = &NumberOfPotholes;
*ptr = 6087;
cout << NumberOfPotholes << endl;
return 0;
}
In Listing 6-2, the first line declares an integer variable, while the second line declares a pointer to an integer. The next line takes the address of the integer variable and stores it in the pointer. Then the fourth line modifies the original integer by dereferencing the pointer. And just to make sure that the process really worked, the next line prints the value of NumberOfPotholes. When you run the program, you will see the following output:
6087
This is correct; it is the value that the program stored in the original variable by using the pointer variable.
You can also read value of the original variable through the pointer. Take a look at Listing 6-3. This code accesses the value of NumberOfPotholes through the pointer variable, ptr. When the code gets the value, it saves it in another variable called SaveForLater.
Listing 6-3: Accessing a Value through a Pointer
#include <iostream>
using namespace std;
int main()
{
int NumberOfPotholes;
int *ptr = &NumberOfPotholes;
int SaveForLater;
*ptr = 6087;
SaveForLater = *ptr;
cout << SaveForLater << endl;
*ptr = 7000;
cout << *ptr << endl;
cout << SaveForLater << endl;
return 0;
}
When you run this program, you see the following output.
6087
7000
6087
Notice also in this listing that we changed the value through ptr again, this time to 7000. When we run the program, you can see that the value did indeed change, but the value in SaveForLater remained the same. That’s because SaveForLater is a separate variable and is not connected to the other two. The other two, however, are connected to each other.
Pointing at a string
Pointer variables enjoy pointing. Pointer variables can point to any type, including strings. However, after you say that a variable points to a certain type, it can only point to that type. That is, like any variable, you cannot change its type out from underneath it. The compiler won’t let you do it.
To create a pointer to a string, you simply make the type of the variable string *. You can then set it equal to the address of a string variable. Listing 6-4 demonstrates this.
Listing 6-4: Pointing to a String with Pointers
#include <iostream>
using namespace std;
int main()
{
string GoodMovie;
string *ptrToString;
GoodMovie = “Best in Show”;
ptrToString = &GoodMovie;
cout << *ptrToString << endl;
return 0;
}
In Listing 6-4, you can see that the pointer variable called ptrToString points to the variable called GoodMovie. But when you want to use the pointer to access the string itself, you need to dereference the pointer by putting an asterisk, *, in front of it.
When you run this code, you see the results of the dereferenced pointer, which is the value of the GoodMovie variable:
Best in Show
You can change the value of the string through the pointer, again by dereferencing it, as in the following code:
*ptrToString = “Galaxy Quest”;
cout << GoodMovie << endl;
Here, we dereferenced the pointer to set it equal to the string “Galaxy Quest” (a fine movie, we might add). Then to show that it really changed, we printed the variable itself, GoodMovie. The result of this code, when added at the end of Listing 6-4 (but prior to the return 0) is
Galaxy Quest
You can also use the pointer to access the individual parts of the string, as we did in Listing 6-5.
Listing 6-5: Using Pointers to Point to a String
#include <iostream>
using namespace std;
int main()
{
string HorribleMovie;
string *ptrToString;
HorribleMovie = “L.A. Confidential”;
ptrToString = &HorribleMovie;
for (unsigned i = 0; i < HorribleMovie.length(); i++)
{
cout << (*ptrToString)[i] << “ “;
}
cout << endl;
return 0;
}
When you run this program, you see the letters of the terrible movie appear one with spaces between them, as in the following.
L . A . C o n f i d e n t i a l
Okay, so we didn’t like L.A. Confidential. But it won two Oscars and was nominated for seven more, and it won a boatload of other awards, so we don’t feel so bad saying so.
When you access the characters of the string through a pointer, you need to put parentheses around the asterisk and the pointer variable. Otherwise, the compiler gets confused and first tries to do the index in brackets with the variable name and afterwards applies the asterisk. That’s backwards, and it won’t make sense to the computer, so the compiler gives you an error message. But you can make it all better by using parentheses, as we did in Listing 6-5.
This program loops through the entire string, character by character. We used the length function for the string to find out how many characters are in the string. And inside the loop we grabbed the individual characters of the string, printing them with a space after each.
Notice that i is of type unsigned, rather than int. The length function returns an unsigned value, rather than an int value. If you try to use an int for i, the compiler will display the following warning:
warning: comparison between signed and unsigned integer
It’s important to use the correct data types for loop variables. Otherwise, when the loop value increases over the amount that the loop variable can support, the application will fail. Trying to find such an error can prove frustrating even for the best developers.
You can also change the individual characters in a string through a pointer. You can do this by using a line like (*ptrToString)[5] = ‘X’;. Notice, as before, that we had to put parentheses around the variable name along with the dereferencing (that is, the asterisk) character.
The length of a string is also available through the pointer. You can call the length function by dereferencing the pointer, again with the carefully placed parentheses, such as in the following:
for (unsigned i = 0; i < (*ptrToString).length(); i++)
{
cout << (*ptrToString)[i] << “ “;
}
Pointing to something else
When you create a pointer variable, you must specify what type of data it points to. After that, you cannot change the type of data it points to, but you can change what it points to. For example, if you have a pointer to an integer, you make it point to the integer variable called ExpensiveComputer. Then, later, in the same program, you can make it point to the integer variable called CheapComputer. We demonstrate this in Listing 6-6.
Listing 6-6: Using Pointers to Point to Something Else and Back Again
#include <iostream>
using namespace std;
int main()
{
int ExpensiveComputer;
int CheapComputer;
int *ptrToComp;
ptrToComp = &ExpensiveComputer;
*ptrToComp = 2000;
cout << *ptrToComp << endl;
ptrToComp = &CheapComputer;
*ptrToComp = 500;
This code starts out by initializing all the goodies involved — two integers and a pointer to an integer.
Next, the code points the pointer to ExpensiveComputer and uses the pointer to put something inside ExpensiveComputer. It then writes the contents of ExpensiveComputer, again by using the pointer.
Then the code changes what the pointer points to. To do this, we set the pointer to the address of a different variable, &CheapComputers. Pretty simple. And the next line stores 500 in whatever the pointer points to. But that’s CheapComputers. And again we print it.
Now just to drive the point home in case the computer isn’t listening, we then point the pointer back to the original variable, ExpensiveComputer. But we don’t store anything in it. This time we just print what’s already inside this high-powered supermachine. We do this again by dereferencing the pointer. And when we run the program, we see that ExpensiveComputer still has 2000 in it, which is what we originally put in it. That means that after we pointed the pointer to something else and did some finagling, the original variable remained unchanged. That’s a good thing, considering that nobody was pointing at it and it was just being left alone, totally ignored in a world all by itself, feeling neglected.
Be careful if you use one pointer to bounce around several different variables. It’s easy to lose track of which variable the pointer is pointing to.
Tips on pointer variables
Here are some pretty good tips on using pointer variables.
You can declare two pointer variables of the same type by putting them together in a single statement, as you can with regular variables. However, you must precede each one with an asterisk, as in the following line.
int *ptrOne, *ptrTwo;
If you try to declare multiple pointers on a single line but put an asterisk only before the first pointer, only that one will be a pointer. The rest will not be. This can cause serious headaches and muscle spasms later because this line will compile fine. The following line is just such an example:
int *ptrOne, Confused;
Here, Confused is not a pointer to an integer; rather, it’s just an integer. So beware!
Some people like to put the asterisk right after the type, as in the following, to emphasize the fact that the type is pointer to integer.
int* ptrOne;
However, we prefer not to do that simply because it makes it easy for a forgetful persons like ourselves to not remember that any variables that follow, separated by a comma, need their own asterisks if they are to be pointers.
When we declare a pointer variable, we usually start its name with the letters ptr, which is an abbreviation for pointer. That way, we immediately know (when we’re looking at our code) that it’s a pointer variable. That makes life a little easier sometimes, at least in the sanity areas of life.

Dynamically Allocating with new

The heap is a special place where you can declare storage. However, to use this storage, you take a different approach from just declaring a variable.
When you create a variable, you go through the process of actually typing a variable, giving it a type, a name, and (sooner or later) a value. When you write the code, that’s when you decide that you want a variable. However, you can also write code that can cause the computer to allocate space only after it’s running. The computer allocates this space on the heap. This process is called dynamic allocation.
Using new
To declare a storage bin on the heap, first you need to set up a variable that will help you keep track of the storage bin. This variable must be a pointer variable.
For example, suppose you already have an integer declared out on the heap somewhere. (We show you how to do that in the next paragraph.) We won’t give it a name, because such variables don’t have names. Just think of it as an integer on the heap. Then, with the integer variable, you could have a second variable. This second variable is not on the heap, and it’s a pointer holding the address of the integer variable. So if you want to access the integer variable, you do so by dereferencing the pointer variable.
To allocate memory on the heap, you need to do two things: First, declare a pointer variable. Second, call a function called new. The new function is a little different from other functions in that you don’t put parentheses around its parameter. For this reason, it’s actually considered to be an operator. Other operators are + and - for adding and subtracting integers. These other operators behave similar to functions, but you don’t use parentheses.
To use the new function, you specify the type of variable you want to create. For example, the following line creates a new integer variable:
int *somewhere = new int;
After the computer creates the new integer variable on the heap, it stores the address of the integer variable in the somewhere variable. And that makes sense: The somewhere variable is a pointer to an integer. Thus, it holds the address of an integer variable. Listing 6-7 demonstrates this.
Listing 6-7: Allocating Memory by Using new
#include <iostream>
using namespace std;
int main()
{
int *ptr = new int;
*ptr = 10;
cout << *ptr << endl;
return 0;
}
When you run this program, you see the sweet and simple output:
10
In this program, we first allocated a pointer variable, which we called ptr. Then we called new with an int type, which returns a pointer to an integer. We saved that return value in the ptr variable.
Then we started doing our magic on it. Okay, so it’s not all that magical, but we saved a 10 in the thing that ptr points to. And then we printed the value stored in the thing that ptr points to.
But what exactly is the thing that ptr points to, and why does it fancy itself so important as to justify italics? It’s the memory that was allocated by the new operator. Think of it as a variable out there somewhere. But unlike regular variables, this variable doesn’t have a name. And because it doesn’t have a name, the only way you can access it is through the pointer. It’s kind of like an anonymous author with a publicist. If you want to send fan mail to the author, you have to go through the publicist. Here, the only way to reach this unnamed but famous variable is through the pointer.
But this doesn’t mean that the variable has a secret name such as BlueCheese and that, if you dig deep enough, you might discover it; it just means that the variable has no name. Sorry.
When you call new, you get back a pointer. This pointer is of the type that you specify in your call to new. You can then store the pointer only in a pointer variable of the same type.
When you use the new operator, the usual terminology is that you are allocating memory on the heap.
Now at this point, you may be asking the all-important question: Why? Why would we go through the trouble of creating an integer variable somewhere out on the heap, a variable that has no name, if we just have to create a second variable to point to it? Doesn’t that seem counterproductive?
The answer is this: You can take advantage of many features if you allocate your variables on the heap. You can use pointers along with something called an array. An array is simply a large storage bin that has multiple slots, each of which holds one item. And if you set up an array that holds pointers, you can store away all these pointers without having to name them individually. And these pointers can point to complex things, called objects. (We cover objects in Minibook I, Chapter 7, and arrays in Minibook I, Chapter 8.) And then if you want to, for example, pass all these variables (which could be quite large, if they’re strings) to a function, you need to pass only the array, not the strings themselves. That step saves memory on the stack.
In addition to objects and arrays, you can also have a function create and return a variable. Then, when you get the variable back from the function, you can use it, and when you are finished with the variable, delete it. Finally, you can pass a pointer into a function. When you do so, the function can actually modify the pointer for you. See “Passing Pointer Variables to Functions” and “Returning Pointer Variables from Functions,” later in this chapter.
Using an initializer
When you call new, you can provide an initial value for the memory you are allocating. For example, if you are allocating a new integer, you can, in one swoop, also store the number 10 in the integer.
Listing 6-8 demonstrates this.
Listing 6-8: Putting a Value in Parentheses to Initialize Memory That You Allocate
#include <iostream>
using namespace std;
int main()
{
int *ptr = new int(10);
cout << *ptr << endl;
return 0;
}
In this code, we called new, but we also put a number in parentheses. That number will get put in the memory initially. This line of code is equivalent to the following two lines of code:
int *ptr = new int;
*ptr = 10;
When you initialize a value in the new operator, the technical phrase for what you are doing is invoking a constructor. The reason is that the compiler adds a bunch of code to your program, code that operates behind the scenes. This code is called the runtime library. The library includes a function that initializes an integer variable if you pass an initial value. The function that does this is known as a constructor. When you run it, you are invoking it. Thus, you are invoking the constructor. For more information on constructors, see Minibook I, Chapter 7.
Making new strings
You can use new to allocate almost any type, including strings. You simply type new followed by string.
You cannot allocate one special type with new. If a function has no return, you specify the return type as void. You cannot use new to allocate a void type. For that matter, you also cannot create a variable of type void. The compiler won’t let you do it.
Listing 6-9 is an example of calling new for a string. As usual, remember the include line for <string>.
Listing 6-9: Using the new Operator with Strings
#include <iostream>
using namespace std;
int main()
{
string *Password = new string;
*Password = “The egg salad is not fresh.”;
cout << *Password << endl;
return 0;
}
This code allocates a new string by using the new keyword and saves the results in the Password variable. Next, it stores an interesting commentary in the newly allocated string by dereferencing the pointer. Finally, it prints the commentary, again by dereferencing the pointer. Remember, the string variable itself is off in the heap somewhere and has no name. And if it’s going to make comments like those heard at a fine restaurant, it’s probably best that it remain nameless.
When you store a string of characters in a string variable that you allocated by using new, you are storing the string in the allocated memory, not in the pointer variable. The pointer variable still holds the address of the allocated memory. The pointer is just the publicist for the memory, handling all its deals and transactions for it, whether ethical or not.
When you are working with strings, you can use a shortcut to the somewhat cumbersome method of putting parentheses around the name preceded by an asterisk in order to call the various string functions. (That was even hard to type!) Instead of typing (*Password).length(), for example, you can use a shortcut notation that looks like the following line of code. (The characters after Password are a minus sign and then a greater than sign, which together resemble an arrow.)
cout << Password->length() << endl;
You can initialize a string by using parentheses when you call new for a string type. To do this, simply put the string in quotes and then in parentheses after the word string, as in the following line of code:
string *Password = new string(“The egg salad is still not fresh.”);
This line of code is equivalent to the first two lines of code inside main in Listing 6-9, shown previously.
Even though the pointer points to a string, the pointer itself still holds a number (in particular, the address of the string it’s pointing to). This is a number, but do not confuse it with an integer. However, you can do some basic arithmetic with pointers, as detailed in Minibook I, Chapter 8.

Freeing Pointers

When you allocate memory on the heap by calling the new function and you’re finished using the memory, you need to let the computer know, whether it’s just a little bit of memory or a lot. The computer doesn’t look ahead into your code to find out if you’re still going to use the memory. So in your code, when you are finished with the memory, you free the memory.
The way you free the memory is by calling the delete function and passing the name of the pointer:
delete MyPointer;
This line would appear after you’re finished using a pointer that you allocated by using new. (Like the new operator, delete is also an operator and does not require parentheses around the parameter.)
Listing 6-10 shows a complete example that allocates a pointer, uses it, and then frees it.
Listing 6-10: Using delete to Clean Up Your Pointers
#include <iostream>
using namespace std;
int main()
{
string *phrase = new string(“All presidents are cool!!!”);
cout << *phrase << endl;
(*phrase)[20] = ‘r’;
phrase->replace(22, 4, “oked”);
cout << *phrase << endl;
delete phrase;
return 0;
}
When you run this program, you see the following output:
All presidents are cool!!!
All presidents are crooked
In this code, we first allocated a new string and initialized it, saving its address in the pointer variable called phrase. Then we wrote the phrase, manipulated it (providing some editorial content), and then wrote it again. Finally, we freed the memory used by the phrase.
Although people usually say that you’re deleting the pointer or freeing the pointer, really you’re freeing the memory that the pointer points to. The pointer can still be used for subsequent new operations. Nevertheless, we will abide by tradition and use these phrases.
You can actually get away with not freeing your pointers because the computer frees all the memory used by your program when it ends. That way, your memory is available to all the other cool programs you want to run. However, getting into the habit of freeing your pointers when you are finished using them is a good practice; otherwise, you may use all the memory allotted for the heap while your program is running. And some big software systems at big companies run on and on, shutting down maybe once a week or every two weeks. If one part of the program continues to refuse to free its data, eventually the heap probably fills and the whole program shuts down.
If you free a pointer, the memory it points to is now free. However, immediately after the call to delete, the pointer still points to that particular memory location, even though it’s no longer being used. Therefore, do not try to use the pointer after that until you set it to point to something else through a call to new or by setting it to another variable.
Whenever you free a pointer, a good habit is to set the pointer to the value 0. (Some people set it to the value null, but that’s the same thing, and 0 is guaranteed to work on all compilers.) Then, whenever you use a pointer, first check whether it’s equal to 0 and only use it if it’s not 0. This always works because the computer will never allocate memory for you at address 0. So the number 0 can be reserved to mean I point to nothing at all.
The following code sample shows this. First, this code frees the pointer and then clears it by setting it to 0:
delete ptrToSomething;
ptrToSomething = 0;
This code checks if the pointer is not 0 before using it:
ptrToComp = new int;
*ptrToComp = 10;
if (ptrToComp != 0)
{
cout << *ptrToComp << endl;
}
Only call delete on memory that you allocated by using new. Although the free compiler that ships with this book doesn’t seem to complain when you delete a pointer that points to a regular variable, it serves no purpose to do so. You can free only memory on the heap, not local variables on the stack.

Passing Pointer Variables to Functions

One of the most important uses for pointers is this: If they point to a variable, you can pass the pointer to a function, and the function can modify the original variable. This lets you write functions that can actually modify the variables passed to them.
Changing variable values with pointers
Normally, when you call a function and you pass a few variables to the function, the computer just grabs the values out of the variables and passes those values. Take a close look at Listing 6-11.
Listing 6-11: A Function Cannot Change the Original Variables Passed into It
#include <iostream>
using namespace std;
void ChangesAreGood(int myparam)
{
myparam += 10;
cout << “Inside the function:” << endl;
cout << myparam << endl;
}
int main()
{
int mynumber = 30;
cout << “Before the function:” << endl;
cout << mynumber << endl;
ChangesAreGood(mynumber);
cout << “After the function:” << endl;
cout << mynumber << endl;
return 0;
}
Listing 6-11 includes a function called ChangesAreGood that modifies the parameter it receives. (It adds 10 to its parameter called myparam.) It then prints the new value of the parameter.
The main function initializes an integer variable, mynumber, to 30 and prints its value. It then calls the ChangesAreGood function, which changes its parameter. After coming back from the ChangesAreGood function, main prints the value again.
When you run this program, you see the following output:
Before the function:
30
Inside the function:
40
After the function:
30
Before the function call, mynumber is 30. And after the function call, it’s still 30. But the function added 10 to its parameter. This means that when the function modified its parameter, the original variable remained untouched. The two are separate entities. Only the value 30 went into the function. The actual variable did not. It stayed in main.
That keeps mean and nasty functions from messing things up in the outside world. But what if you write a function that you want to modify the original variable?
A pointer contains a number, which represents the address of a variable. If you pass this address into a function and the function stores that address into one of its own variables, its own variable also points to the same variable that the original pointer did. Make sense? The pointer variable in main and the pointer variable in the function both point to the same variable because both pointers hold the same address.
That’s how you let a function modify data in a variable: You pass a pointer. But when you call a function, the process is easy, because you don’t need to make a pointer variable. Instead, you can just call the function, putting an & in front of the variable. Then, you are not passing the variable or its value — instead, you are passing the address of the variable.
Listing 6-12 is a modified form of Listing 6-11; this time the function actually manages to modify the original variable.
Listing 6-12: Using Pointers to Modify a Variable Passed into a Function
#include <iostream>
using namespace std;
void ChangesAreGood(int *myparam)
{
(*myparam) += 10;
cout << “Inside the function:” << endl;
cout << (*myparam) << endl;
}
int main()
{
int mynumber = 30;
cout << “Before the function:” << endl;
cout << mynumber << endl;
ChangesAreGood(&mynumber);
cout << “After the function:” << endl;
cout << mynumber << endl;
return 0;
}
When you run this program, you see the following output:
Before the function:
30
Inside the function:
40
After the function:
40
Notice the important difference between this and the output from Listing 6-11: The final line of output is 40, not 30. The variable was modified by the function!
To understand how this happened, first look at main. The only difference we had to make to main was a little one: We threw an ampersand, &, in front of the mynumber argument in the call to ChangesAreGood. That’s it: Instead of passing the value stored in mynumber, we passed the address of mynumber.
Now the function has some major changes. We rewrote the function header so it takes a pointer rather than a number. We did this by adding an asterisk, *,so the parameter is a pointer variable. This pointer receives the address being passed into it. Thus, it points to the variable mynumber. Therefore, any modifications we make by dereferencing the pointer will attack the original variable. And attack it, it does: It changes it! The following line changes the original variable. Excellent!
(*myparam) += 10;
When you pass a pointer to a function, you are still passing a number. In Listing 6-11, you are passing to the function the value stored in mynumber. In Listing 6-12, you aren’t somehow passing the variable itself. Instead, you are passing the value of mynumber’s address. The value is still a number either way. However, in Listing 6-12, because the number is an address now, we had to modify the function header so it expects an address, not just a number. To do that, we used a pointer variable because it is a storage bin that holds an address. Then we had to modify the remainder of the function to make use of the pointer, instead of a number.
The ChangesAreGood function in Listing 6-12 no longer modifies its own parameter. The parameter starts holding the address of the original mynumber variable, and that never changes. Throughout the function, the pointer variable myparam holds the mynumber address. And any changes the function performs are on the dereferenced variable, which is mynumber. The pointer variable does not change.
Modifying string parameters
Modifying a string parameter is just as easy as modifying an integer variable. But with string variables, you have the added benefit that if you’re working with pointers, you can use the shortcut -> notation.
Listing 6-13 is an example of a function that modifies the original string variable that is passed into it. The function expects a pointer to a string. Inside, the function uses the -> notation to access the string functions. Then the function returns. main creates a string, initializes it, prints the string’s value, calls the function, and prints the value again. As you see when you run the program, the value of the string has changed.
Listing 6-13: Using a Function to Modify a String Passed into It by Using Pointers
#include <iostream>
using namespace std;
void Paranoid(string *realmessage)
{
(*realmessage)[6] = ‘i’;
realmessage->replace(9, 1, “”);
realmessage->insert(18, “ad”);
realmessage->replace(15, 2, “in”);
realmessage->replace(23, 7, “!”);
realmessage->replace(4, 3, “ali”);
}
int main()
{
string message = “The friends are having dinner”;
cout << message << endl;
Paranoid(&message);
cout << message << endl;
return 0;
}
In Listing 6-13, we chose to not make the message<