`
`C++ DEMYSTIF~E~
`
`~
`
`_:
`~
`
`N
`
`Q ~ ~' ~ ~ p
`Q+ ^ ~ ~ N U
`
`Facebook's Exhibit No. 1010 - Page 1
`
`
`
`~Ji~l
`
`~-
`
`D
`
`No formal training ~
`in C++ needed!
`
`Create and run your own
`computer programs
`
`~
`
`Many examples illustrating
`application of concepts
`
`~
`
`~ z:
`
`,_
`
`Complete with chapter-ending
`quizzes and final exam
`Je f f Ken t
`
`Osborne
`
`Facebook's Exhibit No. 1010 - Page 2
`
`
`
`TX 6-017-150
`IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
`
`~TX000601715pa
`
`IIIIIIIIIIIIIIII
`
`_
`
`„ .
`
`_
`
`_
`
`. .
`
`,s
`
`_ .._._
`
`.;
`
`C++ DEMYSTIFIED
`
`JEFF KENT
`..
`
`McGraw-HilUOsborne
`New York Chicago San Francisco Lisbon London
`Madrid Mexico City Milan New Delhi San Juan
`Seoul Singapore Sydney Toronto
`
`Y~
`
`i'r
`
`Facebook's Exhibit No. 1010 - Page 3
`
`
`
`The MCGI'Ow~Hill Companies
`
`McGraw-HilUOsborne
`2100 Powell Street, 10th Floor
`Emeryville, California 94608
`U.5.A.
`
`To arrange bulk purchase discounts for sales promotions, premiums, or fund-raisers, please con-
`tactMcGraw-HilllOsborne atthe above address. For information on translations or book distrib-
`utors outside the U.S.A., please see the International Contact Information page immediately
`following the index of this book.
`
`C++Demystified
`
`~~, .
`
`Copyright D 2004 by The McGraw-Hill Companies. All rights reserved. Printed in the United
`States of America. Except as permitted under the Copyright Act of 1976, no part of this publica-
`tion may be reproduced or distributed in any form or by any means, or stored in a database or re-
`trieval system, without the prior written permission of publisher, with the exception that the
`program listings may be entered, stored, and executed in a computer system, but they may not be
`reproduced for publication.
`
`~
`
`. '
`
`~~~~
`
`1234567890 FGR FGR 01987654
`
`ISBN 0-07-225370-3
`
`Publisher
`Brandon A. Nordin
`Vice President &Associate Publisher
`Scott Rogers
`Editorial Director
`Wendy Rinaldi
`Project Editor
`Lisa Wolters-Broder
`Acquisitions Coordinator
`Athena Honore
`Technical Editor
`Jim Keogh
`Copy Editor
`Mike McGee
`
`~~
`
`)r
`nc
`
`. ,
`
`3
`~
`
`d ~
`~ ~
`r '
`
`~ .
`
`eM
`
`° 73Gl~3k~~~
`
`a d C?
`
`CO~~/ o~.
`J
`
`Proofreader
`Susie Elkind
`Indexer
`Iry Hershman
`Composition
`Apollo Publishing Services, Lucie Ericksen
`Illustrators
`Kathleen Edwards, Melinda Lytle
`Cover Series Design
`Margaret Webster-Shapiro
`Cover Illustration
`Lance Lekander
`
`This book was composed with Corel VENTURA'~ Publisher.
`
`~~~~~`J~~~~~
`
`Information has been obtained by McGraw-Hill/Osbome from sources believed to be reliable. However, because ofthe possibility
`ofhuman or mechanical error by our sources, McGraw-HiIVOsborne, or others, McGraw-HilUOsborne does not guazantee the ac-
`curacy,adequacy, orcompleteness ofany information and is not responsible for any errors or omissions or the results obtained from
`the use of such information.
`
`Facebook's Exhibit No. 1010 - Page 4
`
`
`
`CONTENTS AT A GLANCE
`
`IN rya:y?y
`
`o~
`
`~
`
`S,
`
`-
`
`:r i f f
`a '!
`.e `i'
`
`n t
`
`°Y
`
`h~~
`
`.~Cb~
`
`CHAPTER 1
`CHAPTER 2
`CHAPTER 3
`CHAPTER 4
`CHAPTER 5
`CHAPTER 6
`CHAPTER 7
`CHAPTER 8
`CHAPTER 9
`CHAPTER 10
`CHAPTER 11
`CHAPTER 12
`
`CHAPTER 13
`CHAPTER 14
`
`How a C++ Program Works
`Memory and Data Types
`Variables
`Arithmetic Operators
`Making Decisions: if and switch Statements
`Nested if Statements and Logical Operators
`The For Loop
`While and Do While Loops
`Functions
`Arrays
`What's the Address? Pointers
`Character, C-String, and C++ String
`Class Functions
`Persistent Data: File Input and Output
`The Road Ahead: Structures and Classes
`Final Exam
`Answers to Quizzes and Final Exam
`Index
`
`1
`21
`45
`65
`83
`109
`125
`143
`161
`187
`213
`
`243
`269
`293
`317
`323
`339
`
`~~-`r'
`
`~~i
`
`Facebook's Exhibit No. 1010 - Page 5
`
`
`
`ABOUT
`
`AUTH 0 R
`
`~ ,
`
`Jeff Kent is an Associate Professor of Computer Science at Los Angeles Valley Col-
`lege in Valley Glen, California. He teaches a number of programming languages, in-
`cluding Visual Basic, C++, Java and, when he's feeling masochistic, Assembler, but
`mostly he teaches C++. He also manages a network for a Los Angeles law firm
`whose employees are guinea pigs for his applications, and as an attorney gives
`advice to young attorneys whether they want it or not. He also has written several
`books on computer programming, including the recent Visual Basic.NET A Begin-
`ner's Guide for McGraw-Hill/Osborne.
`Jeffhas had a varied career—or careers. He graduated from UCLA with a Bache-
`for of Science degree in economics, then obtained a Juris Doctor degree from Loyola
`(Los Angeles) School of Law, and went on to practice law. During this time, when
`personal computers still were a gleam in Bill Gates's eye, Jeff was also a profes-
`sional chess master, earning athird-place finish in the United States Under-21
`Championship and, later, an international title.
`' Jeff does find time to spend with his wife, Devvie, which is not difficult since she
`also is a computer science professor at Valley College. He also acts as personal
`chauffeur for his teenaged daughter, Emily (his older daughter, Elise, now has her
`~ own driver's license) and in his remaining spare time enjoys watching international
`chess tournaments on the Internet. His goal is to resume running marathons, since
`otherwise, given his losing battle to lose weight, his next book maybe Sumo Wres-
`tling Demystified.
`
`C
`
`I would like to dedicate this book to my wife, Dewie Schneider Kent. There is not
`room here to describe how she has helped me in my personal and pYofessional life,
`though I do mention several ways in the Acknowledgments. She also has been my
`computer programming teacher in more ways than one; I wouldn't be writing this
`and other computer programming books if it wasn't for her.
`
`Jeff Kent
`
`Facebook's Exhibit No. 1010 - Page 6
`
`
`
`CONTENTS
`
`CHAPTER 1
`
`Acknowledgments &Introduction
`How a C++ Program Works
`What Is a Computer Program?
`What Is a Programming Language?
`Anatomy of a C++ Program
`The main Function
`The Function Body
`tout
`The return 0 Statement
`The #include Directive
`Namespace
`Translating the Code for the Computer
`Preprocessor
`Compiler
`Linker
`Using an IDE to Create and Run the
`"Hello World!" Project
`Setting Up the "Hello World!" Project
`Writing the Source Code
`Building the Project
`Running the Code
`
`Quiz
`
`xiii
`1
`2
`2
`3
`5
`5
`5
`6
`6
`7
`7
`8
`8
`8
`
`9
`10
`13
`17
`19
`20
`
`O
`
`Facebook's Exhibit No. 1010 - Page 7
`
`
`
`~:. vi
`
`CH~~'TER 2
`
`i ~A~T~R 3
`
`C++ Demystified
`
`Memory and Data Types
`Memory
`Types of Memory
`Addresses
`Bits and Bytes
`Binary Numbering System
`Converting Between Decimal
`and Binary or Hexadecimal
`Data Types
`Whole Number Data Types
`Floating-Point Data Types
`Text Data Types
`The boot Data Type
`Project: Determining the Size of Data Types
`The sizeof Operator
`Changing the Source File of Your Project
`Code and Output
`Expressions
`Outputting an Expression
`Escape Sequences
`
`Quiz
`Variables
`Declaring Variables
`Syntax of Declaring Variables
`Declaring Multiple Variables of the Same
`Data Type
`Naming the Variable
`Naming Conventions
`The Address Operator
`Using the Address and sizeof Operators
`with Variables
`
`21
`22
`22
`24
`25
`26
`
`26
`28
`28
`32
`35
`36
`36
`37
`37
`40
`41
`41
`42
`43
`45
`45
`46
`
`47
`48
`49
`49
`
`Facebook's Exhibit No. 1010 - Page 8
`
`
`
`CONTENTS
`
`CHAPTER 4
`
`CHAPTER 5
`
`~~
`
`Assigning Values to Variables
`Assignment Operator
`Using the cin Object
`
`Quiz
`Arithmetic Operators
`Arithmetic Operators
`The Addition Operator
`The Subtraction Operator
`The Multiplication Operator
`Division Operators
`Exponents
`The Change Machine Project
`Program Description
`The Code
`The Algorithm
`
`Quiz
`Making Decisions: if and switch Statements
`Relational Operators
`Relational Expressions
`Precedence
`Flowcharting
`The if Statement
`Indenting
`Common Mistakes
`The if /else Statement
`Conditional Operator
`Common Mistakes
`The if /else if /else Statement
`The switch Statement
`Differences Between switch
`and if /else if /else Statements
`
`Quiz
`
`51
`52
`56
`63
`65
`66
`67
`70
`71
`73
`76
`77
`78
`78
`79
`81
`83
`84
`85
`86
`87
`89
`91
`91
`94
`94
`96
`98
`100
`
`103
`108
`
`Facebook's Exhibit No. 1010 - Page 9
`
`
`
`CHAPTER 6
`
`CHAPTER 7
`
`CHAPTERS
`
`C++ Demystified
`
`Nested if Statements and Logical Operators
`Nested if Statements
`Testing if Both Boolean Expressions
`Are True
`Testing if Either Boolean Expression
`Is True
`Logical Operators
`The && Operator
`The ~ ~ Operator
`The !Operator
`Precedence
`Using the switch Statement with
`Logical Operators
`Quiz
`The For Loop
`Increment and Decrement Operators
`The Increment Operator
`The Decrement Operator
`The Difference Between Prefix
`and Postfix
`The For Loop
`The Syntax of the For Loop
`Beware the Infinite Loop
`A Factorial Example
`Breaking Out of a Loop
`The Continue Keyword
`Nesting For Loops
`
`Quiz
`While and Do While Loops
`The While Loop
`Comparison of for and while Loops
`Using the break Keyword
`
`109
`110
`
`110
`
`113
`115
`115
`117
`119
`120
`
`122
`124
`125
`126
`126
`127
`
`128
`130
`132
`134
`135
`135
`138
`139
`142
`143
`144
`146
`147
`
`Facebook's Exhibit No. 1010 - Page 10
`
`
`
`CONTENTS
`
`CHAPTER 9
`
`CHAPTER 1Q
`
`Flags
`While (true)
`The continue Keyword
`Nesting While Loops
`The Do While Loop
`Syntax
`A Do While Loop Example
`Comparison of the Do While and
`While Loop
`Scope
`
`Quiz
`Functions
`Defining and Calling a Function
`Terminology of a Function
`Defining a Function
`Calling a Function
`Prototyping
`Variable Scope and Lifetime
`Local Variables
`Global Variables
`Static Local Variables
`Sending Information to a Function
`Passing Arguments by Value
`Passing Arguments by Reference
`Returning a Value from a Function
`Quiz
`Arrays
`Declaring an Array
`Constants
`Array Index
`Initialization
`Explicit Array Sizing
`
`~~
`
`148
`151
`152
`154
`154
`155
`155
`
`156
`157
`159
`161
`162
`162
`163
`164
`165
`167
`167
`169
`171
`173
`174
`178
`182
`185
`187
`188
`189
`193
`194
`195
`
`Facebook's Exhibit No. 1010 - Page 11
`
`
`
`CHAPTER 11
`
`C++ Demystified
`
`Implicit Array Sizing
`Initializing a Character Array
`Constant Arrays
`When to Use Initialization
`Assigning and Displaying Array Values
`Using the cin and cout Objects
`with Arrays
`The cin Object's getline Function
`Passing Arrays as Function Arguments
`Quiz
`What's the Address? Pointers
`Declari ng a Poi nter
`Syntax of a Pointer Declaration
`The Meaning of Pointer Data Types
`Assigning a Value to a Pointer
`Why You Should Not Try to Use
`an Unassigned Pointer
`Null Pointers
`Assigning a Pointer the Address of
`a Variable or Constant
`Indirection Operator and Dereferencing
`The Pointer as a Variable or a Constant
`Pointer as a Variable
`The Array Name as a Constant Pointer
`Pointer Arithmetic
`Using a Variable Pointer to Point to
`an Array
`Incrementing a Pointer
`Comparing Addresses
`Decrementing a Pointer
`Pointers as Function Arguments
`Passing an Array Using Pointer Notation
`
`196
`196
`198
`199
`199
`
`202
`205
`208
`211
`213
`214
`214
`215
`216
`
`216
`217
`
`218
`219
`220
`221
`221
`222
`
`222
`224
`225
`227
`228
`228
`
`Facebook's Exhibit No. 1010 - Page 12
`
`
`
`CONTENTS
`
`~~:
```-
`
`Passing a Single Variable Using
`Pointer Notation
`Dynamic Memory Allocation
`Returning Pointers from Functions
`Returning a Pointer to a Local Variable
`(Not a Good Idea)
`Returning a Pointer to a Static
`Local Variable
`Returning a Pointer to a
`Dynamically Created Variable
`
`Quiz
`Character, C-String, and C++ String
`Class Functions
`Reading a Character
`The "Press Any Key to Continue" Problem
`Combining Use of cin, cin.get,
`and cin.get(ine
`Rules to Live By
`Useful Character Functions
`Case Conversion Functions
`Functions that Check the Value of
`a Character
`Useful C-String and C++ String Functions
`Determining the Length of a String
`Assigning a Value to a String
`Appending to a String
`Comparing Two Strings
`Conversion Between a C-String and
`a Number
`
`Quiz
`Persistent Data: File Input and Output
`Text vs. Binary Files
`The fstream Standard Library
`
`230
`233
`236
`
`236
`
`237
`
`238
`241
`
`243
`244
`245
`
`252
`255
`256
`256
`
`258
`259
`259
`260
`261
`262
`
`264
`268
`269
`270
`271
`
`CHAPTER 12
`
`CHAPTER 13
`
`Facebook's Exhibit No. 1010 - Page 13
`
`
`
`xii
`
`C++ Demystified
`
`CHAPTER 14
`
`The File Access Life Cycle
`Opening a File
`Opening a File for Writing
`Opening a File for Reading
`Opening a File for Reading and Writing
`Checking if the File Was Opened
`Closing a File
`Writing to a File
`Reading from a File
`Reading a Line of a File
`Looping Through the File
`File Stream Objects as Function Arguments
`Quiz
`The Road Ahead: Structures and Classes
`Your Reasons for Reading This Book?
`Object-Oriented Programming
`Structures
`Declaring a Structure
`Declaring a Structure Variable
`Accessing Structure Member Variables
`Initializing a Structure
`Passing Structures as Function
`Arguments
`Nesting Structures
`Classes
`Quiz
`Final Exam
`Answers to Quizzes and Finat Exam
`
`Index
`
`272
`272
`272
`276
`277
`278
`280
`280
`282
`283
`285
`287
`291
`293
`294
`294
`296
`296
`297
`298
`300
`
`305
`307
`309
`316
`317
`323
`
`339'
`
`Facebook's Exhibit No. 1010 - Page 14
`
`
`
`ACKNOWLEDGMENTS
`It seems obligatory in acknowledgments for authors to thank their publishers (espe-
`cially ifthey want to write for them again), but I really mean it. This is my fourth book
`for McGraw-HilUOsborne, and I hope there will be many more. It truly is a pleasure to
`work with professionals who are nice people as well as very good at what they do
`(even when what they are good at is keeping accuxate track of the deadlines I miss).
`I first want to thank Wendy Rinaldi, who got me started with McGraw-HiIU
`Osborne back in 1998 (has it been that long?). Wendy was also my first Acquisitions
`Editor. Indeed, I got started on this book through a telephone call with Wendy at the
`end of a vacation with my wife, Dewie, who, being in earshot, and with an "are you
`insane" tone in her voice, asked incredulously, "You're writing another book?"
`I also must thank my Acquisitions Coordinator, Athena Honore, and my Project Edi-
`tor, Lisa Wolters-Broder. Both were unfailingly helpful and patient, while still keeping
`me on track in this deadline-sensitive business (e.g., "I'm so sorry you broke both your
`arms and legs; you'll still have the next chapter turned in by this Friday, right?").
`Mike McGee did the copyediting, together with Lisa. They were kind about my
`obvious failure during my school days to pay attention to my grammar lessons. They
`improved what I wrote while still keeping it in my words (that way, if something is
`wrong, it is still my fault). Mike also indicated he liked some of my stale jokes,
`which makes him a friend for life.
`Jim Keogh was my technical editor. Jim and I had a balance of terror going be-
`tween us, in that while he was tech editing this book, I was tech editing two books on
`which he was the main author, Data StructuNes Demystified and OOP Demystified.
`Seriously, Jim's suggestions were quite helpful and added value to this book.
`There are a lot of other talented people behind the scenes who also helped get this
`book out to press, but, as in an Academy Awards speech, I can't list them all. That
`doesn't mean I don't appreciate all their hard work, because I do.
`I truly thank my wife Dewie, who in addition to being my wife, best friend
`(maybe my only one), and partner (I'm leaving out lover because computer pro-
`grammersaren't supposed to be interested in such things), also was my personal tech
`
`X111
`
`Facebook's Exhibit No. 1010 - Page 15
`
`
`
`xiv
`
`C++ Demystified
`
`editor. She iswell-qualified for that task, since she has been a computer science pro-
`fessor for 15 years, and also is a stickler for correct English (yes, I know, you can't
`modify the word "unique"). She made this a much better book.
`Finally, I would like to give thanks to my daughters, Elise and Emily, and my
`mom, Bea Kent, for tolerating me when I excused myself from family gatherings,
`muttering to myself about unreasonable chapter deadlines and merciless editors
`(sorry, Athena and Lisa). I also should thank my family in advance for not having me
`committed when I talk about writing my next book.
`
`INTRODUCTION
`C++was my first programming language. While I've since learned others, I've al-
`ways thought C++ was the "best" programming language, perhaps because of the
`power it gives the programmer. Of course, this power is adouble-edged sword, being
`also the power to hang yourself if you are not careful. Nonetheless, C++has always
`been my favorite programming language.
`C++also has been the first choice of others, not just in the business world because
`of its power, but also in academia. Additionally, many other programming lan-
`guages, including Java and C#, are based on C++. Indeed, the Java programming
`language was written using C++. Therefore, knowing C++_also makes learning
`other programming languages easier.
`
`Why Did I Write this Book?
`Not as a road to riches, fame, or beautiful women. I may be misguided, but I'm not
`completely delusional.
`To be sure, there are many introductory level books on C++. Nevertheless, I wrote
`this book because I believe I bring a different and, I hope, valuable perspective.
`As you may know from my author biography, I teach computer science at Los An-
`geles Valley College, a community college in the San Fernando Valley area of Los
`Angeles, where I grew up and have lived most of my life. I also write computer pro-
`grams, but teaching programming has provided me with insights into how students
`learn that I could never obtain from writing programs. These insights are gained not
`just from answering student questions during lectures. I spend hours each week in
`our college's computer lab helping students with their programs, and more hours
`each week reviewing and grading their assignments. Patterns emerge regarding
`which teaching methods work and which don't, the order in which to introduce
`programming topics, the level of difficulty at which to introduce a new topic, and so
`
`Facebook's Exhibit No. 1010 - Page 16
`
`
`
`CONTENTS
`
`xv
`
`on. I joke with my students that they are my beta testers in mynever-ending attempt
`to become a better teacher, but, there is much truth in that j oke.
`Additionally, my beta testers... err, students, seem to complain about the text-
`book no matter which book I adopt. Many ask me why I don't write a book they
`coulduse to learn C++. They may be saying this to flatter me (I'm not saying it does-
`n'twork), or for the more sinister reason that they will be able to blame the teacher
`fox a poor book as well as poor instruction. Nevertheless, having written other
`books, these questions planted in my mind the idea of writing a book that, in addition
`to being sold to the general public, also could be used as a supplement to a textbook.
`
`Who Should Read this Book
`Anyone who will pay for it! Just kidding, though no buyers will be turned away.
`It is hardly news that publishers and authors want the largest possible audience for
`their books. Therefore, this section of the introduction usually tells you this book is
`for you whoever you may be and whatever you do. However, no programming book
`is for everyone. For example, if you exclusively create game programs using Java,
`this book may not be for you (though being a community college teacher I may be
`your next customer if you create a space beasts vs. community college administra-
`tors game).
`While this book is, of course, not for everyone, it very well maybe for you. Many
`people need or want to learn C++, either as part of a degree program, j ob training, or
`even as a hobby. C++ is not the easiest subject to learn, and unfortunately many
`books don't make learning C++ any easier, throwing at you a veritable telephone
`book of complexity and jargon. By contrast, this book, as its title suggests, is de-
`signed to "demystify" C++. Therefore, it goes straight to the core concepts and ex-
`plains them in a logical order and in plain English.
`
`What this Book Covers
`I strongly believe that the best way to learn programming is to write programs. The
`concepts covered by the chapters are illustrated by clearly and thoroughly explained
`code. You can run this code yourself, or use the code as the basis for writing further
`programs that expand on the covered concepts.
`Chapter 1 gets you started. This chapter answers questions such as what is a com-
`puter program and what is a programming language. It then discusses the anatomy
`of a basic C++program, including both the code you see and what happens "under
`the hood," explaining how the preprocessor, compiler, and linker work together
`to translate your code into instructions the computer can understand. Finally, the
`
`Facebook's Exhibit No. 1010 - Page 17
`
`
`
`xvi
`
`C++ Demystified
`
`chapter tells-you how to use an integrated development environment (IDE) to create
`and run a project.
`Being able to create and run a program that outputs "Hello World!" as in Chapter 1 is
`a good start. However, most programs require the storing of information of different
`types, such as numeric and text. Chapter 2 first explains the different types of computer
`memory, including random access memory, or RAM. The chapter then discusses ad-
`dresses, which identify where data is stored in RAM, and bytes, the unit of value for the
`amount of space required to store information. Because information comes in different
`forms, this chapter next discusses the different data. types for whole numbers, floating
`point numbers and text.
`The featured star of Chapter 3 is the variable, which not only reserves the amount
`of memory necessary to store information, but also provides you with a name by
`which that information later may be retrieved. Because the purpose of a variable is to
`store a value, a variable without an assigned value is as pointless as a bank account
`without money. Therefore, this chapter explains how to assign a value to a variable,
`either at compile time using the assignment operator or at run time using the cin ob-
`j ect and the stream extraction operator.
`As a former professional chess player, I have marveled at the ability of chess com-
`puters toplay world champions on even terms. The reason the chess computers have
`this ability is because they can calculate far more quickly and accurately than we
`can. Chapter 4 covers arithmetic operators, which we use in code to harness the com-
`puter's calculating ability.
`As programs become more sophisticated, they often branch in two or more direc-
`tions based on whether a condition is true or false. For example, while a calculator
`program would use the arithmetic operators you learned about in Chapter 4, your
`program first would need to determine whether the user chose addition, subtraction,
`multiplication, or division before performing the indicated arithmetic operation.
`Chapters 5 and 6 introduce relational and logical operators, which are useful in de-
`termining auser's choice, and the if and switch statements, used to direct the path the
`code will follow based on the user's choice.
`When you were a child, your parents may have told you not to repeat yourself.
`However, sometimes your code needs to repeat itself. For example, if an application
`user enters invalid data, your code may continue to ask the user whether they want to
`retry or quit until the user either enters valid data or quits. The primary subject of
`Chapters 7 and 8 are loops, which are used to repeat code execution until a condition
`is no longer true. Chapter 7 starts with the for loop, and also introduces the increment
`and decrement operators, which are very useful when working with loops. Chapter 8
`completes the discussion of loops with the while and do while loops.
`Chapter 9 is about functions. A function is a block of one or more code state-
`ments. All of your C++code that executes is written within functions. This chapter
`
`Facebook's Exhibit No. 1010 - Page 18
`
`
`
`CpNTENTS
`
`xvii
`
`will explain why and how you should write your own functions. It first explains how
`to prototype and define a function, and then how to call the function. This chapter
`also explains how you use arguments to pass information from the calling function
`to a called function and a return value to pass information back from the called func-
`tion to a calling function. Passing by value and by reference also are explained and
`distinguished. This chapter winds up explaining variable scope and lifetime, and
`both explaining and distinguishing local, static, and global variables.
`Chapter 10 is about arrays. Unlike the variables covered previously in the book,
`which may hold only one value at a time, arrays may hold multiple values at one time.
`Additionally, arrays work very well with loops, which are covered in Chapters 7 and 8.
`This chapter also distinguishes character arrays from arrays of other data types.
`Finally, this chapter covers constants, which are similar to variables, but differ in that
`their initial value never changes while the program is running.
`Chapter 11 is about pointers. The term pointers often strikes fear in the heart of a
`C++student, but it shouldn't. As you learned back in Chapters 2 and 3, information
`is stored at addresses in memory. Pointers simply provide you with an efficient
`way to access those addresses. You also will learn in this chapter about the indirec-
`tion operator and dereferencing as well as pointer arithmetic.
`Most information, including user input, is in the form of character, C-string, and
`C++string class data types. Chapter 12 shows you functions that are useful in work-
`ing with these data types, including member functions of the cin object.
`Information is stored in files so it will be available after the program ends. Chap-
`ter 13 teaches you about the file stream obj ects, fstream, afstream, and ofstream, and
`how to use them and their member functions to open, read, write and close files.
`Finally, to provide you with a strong basis to go to the next step after this introduc-
`torylevel book, Chapter 14 introduces you to OOP, Object-Oriented Programming,
`and two programming concepts heavily used in OOP, structures and classes.
`A Quiz follows each chapter. Each quiz helps you confirm that you have absorbed
`the basics of the chapter. Unlike quizzes you took in school, you also have an an-
`swers appendix.
`Similarly, this book concludes with a Final Exam in the first appendix, and the an-
`swers to that also found in the second appendix.
`
`How to Read this Book
`I have organized this book to be read from beginning to end. While this may seem
`patently obvious, my students often express legitimate frustration about books (or
`teachers) that, in discussing a programming concept, mention other concepts that
`are covered several chapters later or, even worse, not at all. Therefore, I have endeav-
`ored topresent the material in a linear, logical progression. This not only avoids the
`
`Facebook's Exhibit No. 1010 - Page 19
`
`
`
`vii'
`
`C++ Demystified
`
`frustration of material that is out of order, but also enables you in each succeeding
`chapter to build on the skills you learned in the preceding chapters.
`
`Special Features
`Throughout each chapter are Notes, Tips, and Cautions, as well as detailed code list-
`ings. To provide you with additional opportunities to review, there is a Quiz at the
`end of each chapter and a Final Exam (found in the first appendix) at the end of this
`book. Answers to both are contained in the following appendix.
`The overall objective is to get you up to speed quickly, without a lot of dry theory
`or unnecessary detail. So let's get started. It's easy and fun to write C++programs.
`
`Contacting the Author
`Hmmin... it depends why. Just kidding. While I always welcome gushing praise and
`shameless flattery, comments, suggestions, and yes, even criticism also can be valu-
`able. The best way to contact me isvia e-mail; you can use jkent@genghiskhent.com
`(the domain name is based on my students' fond nickname for me). Alternately, you
`can visit my web site, http://www.genghiskhent.com/. Don't be thrown offby the en-
`trypage; Iuse this site primarily to support the online classes and online components
`of other classes that I teach at the college, but there will be a link to the section that sup-
`ports this book.
`I hope you enjoy this book as much as I enjoyed writing it.
`
`Facebook's Exhibit No. 1010 - Page 20
`
`
`
``"' .
`
`~~
`
`ro ram or s
`
`You probably interact with computer programs many times during an average day.
`When you arrive at work and find out your computer doesn't work, you call tech sup-
`port. At the other end of the telephone line, a computer program forces you to navi-
`gate a voicemail menu maze and then tortures you while you are on perpetual hold
`with repeated insincere messages about how important your call is, along with false
`promises about how soon you will get through.
`When you're finally done with tech support, you decide to take a break and log on
`o your now-working computer to do battle with giant alien insects from the planet
`egazoid. Unfortunately, the network administrator catches you goofing offusing yet
`other computer program which monitors employee computer usage. Assuming you
`still employed, an accounts payable program then generates your payroll check.
`n your way home, you decide you need some cash and stop at an ATM, where a
``_ ` com„uter program confirnis (hopefully) you have enough money in your bank account
`and then instructs the machine to dispense the requested cash and (unfortunately)
`deducts that same amount from your account.
`Tr
`
`3
`
`O
`
`,~
`
`~ ~
`
`Facebook's Exhibit No. 1010 - Page 21
`
`
`
`~~~
`
`C++ Demystified
`
`Most people, when they interact with computers as part of their daily routine,
`don't need to consider what a computer program is or how it works. However, a com-
`puter programmer should. know the answers to these and related questions, such as
`what is a programming language, and how does a C++ program actually work?
`When you have completed this chapter, you will know the answers to these ques-
`tions, and also understand how to create and run your own computer program.
`
`What Is a Computer Program?
`
`Computers are so widespread in our society because they have three advantages over
`us humans. First, computers can store huge amounts of information. Second, they
`can recall that information quickly and accurately. Third, computers can perform
`calculations with lightning speed and perfect accuracy.
`The advantages that computers have over us even extend to thinking sports like
`chess. In 1997, the computer Deep Blue beat the world chess champion, Garry
`Kasparov, in a chess match. In 2003, Kasparov was out for revenge against another
`computer, Deep Junior, but only drew the match. Kasparov, while perhaps the best
`chess player ever, is only human, and therefore no match for the computer's ability
`to calculate and remember prior games.
`However, we have one very significant advantage over computers. We think on our
`own, while computers don't, at least not yet anyway. Indeed, computers fundamen-
`tallyare far more brawn than brain. A computer cannot do anything without step-by-
`step instructions from us telling it what to do. These instructions are called a computer
`program, and of course are written by a human, namely a computer programmer.
`Computer programs enable us to harness the computer's tremendous power.
`
`What Is a Programming Language?
`
`When you enter a darkened room and want to see what is inside, you turn on a light
`switch. When you leave the room, you turn the light switch off.
`The first computers were not too different than that light switch. These early com-
`putersconsisted ofwires and switches in which the electrical current followed a path
`dependent on which switches were in the on (one) or off (zero) position. Indeed, I
`built such a simple computer when I was a kid (which according to my own children
`was back when dinosaurs still ruled the earth).
`
`Facebook's Exhibit No. 1010 - Page 22
`
`
`
`CHAPTER 1 How a C++ Program Works
`
`Q~
`
`Each switch's position could be expressed as a number:l for the on position, 0 for
`the off position. Thus, the instructions given to these first computers, in the form
`of the switches' positions, essentially were a series of ones and zeroes.
`Today's computers, of course, are far more powerful and sophisticated than these
`early computers. However, the language that computers understand, called machine
`language, remains the same, essentially ones and zeroes.
`While computers think in ones and zeroes, the humans who write computer pro-
`grams usually don't. Additionally, a complex program may consist of thousands or
`even millions of step-by-step machine language instructions, which would require
`an inordinately long amount of time to write. This is an important consideration
`since, due to competitive market forces, the amount of time within which a program
`has to be written is becoming increasingly less and less.
`Fortunately, we do not have to write instructions to computers in machine lan-
`guage.Instead, wecan write instructions in a programming language. Programming
`languages are far more understandable to programmers than machine language be-
`causeprogramming languages resemble the structure and syntax of human language,
`not ones and zeroes. Additionally, code can be written much faster with programming
`languages than machine language because programming languages automat