You are on page 1of 95

Day 1

Getting Started Introduction A Brief History of C++ Programs Solving Problems Procedural, Structured, and b!ect" riented Programming C++ and b!ect" riented Programming Ho# C++ $volved %&e A'SI Standard S&ould I (earn C )irst* Pre+aring to Program ,our Develo+ment $nvironment Com+iling t&e Source Code Creating an $-ecutable )ile #it& t&e (in.er %&e Develo+ment Cycle )igure 1/1/ H$(( /CPP,our )irst C++ Program (isting 1/1/ H$(( /CPP, t&e Hello 0orld +rogram/ Com+ile $rrors (isting 1/1/ Demonstration of com+iler error/ Summary 23A 0or.s&o+ 2ui4 $-ercises

Day 1 Getting Started


Introduction
0elcome to %eac& ,ourself C++ in 11 Days5 %oday you #ill get started on your #ay to becoming a +roficient C++ +rogrammer/ ,ou6ll learn

0&y C++ is t&e emerging standard in soft#are develo+ment/ %&e ste+s to develo+ a C++ +rogram/

Ho# to enter, com+ile, and lin. your first #or.ing C++ +rogram/

A Brief History of C++


Com+uter languages &ave undergone dramatic evolution since t&e first electronic com+uters #ere built to assist in telemetry calculations during 0orld 0ar II/ $arly on, +rogrammers #or.ed #it& t&e most +rimitive com+uter instructions7 mac&ine language/ %&ese instructions #ere re+resented by long strings of ones and 4eroes/ Soon, assemblers #ere invented to ma+ mac&ine instructions to &uman"readable and "manageable mnemonics, suc& as ADD and MOV/ In time, &ig&er"level languages evolved, suc& as BASIC and C B (/ %&ese languages let +eo+le #or. #it& somet&ing a++ro-imating #ords and sentences, suc& as Let I = 100/ %&ese instructions #ere translated bac. into mac&ine language by inter+reters and com+ilers/ An inter+reter translates a +rogram as it reads it, turning t&e +rogram instructions, or code, directly into actions/ A com+iler translates t&e code into an intermediary form/ %&is ste+ is called com+iling, and +roduces an ob!ect file/ %&e com+iler t&en invo.es a lin.er, #&ic& turns t&e ob!ect file into an e-ecutable +rogram/ Because inter+reters read t&e code as it is #ritten and e-ecute t&e code on t&e s+ot, inter+reters are easy for t&e +rogrammer to #or. #it&/ Com+ilers, &o#ever, introduce t&e e-tra ste+s of com+iling and lin.ing t&e code, #&ic& is inconvenient/ Com+ilers +roduce a +rogram t&at is very fast eac& time it is run/ Ho#ever, t&e time"consuming tas. of translating t&e source code into mac&ine language &as already been accom+lis&ed/ Anot&er advantage of many com+iled languages li.e C++ is t&at you can distribute t&e e-ecutable +rogram to +eo+le #&o don6t &ave t&e com+iler/ 0it& an inter+retive language, you must &ave t&e language to run t&e +rogram/ )or many years, t&e +rinci+le goal of com+uter +rogrammers #as to #rite s&ort +ieces of code t&at #ould e-ecute 8uic.ly/ %&e +rogram needed to be small, because memory #as e-+ensive, and it needed to be fast, because +rocessing +o#er #as also e-+ensive/ As com+uters &ave become smaller, c&ea+er, and faster, and as t&e cost of memory &as fallen, t&ese +riorities &ave c&anged/ %oday t&e cost of a +rogrammer6s time far out#eig&s t&e cost of most of t&e com+uters in use by businesses/ 0ell"#ritten, easy"to" maintain code is at a +remium/ $asy" to"maintain means t&at as business re8uirements c&ange, t&e +rogram can be e-tended and en&anced #it&out great e-+ense/

Programs
%&e #ord +rogram is used in t#o #ays7 to describe individual instructions, or source code, created by t&e +rogrammer, and to describe an entire +iece of e-ecutable soft#are/ %&is distinction can cause enormous confusion, so #e #ill try to distinguis& bet#een t&e source code on one &and, and t&e e-ecutable on t&e ot&er/

New Term: A program can be defined as eit&er a set of #ritten instructions created by a +rogrammer or an e-ecutable +iece of soft#are/ Source code can be turned into an e-ecutable +rogram in t#o #ays7 Inter+reters translate t&e source code into com+uter instructions, and t&e com+uter acts on t&ose instructions immediately/ Alternatively, com+ilers translate source code into a +rogram, #&ic& you can run at a later time/ 0&ile inter+reters are easier to #or. #it&, most serious +rogramming is done #it& com+ilers because com+iled code runs muc& faster/ C++ is a com+iled language/

So !ing Pro" ems


%&e +roblems +rogrammers are as.ed to solve &ave been c&anging/ %#enty years ago, +rograms #ere created to manage large amounts of ra# data/ %&e +eo+le #riting t&e code and t&e +eo+le using t&e +rogram #ere all com+uter +rofessionals/ %oday, com+uters are in use by far more +eo+le, and most .no# very little about &o# com+uters and +rograms #or./ Com+uters are tools used by +eo+le #&o are more interested in solving t&eir business +roblems t&an struggling #it& t&e com+uter/ Ironically, in order to become easier to use for t&is ne# audience, +rograms &ave become far more so+&isticated/ Gone are t&e days #&en users ty+ed in cry+tic commands at esoteric +rom+ts, only to see a stream of ra# data/ %oday6s +rograms use so+&isticated 9user"friendly interfaces,9 involving multi+le #indo#s, menus, dialog bo-es, and t&e myriad of meta+&ors #it& #&ic& #e6ve all become familiar/ %&e +rograms #ritten to su++ort t&is ne# a++roac& are far more com+le- t&an t&ose #ritten !ust ten years ago/ As +rogramming re8uirements &ave c&anged, bot& languages and t&e tec&ni8ues used for #riting +rograms &ave evolved/ 0&ile t&e com+lete &istory is fascinating, t&is boo. #ill focus on t&e transformation from +rocedural +rogramming to ob!ect"oriented +rogramming/ Procedura # Structured# and $"%ect&$riented Programming :ntil recently, +rograms #ere t&oug&t of as a series of +rocedures t&at acted u+on data/ A +rocedure, or function, is a set of s+ecific instructions e-ecuted one after t&e ot&er/ %&e data #as 8uite se+arate from t&e +rocedures, and t&e tric. in +rogramming #as to .ee+ trac. of #&ic& functions called #&ic& ot&er functions, and #&at data #as c&anged/ %o ma.e sense of t&is +otentially confusing situation, structured +rogramming #as created/ %&e +rinci+le idea be&ind structured +rogramming is as sim+le as t&e idea of divide and con8uer/ A com+uter +rogram can be t&oug&t of as consisting of a set of tas.s/ Any tas. t&at is too com+le- to be described sim+ly #ould be bro.en do#n into a set of smaller com+onent tas.s, until t&e tas.s #ere sufficiently small and self"contained enoug& t&at t&ey #ere easily understood/

As an e-am+le, com+uting t&e average salary of every em+loyee of a com+any is a rat&er com+le- tas./ ,ou can, &o#ever, brea. it do#n into t&ese subtas.s7 1' )ind out #&at eac& +erson earns/ (' Count &o# many +eo+le you &ave/ )' %otal all t&e salaries/ *' Divide t&e total by t&e number of +eo+le you &ave/ %otaling t&e salaries can be bro.en do#n into 1' Get eac& em+loyee6s record/ (' Access t&e salary/ )' Add t&e salary to t&e running total/ *' Get t&e ne-t em+loyee6s record/ In turn, obtaining eac& em+loyee6s record can be bro.en do#n into 1' +en t&e file of em+loyees/ (' Go to t&e correct record/ )' ;ead t&e data from dis./ Structured +rogramming remains an enormously successful a++roac& for dealing #it& com+le- +roblems/ By t&e late 1<=>s, &o#ever, some of t&e deficiencies of structured +rograming &ad became all too clear/ )irst, it is natural to t&in. of your data ?em+loyee records, for e-am+le@ and #&at you can do #it& your data ?sort, edit, and so on@ as related ideas/ Second, +rogrammers found t&emselves constantly reinventing ne# solutions to old +roblems/ %&is is often called 9reinventing t&e #&eel,9 and is t&e o++osite of reusability/ %&e idea be&ind reusability is to build com+onents t&at &ave .no#n +ro+erties, and t&en to be able to +lug t&em into your +rogram as you need t&em/ %&is is modeled after t&e &ard#are #orld""#&en an engineer needs a ne# transistor, s&e doesn6t usually invent one, s&e goes to t&e big bin of transistors and finds one t&at #or.s t&e #ay s&e needs it to, or +er&a+s modifies it/ %&ere #as no similar o+tion for a soft#are engineer/ New Term: %&e #ay #e are no# using com+uters""#it& menus and buttons and #indo#s""fosters a more interactive, event"driven a++roac& to com+uter

+rogramming/ Event-driven means t&at an event &a++ens""t&e user +resses a button or c&ooses from a menu""and t&e +rogram must res+ond/ Programs are becoming increasingly interactive, and it &as became im+ortant to design for t&at .ind of functionality/ ld"fas&ioned +rograms forced t&e user to +roceed ste+"by"ste+ t&roug& a series of screens/ Aodern event"driven +rograms +resent all t&e c&oices at once and res+ond to t&e user6s actions/ b!ect"oriented +rogramming attem+ts to res+ond to t&ese needs, +roviding tec&ni8ues for managing enormous com+le-ity, ac&ieving reuse of soft#are com+onents, and cou+ling data #it& t&e tas.s t&at mani+ulate t&at data/ %&e essence of ob!ect"oriented +rogramming is to treat data and t&e +rocedures t&at act u+on t&e data as a single 9ob!ect9""a self"contained entity #it& an identity and certain c&aracteristics of its o#n/ C++ and $"%ect&$riented Programming C++ fully su++orts ob!ect"oriented +rogramming, including t&e four +illars of ob!ect" oriented develo+ment7 enca+sulation, data &iding, in&eritance, and +olymor+&ism/ $nca+sulation and Data Hiding 0&en an engineer needs to add a resistor to t&e device s&e is creating, s&e doesn6t ty+ically build a ne# one from scratc&/ S&e #al.s over to a bin of resistors, e-amines t&e colored bands t&at indicate t&e +ro+erties, and +ic.s t&e one s&e needs/ %&e resistor is a 9blac. bo-9 as far as t&e engineer is concerned""s&e doesn6t muc& care &o# it does its #or. as long as it conforms to &er s+ecificationsB s&e doesn6t need to loo. inside t&e bo- to use it in &er design/ %&e +ro+erty of being a self"contained unit is called enca+sulation/ 0it& enca+sulation, #e can accom+lis& data &iding/ Data &iding is t&e &ig&ly valued c&aracteristic t&at an ob!ect can be used #it&out t&e user .no#ing or caring &o# it #or.s internally/ Cust as you can use a refrigerator #it&out .no#ing &o# t&e com+ressor #or.s, you can use a #ell"designed ob!ect #it&out .no#ing about its internal data members/ Similarly, #&en t&e engineer uses t&e resistor, s&e need not .no# anyt&ing about t&e internal state of t&e resistor/ All t&e +ro+erties of t&e resistor are enca+sulated in t&e resistor ob!ectB t&ey are not s+read out t&roug& t&e circuitry/ It is not necessary to understand &o# t&e resistor #or.s in order to use it effectively/ Its data is &idden inside t&e resistor6s casing/ C++ su++orts t&e +ro+erties of enca+sulation and data &iding t&roug& t&e creation of user"defined ty+es, called classes/ ,ou6ll see &o# to create classes on Day D, 9Basic Classes/9 nce created, a #ell"defined class acts as a fully enca+sulated entity""it is used as a #&ole unit/ %&e actual inner #or.ings of t&e class s&ould be &idden/ :sers of a #ell" defined class do not need to .no# &o# t&e class #or.sB t&ey !ust need to .no# &o# to use it/ In&eritance and ;euse 0&en t&e engineers at Acme Aotors #ant to build a ne#

car, t&ey &ave t#o c&oices7 %&ey can start from scratc&, or t&ey can modify an e-isting model/ Per&a+s t&eir Star model is nearly +erfect, but t&ey6d li.e to add a turboc&arger and a si-"s+eed transmission/ %&e c&ief engineer #ould +refer not to start from t&e ground u+, but rat&er to say, 9(et6s build anot&er Star, but let6s add t&ese additional ca+abilities/ 0e6ll call t&e ne# model a 2uasar/9 A 2uasar is a .ind of Star, but one #it& ne# features/ C++ su++orts t&e idea of reuse t&roug& in&eritance/ A ne# ty+e, #&ic& is an e-tension of an e-isting ty+e, can be declared/ %&is ne# subclass is said to derive from t&e e-isting ty+e and is sometimes called a derived ty+e/ %&e 2uasar is derived from t&e Star and t&us in&erits all its 8ualities, but can add to t&em as needed/ In&eritance and its a++lication in C++ are discussed on Day 11, 9In&eritance,9 and Day 1E, 9Advanced In&eritance/9 Polymor+&ism %&e ne# 2uasar mig&t res+ond differently t&an a Star does #&en you +ress do#n on t&e accelerator/ %&e 2uasar mig&t engage fuel in!ection and a turboc&arger, #&ile t&e Star #ould sim+ly let gasoline into its carburetor/ A user, &o#ever, does not &ave to .no# about t&ese differences/ He can !ust 9floor it,9 and t&e rig&t t&ing #ill &a++en, de+ending on #&ic& car &e6s driving/ C++ su++orts t&e idea t&at different ob!ects do 9t&e rig&t t&ing9 t&roug& #&at is called function +olymor+&ism and class +olymor+&ism/ Poly means many, and mor+& means form/ Polymor+&ism refers to t&e same name ta.ing many forms, and is discussed on Day 1>, 9Advanced )unctions,9 and Day 1F, 9Polymor+&ism/9

How C++ +!o !ed


As ob!ect"oriented analysis, design, and +rogramming began to catc& on, B!arne Stroustru+ too. t&e most +o+ular language for commercial soft#are develo+ment, C, and e-tended it to +rovide t&e features needed to facilitate ob!ect"oriented +rogramming/ He created C++, and in less t&an a decade it &as gone from being used by only a &andful of develo+ers at A%3% to being t&e +rogramming language of c&oice for an estimated one million develo+ers #orld#ide/ It is e-+ected t&at by t&e end of t&e decade, C++ #ill be t&e +redominant language for commercial soft#are develo+ment/ 0&ile it is true t&at C++ is a su+erset of C, and t&at virtually any legal C +rogram is a legal C++ +rogram, t&e lea+ from C to C++ is very significant/ C++ benefited from its relations&i+ to C for many years, as C +rogrammers could ease into t&eir use of C++/ %o really get t&e full benefit of C++, &o#ever, many +rogrammers found t&ey &ad to unlearn muc& of #&at t&ey .ne# and learn a #&ole ne# #ay of conce+tuali4ing and solving +rogramming +roblems/

T,e ANSI Standard


%&e Accredited Standards Committee, o+erating under t&e +rocedures of t&e American 'ational Standards Institute ?A'SI@, is #or.ing to create an international standard for C+ +/

%&e draft of t&is standard &as been +ublis&ed, and a lin. is available at www.libertyassociates.com/ %&e A'SI standard is an attem+t to ensure t&at C++ is +ortable""t&at code you #rite for Aicrosoft6s com+iler #ill com+ile #it&out errors, using a com+iler from any ot&er vendor/ )urt&er, because t&e code in t&is boo. is A'SI com+liant, it s&ould com+ile #it&out errors on a Aac, a 0indo#s bo-, or an Al+&a/ )or most students of C++, t&e A'SI standard #ill be invisible/ %&e standard &as been stable for a #&ile, and all t&e ma!or manufacturers su++ort t&e A'SI standard/ 0e &ave endeavored to ensure t&at all t&e code in t&is edition of t&is boo. is A'SI com+liant/

S,ou d I -earn C .irst/


%&e 8uestion inevitably arises7 9Since C++ is a su+erset of C, s&ould I learn C first*9 Stroustru+ and most ot&er C++ +rogrammers agree/ 'ot only is it unnecessary to learn C first, it may be advantageous not to do so/ %&is boo. attem+ts to meet t&e needs of +eo+le li.e you, #&o come to C++ #it&out +rior e-+erience of C/ In fact, t&is boo. assumes no +rogramming e-+erience of any .ind/

Pre0aring to Program
C++, +er&a+s more t&an ot&er languages, demands t&at t&e +rogrammer design t&e +rogram before #riting it/ %rivial +roblems, suc& as t&e ones discussed in t&e first fe# c&a+ters of t&is boo., don6t re8uire muc& design/ Com+le- +roblems, &o#ever, suc& as t&e ones +rofessional +rogrammers are c&allenged #it& every day, do re8uire design, and t&e more t&oroug& t&e design, t&e more li.ely it is t&at t&e +rogram #ill solve t&e +roblems it is designed to solve, on time and on budget/ A good design also ma.es for a +rogram t&at is relatively bug"free and easy to maintain/ It &as been estimated t&at fully <> +ercent of t&e cost of soft#are is t&e combined cost of debugging and maintenance/ %o t&e e-tent t&at good design can reduce t&ose costs, it can &ave a significant im+act on t&e bottom"line cost of t&e +ro!ect/ %&e first 8uestion you need to as. #&en +re+aring to design any +rogram is, 90&at is t&e +roblem I6m trying to solve*9 $very +rogram s&ould &ave a clear, #ell"articulated goal, and you6ll find t&at even t&e sim+lest +rograms in t&is boo. do so/ %&e second 8uestion every good +rogrammer as.s is, 9Can t&is be accom+lis&ed #it&out resorting to #riting custom soft#are*9 ;eusing an old +rogram, using +en and +a+er, or buying soft#are off t&e s&elf is often a better solution to a +roblem t&an #riting somet&ing ne#/ %&e +rogrammer #&o can offer t&ese alternatives #ill never suffer from lac. of #or.B finding less"e-+ensive solutions to today6s +roblems #ill al#ays generate ne# o++ortunities later/ Assuming you understand t&e +roblem, and it re8uires #riting a ne# +rogram, you are ready to begin your design/

1our De!e o0ment +n!ironment


%&is boo. ma.es t&e assum+tion t&at your com+uter &as a mode in #&ic& you can #rite directly to t&e screen, #it&out #orrying about a gra+&ical environment, suc& as t&e ones in 0indo#s or on t&e Aacintos&/ ,our com+iler may &ave its o#n built"in te-t editor, or you may be using a commercial te-t editor or #ord +rocessor t&at can +roduce te-t files/ %&e im+ortant t&ing is t&at #&atever you #rite your +rogram in, it must save sim+le, +lain"te-t files, #it& no #ord +rocessing commands embedded in t&e te-t/ $-am+les of safe editors include 0indo#s 'ote+ad, t&e D S $dit command, Brief, $+silon, $AACS, and vi/ Aany commercial #ord +rocessors, suc& as 0ordPerfect, 0ord, and do4ens of ot&ers, also offer a met&od for saving sim+le te-t files/ %&e files you create #it& your editor are called source files, and for C++ t&ey ty+ically are named #it& t&e e-tension .CPP, .CP, or .C/ In t&is boo., #e6ll name all t&e source code files #it& t&e .CPP e-tension, but c&ec. your com+iler for #&at it needs/ N$T+: Aost C++ com+ilers don6t care #&at e-tension you give your source code, but if you don6t s+ecify ot&er#ise, many #ill use .CPP by default/ D use a sim+le te-t editor to create your source code, or use t&e built"in editor t&at comes #it& your com+iler/ D '6% use a #ord +rocessor t&at saves s+ecial formatting c&aracters/ If you do use a #ord +rocessor, save t&e file as ASCII te-t/ D save your files #it& t&e .C, .CP, or .CPP e-tension/ D c&ec. your documentation for s+ecifics about your com+iler and lin.er to ensure t&at you .no# &o# to com+ile and lin. your +rograms/

Com0i ing t,e Source Code


Alt&oug& t&e source code in your file is some#&at cry+tic, and anyone #&o doesn6t .no# C++ #ill struggle to understand #&at it is for, it is still in #&at #e call &uman"readable form/ ,our source code file is not a +rogram, and it can6t be e-ecuted, or run, as a +rogram can/ %o turn your source code into a +rogram, you use a com+iler/ Ho# you invo.e your com+iler, and &o# you tell it #&ere to find your source code, #ill vary from com+iler to com+ilerB c&ec. your documentation/ In Borland6s %urbo C++ you +ic. t&e RUN menu command or ty+e
tc < ile!ame"

from t&e command line, #&ere <filename" is t&e name of your source code file ?for e-am+le, test.c##@/ t&er com+ilers may do t&ings slig&tly differently/

N$T+: If you com+ile t&e source code from t&e o+erating system6s command line, you s&ould ty+e t&e follo#ing7 )or t&e Borland C++ com+iler7 bcc GfilenameH )or t&e Borland C++ for 0indo#s com+iler7 bcc GfilenameH )or t&e Borland %urbo C++ com+iler7 tc GfilenameH )or t&e Aicrosoft com+ilers7 cl GfilenameH

After your source code is com+iled, an ob!ect file is +roduced/ %&is file is often named #it& t&e e-tension .O$%/ %&is is still not an e-ecutable +rogram, &o#ever/ %o turn t&is into an e-ecutable +rogram, you must run your lin.er/

Creating an +2ecuta" e .i e wit, t,e -in3er


C++ +rograms are ty+ically created by lin.ing toget&er one or more BC files #it& one or more libraries/ A library is a collection of lin.able files t&at #ere su++lied #it& your com+iler, t&at you +urc&ased se+arately, or t&at you created and com+iled/ All C++ com+ilers come #it& a library of useful functions ?or +rocedures@ and classes t&at you can include in your +rogram/ A function is a bloc. of code t&at +erforms a service, suc& as adding t#o numbers or +rinting to t&e screen/ A class is a collection of data and related functionsB #e6ll be tal.ing about classes a lot, starting on Day E, 9)unctions/9 %&e ste+s to create an e-ecutable file are 1' Create a source code file, #it& a .CPP e-tension/ (' Com+ile t&e source code into a file #it& t&e .O$% e-tension/ )' (in. your BC file #it& any needed libraries to +roduce an e-ecutable +rogram/

T,e De!e o0ment Cyc e


If every +rogram #or.ed t&e first time you tried it, t&at #ould be t&e com+lete develo+ment cycle7 0rite t&e +rogram, com+ile t&e source code, lin. t&e +rogram, and run it/ :nfortunately, almost every +rogram, no matter &o# trivial, can and #ill &ave errors, or bugs, in t&e +rogram/ Some bugs #ill cause t&e com+ile to fail, some #ill cause t&e lin. to fail, and some #ill only s&o# u+ #&en you run t&e +rogram/ 0&atever ty+e of bug you find, you must fi- it, and t&at involves editing your source code, recom+iling and relin.ing, and t&en rerunning t&e +rogram/ %&is cycle is re+resented in )igure 1/1, #&ic& diagrams t&e ste+s in t&e develo+ment cycle/

)igure 1/1/ The steps in the development of a C++ program.

H+--$'CPP1our .irst C++ Program


%raditional +rogramming boo.s begin by #riting t&e #ords &ello 'orl( to t&e screen, or a variation on t&at statement/ %&is time"&onored tradition is carried on &ere/ %y+e t&e first +rogram directly into your editor, e-actly as s&o#n/ nce you are certain it is correct, save t&e file, com+ile it, lin. it, and run it/ It #ill +rint t&e #ords &ello 'orl( to your screen/ Don6t #orry too muc& about &o# it #or.s, t&is is really !ust to get you comfortable #it& t&e develo+ment cycle/ $very as+ect of t&is +rogram #ill be covered over t&e ne-t cou+le of days/ 4A5NING: %&e follo#ing listing contains line numbers on t&e left/ %&ese numbers are for reference #it&in t&e boo./ %&ey s&ould not be ty+ed in to your editor/ )or e-am+le, in line 1 of (isting 1/1, you s&ould enter7
)i!cl*(e <iostream.+"

-isting 1'1' H+--$'CPP# t,e He o 4or d 0rogram'


1, -, ., 1, 3, 8, 9, )i!cl*(e <iostream.+" i!t mai!/0 2 co*t << 4&ello 'orl(56!47 ret*r! 07 :

Aa.e certain you enter t&is e-actly as s&o#n/ Pay careful attention to t&e +unctuation/ %&e << in line E is t&e redirection symbol, +roduced on most .eyboards by &olding t&e S&ift .ey and +ressing t&e comma .ey t#ice/ (ine E ends #it& a semicolonB don6t leave t&is off5 Also c&ec. to ma.e sure you are follo#ing your com+iler directions +ro+erly/ Aost com+ilers #ill lin. automatically, but c&ec. your documentation/ If you get errors, loo. over your code carefully and determine &o# it is different from t&e above/ If you see an error on line 1, suc& as ca!!ot i!( ile iostream.+, c&ec. your com+iler documentation for directions on setting u+ your i!cl*(e +at& or environment variables/ If you receive an error t&at t&ere is no +rototy+e for mai!, add t&e line i!t mai!/07 !ust before line F/ ,ou #ill need to add t&is line before t&e beginning of t&e mai! function in every +rogram in t&is boo./ Aost com+ilers don6t re8uire t&is, but a fe# do/ ,our finis&ed +rogram #ill loo. li.e t&is7
1, )i!cl*(e <iostream.+" -, .,

1, 3, 8, 9, ;,

i!t mai!/07 2 co*t <<4&ello 'orl(56!47 ret*r! 07 :

%ry running &<LLO.<=<B it s&ould #rite


&ello 'orl(5

directly to your screen/ If so, congratulations5 ,ou6ve !ust entered, com+iled, and run your first C++ +rogram/ It may not loo. li.e muc&, but almost every +rofessional C++ +rogrammer started out #it& t&is e-act +rogram/

Com0i e +rrors
Com+ile"time errors can occur for any number of reasons/ :sually t&ey are a result of a ty+o or ot&er inadvertent minor error/ Good com+ilers #ill not only tell you #&at you did #rong, t&ey6ll +oint you to t&e e-act +lace in your code #&ere you made t&e mista.e/ %&e great ones #ill even suggest a remedy5 ,ou can see t&is by intentionally +utting an error into your +rogram/ If &<LLO.CPP ran smoot&ly, edit it no# and remove t&e closing brace on line D/ ,our +rogram #ill no# loo. li.e (isting 1/1/

-isting 1'(' Demonstration of com0i er error'


1, -, ., 1, 3, 8, )i!cl*(e <iostream.+" i!t mai!/0 2 co*t << 4&ello 'orl(56!47 ret*r! 07

;ecom+ile your +rogram and you s&ould see an error t&at loo.s similar to t&e follo#ing7
&ello.c##> li!e 3, Com#o*!( stateme!t missi!? termi!ati!? : i! mai!/0. *!ctio!

%&is error tells you t&e file and line number of t&e +roblem, and #&at t&e +roblem is ?alt&oug& I admit it is some#&at cry+tic@/ 'ote t&at t&e error message +oints you to line E/ %&e com+iler #asn6t sure if you intended to +ut t&e closing brace before or after t&e co*t statement on line E/ Sometimes t&e errors !ust get you to t&e general vicinity of t&e +roblem/ If a com+iler could +erfectly identify every +roblem, it #ould fi- t&e code itself/

Summary

After reading t&is c&a+ter, you s&ould &ave a good understanding of &o# C++ evolved and #&at +roblems it #as designed to solve/ ,ou s&ould feel confident t&at learning C++ is t&e rig&t c&oice for anyone interested in +rogramming in t&e ne-t decade/ C++ +rovides t&e tools of ob!ect"oriented +rogramming and t&e +erformance of a systems" level language, #&ic& ma.es C++ t&e develo+ment language of c&oice/ %oday you learned &o# to enter, com+ile, lin., and run your first C++ +rogram, and #&at t&e normal develo+ment cycle is/ ,ou also learned a little of #&at ob!ect"oriented +rogramming is all about/ ,ou #ill return to t&ese to+ics during t&e ne-t t&ree #ee.s/

67A
6' 4,at is t,e difference "etween a te2t editor and a word 0rocessor/ A' A te-t editor +roduces files #it& +lain te-t in t&em/ %&ere are no formatting commands or ot&er s+ecial symbols re8uired by a +articular #ord +rocessor/ %e-t files do not &ave automatic #ord #ra+, bold +rint, italics, and so fort&/ 6' If my com0i er ,as a "ui t&in editor# must I use it/ A' Almost all com+ilers #ill com+ile code +roduced by any te-t editor/ %&e advantages of using t&e built"in te-t editor, &o#ever, mig&t include t&e ability to 8uic.ly move bac. and fort& bet#een t&e edit and com+ile ste+s of t&e develo+ment cycle/ So+&isticated com+ilers include a fully integrated develo+ment environment, allo#ing t&e +rogrammer to access &el+ files, edit, and com+ile t&e code in +lace, and to resolve com+ile and lin. errors #it&out ever leaving t&e environment/ 6' Can I ignore warning messages from my com0i er/ A' Aany boo.s &edge on t&is one, but I6ll sta.e myself to t&is +osition7 'o5 Get into t&e &abit, from day one, of treating #arning messages as errors/ C++ uses t&e com+iler to #arn you #&en you are doing somet&ing you may not intend/ Heed t&ose #arnings, and do #&at is re8uired to ma.e t&em go a#ay/ 6' 4,at is com0i e time/ A' Com+ile time is t&e time #&en you run your com+iler, as o++osed to lin. time ?#&en you run t&e lin.er@ or run"time ?#&en running t&e +rogram@/ %&is is !ust +rogrammer s&ort&and to identify t&e t&ree times #&en errors usually surface/

4or3s,o0
%&e 0or.s&o+ +rovides 8ui4 8uestions to &el+ you solidify your understanding of t&e material covered and e-ercises to +rovide you #it& e-+erience in using #&at you6ve learned/ %ry to ans#er t&e 8ui4 and e-ercise 8uestions before c&ec.ing t&e ans#ers in

A++endi- D, and ma.e sure you understand t&e ans#ers before continuing to t&e ne-t c&a+ter/ 6ui8 1' 0&at is t&e difference bet#een an inter+reter and a com+iler* (' Ho# do you com+ile t&e source code #it& your com+iler* )' 0&at does t&e lin.er do* *' 0&at are t&e ste+s in t&e normal develo+ment cycle* +2ercises 1' (oo. at t&e follo#ing +rogram and try to guess #&at it does #it&out running it/
1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, i!t @ = 37 3, i!t y = 97 8, co*t 46!47 9, co*t << @ A y << 4 4 << @ B y7 ;, co*t 46!47 C,ret*r! 07 10, :

(' %y+e in t&e +rogram from $-ercise 1, and t&en com+ile and lin. it/ 0&at does it do* Does it do #&at you guessed* )' %y+e in t&e follo#ing +rogram and com+ile it/ 0&at error do you receive*
1, -, ., 1, 3, 8, i!cl*(e <iostream.+" i!t mai!/0 2 co*t << 4&ello 'orl(6!47 ret*r! 07 :

*' )i- t&e error in t&e +rogram in $-ercise F, and recom+ile, lin., and run it/ 0&at does it do*

Day 1
o

%&e Parts of a C++ Program A Sim+le Program (isting 1/1/ H$(( /CPP demonstrates t&e +arts of a C++ +rogram/ A Brief (oo. at cout (isting 1/1/

:sing cout/ Comments %y+es of Comments :sing Comments (isting 1/F/ H$(P/CPP demonstrates comments/ Comments at t&e %o+ of $ac& )ile A )inal 0ord of Caution About Comments )unctions (isting 1/I/ Demonstrating a call to a function/ :sing )unctions (isting 1/E/ ):'C/CPP demonstrates a sim+le function/ Summary 23A 0or.s&o+ 2ui4 $-ercises

Day ( T,e Parts of a C++ Program


C++ +rograms consist of ob!ects, functions, variables, and ot&er com+onent +arts/ Aost of t&is boo. is devoted to e-+laining t&ese +arts in de+t&, but to get a sense of &o# a +rogram fits toget&er you must see a com+lete #or.ing +rogram/ %oday you learn

%&e +arts of a C++ +rogram/ Ho# t&e +arts #or. toget&er/ 0&at a function is and #&at it does/

A Sim0 e Program
$ven t&e sim+le +rogram H$(( /CPP from Day 1, 9Getting Started,9 &ad many interesting +arts/ %&is section #ill revie# t&is +rogram in more detail/ (isting 1/1 re+roduces t&e original version of H$(( /CPP for your convenience/

-isting ('1' H+--$'CPP demonstrates t,e 0arts of a C++ 0rogram'


1, )i!cl*(e <iostream.+" -, ., i!t mai!/0 1, 2 3, co*t << 4&ello 'orl(56!47 8, ret*r! 07 9, :

&ello 'orl(5

n line 1, t&e file iostream/& is included in t&e file/ %&e first c&aracter is t&e J symbol, #&ic& is a signal to t&e +re+rocessor/ $ac& time you start your com+iler, t&e +re+rocessor is run/ %&e +re+rocessor reads t&roug& your source code, loo.ing for lines t&at begin #it& t&e +ound symbol ?J@, and acts on t&ose lines before t&e com+iler runs/ include is a +re+rocessor instruction t&at says, 90&at follo#s is a filename/ )ind t&at file and read it in rig&t &ere/9 %&e angle brac.ets around t&e filename tell t&e +re+rocessor to loo. in all t&e usual +laces for t&is file/ If your com+iler is set u+ correctly, t&e angle brac.ets #ill cause t&e +re+rocessor to loo. for t&e file iostream/& in t&e directory t&at &olds all t&e H files for your com+iler/ %&e file iostream/& ?In+ut" ut+ut"Stream@ is used by cout, #&ic& assists #it& #riting to t&e screen/ %&e effect of line 1 is to include t&e file iostream/& into t&is +rogram as if you &ad ty+ed it in yourself/ 'e# %erm7 %&e +re+rocessor runs before your com+iler eac& time t&e com+iler is invo.ed/ %&e +re+rocessor translates any line t&at begins #it& a +ound symbol ?J@ into a s+ecial command, getting your code file ready for t&e com+iler/ (ine F begins t&e actual +rogram #it& a function named main?@/ $very C++ +rogram &as a main?@ function/ In general, a function is a bloc. of code t&at +erforms one or more actions/ :sually functions are invo.ed or called by ot&er functions, but main?@ is s+ecial/ 0&en your +rogram starts, main?@ is called automatically/ main?@, li.e all functions, must state #&at .ind of value it #ill return/ %&e return value ty+e for main?@ in H$(( /CPP is void, #&ic& means t&at t&is function #ill not return any value at all/ ;eturning values from functions is discussed in detail on Day I, 9$-+ressions and Statements/9 All functions begin #it& an o+ening brace ?K@ and end #it& a closing brace ?L@/ %&e braces for t&e main?@ function are on lines I and M/ $veryt&ing bet#een t&e o+ening and closing braces is considered a +art of t&e function/ %&e meat and +otatoes of t&is +rogram is on line E/ %&e ob!ect cout is used to +rint a message to t&e screen/ 0e6ll cover ob!ects in general on Day D, 9Basic Classes,9 and cout and its related ob!ect cin in detail on Day 1M, 9%&e Pre+rocessor/9 %&ese t#o ob!ects, cout and cin, are used in C++ to +rint strings and values to t&e screen/ A string is !ust a set of c&aracters/ Here6s &o# cout is used7 ty+e t&e #ord cout, follo#ed by t&e out+ut redirection o+erator ?GG@/ 0&atever follo#s t&e out+ut redirection o+erator is #ritten to t&e screen/ If you #ant a string of c&aracters #ritten, be sure to enclose t&em in double 8uotes ?9@, as s&o#n on line E/ 'e# %erm7 A te-t string is a series of +rintable c&aracters/

%&e final t#o c&aracters, Nn, tell cout to +ut a ne# line after t&e #ords Hello 0orld5 %&is s+ecial code is e-+lained in detail #&en cout is discussed on Day 1M/ All A'SI"com+liant +rograms declare main?@ to return an int/ %&is value is 9returned9 to t&e o+erating system #&en your +rogram com+letes/ Some +rogrammers signal an error by returning t&e value 1/ In t&is boo., main?@ #ill al#ays return >/ %&e main?@ function ends on line M #it& t&e closing brace/

A Brief -oo3 at cout


n Day 1D, 9Streams,9 you #ill see &o# to use cout to +rint data to t&e screen/ )or no#, you can use cout #it&out fully understanding &o# it #or.s/ %o +rint a value to t&e screen, #rite t&e #ord cout, follo#ed by t&e insertion o+erator ?GG@, #&ic& you create by ty+ing t&e less"t&an c&aracter ?G@ t#ice/ $ven t&oug& t&is is t#o c&aracters, C++ treats it as one/ )ollo# t&e insertion c&aracter #it& your data/ (isting 1/1 illustrates &o# t&is is used/ %y+e in t&e e-am+le e-actly as #ritten, e-ce+t substitute your o#n name #&ere you see Cesse (iberty ?unless your name is Cesse (iberty, in #&ic& case leave it !ust t&e #ay it isB it6s +erfect"" but I6m still not s+litting royalties5@/

-isting ('('9sing cout'


1, DD Listi!? -.- *si!? co*t -, ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, co*t << 4&ello t+ere.6!47 9, co*t << 4&ere is 3, 4 << 3 << 46!47 ;, co*t << 4E+e ma!i#*lator e!(l writes a !ew li!e to t+e scree!.4 << Fe!(l7 C, co*t << 4&ere is a Gery bi? !*mber,6t4 << 90000 << e!(l7 10, co*t << 4&ere is t+e s*m o ; a!( 3,6t4 << ;A3 << e!(l7 11, co*t << 4&ereHs a ractio!,6t6t4 << / loat0 3D; << e!(l7 1-, co*t << 4A!( a Gery Gery bi? !*mber,6t4 << /(o*ble0 9000 B 9000 << Fe!(l7 1., co*t << 4Do!Ht or?et to re#lace %esse Liberty wit+ yo*r !ame...6!47 11, co*t << 4%esse Liberty is a CAA #ro?rammer56!47 13, ret*r! 07 18, : &ello t+ere. &ere is 3, 3 E+e ma!i#*lator e!(l writes a !ew li!e to t+e scree!. &ere is a Gery bi? !*mber, 90000 &ere is t+e s*m o ; a!( 3, 1. &ereHs a ractio!, 0.8-3

A!( a Gery Gery bi? !*mber, 1.CeA09 Do!Ht or?et to re#lace %esse Liberty wit+ yo*r !ame... %esse Liberty is a CAA #ro?rammer5

n line F, t&e statement Jinclude Giostream/&H causes t&e iostream/& file to be added to your source code/ %&is is re8uired if you use cout and its related functions/ n line D is t&e sim+lest use of cout, +rinting a string or series of c&aracters/ %&e symbol Nn is a s+ecial formatting c&aracter/ It tells cout to +rint a ne#line c&aracter to t&e screen/ %&ree values are +assed to cout on line M, and eac& value is se+arated by t&e insertion o+erator/ %&e first value is t&e string 9Here is E7 9/ 'ote t&e s+ace after t&e colon/ %&e s+ace is +art of t&e string/ 'e-t, t&e value E is +assed to t&e insertion o+erator and t&e ne#line c&aracter ?al#ays in double 8uotes or single 8uotes@/ %&is causes t&e line
&ere is 3, 3

to be +rinted to t&e screen/ Because t&ere is no ne#line c&aracter after t&e first string, t&e ne-t value is +rinted immediately after#ards/ %&is is called concatenating t&e t#o values/ n line =, an informative message is +rinted, and t&en t&e mani+ulator endl is used/ %&e +ur+ose of endl is to #rite a ne# line to t&e screen/ ? t&er uses for endl are discussed on Day 1D/@ n line <, a ne# formatting c&aracter, Nt, is introduced/ %&is inserts a tab c&aracter and is used on lines ="11 to line u+ t&e out+ut/ (ine < s&o#s t&at not only integers, but long integers as #ell can be +rinted/ (ine 1> demonstrates t&at cout #ill do sim+le addition/ %&e value of =+E is +assed to cout, but 1F is +rinted/ n line 11, t&e value EO= is inserted into cout/ %&e term ?float@ tells cout t&at you #ant t&is value evaluated as a decimal e8uivalent, and so a fraction is +rinted/ n line 11 t&e value M>>> P M>>> is given to cout, and t&e term ?double@ is used to tell cout t&at you #ant t&is to be +rinted using scientific notation/ All of t&is #ill be e-+lained on Day F, 9Qariables and Constants,9 #&en data ty+es are discussed/ n line 1I, you substituted your name, and t&e out+ut confirmed t&at you are indeed a C+ + +rogrammer/ It must be true, because t&e com+uter said so5

Comments
0&en you are #riting a +rogram, it is al#ays clear and self"evident #&at you are trying to do/ )unny t&ing, t&oug&""a mont& later, #&en you return to t&e +rogram, it can be 8uite confusing and unclear/ I6m not sure &o# t&at confusion cree+s into your +rogram, but it al#ays does/

%o fig&t t&e onset of confusion, and to &el+ ot&ers understand your code, you6ll #ant to use comments/ Comments are sim+ly te-t t&at is ignored by t&e com+iler, but t&at may inform t&e reader of #&at you are doing at any +articular +oint in your +rogram/ Ty0es of Comments C++ comments come in t#o flavors7 t&e double"slas& ?OO@ comment, and t&e slas&"star ?OP@ comment/ %&e double"slas& comment, #&ic& #ill be referred to as a C++"style comment, tells t&e com+iler to ignore everyt&ing t&at follo#s t&is comment, until t&e end of t&e line/ %&e slas&"star comment mar. tells t&e com+iler to ignore everyt&ing t&at follo#s until it finds a star"slas& ?PO@ comment mar./ %&ese mar.s #ill be referred to as C"style comments/ $very OP must be matc&ed #it& a closing PO/ As you mig&t guess, C"style comments are used in t&e C language as #ell, but C++"style comments are not +art of t&e official definition of C/ Aany C++ +rogrammers use t&e C++"style comment most of t&e time, and reserve C" style comments for bloc.ing out large bloc.s of a +rogram/ ,ou can include C++"style comments #it&in a bloc. 9commented out9 by C"style commentsB everyt&ing, including t&e C++"style comments, is ignored bet#een t&e C"style comment mar.s/ 9sing Comments As a general rule, t&e overall +rogram s&ould &ave comments at t&e beginning, telling you #&at t&e +rogram does/ $ac& function s&ould also &ave comments e-+laining #&at t&e function does and #&at values it returns/ )inally, any statement in your +rogram t&at is obscure or less t&an obvious s&ould be commented as #ell/ (isting 1/F demonstrates t&e use of comments, s&o#ing t&at t&ey do not affect t&e +rocessing of t&e +rogram or its out+ut/

-isting (')' H+-P'CPP demonstrates comments'


1, )i!cl*(e <iostream.+" -, ., i!t mai!/0 1, 2 3, DB t+is is a comme!t 8, a!( it e@te!(s *!til t+e closi!? 9, starIslas+ comme!t marJ BD ;, co*t << 4&ello 'orl(56!47 C, DD t+is comme!t e!(s at t+e e!( o t+e li!e 10, co*t << 4E+at comme!t e!(e(56!47 11, 1-, DD (o*ble slas+ comme!ts ca! be alo!e o! a li!e 1., DB as ca! slas+Istar comme!ts BD 11, ret*r! 07

13, : &ello 'orl(5 E+at comme!t e!(e(5

%&e comments on lines E t&roug& M are com+letely ignored by t&e com+iler, as are t&e comments on lines <, 11, and 1F/ %&e comment on line < ended #it& t&e end of t&e line, &o#ever, #&ile t&e comments on lines E and 1F re8uired a closing comment mar./ Comments at t,e To0 of +ac, .i e It is a good idea to +ut a comment bloc. at t&e to+ of every file you #rite/ %&e e-act style of t&is bloc. of comments is a matter of individual taste, but every suc& &eader s&ould include at least t&e follo#ing information7

%&e name of t&e function or +rogram/ %&e name of t&e file/ 0&at t&e function or +rogram does/ A descri+tion of &o# t&e +rogram #or.s/ %&e aut&or6s name/ A revision &istory ?notes on eac& c&ange made@/ 0&at com+ilers, lin.ers, and ot&er tools #ere used to ma.e t&e +rogram/ Additional notes as needed/

)or e-am+le, t&e follo#ing bloc. of comments mig&t a++ear at t&e to+ of t&e Hello 0orld +rogram/
DBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Pro?ram, Kile, K*!ctio!, Descri#tio!, A*t+or, <!Giro!me!t, Notes, ReGisio!s, &ello 'orl( &ello.c## Mai! /com#lete #ro?ram listi!? i! t+is ile0

Pri!ts t+e wor(s 4&ello worl(4 to t+e scree! %esse Liberty /Ll0 E*rbo CAA Gersio! 1> 1;8D88 .-mb RAM> 'i!(ows ..1 DOM 8.0. <asy'i! mo(*le. E+is is a! i!tro(*ctory> sam#le #ro?ram. 1.00 1.01 10D1DC1 /Ll0 Kirst release 10D-DC1 /Ll0 Ca#italiNe( 4'orl(4

BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBD

It is very im+ortant t&at you .ee+ t&e notes and descri+tions u+"to"date/ A common +roblem #it& &eaders li.e t&is is t&at t&ey are neglected after t&eir initial creation, and

over time t&ey become increasingly misleading/ 0&en +ro+erly maintained, &o#ever, t&ey can be an invaluable guide to t&e overall +rogram/ %&e listings in t&e rest of t&is boo. #ill leave off t&e &eadings in an attem+t to save room/ %&at does not diminis& t&eir im+ortance, &o#ever, so t&ey #ill a++ear in t&e +rograms +rovided at t&e end of eac& #ee./ A .ina 4ord of Caution A"out Comments Comments t&at state t&e obvious are less t&an useful/ In fact, t&ey can be counter+roductive, because t&e code may c&ange and t&e +rogrammer may neglect to u+date t&e comment/ 0&at is obvious to one +erson may be obscure to anot&er, &o#ever, so !udgment is re8uired/ %&e bottom line is t&at comments s&ould not say #&at is &a++ening, t&ey s&ould say #&y it is &a++ening/ D$ add comments to your code/ D$ .ee+ comments u+"to"date/ D$ use comments to tell #&at a section of code does/ D$N:T use comments for self"e-+lanatory code/

.unctions
0&ile main?@ is a function, it is an unusual one/ %y+ical functions are called, or invo.ed, during t&e course of your +rogram/ A +rogram is e-ecuted line by line in t&e order it a++ears in your source code, until a function is reac&ed/ %&en t&e +rogram branc&es off to e-ecute t&e function/ 0&en t&e function finis&es, it returns control to t&e line of code immediately follo#ing t&e call to t&e function/ A good analogy for t&is is s&ar+ening your +encil/ If you are dra#ing a +icture, and your +encil brea.s, you mig&t sto+ dra#ing, go s&ar+en t&e +encil, and t&en return to #&at you #ere doing/ 0&en a +rogram needs a service +erformed, it can call a function to +erform t&e service and t&en +ic. u+ #&ere it left off #&en t&e function is finis&ed running/ (isting 1/I demonstrates t&is idea/

-isting ('*' Demonstrating a ca to a function'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, )i!cl*(e <iostream.+" DD *!ctio! Demo!stratio! K*!ctio! DD #ri!ts o*t a *se *l messa?e Goi( Demo!stratio!K*!ctio!/0 2 co*t << 4I! Demo!stratio! K*!ctio!6!47 : DD *!ctio! mai! I #ri!ts o*t a messa?e> t+e! DD calls Demo!stratio!K*!ctio!> t+e! #ri!ts o*t DD a seco!( messa?e.

1., i!t mai!/0 11, 2 13, co*t << 4I! mai!6!4 7 18, Demo!stratio!K*!ctio!/07 19, co*t << 4$acJ i! mai!6!47 1;, ret*r! 07 1C, : I! mai! I! Demo!stratio! K*!ctio! $acJ i! mai!

%&e function Demonstration)unction?@ is defined on lines E"M/ 0&en it is called, it +rints a message to t&e screen and t&en returns/ (ine 1F is t&e beginning of t&e actual +rogram/ n line 1E, main?@ +rints out a message saying it is in main?@/ After +rinting t&e message, line 1D calls Demonstration)unction?@/ %&is call causes t&e commands in Demonstration)unction?@ to e-ecute/ In t&is case, t&e entire function consists of t&e code on line M, #&ic& +rints anot&er message/ 0&en Demonstration)unction?@ com+letes ?line =@, it returns bac. to #&ere it #as called from/ In t&is case t&e +rogram returns to line 1M, #&ere main?@ +rints its final line/ 9sing .unctions )unctions eit&er return a value or t&ey return void, meaning t&ey return not&ing/ A function t&at adds t#o integers mig&t return t&e sum, and t&us #ould be defined to return an integer value/ A function t&at !ust +rints a message &as not&ing to return and #ould be declared to return void/ )unctions consist of a &eader and a body/ %&e &eader consists, in turn, of t&e return ty+e, t&e function name, and t&e +arameters to t&at function/ %&e +arameters to a function allo# values to be +assed into t&e function/ %&us, if t&e function #ere to add t#o numbers, t&e numbers #ould be t&e +arameters to t&e function/ Here6s a ty+ical function &eader7
i!t M*m/i!t a> i!t b0

A +arameter is a declaration of #&at ty+e of value #ill be +assed inB t&e actual value +assed in by t&e calling function is called t&e argument/ Aany +rogrammers use t&ese t#o terms, +arameters and arguments, as synonyms/ t&ers are careful about t&e tec&nical distinction/ %&is boo. #ill use t&e terms interc&angeably/ %&e body of a function consists of an o+ening brace, 4ero or more statements, and a closing brace/ %&e statements constitute t&e #or. of t&e function/ A function may return a value, using a return statement/ %&is statement #ill also cause t&e function to e-it/ If you don6t +ut a return statement into your function, it #ill automatically return void at t&e end of t&e function/ %&e value returned must be of t&e ty+e declared in t&e function &eader/

N$T+: )unctions are covered in more detail on Day E, 9)unctions/9 %&e ty+es t&at can be returned from a function are covered in more det+RradicalSRDeltaSRinfinitySon Day F/ %&e information +rovided today is to +resent you #it& an overvie#, because functions #ill be used in almost all of your C++ +rograms/ (isting 1/E demonstrates a function t&at ta.es t#o integer +arameters and returns an integer value/ Don6t #orry about t&e synta- or t&e s+ecifics of &o# to #or. #it& integer values ?for e-am+le, int -@ for no#B t&at is covered in detail on Day F/

-isting (';' .9NC'CPP demonstrates a sim0 e function'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, 1., 11, 13, 18, 19, 1;, 1C, -0, -1, --, : )i!cl*(e <iostream.+" i!t A(( /i!t @> i!t y0 2 co*t << 4I! A((/0> receiGe( 4 << @ << 4 a!( 4 << y << 46!47 ret*r! /@Ay07 : i!t mai!/0 2 co*t << 4IHm i! mai!/056!47 i!t a> b> c7 co*t << 4<!ter two !*mbers, 47 ci! "" a7 ci! "" b7 co*t << 46!Calli!? A((/06!47 c=A((/a>b07 co*t << 46!$acJ i! mai!/0.6!47 co*t << 4c was set to 4 << c7 co*t << 46!<@iti!?...6!6!47 ret*r! 07

IHm i! mai!/05 <!ter two !*mbers, . 3 Calli!? A((/0 I! A((/0> receiGe( . a!( 3 $acJ i! mai!/0. c was set to ; <@iti!?...

%&e function Add?@ is defined on line 1/ It ta.es t#o integer +arameters and returns an integer value/ %&e +rogram itself begins on line < and on line 11, #&ere it +rints a message/ %&e +rogram +rom+ts t&e user for t#o numbers ?lines 1F to 1E@/ %&e user ty+es eac& number, se+arated by a s+ace, and t&en +resses t&e $nter .ey/ main?@ +asses t&e t#o numbers ty+ed in by t&e user as arguments to t&e Add?@ function on line 1M/

Processing branc&es to t&e Add?@ function, #&ic& starts on line 1/ %&e +arameters a and b are +rinted and t&en added toget&er/ %&e result is returned on line D, and t&e function returns/ In lines 1I and 1E, t&e cin ob!ect is used to obtain a number for t&e variables a and b, and cout is used to #rite t&e values to t&e screen/ Qariables and ot&er as+ects of t&is +rogram are e-+lored in de+t& in t&e ne-t fe# days/

Summary
%&e difficulty in learning a com+le- sub!ect, suc& as +rogramming, is t&at so muc& of #&at you learn de+ends on everyt&ing else t&ere is to learn/ %&is c&a+ter introduced t&e basic +arts of a sim+le C++ +rogram/ It also introduced t&e develo+ment cycle and a number of im+ortant ne# terms/

67A
6' 4,at does <inc ude do/ A' %&is is a directive to t&e +re+rocessor, #&ic& runs #&en you call your com+iler/ %&is s+ecific directive causes t&e file named after t&e #ord include to be read in, as if it #ere ty+ed in at t&at location in your source code/ 6' 4,at is t,e difference "etween == comments and => sty e comments/ A' %&e double"slas& comments ?OO@ 9e-+ire9 at t&e end of t&e line/ Slas&"star ?OP@ comments are in effect until a closing comment ?PO@/ ;emember, not even t&e end of t&e function terminates a slas&"star commentB you must +ut in t&e closing comment mar., or you #ill get a com+ile"time error/ 6' 4,at differentiates a good comment from a "ad comment/ A' A good comment tells t&e reader #&y t&is +articular code is doing #&atever it is doing or e-+lains #&at a section of code is about to do/ A bad comment restates #&at a +articular line of code is doing/ (ines of code s&ould be #ritten so t&at t&ey s+ea. for t&emselves/ ;eading t&e line of code s&ould tell you #&at it is doing #it&out needing a comment/

4or3s,o0
%&e 0or.s&o+ +rovides 8ui4 8uestions to &el+ you solidify your understanding of t&e material covered and e-ercises to +rovide you #it& e-+erience in using #&at you6ve learned/ %ry to ans#er t&e 8ui4 and e-ercise 8uestions before c&ec.ing t&e ans#ers in A++endi- D, and ma.e sure you understand t&e ans#ers before continuing to t&e ne-t c&a+ter/

6ui8 1' 0&at is t&e difference bet#een t&e com+iler and t&e +re+rocessor* (' 0&y is t&e function main?@ s+ecial* )' 0&at are t&e t#o ty+es of comments, and &o# do t&ey differ* */ Can comments be nested* ;' Can comments be longer t&an one line* +2ercises 1' 0rite a +rogram t&at #rites I love C++ to t&e screen/ (' 0rite t&e smallest +rogram t&at can be com+iled, lin.ed, and run/ )' B:G B:S%$;S7 $nter t&is +rogram and com+ile it/ 0&y does it fail* Ho# can you fi- it*
1, -, ., 1, 3, )i!cl*(e <iostream.+" Goi( mai!/0 2 co*t << Is t+ere a b*? +ereO47 :

*' )i- t&e bug in $-ercise F and recom+ile, lin., and run it/

Day F
o

Qariables and Constants 0&at Is a Qariable* )igure F/1/ Setting Aside Aemory Si4e of Integers (isting F/1/ Determining t&e si4e of variable ty+es on your com+uter/ signed and unsigned )undamental Qariable %y+es Defining a Qariable Case Sensitivity Tey#ords

Creating Aore %&an ne Qariable at a %ime Assigning Qalues to ,our Qariables (isting F/1/ A demonstration of t&e use of variables/ ty+edef (isting F/F/ A demonstration of ty+edef/ 0&en to :se s&ort and 0&en to :se long 0ra++ing Around an unsigned Integer (isting F/I/ A demonstration of +utting too large a value in an unsigned integer/ 0ra++ing Around a signed Integer (isting F/E/ A demonstration of adding too large a number to a signed integer/ C&aracters C&aracters and 'umbers (isting F/D/ Printing c&aracters based on numbers/ S+ecial Printing C&aracters Constants (iteral Constants Symbolic Constants $numerated Constants (isting F/M/ A demonstration of enumerated constants / Summary 23A 0or.s&o+ 2ui4 $-ercises

Day ) ?aria" es and Constants


Programs need a #ay to store t&e data t&ey use/ Qariables and constants offer various #ays to re+resent and mani+ulate t&at data/ %oday you #ill learn

Ho# to declare and define variables and constants/ Ho# to assign values to variables and mani+ulate t&ose values/ Ho# to #rite t&e value of a variable to t&e screen/

4,at Is a ?aria" e/

In C++ a variable is a +lace to store information/ A variable is a location in your com+uter6s memory in #&ic& you can store a value and from #&ic& you can later retrieve t&at value/ ,our com+uter6s memory can be vie#ed as a series of cubby&oles/ $ac& cubby&ole is one of many, many suc& &oles all lined u+/ $ac& cubby&ole""or memory location""is numbered se8uentially/ %&ese numbers are .no#n as memory addresses/ A variable reserves one or more cubby&oles in #&ic& you may store a value/ ,our variable6s name ?for e-am+le, myVariable@ is a label on one of t&ese cubby&oles, so t&at you can find it easily #it&out .no#ing its actual memory address/ )igure F/1 is a sc&ematic re+resentation of t&is idea/ As you can see from t&e figure, myVariable starts at memory address 10./ De+ending on t&e si4e of myVariable, it can ta.e u+ one or more memory addresses/ )igure F/1/ A schematic representation of memory. N$T+: ;AA is random access memory/ 0&en you run your +rogram, it is loaded into ;AA from t&e dis. file/ All variables are also created in ;AA/ 0&en +rogrammers tal. of memory, it is usually ;AA to #&ic& t&ey are referring/ Setting Aside @emory 0&en you define a variable in C++, you must tell t&e com+iler #&at .ind of variable it is7 an integer, a c&aracter, and so fort&/ %&is information tells t&e com+iler &o# muc& room to set aside and #&at .ind of value you #ant to store in your variable/ $ac& cubby&ole is one byte large/ If t&e ty+e of variable you create is t#o bytes in si4e, it needs t#o bytes of memory, or t#o cubby&oles/ %&e ty+e of t&e variable ?for e-am+le, integer@ tells t&e com+iler &o# muc& memory ?&o# many cubby&oles@ to set aside for t&e variable/ Because com+uters use bits and bytes to re+resent values, and because memory is measured in bytes, it is im+ortant t&at you understand and are comfortable #it& t&ese conce+ts/ )or a full revie# of t&is to+ic, +lease read A++endi- B, 9C++ Tey#ords/9 Si8e of Integers n any one com+uter, eac& variable ty+e ta.es u+ a single, unc&anging amount of room/ %&at is, an integer mig&t be t#o bytes on one mac&ine, and four on anot&er, but on eit&er com+uter it is al#ays t&e same, day in and day out/ A c+ar variable ?used to &old c&aracters@ is most often one byte long/ A s+ort integer is t#o bytes on most com+uters, a lo!? integer is usually four bytes, and an integer ?#it&out t&e .ey#ord s+ort or lo!?@ can be t#o or four bytes/ (isting F/1 s&ould &el+ you determine t&e e-act si4e of t&ese ty+es on your com+uter/

New Term: A character is a single letter, number, or symbol t&at ta.es u+ one byte of memory/

-isting )'1' Determining t,e si8e of !aria" e ty0es on your com0uter'


1, )i!cl*(e <iostream.+" -, ., i!t mai!/0 1, 2 3, co*t << 4E+e siNe o a! i!t is,6t6t4 << bytes.6!47 8, co*t << 4E+e siNe o a s+ort i!t is,6t4 << bytes.6!47 9, co*t << 4E+e siNe o a lo!? i!t is,6t4 << bytes.6!47 ;, co*t << 4E+e siNe o a c+ar is,6t6t4 << bytes.6!47 C, co*t << 4E+e siNe o a loat is,6t6t4 << bytes.6!47 10, co*t << 4E+e siNe o a (o*ble is,6t4 << bytes.6!47 11, 1-, ret*r! 07 1., : O*t#*t, E+e siNe o a! i!t is, - bytes. E+e siNe o a s+ort i!t is, - bytes. E+e siNe o a lo!? i!t is, 1 bytes. E+e siNe o a c+ar is, 1 bytes. E+e siNe o a loat is, 1 bytes. E+e siNe o a (o*ble is, ; bytes.

siNeo /i!t0 siNeo /s+ort0 siNeo /lo!?0 siNeo /c+ar0 siNeo / loat0

<< 4 << 4 << 4 << 4 << 4

siNeo /(o*ble0 << 4

N$T+: n your com+uter, t&e number of bytes +resented mig&t be different/ Ana ysis: Aost of (isting F/1 s&ould be +retty familiar/ %&e one ne# feature is t&e use of t&e siNeo /0 function in lines E t&roug& 1>/ siNeo /0 is +rovided by your com+iler, and it tells you t&e si4e of t&e ob!ect you +ass in as a +arameter/ )or e-am+le, on line E t&e .ey#ord i!t is +assed into siNeo /0/ :sing siNeo /0, I #as able to determine t&at on my com+uter an i!t is e8ual to a s+ort i!t, #&ic& is 1 bytes/ signed and unsigned In addition, all integer ty+es come in t#o varieties7 si?!e( and *!si?!e(/ %&e idea &ere is t&at sometimes you need negative numbers, and sometimes you don6t/ Integers ?s+ort and lo!?@ #it&out t&e #ord 9unsigned9 are assumed to be si?!e(/ Mi?!e( integers are eit&er negative or +ositive/ U!si?!e( integers are al#ays +ositive/ Because you &ave t&e same number of bytes for bot& si?!e( and *!si?!e( integers, t&e largest number you can store in an *!si?!e( integer is t#ice as big as t&e largest +ositive number you can store in a si?!e( integer/ An *!si?!e( s+ort integer can &andle numbers from > to DE,EFE/ Half t&e numbers re+resented by a si?!e( s+ort are

negative, t&us a si?!e( s+ort can only re+resent numbers from "F1,MD= to F1,MDM/ If t&is is confusing, be sure to read A++endi- A, 9 +erator Precedence/9 .undamenta ?aria" e Ty0es Several ot&er variable ty+es are built into C++/ %&ey can be conveniently divided into integer variables ?t&e ty+e discussed so far@, floating"+oint variables, and c&aracter variables/ )loating"+oint variables &ave values t&at can be e-+ressed as fractions""t&at is, t&ey are real numbers/ C&aracter variables &old a single byte and are used for &olding t&e 1ED c&aracters and symbols of t&e ASCII and e-tended ASCII c&aracter sets/ New Term: The ASCII character set is t&e set of c&aracters standardi4ed for use on com+uters/ ASCII is an acronym for American Standard Code for Information Interc&ange/ 'early every com+uter o+erating system su++orts ASCII, t&oug& many su++ort ot&er international c&aracter sets as #ell/ %&e ty+es of variables used in C++ +rograms are described in %able F/1/ %&is table s&o#s t&e variable ty+e, &o# muc& room t&is boo. assumes it ta.es in memory, and #&at .inds of values can be stored in t&ese variables/ %&e values t&at can be stored are determined by t&e si4e of t&e variable ty+es, so c&ec. your out+ut from (isting F/1/

Ta" e )'1' ?aria" e Ty0es'


Type
*!si?!e( s+ort i!t s+ort i!t

Size 1 bytes

Values > to DE,EFE "F1,MD= to F1,MDM > to I,1<I,<DM,1<E "1,1IM,I=F,DI= to 1,1IM,I=F,DIM "F1,MD= to F1,MDM "1,1IM,I=F,DI= to 1,1IM,I=F,DIM > to DE,EFE > to I,1<I,<DM,1<E

1 bytes *!si?!e( lo!? i!t I bytes lo!? i!t I bytes i!t /18 bit0 1 bytes i!t /.- bit0 I bytes
*!si?!e( i!t /18 bit0 *!si?!e( i!t /.bit0 c+ar

1 bytes 1 bytes

1 byte 1ED c&aracter values loat I bytes 1/1e"F= to F/IeF= (o*ble = bytes 1/1e"F>= to 1/=eF>= N$T+: %&e si4es of variables mig&t be different from t&ose s&o#n in %able F/1, de+ending on t&e com+iler and t&e com+uter you are using/ If your com+uter &ad t&e same out+ut as #as +resented in (isting F/1, %able F/1 s&ould a++ly to your com+iler/ If your out+ut from (isting F/1 #as different, you s&ould consult your com+iler6s manual for t&e values t&at your variable ty+es can &old/

Defining a ?aria" e
,ou create or define a variable by stating its ty+e, follo#ed by one or more s+aces, follo#ed by t&e variable name and a semicolon/ %&e variable name can be virtually any combination of letters, but cannot contain s+aces/ (egal variable names include @, %-.Prs! , and myA?e/ Good variable names tell you #&at t&e variables are forB using good names ma.es it easier to understand t&e flo# of your +rogram/ %&e follo#ing statement defines an integer variable called myA?e7
i!t myA?e7

As a general +rogramming +ractice, avoid suc& &orrific names as %-.Prs! , and restrict single"letter variable names ?suc& as @ or i@ to variables t&at are used only very briefly/ %ry to use e-+ressive names suc& as myA?e or +owMa!y/ Suc& names are easier to understand t&ree #ee.s later #&en you are scratc&ing your &ead trying to figure out #&at you meant #&en you #rote t&at line of code/ %ry t&is e-+eriment7 Guess #&at t&ese +ieces of +rograms do, based on t&e first fe# lines of code7 $-am+le 1
mai!/0 2 *!si?!e( s+ort @7 *!si?!e( s+ort y7 ULONQ N7 N = @ B y7 :

$-am+le 1
mai! /0 2 *!si?!e( s+ort *!si?!e( s+ort *!si?!e( s+ort Area = 'i(t+ B :

'i(t+7 Le!?t+7 Area7 Le!?t+7

Clearly, t&e second +rogram is easier to understand, and t&e inconvenience of &aving to ty+e t&e longer variable names is more t&an made u+ for by &o# muc& easier it is to maintain t&e second +rogram/ Case Sensiti!ity C++ is case"sensitive/ In ot&er #ords, u++ercase and lo#ercase letters are considered to be different/ A variable named a?e is different from A?e, #&ic& is different from AQ</

N$T+: Some com+ilers allo# you to turn case sensitivity off/ Don6t be tem+ted to do t&isB your +rograms #on6t #or. #it& ot&er com+ilers, and ot&er C++ +rogrammers #ill be very confused by your code/ %&ere are various conventions for &o# to name variables, and alt&oug& it doesn6t muc& matter #&ic& met&od you ado+t, it is im+ortant to be consistent t&roug&out your +rogram/ Aany +rogrammers +refer to use all lo#ercase letters for t&eir variable names/ If t&e name re8uires t#o #ords ?for e-am+le, my car@, t&ere are t#o +o+ular conventions7 myRcar or myCar/ %&e latter form is called camel"notation, because t&e ca+itali4ation loo.s somet&ing li.e a camel6s &um+/ Some +eo+le find t&e underscore c&aracter ?myRcar@ to be easier to read, #&ile ot&ers +refer to avoid t&e underscore, because it is more difficult to ty+e/ %&is boo. uses camel" notation, in #&ic& t&e second and all subse8uent #ords are ca+itali4ed7 myCar, t+eS*icJ$row!Ko@, and so fort&/ N$T+: Aany advanced +rogrammers em+loy a notation style t&at is often referred to as Hungarian notation/ %&e idea be&ind Hungarian notation is to +refi- every variable #it& a set of c&aracters t&at describes its ty+e/ Integer variables mig&t begin #it& a lo#ercase letter i, longs mig&t begin #it& a lo#ercase l/ t&er notations indicate constants, globals, +ointers, and so fort&/ Aost of t&is is muc& more im+ortant in C +rogramming, because C++ su++orts t&e creation of user"defined ty+es ?see Day D, 9Basic Classes9@ and because C++ is strongly ty+ed/ Aeywords Some #ords are reserved by C++, and you may not use t&em as variable names/ %&ese are .ey#ords used by t&e com+iler to control your +rogram/ Tey#ords include i , w+ile, or, and mai!/ ,our com+iler manual s&ould +rovide a com+lete list, but generally, any reasonable name for a variable is almost certainly not a .ey#ord/ D$ define a variable by #riting t&e ty+e, t&en t&e variable name/ D$ use meaningful variable names/ D remember t&at C++ is case sensitive/ D$N:T use C++ .ey#ords as variable names/ D understand t&e number of bytes eac& variable ty+e consumes in memory, and #&at values can be stored in variables of t&at ty+e/ D$N:T use *!si?!e( variables for negative numbers/

Creating @ore T,an $ne ?aria" e at a Time


,ou can create more t&an one variable of t&e same ty+e in one statement by #riting t&e ty+e and t&en t&e variable names, se+arated by commas/ )or e-am+le7
*!si?!e( i!t myA?e> my'ei?+t7 lo!? area> wi(t+> le!?t+7 DD two *!si?!e( i!t Gariables DD t+ree lo!?s

As you can see, myA?e and my'ei?+t are eac& declared as *!si?!e( integer variables/ %&e second line declares t&ree individual lo!? variables named area, wi(t+, and le!?t+/ %&e ty+e ?lo!?@ is assigned to all t&e variables, so you cannot mi- ty+es in one definition statement/

Assigning ?a ues to 1our ?aria" es


,ou assign a value to a variable by using t&e assignment o+erator ?=@/ %&us, you #ould assign 3 to 'i(t+ by #riting
*!si?!e( s+ort 'i(t+7 'i(t+ = 37

,ou can combine t&ese ste+s and initiali4e 'i(t+ #&en you define it by #riting
*!si?!e( s+ort 'i(t+ = 37

Initiali4ation loo.s very muc& li.e assignment, and #it& integer variables, t&e difference is minor/ (ater, #&en constants are covered, you #ill see t&at some values must be initiali4ed because t&ey cannot be assigned to/ %&e essential difference is t&at initiali4ation ta.es +lace at t&e moment you create t&e variable/ Cust as you can define more t&an one variable at a time, you can initiali4e more t&an one variable at creation/ )or e-am+le7
DD create two lo!? Gariables a!( i!itialiNe t+em Flo!? wi(t+ = 3> le!?t+ = 97

%&is e-am+le initiali4es t&e lo!? integer variable wi(t+ to t&e value 3 and t&e lo!? integer variable le!?t+ to t&e value 9/ ,ou can even mi- definitions and initiali4ations7
i!t myA?e = .C> yo*rA?e> +isA?e = 107

%&is e-am+le creates t&ree ty+e i!t variables, and it initiali4es t&e first and t&ird/ (isting F/1 s&o#s a com+lete +rogram, ready to com+ile, t&at com+utes t&e area of a rectangle and #rites t&e ans#er to t&e screen/

-isting )'(' A demonstration of t,e use of !aria" es'


1, -, ., 1, 3, 8, 9, ;, DD Demo!stratio! o Gariables )i!cl*(e <iostream.+" i!t mai!/0 2 *!si?!e( s+ort i!t 'i(t+ = 3> Le!?t+7 Le!?t+ = 107

C, DD create a! *!si?!e( s+ort a!( i!itialiNe wit+ res*lt 10, DD o m*lti#lyi!? 'i(t+ by Le!?t+ 11, *!si?!e( s+ort i!t Area = 'i(t+ B Le!?t+7 1-, 1., co*t << 4'i(t+,4 << 'i(t+ << 46!47 11, co*t << 4Le!?t+, 4 << Le!?t+ << e!(l7 13, co*t << 4Area, 4 << Area << e!(l7 18, ret*r! 07 19, : O*t#*t, 'i(t+,3 Le!?t+, 10 Area, 30

Ana ysis: (ine 1 includes t&e re8uired i!cl*(e statement for t&e iostream6s library so t&at co*t #ill #or./ (ine I begins t&e +rogram/ n line D, 'i(t+ is defined as an *!si?!e( s+ort integer, and its value is initiali4ed to 3/ Anot&er *!si?!e( s+ort integer, Le!?t+, is also defined, but it is not initiali4ed/ n line M, t&e value 10 is assigned to Le!?t+/ n line 11, an *!si?!e( s+ort integer, Area, is defined, and it is initiali4ed #it& t&e value obtained by multi+lying 'i(t+ times Le!?t+/ n lines 1F"1E, t&e values of t&e variables are +rinted to t&e screen/ 'ote t&at t&e s+ecial #ord e!(l creates a ne# line/

ty0edef
It can become tedious, re+etitious, and, most im+ortant, error"+rone to .ee+ #riting *!si?!e( s+ort i!t/ C++ enables you to create an alias for t&is +&rase by using t&e .ey#ord ty#e(e , #&ic& stands for ty+e definition/ In effect, you are creating a synonym, and it is im+ortant to distinguis& t&is from creating a ne# ty+e ?#&ic& you #ill do on Day D@/ ty#e(e is used by #riting t&e .ey#ord ty#e(e , follo#ed by t&e e-isting ty+e and t&en t&e ne# name/ )or e-am+le
ty#e(e *!si?!e( s+ort i!t UM&ORE

creates t&e ne# name UM&ORE t&at you can use any#&ere you mig&t &ave #ritten *!si?!e( s+ort i!t/ (isting F/F is a re+lay of (isting F/1, using t&e ty+e definition UM&ORE rat&er t&an *!si?!e( s+ort i!t/

-isting )')' A demonstration of ty0edef'


1, -, ., 1, 3, 8, 9, DD BBBBBBBBBBBBBBBBB DD Demo!strates ty#e(e )i!cl*(e <iostream.+" ty#e(e Jeywor( DDty#e(e (e i!e(

*!si?!e( s+ort i!t UM&ORE7

Goi( mai!/0

;, 2 C, UM&ORE 'i(t+ = 37 10, UM&ORE Le!?t+7 11, Le!?t+ = 107 1-, UM&ORE Area = 'i(t+ B Le!?t+7 1., co*t << 4'i(t+,4 << 'i(t+ << 46!47 11, co*t << 4Le!?t+, 4 << Le!?t+ << e!(l7 13, co*t << 4Area, 4 << Area <<e!(l7 18, : O*t#*t, 'i(t+,3 Le!?t+, 10 Area, 30

Ana ysis: n line E, UM&ORE is ty+edefined as a synonym for *!si?!e( s+ort i!t/ %&e +rogram is very muc& li.e (isting F/1, and t&e out+ut is t&e same/

4,en to 9se s,ort and 4,en to 9se ong


ne source of confusion for ne# C++ +rogrammers is #&en to declare a variable to be ty+e lo!? and #&en to declare it to be ty+e s+ort/ %&e rule, #&en understood, is fairly straig&tfor#ard7 If t&ere is any c&ance t&at t&e value you6ll #ant to +ut into your variable #ill be too big for its ty+e, use a larger ty+e/ As seen in %able F/1, *!si?!e( s+ort integers, assuming t&at t&ey are t#o bytes, can &old a value only u+ to DE,EFE/ Mi?!e( s+ort integers can &old only &alf t&at/ Alt&oug& *!si?!e( lo!? integers can &old an e-tremely large number ?I,1<I,<DM,1<E@ t&at is still 8uite finite/ If you need a larger number, you6ll &ave to go to loat or (o*ble, and t&en you lose some +recision/ )loats and doubles can &old e-tremely large numbers, but only t&e first M or 1< digits are significant on most com+uters/ %&at means t&at t&e number is rounded off after t&at many digits/ 4ra00ing Around an unsigned Integer %&e fact t&at *!si?!e( lo!? integers &ave a limit to t&e values t&ey can &old is only rarely a +roblem, but #&at &a++ens if you do run out of room* 0&en an *!si?!e( integer reac&es its ma-imum value, it #ra+s around and starts over, muc& as a car odometer mig&t/ (isting F/I s&o#s #&at &a++ens if you try to +ut too large a value into a s+ort integer/

-isting )'*'A demonstration of 0utting too arge a !a ue in an unsigned integer'


1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, *!si?!e( s+ort i!t smallN*mber7 3, smallN*mber = 833.37 8, co*t << 4small !*mber,4 << smallN*mber << e!(l7

9, smallN*mberAA7 ;, co*t << 4small !*mber,4 << smallN*mber << e!(l7 C, smallN*mberAA7 10, co*t << 4small !*mber,4 << smallN*mber << e!(l7 11, ret*r! 07 1-, : O*t#*t, small !*mber,833.3 small !*mber,0 small !*mber,1

Ana ysis: n line I, smallN*mber is declared to be an *!si?!e( s+ort i!t, #&ic& on my com+uter is a t#o"byte variable, able to &old a value bet#een > and DE,EFE/ n line E, t&e ma-imum value is assigned to smallN*mber, and it is +rinted on line D/ n line M, smallN*mber is incrementedB t&at is, 1 is added to it/ %&e symbol for incrementing is AA ?as in t&e name C++""an incremental increase from C@/ %&us, t&e value in smallN*mber #ould be 83>3.8/ Ho#ever, *!si?!e( s+ort integers can6t &old a number larger t&an DE,EFE, so t&e value is #ra++ed around to 0, #&ic& is +rinted on line =/ n line < smallN*mber is incremented again, and t&en its ne# value, 1, is +rinted/ 4ra00ing Around a signed Integer A si?!e( integer is different from an *!si?!e( integer, in t&at &alf of t&e values you can re+resent are negative/ Instead of +icturing a traditional car odometer, you mig&t +icture one t&at rotates u+ for +ositive numbers and do#n for negative numbers/ ne mile from > is eit&er 1 or "1/ 0&en you run out of +ositive numbers, you run rig&t into t&e largest negative numbers and t&en count bac. do#n to >/ (isting F/E s&o#s #&at &a++ens #&en you add 1 to t&e ma-imum +ositive number in an *!si?!e( s+ort integer/

-isting )';' A demonstration of adding too arge a num"er to a signed integer'


1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, s+ort i!t smallN*mber7 3, smallN*mber = .-9897 8, co*t << 4small !*mber,4 << smallN*mber << e!(l7 9, smallN*mberAA7 ;, co*t << 4small !*mber,4 << smallN*mber << e!(l7 C, smallN*mberAA7 10, co*t << 4small !*mber,4 << smallN*mber << e!(l7 11, ret*r! 07 1-, : O*t#*t, small !*mber,.-989 small !*mber,I.-98; small !*mber,I.-989

Ana ysis: n line I, smallN*mber is declared t&is time to be a si?!e( s+ort integer ?if you don6t e-+licitly say t&at it is *!si?!e(, it is assumed to be si?!e(@/ %&e +rogram +roceeds muc& as t&e +receding one, but t&e out+ut is 8uite different/ %o fully understand t&is out+ut, you must be comfortable #it& &o# si?!e( numbers are re+resented as bits in a t#o"byte integer/ )or details, c&ec. A++endi- C, 9Binary and He-adecimal/9 %&e bottom line, &o#ever, is t&at !ust li.e an *!si?!e( integer, t&e si?!e( integer #ra+s around from its &ig&est +ositive value to its &ig&est negative value/

C,aracters
C&aracter variables ?ty#e c+ar@ are ty+ically 1 byte, enoug& to &old 1ED values ?see A++endi- C@/ A c+ar can be inter+reted as a small number ?>"1EE@ or as a member of t&e ASCII set/ ASCII stands for t&e American Standard Code for Information Interc&ange/ %&e ASCII c&aracter set and its IS ?International Standards rgani4ation@ e8uivalent are a #ay to encode all t&e letters, numerals, and +unctuation mar.s/ Com+uters do not .no# about letters, +unctuation, or sentences/ All t&ey understand are numbers/ In fact, all t&ey really .no# about is #&et&er or not a sufficient amount of electricity is at a +articular !unction of #ires/ If so, it is re+resented internally as a 1B if not, it is re+resented as a 0/ By grou+ing ones and 4eros, t&e com+uter is able to generate +atterns t&at can be inter+reted as numbers, and t&ese in turn can be assigned to letters and +unctuation/ In t&e ASCII code, t&e lo#ercase letter 9a9 is assigned t&e value C9/ All t&e lo#er" and u++ercase letters, all t&e numerals, and all t&e +unctuation mar.s are assigned values bet#een 1 and 11=/ Anot&er 11= mar.s and symbols are reserved for use by t&e com+uter ma.er, alt&oug& t&e IBA e-tended c&aracter set &as become somet&ing of a standard/ C,aracters and Num"ers 0&en you +ut a c&aracter, for e-am+le, TaH, into a c+ar variable, #&at is really t&ere is !ust a number bet#een > and 1EE/ %&e com+iler .no#s, &o#ever, &o# to translate bac. and fort& bet#een c&aracters ?re+resented by a single 8uotation mar. and t&en a letter, numeral, or +unctuation mar., follo#ed by a closing single 8uotation mar.@ and one of t&e ASCII values/ %&e valueOletter relations&i+ is arbitraryB t&ere is no +articular reason t&at t&e lo#ercase 9a9 is assigned t&e value C9/ As long as everyone ?your .eyboard, com+iler, and screen@ agrees, t&ere is no +roblem/ It is im+ortant to reali4e, &o#ever, t&at t&ere is a big difference bet#een t&e value 3 and t&e c&aracter T3H/ %&e latter is actually valued at 3., muc& as t&e letter TaH is valued at C9/

-isting )'B' Printing c,aracters "ased on num"ers


1, )i!cl*(e <iostream.+"

-, i!t mai!/0 ., 2 1, or /i!t i = .-7 i<1-;7 iAA0 3, co*t << /c+ar0 i7 8, ret*r! 07 9, : O*t#*t, 54)UVQH/0BA>.D01-.1389;C,7<"OWA$CD<KQ&I%XLMNOP RSRMEUV'=YZ[6\]Habc(e ?+iLJlm!o#Prst*Gw@yN<^"_s

%&is sim+le +rogram +rints t&e c&aracter values for t&e integers F1 t&roug& 11M/ S0ecia Printing C,aracters %&e C++ com+iler recogni4es some s+ecial c&aracters for formatting/ %able F/1 s&o#s t&e most common ones/ ,ou +ut t&ese into your code by ty+ing t&e bac.slas& ?called t&e esca+e c&aracter@, follo#ed by t&e c&aracter/ %&us, to +ut a tab c&aracter into your code, you #ould enter a single 8uotation mar., t&e slas&, t&e letter t, and t&en a closing single 8uotation mar.7
c+ar tabC+aracter = T6tH7

%&is e-am+le declares a c+ar variable ?tabC+aracter@ and initiali4es it #it& t&e c&aracter value 6t, #&ic& is recogni4ed as a tab/ %&e s+ecial +rinting c&aracters are used #&en +rinting eit&er to t&e screen or to a file or ot&er out+ut device/ New Term: An escape character c&anges t&e meaning of t&e c&aracter t&at follo#s it/ )or e-am+le, normally t&e c&aracter ! means t&e letter n, but #&en it is +receded by t&e esca+e c&aracter ?6@ it means ne# line/

Ta" e )'(' T,e +sca0e C,aracters/


Character What it means 6! ne# line 6t tab 6b bac.s+ace 64 double 8uote 6H single 8uote 6O 8uestion mar. 66 bac.slas&

Constants
(i.e variables, constants are data storage locations/ :nli.e variables, and as t&e name im+lies, constants don6t c&ange/ ,ou must initiali4e a constant #&en you create it, and you cannot assign a ne# value later/

-itera Constants C++ &as t#o ty+es of constants7 literal and symbolic/ A literal constant is a value ty+ed directly into your +rogram #&erever it is needed/ )or e-am+le
i!t myA?e = .C7

is a variable of ty+e i!tB .C is a literal constant/ ,ou can6t assign a value to .C, and its value can6t be c&anged/
myA?e

Sym"o ic Constants A symbolic constant is a constant t&at is re+resented by a name, !ust as a variable is re+resented/ :nli.e a variable, &o#ever, after a constant is initiali4ed, its value can6t be c&anged/ If your +rogram &as one integer variable named st*(e!ts and anot&er named classes, you could com+ute &o# many students you &ave, given a .no#n number of classes, if you .ne# t&ere #ere 1E students +er class7
st*(e!ts = classes B 137

N$T+: B indicates multi+lication/ In t&is e-am+le, 13 is a literal constant/ ,our code #ould be easier to read, and easier to maintain, if you substituted a symbolic constant for t&is value7
st*(e!ts = classes B st*(e!tsPerClass

If you later decided to c&ange t&e number of students in eac& class, you could do so #&ere you define t&e constant st*(e!tsPerClass #it&out &aving to ma.e a c&ange every +lace you used t&at value/ %&ere are t#o #ays to declare a symbolic constant in C++/ %&e old, traditional, and no# obsolete #ay is #it& a +re+rocessor directive, )(e i!e/ Defining Constants #it& Jdefine %o define a constant t&e traditional #ay, you #ould enter t&is7
)(e i!e st*(e!tsPerClass 13

'ote t&at st*(e!tsPerClass is of no +articular ty+e ?i!t, c+ar, and so on@/ )(e i!e does a sim+le te-t substitution/ $very time t&e +re+rocessor sees t&e #ord st*(e!tsPerClass, it +uts in t&e te-t 13/

Because t&e +re+rocessor runs before t&e com+iler, your com+iler never sees your constantB it sees t&e number 13/ Defining Constants #it& const Alt&oug& )(e i!e #or.s, t&ere is a ne#, muc& better #ay to define constants in C++7
co!st *!si?!e( s+ort i!t st*(e!tsPerClass = 137

%&is e-am+le also declares a symbolic constant named st*(e!tsPerClass, but t&is time st*(e!tsPerClass is ty+ed as an *!si?!e( s+ort i!t/ %&is met&od &as several advantages in ma.ing your code easier to maintain and in +reventing bugs/ %&e biggest difference is t&at t&is constant &as a ty+e, and t&e com+iler can enforce t&at it is used according to its ty+e/ N$T+: Constants cannot be c&anged #&ile t&e +rogram is running/ If you need to c&ange st*(e!tsPerClass, for e-am+le, you need to c&ange t&e code and recom+ile/ D$N:T use t&e term i!t/ :se s+ort and lo!? to ma.e it clear #&ic& si4e number you intended/ D$ #atc& for numbers overrunning t&e si4e of t&e integer and #ra++ing around incorrect values/ D$ give your variables meaningful names t&at reflect t&eir use/ D$N:T use .ey#ords as variable names/

+numerated Constants
$numerated constants enable you to create ne# ty+es and t&en to define variables of t&ose ty+es #&ose values are restricted to a set of +ossible values/ )or e-am+le, you can declare COLOR to be an enumeration, and you can define t&at t&ere are five values for COLOR7 R<D, $LU<, QR<<N, '&IE<, and $LACX/ %&e synta- for enumerated constants is to #rite t&e .ey#ord e!*m, follo#ed by t&e ty+e name, an o+en brace, eac& of t&e legal values se+arated by a comma, and finally a closing brace and a semicolon/ Here6s an e-am+le7
e!*m COLOR 2 R<D> $LU<> QR<<N> '&IE<> $LACX :7

%&is statement +erforms t#o tas.s7 1' It ma.es COLOR t&e name of an enumeration, t&at is, a ne# ty+e/ (' It ma.es R<D a symbolic constant #it& t&e value 0, $LU< a symbolic constant #it& t&e value 1, QR<<N a symbolic constant #it& t&e value -, and so fort&/ $very enumerated constant &as an integer value/ If you don6t s+ecify ot&er#ise, t&e first constant #ill &ave t&e value 0, and t&e rest #ill count u+ from t&ere/ Any one of t&e constants can be initiali4ed #it& a +articular value, &o#ever, and t&ose t&at are not initiali4ed #ill count u+#ard from t&e ones before t&em/ %&us, if you #rite
e!*m Color 2 R<D=100> $LU<> QR<<N=300> '&IE<> $LACX=900 :7

t&en R<D #ill &ave t&e value 100B $LU<, t&e value 101B QR<<N, t&e value 300B '&IE<, t&e value 301B and $LACX, t&e value 900/ ,ou can define variables of ty+e COLOR, but t&ey can be assigned only one of t&e enumerated values ?in t&is case, R<D, $LU<, QR<<N, '&IE<, or $LACX, or else 100, 101, 300, 301, or 900@/ ,ou can assign any color value to your COLOR variable/ In fact, you can assign any integer value, even if it is not a legal color, alt&oug& a good com+iler #ill issue a #arning if you do/ It is im+ortant to reali4e t&at enumerator variables actually are of ty+e *!si?!e( i!t, and t&at t&e enumerated constants e8uate to integer variables/ It is, &o#ever, very convenient to be able to name t&ese values #&en #or.ing #it& colors, days of t&e #ee., or similar sets of values/ (isting F/M +resents a +rogram t&at uses an enumerated ty+e/

-isting )'C' A demonstration of enumerated constants'


1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, e!*m Days 2 M*!(ay> Mo!(ay> E*es(ay> 'e(!es(ay> E+*rs(ay> Kri(ay> FRMat*r(ay :7 3, 8, Days DayO 7 9, i!t @7 ;, C, co*t << 4'+at (ay wo*l( yo* liJe o /0I80O 47 10, ci! "" @7 11, DayO = Days/@07 1-, 1., i /DayO == M*!(ay ^^ DayO == Mat*r(ay0 11, co*t << 46!Yo*Hre alrea(y o o! weeJe!(s56!47 13, else 18, co*t << 46!OJay> IHll #*t i! t+e Gacatio! (ay.6!47 19, ret*r! 07 1;, : O*t#*t, '+at (ay wo*l( yo* liJe o /0I80O 1 OJay> IHll #*t i! t+e Gacatio! (ay. '+at (ay wo*l( yo* liJe o Yo*Hre alrea(y o /0I80O 0

o! weeJe!(s5

Ana ysis: n line I, t&e enumerated constant DAYM is defined, #it& seven values counting u+#ard from >/ %&e user is +rom+ted for a day on line </ %&e c&osen value, a number bet#een > and D, is com+ared on line 1F to t&e enumerated values for Sunday and Saturday, and action is ta.en accordingly/ %&e i statement #ill be covered in more detail on Day I, 9$-+ressions and Statements/9 ,ou cannot ty+e t&e #ord 9Sunday9 #&en +rom+ted for a dayB t&e +rogram does not .no# &o# to translate t&e c&aracters in M*!(ay into one of t&e enumerated values/

N$T+: )or t&is and all t&e small +rograms in t&is boo., I6ve left out all t&e code you #ould normally #rite to deal #it& #&at &a++ens #&en t&e user ty+es ina++ro+riate data/ )or e-am+le, t&is +rogram doesn6t c&ec., as it #ould in a real +rogram, to ma.e sure t&at t&e user ty+es a number bet#een > and D/ %&is detail &as been left out to .ee+ t&ese +rograms small and sim+le, and to focus on t&e issue at &and/

Summary
%&is c&a+ter &as discussed numeric and c&aracter variables and constants, #&ic& are used by C++ to store data during t&e e-ecution of your +rogram/ 'umeric variables are eit&er integral ?c+ar, s+ort, and lo!? i!t@ or t&ey are floating +oint ? loat and (o*ble@/ 'umeric variables can also be si?!e( or *!si?!e(/ Alt&oug& all t&e ty+es can be of various si4es among different com+uters, t&e ty+e s+ecifies an e-act si4e on any given com+uter/ ,ou must declare a variable before it can be used, and t&en you must store t&e ty+e of data t&at you6ve declared as correct for t&at variable/ If you +ut too large a number into an integral variable, it #ra+s around and +roduces an incorrect result/ %&is c&a+ter also revie#ed literal and symbolic constants, as #ell as enumerated constants, and s&o#ed t#o #ays to declare a symbolic constant7 using )(e i!e and using t&e .ey#ord co!st/

67A
6' If a s,ort int can run out of room and wra0 around# w,y not a ways use ong integers/ A 'Bot& s+ort integers and lo!? integers #ill run out of room and #ra+ around, but a lo!? integer #ill do so #it& a muc& larger number/ )or e-am+le, an *!si?!e( s+ort i!t #ill #ra+ around after DE,EFE, #&ereas an *!si?!e( lo!? i!t #ill not #ra+ around until I,1<I,<DM,1<E/ Ho#ever, on most mac&ines, a lo!? integer ta.es u+ t#ice as muc& memory every time you declare one ?I bytes versus 1 bytes@, and a +rogram #it& 1>> suc& variables #ill consume an e-tra 1>> bytes of ;AA/ )ran.ly, t&is is less of a +roblem t&an it used to be, because most +ersonal com+uters no# come #it& many t&ousands ?if not millions@ of bytes of memory/ 6' 4,at ,a00ens if I assign a num"er wit, a decima 0oint to an integer rat,er t,an to a f oat/ Consider t,e fo owing ine of code:
i!t aN*mber = 3.17

A' A good com+iler #ill issue a #arning, but t&e assignment is com+letely legal/ %&e number you6ve assigned #ill be truncated into an integer/ %&us, if you assign 3.1 to an integer variable, t&at variable #ill &ave t&e value 3/ Information #ill be lost, &o#ever, and if you t&en try to assign t&e value in t&at integer variable to a loat variable, t&e loat variable #ill &ave only 3/

6' 4,y not use itera constantsD w,y go to t,e "ot,er of using sym"o ic constants/ A' If you use t&e value in many +laces t&roug&out your +rogram, a symbolic constant allo#s all t&e values to c&ange !ust by c&anging t&e one definition of t&e constant/ Symbolic constants also s+ea. for t&emselves/ It mig&t be &ard to understand #&y a number is being multi+lied by FD>, but it6s muc& easier to understand #&at6s going on if t&e number is being multi+lied by (e?reesI!ACircle/ 6' 4,at ,a00ens if I assign a negati!e num"er to an unsigned !aria" e/ Consider t,e fo owing ine of code:
*!si?!e( i!t aPositiGeN*mber = I17

A' A good com+iler #ill #arn, but t&e assignment is legal/ %&e negative number #ill be assessed as a bit +attern and assigned to t&e variable/ %&e value of t&at variable #ill t&en be inter+reted as an *!si?!e( number/ %&us, "1, #&ose bit +attern is 11111111 11111111 ?0@KK in &e-@, #ill be assessed as t&e *!si?!e( value 83>3.3/ If t&is information confuses you, refer to A++endi- C/ 6' Can I wor3 wit, C++ wit,out understanding "it 0atterns# "inary arit,metic# and ,e2adecima / A' ,es, but not as effectively as if you do understand t&ese to+ics/ C++ does not do as good a !ob as some languages at 9+rotecting9 you from #&at t&e com+uter is really doing/ %&is is actually a benefit, because it +rovides you #it& tremendous +o#er t&at ot&er languages don6t/ As #it& any +o#er tool, &o#ever, to get t&e most out of C++ you must understand &o# it #or.s/ Programmers #&o try to +rogram in C++ #it&out understanding t&e fundamentals of t&e binary system often are confused by t&eir results/

4or3s,o0
%&e 0or.s&o+ +rovides 8ui4 8uestions to &el+ you solidify your understanding of t&e material covered, and e-ercises to +rovide you #it& e-+erience in using #&at you6ve learned/ %ry to ans#er t&e 8ui4 and e-ercise 8uestions before c&ec.ing t&e ans#ers in A++endi- D, and ma.e sure t&at you understand t&e ans#ers before continuing to t&e ne-t c&a+ter/ 6ui8 1' 0&at is t&e difference bet#een an integral variable and a floating"+oint variable* (' 0&at are t&e differences bet#een an *!si?!e( s+ort i!t and a lo!? i!t*

)' 0&at are t&e advantages of using a symbolic constant rat&er t&an a literal constant* *' 0&at are t&e advantages of using t&e co!st .ey#ord rat&er t&an )(e i!e* ;' 0&at ma.es for a good or bad variable name* B' Given t&is e!*m, #&at is t&e value of $LU<*
e!*m COLOR 2 '&IE<> $LACX = 100> R<D> $LU<> QR<<N = .00 :7

C' 0&ic& of t&e follo#ing variable names are good, #&ic& are bad, and #&ic& are invalid* a' A?e "' 5e@ c' R9C% d' EotalI!come e' RRI!Gali( +2ercises 1' 0&at #ould be t&e correct variable ty+e in #&ic& to store t&e follo#ing information* a' ,our age/ "' %&e area of your bac.yard/ c' %&e number of stars in t&e gala-y/ d' %&e average rainfall for t&e mont& of Canuary/ (' Create good variable names for t&is information/ )' Declare a constant for +i as F/1I1E</ *' Declare a loat variable and initiali4e it using your +i constant/

Day I
o

$-+ressions and Statements Statements 0&ites+ace Bloc.s and Com+ound Statements $-+ressions (isting I/1/ $valuating com+le- e-+ressions/ +erators Assignment +erator Aat&ematical +erators (isting I/1/ A demonstration of subtraction and integer overflo#/ Integer Division and Aodulus Combining t&e Assignment and Aat&ematical +erators Increment and Decrement Prefi- and Postfi (isting I/F/ A demonstration of +refi- and +ostfi- o+erators/ Precedence 'esting Parent&eses %&e 'ature of %rut& ;elational +erators %&e if Statement (isting I/I/ A demonstration of branc&ing based on relational o+erators/ Indentation Styles else (isting I/E/ Demonstrating t&e else .ey#ord/ %&e if Statement Advanced if Statements (isting I/D/ A com+le-, nested if statement/ :sing Braces in 'ested if Statements (isting I/M/ A demonstration of #&y braces &el+ clarify #&ic& else statement goes #it& #&ic& if statement/ (isting I/=/ A demonstration of t&e +ro+er use of braces #it& an if statement/ (ogical +erators (ogical A'D (ogical ; (ogical ' % ;elational Precedence Aore About %rut& and )alse&ood Conditional ?%ernary@ +erator (isting I/</ A demonstration of t&e conditional o+erator/

Summary 23A 0or.s&o+ 2ui4 $-ercises

Day * +20ressions and Statements


At its &eart, a +rogram is a set of commands e-ecuted in se8uence/ %&e +o#er in a +rogram comes from its ca+ability to e-ecute one or anot&er set of commands, based on #&et&er a +articular condition is true or false/ %oday you #ill learn

0&at statements are/ 0&at bloc.s are/ 0&at e-+ressions are/ Ho# to branc& your code based on conditions/ 0&at trut& is, and &o# to act on it/

Statements
In C++ a statement controls t&e se8uence of e-ecution, evaluates an e-+ression, or does not&ing ?t&e null statement@/ All C++ statements end #it& a semicolon, even t&e null statement, #&ic& is !ust t&e semicolon and not&ing else/ ne of t&e most common statements is t&e follo#ing assignment statement7
@ = a A b7

:nli.e in algebra, t&is statement does not mean t&at @ e8uals aAb/ %&is is read, 9Assign t&e value of t&e sum of a and b to @,9 or 9Assign to @, aAb/9 $ven t&oug& t&is statement is doing t#o t&ings, it is one statement and t&us &as one semicolon/ %&e assignment o+erator assigns #&atever is on t&e rig&t side of t&e e8ual sign to #&atever is on t&e left side/ New Term: A null statement is a statement t&at does not&ing/ 4,ites0ace 0&ites+ace ?tabs, s+aces, and ne#lines@ is generally ignored in statements/ %&e assignment statement +reviously discussed could be #ritten as
@=aAb7

or as
@ A b 7 =a

Alt&oug& t&is last variation is +erfectly legal, it is also +erfectly foolis&/ 0&ites+ace can be used to ma.e your +rograms more readable and easier to maintain, or it can be used to create &orrific and indeci+&erable code/ In t&is, as in all t&ings, C++ +rovides t&e +o#erB you su++ly t&e !udgment/ New Term: Whitespace characters ?s+aces, tabs, and ne#lines@ cannot be seen/ If t&ese c&aracters are +rinted, you see only t&e #&ite of t&e +a+er/ B oc3s and Com0ound Statements Any +lace you can +ut a single statement, you can +ut a com+ound statement, also called a bloc./ A bloc. begins #it& an o+ening brace ?2@ and ends #it& a closing brace ?:@/ Alt&oug& every statement in t&e bloc. must end #it& a semicolon, t&e bloc. itself does not end #it& a semicolon/ )or e-am+le
2 tem# = a7 a = b7 b = tem#7

%&is bloc. of code acts as one statement and s#a+s t&e values in t&e variables a and b/ D$ use a closing brace any time you &ave an o+ening brace/ D$ end your statements #it& a semicolon/ D$ use #&ites+ace !udiciously to ma.e your code clearer/

+20ressions
Anyt&ing t&at evaluates to a value is an e-+ression in C++/ An e-+ression is said to return a value/ %&us, .A-7 returns t&e value 3 and so is an e-+ression/ All e-+ressions are statements/ %&e myriad +ieces of code t&at 8ualify as e-+ressions mig&t sur+rise you/ Here are t&ree e-am+les7
..PI Meco!(sPerMi!*te DD ret*r!s t+e Gal*e ..DD loat co!st t+at ret*r!s t+e Gal*e ..11 DD i!t co!st t+at ret*r!s 80

Assuming t&at PI is a constant e8ual to ..11 and Meco!(sPerMi!*te is a constant e8ual to 80, all t&ree of t&ese statements are e-+ressions/

%&e com+licated e-+ression


@ = a A b7

not only adds a and b and assigns t&e result to @, but returns t&e value of t&at assignment ?t&e value of @@ as #ell/ %&us, t&is statement is also an e-+ression/ Because it is an e-+ression, it can be on t&e rig&t side of an assignment o+erator7
y = @ = a A b7

%&is line is evaluated in t&e follo#ing order7 Add a to b/ Assign t&e result of t&e e-+ression a A b to @/ Assign t&e result of t&e assignment e-+ression @ = a A b to y/ If a, b, @, and y are all integers, and if a &as t&e value - and b &as t&e value 3, bot& @ and y #ill be assigned t&e value 9/

-isting *'1' +!a uating com0 e2 e20ressions'


1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, i!t a=0> b=0> @=0> y=.37 3, co*t << 4a, 4 << a << 4 b, 4 << b7 8, co*t << 4 @, 4 << @ << 4 y, 4 << y << e!(l7 9, a = C7 ;, b = 97 C, y = @ = aAb7 10, co*t << 4a, 4 << a << 4 b, 4 << b7 11, co*t << 4 @, 4 << @ << 4 y, 4 << y << e!(l7 1-, ret*r! 07 1., : O*t#*t, a, 0 b, 0 @, 0 y, .3 a, C b, 9 @, 18 y, 18

Ana ysis: n line I, t&e four variables are declared and initiali4ed/ %&eir values are +rinted on lines E and D/ n line M, a is assigned t&e value C/ ne line =, b is assigned t&e value 9/ n line <, t&e values of a and b are summed and t&e result is assigned to @/ %&is e-+ression ?@ = aAb@ evaluates to a value ?t&e sum of a A b@, and t&at value is in turn assigned to y/

$0erators
An o+erator is a symbol t&at causes t&e com+iler to ta.e an action/ +erators act on o+erands, and in C++ all o+erands are e-+ressions/ In C++ t&ere are several different categories of o+erators/ %#o of t&ese categories are

Assignment o+erators/ Aat&ematical o+erators/ Assignment $0erator

%&e assignment o+erator ?=@ causes t&e o+erand on t&e left side of t&e assignment o+erator to &ave its value c&anged to t&e value on t&e rig&t side of t&e assignment o+erator/ %&e e-+ression
@ = a A b7

assigns t&e value t&at is t&e result of adding a and b to t&e o+erand @/ An o+erand t&at legally can be on t&e left side of an assignment o+erator is called an lvalue/ %&at #&ic& can be on t&e rig&t side is called ?you guessed it@ an rvalue/ Constants are r"values/ %&ey cannot be l"values/ %&us, you can #rite
@ = .37 DD oJ

but you can6t legally #rite


.3 = @7 DD error> !ot a! lGal*e5

New Term: An lvalue is an o+erand t&at can be on t&e left side of an e-+ression/ An rvalue is an o+erand t&at can be on t&e rig&t side of an e-+ression/ 'ote t&at all l"values are r"values, but not all r"values are l"values/ An e-am+le of an rvalue t&at is not an lvalue is a literal/ %&us, you can #rite @ = 37, but you cannot #rite 3 = @7/ @at,ematica $0erators %&ere are five mat&ematical o+erators7 addition ?A@, subtraction ?I@, multi+lication ?B@, division ?D@, and modulus ?V@/ Addition and subtraction #or. as you #ould e-+ect, alt&oug& subtraction #it& *!si?!e( integers can lead to sur+rising results, if t&e result is a negative number/ ,ou sa# somet&ing muc& li.e t&is yesterday, #&en variable overflo# #as described/ (isting I/1 s&o#s #&at &a++ens #&en you subtract a large *!si?!e( number from a small *!si?!e( number/

-isting *'(' A demonstration of su"traction and integer o!erf ow'


1, -, ., 1, 3, DD Listi!? 1.- I (emo!strates s*btractio! a!( DD i!te?er oGer low )i!cl*(e <iostream.+" i!t mai!/0

8, 2 9, *!si?!e( i!t (i ere!ce7 ;, *!si?!e( i!t bi?N*mber = 1007 C, *!si?!e( i!t smallN*mber = 307 10, (i ere!ce = bi?N*mber I smallN*mber7 11, co*t << 4Di ere!ce is, 4 << (i ere!ce7 1-, (i ere!ce = smallN*mber I bi?N*mber7 1., co*t << 46!Now (i ere!ce is, 4 << (i ere!ce <<e!(l7 11, ret*r! 07 13, : O*t#*t, Di ere!ce is, 30 Now (i ere!ce is, 1-C1C89-18

Ana ysis: %&e subtraction o+erator is invo.ed on line 1>, and t&e result is +rinted on line 11, muc& as #e mig&t e-+ect/ %&e subtraction o+erator is called again on line 11, but t&is time a large *!si?!e( number is subtracted from a small *!si?!e( number/ %&e result #ould be negative, but because it is evaluated ?and +rinted@ as an *!si?!e( number, t&e result is an overflo#, as described yesterday/ %&is to+ic is revie#ed in detail in A++endiA, 9 +erator Precedence/9 Integer Di!ision and @odu us Integer division is some#&at different from everyday division/ 0&en you divide 11 by I, t&e result is a real number ?a number #it& a fraction@/ Integers don6t &ave fractions, and so t&e 9remainder9 is lo++ed off/ %&e ans#er is t&erefore E/ %o get t&e remainder, you ta.e 11 modulus I ?11 U I@ and t&e result is 1/ %&e modulus o+erator tells you t&e remainder after an integer division/ )inding t&e modulus can be very useful/ )or e-am+le, you mig&t #ant to +rint a statement on every 1>t& action/ Any number #&ose value is > #&en you modulus 1> #it& t&at number is an e-act multi+le of 1>/ %&us 1 U 1> is 1, 1 U 1> is 1, and so fort&, until 1> U 1>, #&ose result is >/ 11 U 1> is bac. to 1, and t&is +attern continues until t&e ne-t multi+le of 1>, #&ic& is 1>/ 0e6ll use t&is tec&ni8ue #&en loo+ing is discussed on Day M, 9Aore Program )lo#/9 4A5NING: Aany novice C++ +rogrammers inadvertently +ut a semicolon after t&eir i statements7
i /MomeVal*e < 1007 MomeVal*e = 107

0&at #as intended &ere #as to test #&et&er MomeVal*e is less t&an 1>, and if so, to set it to 10, ma.ing 10 t&e minimum value for MomeVal*e/ ;unning t&is code sni++et #ill s&o# t&at MomeVal*e is al#ays set to 105 0&y* %&e i statement terminates #it& t&e semicolon ?t&e do"not&ing o+erator@/ ;emember t&at indentation &as no meaning to t&e com+iler/ %&is sni++et could more accurately &ave been #ritten as7
i /MomeVal*e < 100 DD test 7 DD (o !ot+i!? MomeVal*e = 107 DD assi?!

;emoving t&e semicolon #ill ma.e t&e final line +art of t&e i statement and #ill ma.e t&is code do #&at #as intended/

Com"ining t,e Assignment and @at,ematica $0erators


It is not uncommon to #ant to add a value to a variable, and t&en to assign t&e result bac. into t&e variable/ If you &ave a variable myA?e and you #ant to increase t&e value by t#o, you can #rite
i!t myA?e = 37 i!t tem#7 tem# = myA?e A -7 myA?e = tem#7

DD a(( 3 A - a!( #*t it i! tem# DD #*t it bacJ i! myA?e

%&is met&od, &o#ever, is terribly convoluted and #asteful/ In C++, you can +ut t&e same variable on bot& sides of t&e assignment o+erator, and t&us t&e +receding becomes
myA?e = myA?e A -7

#&ic& is muc& better/ In algebra t&is e-+ression #ould be meaningless, but in C++ it is read as 9add t#o to t&e value in myA?e and assign t&e result to myA?e/9 $ven sim+ler to #rite, but +er&a+s a bit &arder to read is
myA?e A= -7

%&e self"assigned addition o+erator ?A=@ adds t&e rvalue to t&e lvalue and t&en reassigns t&e result into t&e lvalue/ %&is o+erator is +ronounced 9+lus"e8uals/9 %&e statement #ould be read 9myA?e +lus"e8uals t#o/9 If myA?e &ad t&e value 1 to start, it #ould &ave 8 after t&is statement/ %&ere are self"assigned subtraction ?I=@, division ?D=@, multi+lication ?B=@, and modulus ?V=@ o+erators as #ell/

Increment and Decrement


%&e most common value to add ?or subtract@ and t&en reassign into a variable is 1/ In C+ +, increasing a value by 1 is called incrementing, and decreasing by 1 is called decrementing/ %&ere are s+ecial o+erators to +erform t&ese actions/ %&e increment o+erator ?AA@ increases t&e value of t&e variable by 1, and t&e decrement o+erator ?II@ decreases it by 1/ %&us, if you &ave a variable, C, and you #ant to increment it, you #ould use t&is statement7
CAA7 DD Mtart wit+ C a!( i!creme!t it.

%&is statement is e8uivalent to t&e more verbose statement

C = C A 17

#&ic& you learned is also e8uivalent to t&e moderately verbose statement


C A= 17

Prefi2 and Postfi2 Bot& t&e increment o+erator ?AA@ and t&e decrement o+erator?II@ come in t#o varieties7 +refi- and +ostfi-/ %&e +refi- variety is #ritten before t&e variable name ?AAmyA?e@B t&e +ostfi- variety is #ritten after ?myA?eAA@/ In a sim+le statement, it doesn6t muc& matter #&ic& you use, but in a com+le- statement, #&en you are incrementing ?or decrementing@ a variable and t&en assigning t&e result to anot&er variable, it matters very muc&/ %&e +refi- o+erator is evaluated before t&e assignment, t&e +ostfi- is evaluated after/ %&e semantics of +refi- is t&is7 Increment t&e value and t&en fetc& it/ %&e semantics of +ostfi- is different7 )etc& t&e value and t&en increment t&e original/ %&is can be confusing at first, but if @ is an integer #&ose value is 3 and you #rite
i!t a = AA@7

you &ave told t&e com+iler to increment @ ?ma.ing it 8@ and t&en fetc& t&at value and assign it to a/ %&us, a is no# 8 and @ is no# 8/ If, after doing t&is, you #rite
i!t b = @AA7

you &ave no# told t&e com+iler to fetc& t&e value in @ ?8@ and assign it to b, and t&en go bac. and increment @/ %&us, b is no# 8, but @ is no# 9/ (isting I/F s&o#s t&e use and im+lications of bot& ty+es/

-isting *')' A demonstration of 0refi2 and 0ostfi2 o0erators'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, DD Listi!? 1.. I (emo!strates *se o DD #re i@ a!( #ost i@ i!creme!t a!( DD (ecreme!t o#erators )i!cl*(e <iostream.+" i!t mai!/0 2 i!t myA?e = .C7 DD i!itialiNe two i!te?ers i!t yo*rA?e = .C7 co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 myA?eAA7 DD #ost i@ i!creme!t AAyo*rA?e7 DD #re i@ i!creme!t

1., co*t << 4O!e year #asses...6!47 11, co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 13, co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 18, co*t << 4A!ot+er year #asses6!47 19, co*t << 4I am, 4 << myA?eAA << 4 years ol(.6!47 1;, co*t << 4Yo* are, 4 << AAyo*rA?e << 4 years ol(6!47 1C, co*t << 4LetHs #ri!t it a?ai!.6!47 -0, co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 -1, co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 --, ret*r! 07 -., : O*t#*t, I am .C years ol( Yo* are .C years ol( O!e year #asses I am 10 years ol( Yo* are 10 years ol( A!ot+er year #asses I am 10 years ol( Yo* are 11 years ol( LetHs #ri!t it a?ai! I am 11 years ol( Yo* are 11 years ol(

Ana ysis: n lines M and =, t#o integer variables are declared, and eac& is initiali4ed #it& t&e value .C/ %&eir values are +rinted on lines < and 1>/ n line 11, myA?e is incremented using t&e +ostfi- increment o+erator, and on line 11, yo*rA?e is incremented using t&e +refi- increment o+erator/ %&e results are +rinted on lines 1I and 1E, and t&ey are identical ?bot& 10@/ n line 1M, myA?e is incremented as +art of t&e +rinting statement, using t&e +ostfiincrement o+erator/ Because it is +ostfi-, t&e increment &a++ens after t&e +rint, and so t&e value 10 is +rinted again/ In contrast, on line 1=, yo*rA?e is incremented using t&e +refiincrement o+erator/ %&us, it is incremented before being +rinted, and t&e value dis+lays as 11/ )inally, on lines 1> and 11, t&e values are +rinted again/ Because t&e increment statement &as com+leted, t&e value in myA?e is no# 11, as is t&e value in yo*rA?e/ Precedence In t&e com+le- statement
@ = 3 A . B ;7

#&ic& is +erformed first, t&e addition or t&e multi+lication* If t&e addition is +erformed first, t&e ans#er is = P =, or DI/ If t&e multi+lication is +erformed first, t&e ans#er is E + 1I, or 1</

$very o+erator &as a +recedence value, and t&e com+lete list is s&o#n in A++endi- A, 9 +erator Precedence/9 Aulti+lication &as &ig&er +recedence t&an addition, and t&us t&e value of t&e e-+ression is 1</ 0&en t#o mat&ematical o+erators &ave t&e same +recedence, t&ey are +erformed in left" to"rig&t order/ %&us
@ = 3 A . A ; B C A 8 B 17

is evaluated multi+lication first, left to rig&t/ %&us, =P< V M1, and DPI V 1I/ 'o# t&e e-+ression is essentially
@ = 3 A . A 9- A -17

'o# t&e addition, left to rig&t, is E + F V =B = + M1 V =>B => + 1I V 1>I/ Be careful #it& t&is/ Some o+erators, suc& as assignment, are evaluated in rig&t"to"left order5 In any case, #&at if t&e +recedence order doesn6t meet your needs* Consider t&e e-+ression
EotalMeco!(s = N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e B 80

In t&is e-+ression, you do not #ant to multi+ly t&e N*mMi!*tesEoEy#e variable by D> and t&en add it to N*mMi!*tesEoE+i!J/ ,ou #ant to add t&e t#o variables to get t&e total number of minutes, and t&en you #ant to multi+ly t&at number by D> to get t&e total seconds/ In t&is case, you use +arent&eses to c&ange t&e +recedence order/ Items in +arent&eses are evaluated at a &ig&er +recedence t&an any of t&e mat&ematical o+erators/ %&us
EotalMeco!(s = /N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e0 B 80

#ill accom+lis& #&at you #ant/

Nesting Parent,eses
)or com+le- e-+ressions, you mig&t need to nest +arent&eses one #it&in anot&er/ )or e-am+le, you mig&t need to com+ute t&e total seconds and t&en com+ute t&e total number of +eo+le #&o are involved before multi+lying seconds times +eo+le7
EotalPerso!Meco!(s = / / /N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e0 B 800 B F/Peo#leI!E+eO ice A Peo#leO!Vacatio!0 0

%&is com+licated e-+ression is read from t&e inside out/ )irst, N*mMi!*tesEoE+i!J is added to N*mMi!*tesEoEy#e, because t&ese are in t&e innermost +arent&eses/ %&en t&is sum is multi+lied by D>/ 'e-t, Peo#leI!E+eO ice is added to Peo#leO!Vacatio!/ )inally, t&e total number of +eo+le found is multi+lied by t&e total number of seconds/

%&is e-am+le raises an im+ortant related issue/ %&is e-+ression is easy for a com+uter to understand, but very difficult for a &uman to read, understand, or modify/ Here is t&e same e-+ression re#ritten, using some tem+orary integer variables7
EotalMi!*tes = N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e7 EotalMeco!(s = EotalMi!*tes B 807 EotalPeo#le = Peo#leI!E+eO ice A Peo#leO!Vacatio!7 EotalPerso!Meco!(s = EotalPeo#le B EotalMeco!(s7

%&is e-am+le ta.es longer to #rite and uses more tem+orary variables t&an t&e +receding e-am+le, but it is far easier to understand/ Add a comment at t&e to+ to e-+lain #&at t&is code does, and c&ange t&e 80 to a symbolic constant/ ,ou t&en #ill &ave code t&at is easy to understand and maintain/ D$ remember t&at e-+ressions &ave a value/ D$ use t&e +refi- o+erator ?AAvariable@ to increment or decrement t&e variable before it is used in t&e e-+ression/ D$ use t&e +ostfi- o+erator ?variableAA@ to increment or decrement t&e variable after it is used/ D$ use +arent&eses to c&ange t&e order of +recedence/ D$N:T nest too dee+ly, because t&e e-+ression becomes &ard to understand and maintain/

T,e Nature of Trut,


In C++, 4ero is considered false, and all ot&er values are considered true, alt&oug& true is usually re+resented by 1/ %&us, if an e-+ression is false, it is e8ual to 4ero, and if an e-+ression is e8ual to 4ero, it is false/ If a statement is true, all you .no# is t&at it is non4ero, and any non4ero statement is true/ 5e ationa $0erators %&e relational o+erators are used to determine #&et&er t#o numbers are e8ual, or if one is greater or less t&an t&e ot&er/ $very relational statement evaluates to eit&er 1 ?ERU<@ or 0 ?KALM<@/ %&e relational o+erators are +resented later, in %able I/1/ If t&e integer variable myA?e &as t&e value .C, and t&e integer variable yo*rA?e &as t&e value 10, you can determine #&et&er t&ey are e8ual by using t&e relational 9e8uals9 o+erator7
myA?e == yo*rA?e7 DD is t+e Gal*e i! myA?e t+e same as i! yo*rA?eO

%&is e-+ression evaluates to 0, or alse, because t&e variables are not e8ual/ %&e e-+ression
myA?e " yo*rA?e7 DD is myA?e ?reater t+a! yo*rA?eO

evaluates to 0 or alse/

4A5NING: Aany novice C++ +rogrammers confuse t&e assignment o+erator ?=@ #it& t&e e8uals o+erator ?==@/ %&is can create a nasty bug in your +rogram/ %&ere are si- relational o+erators7 e8uals ?==@, less t&an ?<@, greater t&an ?"@, less t&an or e8ual to ?<=@, greater t&an or e8ual to ?"=@, and not e8uals ?5=@/ %able I/1 s&o#s eac& relational o+erator, its use, and a sam+le code use/

Ta" e *'1' T,e 5e ationa $0erators'


Name $8uals 'ot $8uals Operator Sample
== 5=

Evaluates

100 == 307 alse 30 == 307 tr*e 100 5= 307 tr*e 30 5= 307 alse alse 100 " 307 tr*e 30 " 307 100 "= 307 tr*e 30 "= 307 tr*e 100 < 307 30 < 307 alse alse

Greater %&an " Greater %&an "= or $8uals (ess %&an <

100 <= 307 alse (ess %&an <= 30 <= 307 tr*e or $8uals D$ remember t&at relational o+erators return t&e value 1 ?tr*e@ or 0 ? alse@/ D$N:T confuse t&e assignment o+erator ?=@ #it& t&e e8uals relational o+erator ?==@/ %&is is one of t&e most common C++ +rogramming mista.es""be on guard for it/

T,e if Statement
'ormally, your +rogram flo#s along line by line in t&e order in #&ic& it a++ears in your source code/ %&e i statement enables you to test for a condition ?suc& as #&et&er t#o variables are e8ual@ and branc& to different +arts of your code, de+ending on t&e result/ %&e sim+lest form of an i statement is t&is7
i /e@#ressio!0 stateme!t7

%&e e-+ression in t&e +arent&eses can be any e-+ression at all, but it usually contains one of t&e relational e-+ressions/ If t&e e-+ression &as t&e value 0, it is considered false, and t&e statement is s.i++ed/ If it &as any non4ero value, it is considered true, and t&e statement is e-ecuted/ Consider t&e follo#ing e-am+le7
i /bi?N*mber " smallN*mber0 bi?N*mber = smallN*mber7

%&is code com+ares bi?N*mber and smallN*mber/ If bi?N*mber is larger, t&e second line sets its value to t&e value of smallN*mber/ Because a bloc. of statements surrounded by braces is e-actly e8uivalent to a single statement, t&e follo#ing ty+e of branc& can be 8uite large and +o#erful7
i 2 /e@#ressio!0 stateme!t17 stateme!t-7 stateme!t.7

Here6s a sim+le e-am+le of t&is usage7


i 2 /bi?N*mber " smallN*mber0 bi?N*mber = smallN*mber7 co*t << 4bi?N*mber, 4 << bi?N*mber << 46!47 co*t << 4smallN*mber, 4 << smallN*mber << 46!47

%&is time, if bi?N*mber is larger t&an smallN*mber, not only is it set to t&e value of smallN*mber, but an informational message is +rinted/ (isting I/I s&o#s a more detailed e-am+le of branc&ing based on relational o+erators/

-isting *'*' A demonstration of "ranc,ing "ased on re ationa o0erators'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, 1., 11, 13, 18, 19, 1;, 1C, -0, -1, --, -., -1, -3, DD Listi!? 1.1 I (emo!strates i stateme!t DD *se( wit+ relatio!al o#erators )i!cl*(e <iostream.+" i!t mai!/0 2 i!t Re(Mo@Mcore> Ya!JeesMcore7 co*t << 4<!ter t+e score or t+e Re( Mo@, 47 ci! "" Re(Mo@Mcore7 co*t << 46!<!ter t+e score ci! "" Ya!JeesMcore7 co*t << 46!47 i i 2 : i 2 /Re(Mo@Mcore == Ya!JeesMcore0 /Re(Mo@Mcore " Ya!JeesMcore0 co*t << 4Qo Mo@56!47 /Re(Mo@Mcore < Ya!JeesMcore0 co*t << 4Qo Ya!Jees56!47 co*t << 4&a##y (ays i! New YorJ56!47 or t+e Ya!Jees, 47

-8, co*t << 4A tieO Naa+> ca!Ht be.6!47 -9, co*t << 4QiGe me t+e real score or t+e Ya!Js, 47 -;, ci! "" Ya!JeesMcore7 -C, .0, i /Re(Mo@Mcore " Ya!JeesMcore0 .1, co*t << 4X!ew it5 Qo Mo@547 .-, .., i /Ya!JeesMcore " Re(Mo@Mcore0 .1, co*t << 4X!ew it5 Qo Ya!Js547 .3, .8, i /Ya!JeesMcore == Re(Mo@Mcore0 .9, co*t << 4'ow> it really was a tie547 .;, : .C, 10, co*t << 46!E+a!Js or telli!? me.6!47 11, ret*r! 07 1-, : O*t#*t, <!ter t+e score or t+e Re( Mo@, 10 <!ter t+e score or t+e Ya!Jees, 10 or t+e Ya!Js, ;

A tieO Naa+> ca!Ht be QiGe me t+e real score X!ew it5 Qo Mo@5 E+a!Js or telli!? me.

Ana ysis: %&is +rogram as.s for user in+ut of scores for t#o baseball teams, #&ic& are stored in integer variables/ %&e variables are com+ared in t&e i statement on lines 1E, 1=, and 1I/ If one score is &ig&er t&an t&e ot&er, an informational message is +rinted/ If t&e scores are e8ual, t&e bloc. of code t&at begins on line 1I and ends on line F= is entered/ %&e second score is re8uested again, and t&en t&e scores are com+ared again/ 'ote t&at if t&e initial ,an.ees score #as &ig&er t&an t&e ;ed So- score, t&e i statement on line 1E #ould evaluate as KALM<, and line 1D #ould not be invo.ed/ %&e test on line 1= #ould evaluate as tr*e, and t&e statements on lines 1> and 11 #ould be invo.ed/ %&en t&e i statement on line 1I #ould be tested, and t&is #ould be false ?if line 1= #as true@/ %&us, t&e +rogram #ould s.i+ t&e entire bloc., falling t&roug& to line F</ In t&is e-am+le, getting a true result in one i statement does not sto+ ot&er i statements from being tested/ Indentation Sty es (isting I/F s&o#s one style of indenting i statements/ 'ot&ing is more li.ely to create a religious #ar, &o#ever, t&an to as. a grou+ of +rogrammers #&at is t&e best style for brace alignment/ Alt&oug& t&ere are do4ens of variations, t&ese a++ear to be t&e favorite t&ree7

Putting t&e initial brace after t&e condition and aligning t&e closing brace under t&e i to close t&e statement bloc./

i :

/e@#ressio!02 stateme!ts

i 2 : i

Aligning t&e braces under t&e i and indenting t&e statements/

/e@#ressio!0 stateme!ts

Indenting t&e braces and statements/

/e@#ressio!0 2 stateme!ts :

%&is boo. uses t&e middle alternative, because I find it easier to understand #&ere bloc.s of statements begin and end if t&e braces line u+ #it& eac& ot&er and #it& t&e condition being tested/ Again, it doesn6t matter muc& #&ic& style you c&oose, as long as you are consistent #it& it/ e se ften your +rogram #ill #ant to ta.e one branc& if your condition is true, anot&er if it is false/ In (isting I/F, you #anted to +rint one message ?Qo Mo@5@ if t&e first test ?Re(Mo@Mcore " Ya!Jees@ evaluated ERU<, and anot&er message ?Qo Ya!Js5@ if it evaluated KALM</ %&e met&od s&o#n so far, testing first one condition and t&en t&e ot&er, #or.s fine but is a bit cumbersome/ %&e .ey#ord else can ma.e for far more readable code7
i /e@#ressio!0 stateme!t7 else stateme!t7

(isting I/E demonstrates t&e use of t&e .ey#ord else/

-isting *';' Demonstrating t,e e se 3eyword'


1, -, ., 1, 3, 8, 9, ;, DD Listi!? 1.3 I (emo!strates i stateme!t DD wit+ else cla*se )i!cl*(e <iostream.+" i!t mai!/0 2 i!t irstN*mber> seco!(N*mber7 co*t << 4Please e!ter a bi? !*mber, 47 ci! "" irstN*mber7

C, 10, 11, 1-, 1., 11, 13, 18, 19, :

co*t << 46!Please e!ter a smaller !*mber, 47 ci! "" seco!(N*mber7 i / irstN*mber " seco!(N*mber0 co*t << 46!E+a!Js56!47 else co*t << 46!Oo#s. E+e seco!( is bi??er547 ret*r! 07

O*t#*t, Please e!ter a bi? !*mber, 10 Please e!ter a smaller !*mber, 1Oo#s. E+e seco!( is bi??er5

Ana ysis: %&e i statement on line 11 is evaluated/ If t&e condition is true, t&e statement on line 11 is runB if it is false, t&e statement on line 1I is run/ If t&e else clause on line 1F #ere removed, t&e statement on line 1I #ould run #&et&er or not t&e i statement #as true/ ;emember, t&e i statement ends after line 11/ If t&e else #as not t&ere, line 1I #ould !ust be t&e ne-t line in t&e +rogram/ ;emember t&at eit&er or bot& of t&ese statements could be re+laced #it& a bloc. of code in braces/

T,e if Statement
%&e synta- for t&e i statement is as follo#s7 )orm 1
i /e@#ressio!0 stateme!t7 !e@t stateme!t7

If t&e e-+ression is evaluated as ERU<, t&e statement is e-ecuted and t&e +rogram continues #it& t&e ne-t statement/ If t&e e-+ression is not true, t&e statement is ignored and t&e +rogram !um+s to t&e ne-t statement/ ;emember t&at t&e statement can be a single statement ending #it& a semicolon or a bloc. enclosed in braces/ )orm 1
i /e@#ressio!0 stateme!t17 else stateme!t-7 !e@t stateme!t7

If t&e e-+ression evaluates ERU<, stateme!t1 is e-ecutedB ot&er#ise, stateme!t- is e-ecuted/ After#ards, t&e +rogram continues #it& t&e ne-t statement/ $-am+le 1
<@am#le i /MomeVal*e < 100 co*t << 4MomeVal*e is less t+a! 10407 else co*t << 4MomeVal*e is !ot less t+a! 105407

co*t << 4Do!e.4 << e!(l7

Ad!anced if Statements It is #ort& noting t&at any statement can be used in an i or else clause, even anot&er i or else statement/ %&us, you mig&t see com+le- i statements in t&e follo#ing form7
i 2 /e@#ressio!10 i /e@#ressio!-0 stateme!t17 else 2 i /e@#ressio!.0 stateme!t-7 else stateme!t.7 : stateme!t17

: else

%&is cumbersome i statement says, 9If e-+ression1 is true and e-+ression1 is true, e-ecute statement1/ If e-+ression1 is true but e-+ression1 is not true, t&en if e-+ressionF is true e-ecute statement1/ If e-+ression1 is true but e-+ression1 and e-+ressionF are false, e-ecute statementF/ )inally, if e-+ression1 is not true, e-ecute statementI/9 As you can see, com+le- i statements can be confusing5 (isting I/D gives an e-am+le of suc& a com+le- i statement/

-isting *'B' A com0 e2# nested if statement'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, 1., 11, 13, 18, 19, 1;, 1C, -0, DD Listi!? 1.3 I a com#le@ !este( DD i stateme!t )i!cl*(e <iostream.+" i!t mai!/0 2 DD AsJ or two !*mbers DD Assi?! t+e !*mbers to bi?N*mber a!( littleN*mber DD I bi?N*mber is bi??er t+a! littleN*mber> DD see i t+ey are eGe!ly (iGisible DD I t+ey are> see i t+ey are t+e same !*mber i!t irstN*mber> seco!(N*mber7 co*t << 4<!ter two !*mbers.6!Kirst, 47 ci! "" irstN*mber7 co*t << 46!Meco!(, 47 ci! "" seco!(N*mber7 co*t << 46!6!47 i 2 / irstN*mber "= seco!(N*mber0

-1, --, -., -1, -3, -8, -9, -;, -C, .0, .1, .-, .., .1, :

i 2

/ / irstN*mber V seco!(N*mber0 == 00 DD eGe!ly (iGisibleO i / irstN*mber == seco!(N*mber0 co*t << 4E+ey are t+e same56!47 else co*t << 4E+ey are eGe!ly (iGisible56!47

: else co*t << 4E+ey are !ot eGe!ly (iGisible56!47 : else co*t << 4&ey5 E+e seco!( o!e is lar?er56!47 ret*r! 07

O*t#*t, <!ter two !*mbers. Kirst, 10 Meco!(, E+ey are eGe!ly (iGisible5

Ana ysis: %#o numbers are +rom+ted for one at a time, and t&en com+ared/ %&e first i statement, on line 1<, c&ec.s to ensure t&at t&e first number is greater t&an or e8ual to t&e second/ If not, t&e else clause on line F1 is e-ecuted/ If t&e first i is true, t&e bloc. of code beginning on line 1> is e-ecuted, and t&e second i statement is tested, on line 11/ %&is c&ec.s to see #&et&er t&e first number modulo t&e second number yields no remainder/ If so, t&e numbers are eit&er evenly divisible or e8ual/ %&e i statement on line 1F c&ec.s for e8uality and dis+lays t&e a++ro+riate message eit&er #ay/ If t&e i statement on line 11 fails, t&e else statement on line 1= is e-ecuted/

9sing Braces in Nested if Statements


Alt&oug& it is legal to leave out t&e braces on i statements t&at are only a single statement, and it is legal to nest i statements, suc& as
i /@ " y0 i /@ < N0 @ = y7 DD i @ is bi??er t+a! y DD a!( i @ is smaller t+a! N DD t+e! set @ to t+e Gal*e i! N

#&en #riting large nested statements, t&is can cause enormous confusion/ ;emember, #&ites+ace and indentation are a convenience for t&e +rogrammerB t&ey ma.e no difference to t&e com+iler/ It is easy to confuse t&e logic and inadvertently assign an else statement to t&e #rong i statement/ (isting I/M illustrates t&is +roblem/

-isting *'C' A demonstration of w,y "races ,e 0 c arify w,ic, e se statement goes wit, w,ic, if statement'

1, DD Listi!? 1.9 I (emo!strates w+y braces -, DD are im#orta!t i! !este( i stateme!ts ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, i!t @7 9, co*t << 4<!ter a !*mber less t+a! 10 or ?reater t+a! 100, 47 ;, ci! "" @7 C, co*t << 46!47 10, 11, i /@ " 100 1-, i /@ " 1000 1., co*t << 4More t+a! 100> E+a!Js56!47 11, else DD !ot t+e else i!te!(e(5 13, co*t << 4Less t+a! 10> E+a!Js56!47 18, 19, ret*r! 07 1;, : O*t#*t, <!ter a !*mber less t+a! 10 or ?reater t+a! 100, -0 Less t+a! 10> E+a!Js5

Ana ysis: %&e +rogrammer intended to as. for a number bet#een 1> and 1>>, c&ec. for t&e correct value, and t&en +rint a t&an."you note/ If t&e i statement on line 11 evaluates ERU<, t&e follo#ing statement ?line 11@ is e-ecuted/ In t&is case, line 11 e-ecutes #&en t&e number entered is greater t&an 1>/ (ine 11 contains an i statement also/ %&is i statement evaluates ERU< if t&e number entered is greater t&an 1>>/ If t&e number is not greater t&an 1>>, t&e statement on line 1F is e-ecuted/ If t&e number entered is less t&an or e8ual to 1>, t&e i statement on line 1> evaluates to KALM</ Program control goes to t&e ne-t line follo#ing t&e i statement, in t&is case line 1D/ If you enter a number less t&an 1>, t&e out+ut is as follo#s7
<!ter a !*mber less t+a! 10 or ?reater t+a! 100, C

%&e else clause on line 1I #as clearly intended to be attac&ed to t&e i statement on line 11, and t&us is indented accordingly/ :nfortunately, t&e else statement is really attac&ed to t&e i statement on line 11, and t&us t&is +rogram &as a subtle bug/ It is a subtle bug because t&e com+iler #ill not com+lain/ %&is is a legal C++ +rogram, but it !ust doesn6t do #&at #as intended/ )urt&er, most of t&e times t&e +rogrammer tests t&is +rogram, it #ill a++ear to #or./ As long as a number t&at is greater t&an 1>> is entered, t&e +rogram #ill seem to #or. !ust fine/ (isting I/= fi-es t&e +roblem by +utting in t&e necessary braces/

-isting *'E' A demonstration of t,e 0ro0er use of "races wit, an if statement

1, DD Listi!? 1.; I (emo!strates #ro#er *se o braces -, DD i! !este( i stateme!ts ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, i!t @7 9, co*t << 4<!ter a !*mber less t+a! 10 or ?reater t+a! 100, 47 ;, ci! "" @7 C, co*t << 46!47 10, 11, i /@ " 100 1-, 2 1., i /@ " 1000 11, co*t << 4More t+a! 100> E+a!Js56!47 13, : 18, else DD !ot t+e else i!te!(e(5 19, co*t << 4Less t+a! 10> E+a!Js56!47 1;, ret*r! 07 1C, : O*t#*t, <!ter a !*mber less t+a! 10 or ?reater t+a! 100, -0

Ana ysis: %&e braces on lines 11 and 1E ma.e everyt&ing bet#een t&em into one statement, and no# t&e else on line 1D a++lies to t&e i on line 11 as intended/ %&e user ty+ed -0, so t&e i statement on line 11 is trueB &o#ever, t&e i statement on line 1F is false, so not&ing is +rinted/ It #ould be better if t&e +rogrammer +ut anot&er else clause after line 1I so t&at errors #ould be caug&t and a message +rinted/ N$T+: %&e +rograms s&o#n in t&is boo. are #ritten to demonstrate t&e +articular issues being discussed/ %&ey are .e+t intentionally sim+leB t&ere is no attem+t to 9bullet+roof9 t&e code to +rotect against user error/ In +rofessional"8uality code, every +ossible user error is antici+ated and &andled gracefully/

-ogica $0erators
ften you #ant to as. more t&an one relational 8uestion at a time/ 9Is it true t&at - is greater t&an y, and also true t&at y is greater t&an 4*9 A +rogram mig&t need to determine t&at bot& of t&ese conditions are true, or t&at some ot&er condition is true, in order to ta.e an action/ Imagine a so+&isticated alarm system t&at &as t&is logic7 9If t&e door alarm sounds A'D it is after si- +/m/ A'D it is ' % a &oliday, ; if it is a #ee.end, t&en call t&e +olice/9 C++6s t&ree logical o+erators are used to ma.e t&is .ind of evaluation/ %&ese o+erators are listed in %able I/1/

Ta" e *'(' T,e -ogica $0erators'


Operator Symbol Example AND `` e-+ression1 `` e-+ression1 OR ^^ e-+ression1 ^^ e-+ression1

NOE

5e-+ression

-ogica AND A logical AND statement evaluates t#o e-+ressions, and if bot& e-+ressions are true, t&e logical AND statement is true as #ell/ If it is true t&at you are &ungry, A'D it is true t&at you &ave money, %H$' it is true t&at you can buy lunc&/ %&us,
i / /@ == 30 `` /y == 30 0

#ould evaluate ERU< if bot& @ and y are e8ual to E, and it #ould evaluate KALM< if eit&er one is not e8ual to E/ 'ote t&at bot& sides must be true for t&e entire e-+ression to be true/ 'ote t&at t&e logical AND is t#o `` symbols/ A single ` symbol is a different o+erator, discussed on Day 11, 90&at6s 'e-t/9 -ogica $5 A logical OR statement evaluates t#o e-+ressions/ If eit&er one is true, t&e e-+ression is true/ If you &ave money ; you &ave a credit card, you can +ay t&e bill/ ,ou don6t need bot& money and a credit cardB you need only one, alt&oug& &aving bot& #ould be fine as #ell/ %&us,
i / /@ == 30 ^^ /y == 30 0

evaluates ERU< if eit&er @ or y is e8ual to E, or if bot& are/ 'ote t&at t&e logical OR is t#o ^^ symbols/ A single ^ symbol is a different o+erator, discussed on Day 11/ -ogica N$T A logical NOE statement evaluates tr*e if t&e e-+ression being tested is false/ Again, if t&e e-+ression being tested is false, t&e value of t&e test is ERU<5 %&us
i / 5/@ == 30 0

is true only if @ is not e8ual to E/ %&is is e-actly t&e same as #riting


i /@ 5= 30

5e ationa Precedence
;elational o+erators and logical o+erators, being C++ e-+ressions, eac& return a value7 1 ?ERU<@ or 0 ?KALM<@/ (i.e all e-+ressions, t&ey &ave a +recedence order ?see A++endi- A@

t&at determines #&ic& relations are evaluated first/ %&is fact is im+ortant #&en determining t&e value of t&e statement
i / @ " 3 `` y " 3 ^^ N " 30

It mig&t be t&at t&e +rogrammer #anted t&is e-+ression to evaluate ERU< if bot& @ and y are greater t&an E or if N is greater t&an E/ n t&e ot&er &and, t&e +rogrammer mig&t &ave #anted t&is e-+ression to evaluate ERU< only if @ is greater t&an E and if it is also true t&at eit&er y is greater t&an E or N is greater t&an E/ If @ is F, and y and N are bot& 1>, t&e first inter+retation #ill be true ?N is greater t&an E, so ignore @ and y@, but t&e second #ill be false ?it isn6t true t&at bot& @ and y are greater t&an E nor is it true t&at N is greater t&an E@/ Alt&oug& +recedence #ill determine #&ic& relation is evaluated first, +arent&eses can bot& c&ange t&e order and ma.e t&e statement clearer7
i / /@ " 30 `` /y " 3 ^^ N " 30 0

:sing t&e values from earlier, t&is statement is false/ Because it is not true t&at @ is greater t&an E, t&e left side of t&e AND statement fails, and t&us t&e entire statement is false/ ;emember t&at an AND statement re8uires t&at bot& sides be true""somet&ing isn6t bot& 9good tasting9 A'D 9good for you9 if it isn6t good tasting/ N$T+: It is often a good idea to use e-tra +arent&eses to clarify #&at you #ant to grou+/ ;emember, t&e goal is to #rite +rograms t&at #or. and t&at are easy to read and understand/

@ore A"out Trut, and .a se,ood


In C++, 4ero is false, and any ot&er value is true/ Because an e-+ression al#ays &as a value, many C++ +rogrammers ta.e advantage of t&is feature in t&eir i statements/ A statement suc& as
i /@0 @ = 07 DD i @ is tr*e /!o!Nero0

can be read as 9If @ &as a non4ero value, set it to >/9 %&is is a bit of a c&eatB it #ould be clearer if #ritten
i /@ 5= 00 @ = 07 DD i @ is !o!Nero

Bot& statements are legal, but t&e latter is clearer/ It is good +rogramming +ractice to reserve t&e former met&od for true tests of logic, rat&er t&an for testing for non4ero values/

%&ese t#o statements also are e8uivalent7


i i /5@0 /@ == 00 DD i DD i @ is alse /Nero0 @ is Nero

%&e second statement, &o#ever, is some#&at easier to understand and is more e-+licit/ D$ +ut +arent&eses around your logical tests to ma.e t&em clearer and to ma.e t&e +recedence e-+licit/ D$ use braces in nested i statements to ma.e t&e else statements clearer and to avoid bugs/ D$N:T use i /@0 as a synonym for i /@ 5= 00B t&e latter is clearer/ D$N:T use i /5@0 as a synonym for i /@ == 00B t&e latter is clearer/ N$T+: It is common to define your o#n enumerated Boolean ?logical@ ty+e #it& e!*m $ool 2KALM<> ERU<:7/ %&is serves to set KALM< to 0 and ERU< to 1/

Conditiona FTernaryG $0erator


%&e conditional o+erator ?O,@ is C++6s only ternary o+eratorB t&at is, it is t&e only o+erator to ta.e t&ree terms/ %&e conditional o+erator ta.es t&ree e-+ressions and returns a value7
/e@#ressio!10 O /e@#ressio!-0 , /e@#ressio!.0

%&is line is read as 9If e-+ression1 is true, return t&e value of e-+ression1B ot&er#ise, return t&e value of e-+ressionF/9 %y+ically, t&is value #ould be assigned to a variable/ (isting I/< s&o#s an i statement re#ritten using t&e conditional o+erator/

-isting *'H' A demonstration of t,e conditiona o0erator'


1, -, ., 1, 3, 8, 9, ;, C, 10, 11, 1-, 1., 11, 13, 18, 19, 1;, DD Listi!? 1.C I (emo!strates t+e co!(itio!al o#erator DD )i!cl*(e <iostream.+" i!t mai!/0 2 i!t @> y> N7 co*t << 4<!ter two !*mbers.6!47 co*t << 4Kirst, 47 ci! "" @7 co*t << 46!Meco!(, 47 ci! "" y7 co*t << 46!47 i /@ " y0 N = @7 else N = y7

1C, co*t << 4N, 4 << N7 -0, co*t << 46!47 -1, --, N = /@ " y0 O @ , y7 -., -1, co*t << 4N, 4 << N7 -3, co*t << 46!47 -8, ret*r! 07 -9, : O*t#*t, <!ter two !*mbers. Kirst, 3 Meco!(, ; N, ; N, ;

Ana ysis: %&ree integer variables are created7 @, y, and N/ %&e first t#o are given values by t&e user/ %&e i statement on line 1I tests to see #&ic& is larger and assigns t&e larger value to N/ %&is value is +rinted on line 1</ %&e conditional o+erator on line 11 ma.es t&e same test and assigns N t&e larger value/ It is read li.e t&is7 9If @ is greater t&an y, return t&e value of @B ot&er#ise, return t&e value of y/9 %&e value returned is assigned to N/ %&at value is +rinted on line 1I/ As you can see, t&e conditional statement is a s&orter e8uivalent to t&e i ...else statement/

Summary
%&is c&a+ter &as covered a lot of material/ ,ou &ave learned #&at C++ statements and e-+ressions are, #&at C++ o+erators do, and &o# C++ i statements #or./ ,ou &ave seen t&at a bloc. of statements enclosed by a +air of braces can be used any#&ere a single statement can be used/ ,ou &ave learned t&at every e-+ression evaluates to a value, and t&at value can be tested in an i statement or by using t&e conditional o+erator/ ,ou6ve also seen &o# to evaluate multi+le statements using t&e logical o+erator, &o# to com+are values using t&e relational o+erators, and &o# to assign values using t&e assignment o+erator/ ,ou &ave e-+lored o+erator +recedence/ And you &ave seen &o# +arent&eses can be used to c&ange t&e +recedence and to ma.e +recedence e-+licit and t&us easier to manage/

67A
6' 4,y use unnecessary 0arent,eses w,en 0recedence wi determine w,ic, o0erators are acted on first/ A' Alt&oug& it is true t&at t&e com+iler #ill .no# t&e +recedence and t&at a +rogrammer can loo. u+ t&e +recedence order, code t&at is easy to understand is easier to maintain/

6' If t,e re ationa o0erators a ways return 1 or I# w,y are ot,er !a ues considered true/ A' %&e relational o+erators return 1 or >, but every e-+ression returns a value, and t&ose values can also be evaluated in an i statement/ Here6s an e-am+le7
i / /@ = a A b0 == .3 0

%&is is a +erfectly legal C++ statement/ It evaluates to a value even if t&e sum of a and b is not e8ual to FE/ Also note t&at @ is assigned t&e value t&at is t&e sum of a and b in any case/ 6' 4,at effect do ta"s# s0aces# and new ines ,a!e on t,e 0rogram/ A/ %abs, s+aces, and ne# lines ?.no#n as #&ites+ace@ &ave no effect on t&e +rogram, alt&oug& !udicious use of #&ites+ace can ma.e t&e +rogram easier to read/ 6' Are negati!e num"ers true or fa se/ A' All non4ero numbers, +ositive and negative, are true/

4or3s,o0
%&e 0or.s&o+ +rovides 8ui4 8uestions to &el+ you solidify your understanding of t&e material covered, and e-ercises to +rovide you #it& e-+erience in using #&at you6ve learned/ %ry to ans#er t&e 8ui4 and e-ercise 8uestions before c&ec.ing t&e ans#ers in A++endi- D, and ma.e sure t&at you understand t&e ans#ers before continuing to t&e ne-t c&a+ter/ 6ui8 1' 0&at is an e-+ression* (' Is @ = 3 A 9 an e-+ression* 0&at is its value* )' 0&at is t&e value of -01 D 1* *' 0&at is t&e value of -01 V 1* ;' If myA?e, a, myA?e = .C7 a = myA?eAA7 b = AAmyA?e7 and b are all i!t variables, #&at are t&eir values after7

B' 0&at is t&e value of ;A-B.* C' 0&at is t&e difference bet#een @ = . and @ == .*

E' Do t&e follo#ing values evaluate to ERU< or KALM<* a/ 0 "' 1 c' I1 d' @ = 0 e/ @ == 0 DD ass*me t+at @ +as t+e Gal*e o +2ercises 1' 0rite a single i statement t&at e-amines t#o integer variables and c&anges t&e larger to t&e smaller, using only one else clause/ (' $-amine t&e follo#ing +rogram/ Imagine entering t&ree numbers, and #rite #&at out+ut you e-+ect/
1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, i!t a> b> c7 3, co*t << 4Please e!ter t+ree !*mbers6!47 8, co*t << 4a, 47 9, ci! "" a7 ;, co*t << 46!b, 47 C, ci! "" b7 10, co*t << 46!c, 47 11, ci! "" c7 1-, 1., i /c = /aIb00 11, 2co*t << 4a, 47 13, co*t << a7 18, co*t << 4mi!*s b, 47 19, co*t << b7 1;, co*t << 4eP*als c, 47 1C, co*t << c << e!(l7: -0, else -1, co*t << 4aIb (oes !ot eP*al c, 4 << e!(l7 --, ret*r! 07 -., :

)' $nter t&e +rogram from $-ercise 1B com+ile, lin., and run it/ $nter t&e numbers 1>, 1>, and E>/ Did you get t&e out+ut you e-+ected* 0&y not* *' $-amine t&is +rogram and antici+ate t&e out+ut7
1, -, ., 1, 3, 8, 9, ;, )i!cl*(e <iostream.+" i!t mai!/0 2 i!t a = 1> b = 1> c7 i /c = /aIb00 co*t << 4E+e Gal*e o c is, 4 << c7 ret*r! 07 :

;' $nter, com+ile, lin., and run t&e +rogram from $-ercise I/ 0&at #as t&e out+ut* 0&y*

Day I
o

$-+ressions and Statements Statements 0&ites+ace Bloc.s and Com+ound Statements $-+ressions (isting I/1/ $valuating com+le- e-+ressions/ +erators Assignment +erator Aat&ematical +erators (isting I/1/ A demonstration of subtraction and integer overflo#/ Integer Division and Aodulus Combining t&e Assignment and Aat&ematical +erators Increment and Decrement Prefi- and Postfi (isting I/F/ A demonstration of +refi- and +ostfi- o+erators/ Precedence 'esting Parent&eses %&e 'ature of %rut& ;elational +erators %&e if Statement (isting I/I/ A demonstration of branc&ing based on relational o+erators/ Indentation Styles else (isting I/E/ Demonstrating t&e else .ey#ord/ %&e if Statement Advanced if Statements (isting I/D/ A com+le-, nested if statement/ :sing Braces in 'ested if Statements (isting I/M/ A demonstration of #&y

braces &el+ clarify #&ic& else statement goes #it& #&ic& if statement/ (isting I/=/ A demonstration of t&e +ro+er use of braces #it& an if statement/ (ogical +erators (ogical A'D (ogical ; (ogical ' % ;elational Precedence Aore About %rut& and )alse&ood Conditional ?%ernary@ +erator (isting I/</ A demonstration of t&e conditional o+erator/ Summary 23A 0or.s&o+ 2ui4 $-ercises

Day * +20ressions and Statements


At its &eart, a +rogram is a set of commands e-ecuted in se8uence/ %&e +o#er in a +rogram comes from its ca+ability to e-ecute one or anot&er set of commands, based on #&et&er a +articular condition is true or false/ %oday you #ill learn

0&at statements are/ 0&at bloc.s are/ 0&at e-+ressions are/ Ho# to branc& your code based on conditions/ 0&at trut& is, and &o# to act on it/

Statements
In C++ a statement controls t&e se8uence of e-ecution, evaluates an e-+ression, or does not&ing ?t&e null statement@/ All C++ statements end #it& a semicolon, even t&e null statement, #&ic& is !ust t&e semicolon and not&ing else/ ne of t&e most common statements is t&e follo#ing assignment statement7
@ = a A b7

:nli.e in algebra, t&is statement does not mean t&at @ e8uals aAb/ %&is is read, 9Assign t&e value of t&e sum of a and b to @,9 or 9Assign to @, aAb/9 $ven t&oug& t&is statement is doing t#o t&ings, it is one statement and t&us &as one semicolon/ %&e assignment

o+erator assigns #&atever is on t&e rig&t side of t&e e8ual sign to #&atever is on t&e left side/ New Term: A null statement is a statement t&at does not&ing/ 4,ites0ace 0&ites+ace ?tabs, s+aces, and ne#lines@ is generally ignored in statements/ %&e assignment statement +reviously discussed could be #ritten as
@=aAb7

or as
@ A b 7 =a

Alt&oug& t&is last variation is +erfectly legal, it is also +erfectly foolis&/ 0&ites+ace can be used to ma.e your +rograms more readable and easier to maintain, or it can be used to create &orrific and indeci+&erable code/ In t&is, as in all t&ings, C++ +rovides t&e +o#erB you su++ly t&e !udgment/ New Term: Whitespace characters ?s+aces, tabs, and ne#lines@ cannot be seen/ If t&ese c&aracters are +rinted, you see only t&e #&ite of t&e +a+er/ B oc3s and Com0ound Statements Any +lace you can +ut a single statement, you can +ut a com+ound statement, also called a bloc./ A bloc. begins #it& an o+ening brace ?2@ and ends #it& a closing brace ?:@/ Alt&oug& every statement in t&e bloc. must end #it& a semicolon, t&e bloc. itself does not end #it& a semicolon/ )or e-am+le
2 tem# = a7 a = b7 b = tem#7

%&is bloc. of code acts as one statement and s#a+s t&e values in t&e variables a and b/ D$ use a closing brace any time you &ave an o+ening brace/ D$ end your statements #it& a semicolon/ D$ use #&ites+ace !udiciously to ma.e your code clearer/

+20ressions

Anyt&ing t&at evaluates to a value is an e-+ression in C++/ An e-+ression is said to return a value/ %&us, .A-7 returns t&e value 3 and so is an e-+ression/ All e-+ressions are statements/ %&e myriad +ieces of code t&at 8ualify as e-+ressions mig&t sur+rise you/ Here are t&ree e-am+les7
..PI Meco!(sPerMi!*te DD ret*r!s t+e Gal*e ..DD loat co!st t+at ret*r!s t+e Gal*e ..11 DD i!t co!st t+at ret*r!s 80

Assuming t&at PI is a constant e8ual to ..11 and Meco!(sPerMi!*te is a constant e8ual to 80, all t&ree of t&ese statements are e-+ressions/ %&e com+licated e-+ression
@ = a A b7

not only adds a and b and assigns t&e result to @, but returns t&e value of t&at assignment ?t&e value of @@ as #ell/ %&us, t&is statement is also an e-+ression/ Because it is an e-+ression, it can be on t&e rig&t side of an assignment o+erator7
y = @ = a A b7

%&is line is evaluated in t&e follo#ing order7 Add a to b/ Assign t&e result of t&e e-+ression a A b to @/ Assign t&e result of t&e assignment e-+ression @ = a A b to y/ If a, b, @, and y are all integers, and if a &as t&e value - and b &as t&e value 3, bot& @ and y #ill be assigned t&e value 9/

-isting *'1' +!a uating com0 e2 e20ressions'


1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, i!t a=0> b=0> @=0> y=.37 3, co*t << 4a, 4 << a << 4 b, 4 << b7 8, co*t << 4 @, 4 << @ << 4 y, 4 << y << e!(l7 9, a = C7 ;, b = 97 C, y = @ = aAb7 10, co*t << 4a, 4 << a << 4 b, 4 << b7 11, co*t << 4 @, 4 << @ << 4 y, 4 << y << e!(l7 1-, ret*r! 07 1., : O*t#*t, a, 0 b, 0 @, 0 y, .3

a, C b, 9 @, 18 y, 18

Ana ysis: n line I, t&e four variables are declared and initiali4ed/ %&eir values are +rinted on lines E and D/ n line M, a is assigned t&e value C/ ne line =, b is assigned t&e value 9/ n line <, t&e values of a and b are summed and t&e result is assigned to @/ %&is e-+ression ?@ = aAb@ evaluates to a value ?t&e sum of a A b@, and t&at value is in turn assigned to y/

$0erators
An o+erator is a symbol t&at causes t&e com+iler to ta.e an action/ +erators act on o+erands, and in C++ all o+erands are e-+ressions/ In C++ t&ere are several different categories of o+erators/ %#o of t&ese categories are

Assignment o+erators/ Aat&ematical o+erators/ Assignment $0erator

%&e assignment o+erator ?=@ causes t&e o+erand on t&e left side of t&e assignment o+erator to &ave its value c&anged to t&e value on t&e rig&t side of t&e assignment o+erator/ %&e e-+ression
@ = a A b7

assigns t&e value t&at is t&e result of adding a and b to t&e o+erand @/ An o+erand t&at legally can be on t&e left side of an assignment o+erator is called an lvalue/ %&at #&ic& can be on t&e rig&t side is called ?you guessed it@ an rvalue/ Constants are r"values/ %&ey cannot be l"values/ %&us, you can #rite
@ = .37 DD oJ

but you can6t legally #rite


.3 = @7 DD error> !ot a! lGal*e5

New Term: An lvalue is an o+erand t&at can be on t&e left side of an e-+ression/ An rvalue is an o+erand t&at can be on t&e rig&t side of an e-+ression/ 'ote t&at all l"values are r"values, but not all r"values are l"values/ An e-am+le of an rvalue t&at is not an lvalue is a literal/ %&us, you can #rite @ = 37, but you cannot #rite 3 = @7/ @at,ematica $0erators

%&ere are five mat&ematical o+erators7 addition ?A@, subtraction ?I@, multi+lication ?B@, division ?D@, and modulus ?V@/ Addition and subtraction #or. as you #ould e-+ect, alt&oug& subtraction #it& *!si?!e( integers can lead to sur+rising results, if t&e result is a negative number/ ,ou sa# somet&ing muc& li.e t&is yesterday, #&en variable overflo# #as described/ (isting I/1 s&o#s #&at &a++ens #&en you subtract a large *!si?!e( number from a small *!si?!e( number/

-isting *'(' A demonstration of su"traction and integer o!erf ow'


1, DD Listi!? 1.- I (emo!strates s*btractio! a!( -, DD i!te?er oGer low ., )i!cl*(e <iostream.+" 1, 3, i!t mai!/0 8, 2 9, *!si?!e( i!t (i ere!ce7 ;, *!si?!e( i!t bi?N*mber = 1007 C, *!si?!e( i!t smallN*mber = 307 10, (i ere!ce = bi?N*mber I smallN*mber7 11, co*t << 4Di ere!ce is, 4 << (i ere!ce7 1-, (i ere!ce = smallN*mber I bi?N*mber7 1., co*t << 46!Now (i ere!ce is, 4 << (i ere!ce <<e!(l7 11, ret*r! 07 13, : O*t#*t, Di ere!ce is, 30 Now (i ere!ce is, 1-C1C89-18

Ana ysis: %&e subtraction o+erator is invo.ed on line 1>, and t&e result is +rinted on line 11, muc& as #e mig&t e-+ect/ %&e subtraction o+erator is called again on line 11, but t&is time a large *!si?!e( number is subtracted from a small *!si?!e( number/ %&e result #ould be negative, but because it is evaluated ?and +rinted@ as an *!si?!e( number, t&e result is an overflo#, as described yesterday/ %&is to+ic is revie#ed in detail in A++endiA, 9 +erator Precedence/9 Integer Di!ision and @odu us Integer division is some#&at different from everyday division/ 0&en you divide 11 by I, t&e result is a real number ?a number #it& a fraction@/ Integers don6t &ave fractions, and so t&e 9remainder9 is lo++ed off/ %&e ans#er is t&erefore E/ %o get t&e remainder, you ta.e 11 modulus I ?11 U I@ and t&e result is 1/ %&e modulus o+erator tells you t&e remainder after an integer division/ )inding t&e modulus can be very useful/ )or e-am+le, you mig&t #ant to +rint a statement on every 1>t& action/ Any number #&ose value is > #&en you modulus 1> #it& t&at number is an e-act multi+le of 1>/ %&us 1 U 1> is 1, 1 U 1> is 1, and so fort&, until 1> U 1>, #&ose result is >/ 11 U 1> is bac. to 1, and t&is +attern continues until t&e ne-t

multi+le of 1>, #&ic& is 1>/ 0e6ll use t&is tec&ni8ue #&en loo+ing is discussed on Day M, 9Aore Program )lo#/9 4A5NING: Aany novice C++ +rogrammers inadvertently +ut a semicolon after t&eir i statements7
i /MomeVal*e < 1007 MomeVal*e = 107

0&at #as intended &ere #as to test #&et&er MomeVal*e is less t&an 1>, and if so, to set it to 10, ma.ing 10 t&e minimum value for MomeVal*e/ ;unning t&is code sni++et #ill s&o# t&at MomeVal*e is al#ays set to 105 0&y* %&e i statement terminates #it& t&e semicolon ?t&e do"not&ing o+erator@/ ;emember t&at indentation &as no meaning to t&e com+iler/ %&is sni++et could more accurately &ave been #ritten as7
i /MomeVal*e < 100 DD test 7 DD (o !ot+i!? MomeVal*e = 107 DD assi?!

;emoving t&e semicolon #ill ma.e t&e final line +art of t&e i statement and #ill ma.e t&is code do #&at #as intended/

Com"ining t,e Assignment and @at,ematica $0erators


It is not uncommon to #ant to add a value to a variable, and t&en to assign t&e result bac. into t&e variable/ If you &ave a variable myA?e and you #ant to increase t&e value by t#o, you can #rite
i!t myA?e = 37 i!t tem#7 tem# = myA?e A -7 myA?e = tem#7

DD a(( 3 A - a!( #*t it i! tem# DD #*t it bacJ i! myA?e

%&is met&od, &o#ever, is terribly convoluted and #asteful/ In C++, you can +ut t&e same variable on bot& sides of t&e assignment o+erator, and t&us t&e +receding becomes
myA?e = myA?e A -7

#&ic& is muc& better/ In algebra t&is e-+ression #ould be meaningless, but in C++ it is read as 9add t#o to t&e value in myA?e and assign t&e result to myA?e/9 $ven sim+ler to #rite, but +er&a+s a bit &arder to read is
myA?e A= -7

%&e self"assigned addition o+erator ?A=@ adds t&e rvalue to t&e lvalue and t&en reassigns t&e result into t&e lvalue/ %&is o+erator is +ronounced 9+lus"e8uals/9 %&e statement #ould be read 9myA?e +lus"e8uals t#o/9 If myA?e &ad t&e value 1 to start, it #ould &ave 8 after t&is statement/

%&ere are self"assigned subtraction ?I=@, division ?D=@, multi+lication ?B=@, and modulus ?V=@ o+erators as #ell/

Increment and Decrement


%&e most common value to add ?or subtract@ and t&en reassign into a variable is 1/ In C+ +, increasing a value by 1 is called incrementing, and decreasing by 1 is called decrementing/ %&ere are s+ecial o+erators to +erform t&ese actions/ %&e increment o+erator ?AA@ increases t&e value of t&e variable by 1, and t&e decrement o+erator ?II@ decreases it by 1/ %&us, if you &ave a variable, C, and you #ant to increment it, you #ould use t&is statement7
CAA7 DD Mtart wit+ C a!( i!creme!t it.

%&is statement is e8uivalent to t&e more verbose statement


C = C A 17

#&ic& you learned is also e8uivalent to t&e moderately verbose statement


C A= 17

Prefi2 and Postfi2 Bot& t&e increment o+erator ?AA@ and t&e decrement o+erator?II@ come in t#o varieties7 +refi- and +ostfi-/ %&e +refi- variety is #ritten before t&e variable name ?AAmyA?e@B t&e +ostfi- variety is #ritten after ?myA?eAA@/ In a sim+le statement, it doesn6t muc& matter #&ic& you use, but in a com+le- statement, #&en you are incrementing ?or decrementing@ a variable and t&en assigning t&e result to anot&er variable, it matters very muc&/ %&e +refi- o+erator is evaluated before t&e assignment, t&e +ostfi- is evaluated after/ %&e semantics of +refi- is t&is7 Increment t&e value and t&en fetc& it/ %&e semantics of +ostfi- is different7 )etc& t&e value and t&en increment t&e original/ %&is can be confusing at first, but if @ is an integer #&ose value is 3 and you #rite
i!t a = AA@7

you &ave told t&e com+iler to increment @ ?ma.ing it 8@ and t&en fetc& t&at value and assign it to a/ %&us, a is no# 8 and @ is no# 8/ If, after doing t&is, you #rite
i!t b = @AA7

you &ave no# told t&e com+iler to fetc& t&e value in @ ?8@ and assign it to b, and t&en go bac. and increment @/ %&us, b is no# 8, but @ is no# 9/ (isting I/F s&o#s t&e use and im+lications of bot& ty+es/

-isting *')' A demonstration of 0refi2 and 0ostfi2 o0erators'


1, DD Listi!? 1.. I (emo!strates *se o -, DD #re i@ a!( #ost i@ i!creme!t a!( ., DD (ecreme!t o#erators 1, )i!cl*(e <iostream.+" 3, i!t mai!/0 8, 2 9, i!t myA?e = .C7 DD i!itialiNe two i!te?ers ;, i!t yo*rA?e = .C7 C, co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 10, co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 11, myA?eAA7 DD #ost i@ i!creme!t 1-, AAyo*rA?e7 DD #re i@ i!creme!t 1., co*t << 4O!e year #asses...6!47 11, co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 13, co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 18, co*t << 4A!ot+er year #asses6!47 19, co*t << 4I am, 4 << myA?eAA << 4 years ol(.6!47 1;, co*t << 4Yo* are, 4 << AAyo*rA?e << 4 years ol(6!47 1C, co*t << 4LetHs #ri!t it a?ai!.6!47 -0, co*t << 4I am, 4 << myA?e << 4 years ol(.6!47 -1, co*t << 4Yo* are, 4 << yo*rA?e << 4 years ol(6!47 --, ret*r! 07 -., : O*t#*t, I am .C years ol( Yo* are .C years ol( O!e year #asses I am 10 years ol( Yo* are 10 years ol( A!ot+er year #asses I am 10 years ol( Yo* are 11 years ol( LetHs #ri!t it a?ai! I am 11 years ol( Yo* are 11 years ol(

Ana ysis: n lines M and =, t#o integer variables are declared, and eac& is initiali4ed #it& t&e value .C/ %&eir values are +rinted on lines < and 1>/ n line 11, myA?e is incremented using t&e +ostfi- increment o+erator, and on line 11, yo*rA?e is incremented using t&e +refi- increment o+erator/ %&e results are +rinted on lines 1I and 1E, and t&ey are identical ?bot& 10@/ n line 1M, myA?e is incremented as +art of t&e +rinting statement, using t&e +ostfiincrement o+erator/ Because it is +ostfi-, t&e increment &a++ens after t&e +rint, and so t&e value 10 is +rinted again/ In contrast, on line 1=, yo*rA?e is incremented using t&e +refiincrement o+erator/ %&us, it is incremented before being +rinted, and t&e value dis+lays as 11/

)inally, on lines 1> and 11, t&e values are +rinted again/ Because t&e increment statement &as com+leted, t&e value in myA?e is no# 11, as is t&e value in yo*rA?e/ Precedence In t&e com+le- statement
@ = 3 A . B ;7

#&ic& is +erformed first, t&e addition or t&e multi+lication* If t&e addition is +erformed first, t&e ans#er is = P =, or DI/ If t&e multi+lication is +erformed first, t&e ans#er is E + 1I, or 1</ $very o+erator &as a +recedence value, and t&e com+lete list is s&o#n in A++endi- A, 9 +erator Precedence/9 Aulti+lication &as &ig&er +recedence t&an addition, and t&us t&e value of t&e e-+ression is 1</ 0&en t#o mat&ematical o+erators &ave t&e same +recedence, t&ey are +erformed in left" to"rig&t order/ %&us
@ = 3 A . A ; B C A 8 B 17

is evaluated multi+lication first, left to rig&t/ %&us, =P< V M1, and DPI V 1I/ 'o# t&e e-+ression is essentially
@ = 3 A . A 9- A -17

'o# t&e addition, left to rig&t, is E + F V =B = + M1 V =>B => + 1I V 1>I/ Be careful #it& t&is/ Some o+erators, suc& as assignment, are evaluated in rig&t"to"left order5 In any case, #&at if t&e +recedence order doesn6t meet your needs* Consider t&e e-+ression
EotalMeco!(s = N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e B 80

In t&is e-+ression, you do not #ant to multi+ly t&e N*mMi!*tesEoEy#e variable by D> and t&en add it to N*mMi!*tesEoE+i!J/ ,ou #ant to add t&e t#o variables to get t&e total number of minutes, and t&en you #ant to multi+ly t&at number by D> to get t&e total seconds/ In t&is case, you use +arent&eses to c&ange t&e +recedence order/ Items in +arent&eses are evaluated at a &ig&er +recedence t&an any of t&e mat&ematical o+erators/ %&us
EotalMeco!(s = /N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e0 B 80

#ill accom+lis& #&at you #ant/

Nesting Parent,eses
)or com+le- e-+ressions, you mig&t need to nest +arent&eses one #it&in anot&er/ )or e-am+le, you mig&t need to com+ute t&e total seconds and t&en com+ute t&e total number of +eo+le #&o are involved before multi+lying seconds times +eo+le7
EotalPerso!Meco!(s = / / /N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e0 B 800 B F/Peo#leI!E+eO ice A Peo#leO!Vacatio!0 0

%&is com+licated e-+ression is read from t&e inside out/ )irst, N*mMi!*tesEoE+i!J is added to N*mMi!*tesEoEy#e, because t&ese are in t&e innermost +arent&eses/ %&en t&is sum is multi+lied by D>/ 'e-t, Peo#leI!E+eO ice is added to Peo#leO!Vacatio!/ )inally, t&e total number of +eo+le found is multi+lied by t&e total number of seconds/ %&is e-am+le raises an im+ortant related issue/ %&is e-+ression is easy for a com+uter to understand, but very difficult for a &uman to read, understand, or modify/ Here is t&e same e-+ression re#ritten, using some tem+orary integer variables7
EotalMi!*tes = N*mMi!*tesEoE+i!J A N*mMi!*tesEoEy#e7 EotalMeco!(s = EotalMi!*tes B 807 EotalPeo#le = Peo#leI!E+eO ice A Peo#leO!Vacatio!7 EotalPerso!Meco!(s = EotalPeo#le B EotalMeco!(s7

%&is e-am+le ta.es longer to #rite and uses more tem+orary variables t&an t&e +receding e-am+le, but it is far easier to understand/ Add a comment at t&e to+ to e-+lain #&at t&is code does, and c&ange t&e 80 to a symbolic constant/ ,ou t&en #ill &ave code t&at is easy to understand and maintain/ D$ remember t&at e-+ressions &ave a value/ D$ use t&e +refi- o+erator ?AAvariable@ to increment or decrement t&e variable before it is used in t&e e-+ression/ D$ use t&e +ostfi- o+erator ?variableAA@ to increment or decrement t&e variable after it is used/ D$ use +arent&eses to c&ange t&e order of +recedence/ D$N:T nest too dee+ly, because t&e e-+ression becomes &ard to understand and maintain/

T,e Nature of Trut,


In C++, 4ero is considered false, and all ot&er values are considered true, alt&oug& true is usually re+resented by 1/ %&us, if an e-+ression is false, it is e8ual to 4ero, and if an e-+ression is e8ual to 4ero, it is false/ If a statement is true, all you .no# is t&at it is non4ero, and any non4ero statement is true/ 5e ationa $0erators %&e relational o+erators are used to determine #&et&er t#o numbers are e8ual, or if one is greater or less t&an t&e ot&er/ $very relational statement evaluates to eit&er 1 ?ERU<@ or 0 ?KALM<@/ %&e relational o+erators are +resented later, in %able I/1/

If t&e integer variable myA?e &as t&e value .C, and t&e integer variable yo*rA?e &as t&e value 10, you can determine #&et&er t&ey are e8ual by using t&e relational 9e8uals9 o+erator7
myA?e == yo*rA?e7 DD is t+e Gal*e i! myA?e t+e same as i! yo*rA?eO

%&is e-+ression evaluates to 0, or alse, because t&e variables are not e8ual/ %&e e-+ression
myA?e " yo*rA?e7 DD is myA?e ?reater t+a! yo*rA?eO

evaluates to 0 or alse/ 4A5NING: Aany novice C++ +rogrammers confuse t&e assignment o+erator ?=@ #it& t&e e8uals o+erator ?==@/ %&is can create a nasty bug in your +rogram/ %&ere are si- relational o+erators7 e8uals ?==@, less t&an ?<@, greater t&an ?"@, less t&an or e8ual to ?<=@, greater t&an or e8ual to ?"=@, and not e8uals ?5=@/ %able I/1 s&o#s eac& relational o+erator, its use, and a sam+le code use/

Ta" e *'1' T,e 5e ationa $0erators'


Name $8uals 'ot $8uals Operator Sample
== 5=

Evaluates

100 == 307 alse 30 == 307 tr*e 100 5= 307 tr*e 30 5= 307 alse alse 100 " 307 tr*e 30 " 307 100 "= 307 tr*e 30 "= 307 tr*e 100 < 307 30 < 307 alse alse

Greater %&an " Greater %&an "= or $8uals (ess %&an <

100 <= 307 alse (ess %&an <= 30 <= 307 tr*e or $8uals D$ remember t&at relational o+erators return t&e value 1 ?tr*e@ or 0 ? alse@/ D$N:T confuse t&e assignment o+erator ?=@ #it& t&e e8uals relational o+erator ?==@/ %&is is one of t&e most common C++ +rogramming mista.es""be on guard for it/

T,e if Statement
'ormally, your +rogram flo#s along line by line in t&e order in #&ic& it a++ears in your source code/ %&e i statement enables you to test for a condition ?suc& as #&et&er t#o variables are e8ual@ and branc& to different +arts of your code, de+ending on t&e result/

%&e sim+lest form of an i statement is t&is7


i /e@#ressio!0 stateme!t7

%&e e-+ression in t&e +arent&eses can be any e-+ression at all, but it usually contains one of t&e relational e-+ressions/ If t&e e-+ression &as t&e value 0, it is considered false, and t&e statement is s.i++ed/ If it &as any non4ero value, it is considered true, and t&e statement is e-ecuted/ Consider t&e follo#ing e-am+le7
i /bi?N*mber " smallN*mber0 bi?N*mber = smallN*mber7

%&is code com+ares bi?N*mber and smallN*mber/ If bi?N*mber is larger, t&e second line sets its value to t&e value of smallN*mber/ Because a bloc. of statements surrounded by braces is e-actly e8uivalent to a single statement, t&e follo#ing ty+e of branc& can be 8uite large and +o#erful7
i 2 /e@#ressio!0 stateme!t17 stateme!t-7 stateme!t.7

Here6s a sim+le e-am+le of t&is usage7


i 2 /bi?N*mber " smallN*mber0 bi?N*mber = smallN*mber7 co*t << 4bi?N*mber, 4 << bi?N*mber << 46!47 co*t << 4smallN*mber, 4 << smallN*mber << 46!47

%&is time, if bi?N*mber is larger t&an smallN*mber, not only is it set to t&e value of smallN*mber, but an informational message is +rinted/ (isting I/I s&o#s a more detailed e-am+le of branc&ing based on relational o+erators/

-isting *'*' A demonstration of "ranc,ing "ased on re ationa o0erators'


1, -, ., 1, 3, 8, 9, ;, C, 10, DD Listi!? 1.1 I (emo!strates i stateme!t DD *se( wit+ relatio!al o#erators )i!cl*(e <iostream.+" i!t mai!/0 2 i!t Re(Mo@Mcore> Ya!JeesMcore7 co*t << 4<!ter t+e score or t+e Re( Mo@, 47 ci! "" Re(Mo@Mcore7 co*t << 46!<!ter t+e score or t+e Ya!Jees, 47

11, ci! "" Ya!JeesMcore7 1-, 1., co*t << 46!47 11, 13, i /Re(Mo@Mcore " Ya!JeesMcore0 18, co*t << 4Qo Mo@56!47 19, 1;, i /Re(Mo@Mcore < Ya!JeesMcore0 1C, 2 -0, co*t << 4Qo Ya!Jees56!47 -1, co*t << 4&a##y (ays i! New YorJ56!47 --, : -., -1, i /Re(Mo@Mcore == Ya!JeesMcore0 -3, 2 -8, co*t << 4A tieO Naa+> ca!Ht be.6!47 -9, co*t << 4QiGe me t+e real score or t+e Ya!Js, 47 -;, ci! "" Ya!JeesMcore7 -C, .0, i /Re(Mo@Mcore " Ya!JeesMcore0 .1, co*t << 4X!ew it5 Qo Mo@547 .-, .., i /Ya!JeesMcore " Re(Mo@Mcore0 .1, co*t << 4X!ew it5 Qo Ya!Js547 .3, .8, i /Ya!JeesMcore == Re(Mo@Mcore0 .9, co*t << 4'ow> it really was a tie547 .;, : .C, 10, co*t << 46!E+a!Js or telli!? me.6!47 11, ret*r! 07 1-, : O*t#*t, <!ter t+e score or t+e Re( Mo@, 10 <!ter t+e score or t+e Ya!Jees, 10 or t+e Ya!Js, ;

A tieO Naa+> ca!Ht be QiGe me t+e real score X!ew it5 Qo Mo@5 E+a!Js or telli!? me.

Ana ysis: %&is +rogram as.s for user in+ut of scores for t#o baseball teams, #&ic& are stored in integer variables/ %&e variables are com+ared in t&e i statement on lines 1E, 1=, and 1I/ If one score is &ig&er t&an t&e ot&er, an informational message is +rinted/ If t&e scores are e8ual, t&e bloc. of code t&at begins on line 1I and ends on line F= is entered/ %&e second score is re8uested again, and t&en t&e scores are com+ared again/ 'ote t&at if t&e initial ,an.ees score #as &ig&er t&an t&e ;ed So- score, t&e i statement on line 1E #ould evaluate as KALM<, and line 1D #ould not be invo.ed/ %&e test on line 1= #ould evaluate as tr*e, and t&e statements on lines 1> and 11 #ould be invo.ed/ %&en t&e i statement on line 1I #ould be tested, and t&is #ould be false ?if line 1= #as true@/ %&us, t&e +rogram #ould s.i+ t&e entire bloc., falling t&roug& to line F</

In t&is e-am+le, getting a true result in one i statement does not sto+ ot&er i statements from being tested/ Indentation Sty es (isting I/F s&o#s one style of indenting i statements/ 'ot&ing is more li.ely to create a religious #ar, &o#ever, t&an to as. a grou+ of +rogrammers #&at is t&e best style for brace alignment/ Alt&oug& t&ere are do4ens of variations, t&ese a++ear to be t&e favorite t&ree7

Putting t&e initial brace after t&e condition and aligning t&e closing brace under t&e i to close t&e statement bloc./

i :

/e@#ressio!02 stateme!ts

i 2 : i

Aligning t&e braces under t&e i and indenting t&e statements/

/e@#ressio!0 stateme!ts

Indenting t&e braces and statements/

/e@#ressio!0 2 stateme!ts :

%&is boo. uses t&e middle alternative, because I find it easier to understand #&ere bloc.s of statements begin and end if t&e braces line u+ #it& eac& ot&er and #it& t&e condition being tested/ Again, it doesn6t matter muc& #&ic& style you c&oose, as long as you are consistent #it& it/ e se ften your +rogram #ill #ant to ta.e one branc& if your condition is true, anot&er if it is false/ In (isting I/F, you #anted to +rint one message ?Qo Mo@5@ if t&e first test ?Re(Mo@Mcore " Ya!Jees@ evaluated ERU<, and anot&er message ?Qo Ya!Js5@ if it evaluated KALM</ %&e met&od s&o#n so far, testing first one condition and t&en t&e ot&er, #or.s fine but is a bit cumbersome/ %&e .ey#ord else can ma.e for far more readable code7
i /e@#ressio!0 stateme!t7 else

stateme!t7

(isting I/E demonstrates t&e use of t&e .ey#ord else/

-isting *';' Demonstrating t,e e se 3eyword'


1, DD Listi!? 1.3 I (emo!strates i stateme!t -, DD wit+ else cla*se ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, i!t irstN*mber> seco!(N*mber7 9, co*t << 4Please e!ter a bi? !*mber, 47 ;, ci! "" irstN*mber7 C, co*t << 46!Please e!ter a smaller !*mber, 47 10, ci! "" seco!(N*mber7 11, i / irstN*mber " seco!(N*mber0 1-, co*t << 46!E+a!Js56!47 1., else 11, co*t << 46!Oo#s. E+e seco!( is bi??er547 13, 18, ret*r! 07 19, : O*t#*t, Please e!ter a bi? !*mber, 10 Please e!ter a smaller !*mber, 1Oo#s. E+e seco!( is bi??er5

Ana ysis: %&e i statement on line 11 is evaluated/ If t&e condition is true, t&e statement on line 11 is runB if it is false, t&e statement on line 1I is run/ If t&e else clause on line 1F #ere removed, t&e statement on line 1I #ould run #&et&er or not t&e i statement #as true/ ;emember, t&e i statement ends after line 11/ If t&e else #as not t&ere, line 1I #ould !ust be t&e ne-t line in t&e +rogram/ ;emember t&at eit&er or bot& of t&ese statements could be re+laced #it& a bloc. of code in braces/

T,e if Statement
%&e synta- for t&e i statement is as follo#s7 )orm 1
i /e@#ressio!0 stateme!t7 !e@t stateme!t7

If t&e e-+ression is evaluated as ERU<, t&e statement is e-ecuted and t&e +rogram continues #it& t&e ne-t statement/ If t&e e-+ression is not true, t&e statement is ignored and t&e +rogram !um+s to t&e ne-t statement/ ;emember t&at t&e statement can be a single statement ending #it& a semicolon or a bloc. enclosed in braces/ )orm 1

/e@#ressio!0 stateme!t17 else stateme!t-7 !e@t stateme!t7

If t&e e-+ression evaluates ERU<, stateme!t1 is e-ecutedB ot&er#ise, stateme!t- is e-ecuted/ After#ards, t&e +rogram continues #it& t&e ne-t statement/ $-am+le 1
<@am#le i /MomeVal*e < 100 co*t << 4MomeVal*e is less t+a! 10407 else co*t << 4MomeVal*e is !ot less t+a! 105407 co*t << 4Do!e.4 << e!(l7

Ad!anced if Statements It is #ort& noting t&at any statement can be used in an i or else clause, even anot&er i or else statement/ %&us, you mig&t see com+le- i statements in t&e follo#ing form7
i 2 /e@#ressio!10 i /e@#ressio!-0 stateme!t17 else 2 i /e@#ressio!.0 stateme!t-7 else stateme!t.7 : stateme!t17

: else

%&is cumbersome i statement says, 9If e-+ression1 is true and e-+ression1 is true, e-ecute statement1/ If e-+ression1 is true but e-+ression1 is not true, t&en if e-+ressionF is true e-ecute statement1/ If e-+ression1 is true but e-+ression1 and e-+ressionF are false, e-ecute statementF/ )inally, if e-+ression1 is not true, e-ecute statementI/9 As you can see, com+le- i statements can be confusing5 (isting I/D gives an e-am+le of suc& a com+le- i statement/

-isting *'B' A com0 e2# nested if statement'


1, -, ., 1, 3, 8, DD Listi!? 1.3 I a com#le@ !este( DD i stateme!t )i!cl*(e <iostream.+" i!t mai!/0 2 DD AsJ or two !*mbers

9, ;, C, 10, 11, 1-, 1., 11, 13, 18, 19, 1;, 1C, -0, -1, --, -., -1, -3, -8, -9, -;, -C, .0, .1, .-, .., .1, :

DD DD DD DD

Assi?! t+e !*mbers to bi?N*mber a!( littleN*mber I bi?N*mber is bi??er t+a! littleN*mber> see i t+ey are eGe!ly (iGisible I t+ey are> see i t+ey are t+e same !*mber

i!t irstN*mber> seco!(N*mber7 co*t << 4<!ter two !*mbers.6!Kirst, 47 ci! "" irstN*mber7 co*t << 46!Meco!(, 47 ci! "" seco!(N*mber7 co*t << 46!6!47 i 2 i 2 / irstN*mber "= seco!(N*mber0 / / irstN*mber V seco!(N*mber0 == 00 DD eGe!ly (iGisibleO i / irstN*mber == seco!(N*mber0 co*t << 4E+ey are t+e same56!47 else co*t << 4E+ey are eGe!ly (iGisible56!47 : else co*t << 4E+ey are !ot eGe!ly (iGisible56!47 : else co*t << 4&ey5 E+e seco!( o!e is lar?er56!47 ret*r! 07

O*t#*t, <!ter two !*mbers. Kirst, 10 Meco!(, E+ey are eGe!ly (iGisible5

Ana ysis: %#o numbers are +rom+ted for one at a time, and t&en com+ared/ %&e first i statement, on line 1<, c&ec.s to ensure t&at t&e first number is greater t&an or e8ual to t&e second/ If not, t&e else clause on line F1 is e-ecuted/ If t&e first i is true, t&e bloc. of code beginning on line 1> is e-ecuted, and t&e second i statement is tested, on line 11/ %&is c&ec.s to see #&et&er t&e first number modulo t&e second number yields no remainder/ If so, t&e numbers are eit&er evenly divisible or e8ual/ %&e i statement on line 1F c&ec.s for e8uality and dis+lays t&e a++ro+riate message eit&er #ay/ If t&e i statement on line 11 fails, t&e else statement on line 1= is e-ecuted/

9sing Braces in Nested if Statements


Alt&oug& it is legal to leave out t&e braces on i statements t&at are only a single statement, and it is legal to nest i statements, suc& as

/@ " y0 i /@ < N0 @ = y7

DD i @ is bi??er t+a! y DD a!( i @ is smaller t+a! N DD t+e! set @ to t+e Gal*e i! N

#&en #riting large nested statements, t&is can cause enormous confusion/ ;emember, #&ites+ace and indentation are a convenience for t&e +rogrammerB t&ey ma.e no difference to t&e com+iler/ It is easy to confuse t&e logic and inadvertently assign an else statement to t&e #rong i statement/ (isting I/M illustrates t&is +roblem/

-isting *'C' A demonstration of w,y "races ,e 0 c arify w,ic, e se statement goes wit, w,ic, if statement'
1, DD Listi!? 1.9 I (emo!strates w+y braces -, DD are im#orta!t i! !este( i stateme!ts ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, i!t @7 9, co*t << 4<!ter a !*mber less t+a! 10 or ?reater t+a! 100, 47 ;, ci! "" @7 C, co*t << 46!47 10, 11, i /@ " 100 1-, i /@ " 1000 1., co*t << 4More t+a! 100> E+a!Js56!47 11, else DD !ot t+e else i!te!(e(5 13, co*t << 4Less t+a! 10> E+a!Js56!47 18, 19, ret*r! 07 1;, : O*t#*t, <!ter a !*mber less t+a! 10 or ?reater t+a! 100, -0 Less t+a! 10> E+a!Js5

Ana ysis: %&e +rogrammer intended to as. for a number bet#een 1> and 1>>, c&ec. for t&e correct value, and t&en +rint a t&an."you note/ If t&e i statement on line 11 evaluates ERU<, t&e follo#ing statement ?line 11@ is e-ecuted/ In t&is case, line 11 e-ecutes #&en t&e number entered is greater t&an 1>/ (ine 11 contains an i statement also/ %&is i statement evaluates ERU< if t&e number entered is greater t&an 1>>/ If t&e number is not greater t&an 1>>, t&e statement on line 1F is e-ecuted/ If t&e number entered is less t&an or e8ual to 1>, t&e i statement on line 1> evaluates to KALM</ Program control goes to t&e ne-t line follo#ing t&e i statement, in t&is case line 1D/ If you enter a number less t&an 1>, t&e out+ut is as follo#s7
<!ter a !*mber less t+a! 10 or ?reater t+a! 100, C

%&e else clause on line 1I #as clearly intended to be attac&ed to t&e i statement on line 11, and t&us is indented accordingly/ :nfortunately, t&e else statement is really attac&ed to t&e i statement on line 11, and t&us t&is +rogram &as a subtle bug/ It is a subtle bug because t&e com+iler #ill not com+lain/ %&is is a legal C++ +rogram, but it !ust doesn6t do #&at #as intended/ )urt&er, most of t&e times t&e +rogrammer tests t&is +rogram, it #ill a++ear to #or./ As long as a number t&at is greater t&an 1>> is entered, t&e +rogram #ill seem to #or. !ust fine/ (isting I/= fi-es t&e +roblem by +utting in t&e necessary braces/

-isting *'E' A demonstration of t,e 0ro0er use of "races wit, an if statement


1, DD Listi!? 1.; I (emo!strates #ro#er *se o braces -, DD i! !este( i stateme!ts ., )i!cl*(e <iostream.+" 1, i!t mai!/0 3, 2 8, i!t @7 9, co*t << 4<!ter a !*mber less t+a! 10 or ?reater t+a! 100, 47 ;, ci! "" @7 C, co*t << 46!47 10, 11, i /@ " 100 1-, 2 1., i /@ " 1000 11, co*t << 4More t+a! 100> E+a!Js56!47 13, : 18, else DD !ot t+e else i!te!(e(5 19, co*t << 4Less t+a! 10> E+a!Js56!47 1;, ret*r! 07 1C, : O*t#*t, <!ter a !*mber less t+a! 10 or ?reater t+a! 100, -0

Ana ysis: %&e braces on lines 11 and 1E ma.e everyt&ing bet#een t&em into one statement, and no# t&e else on line 1D a++lies to t&e i on line 11 as intended/ %&e user ty+ed -0, so t&e i statement on line 11 is trueB &o#ever, t&e i statement on line 1F is false, so not&ing is +rinted/ It #ould be better if t&e +rogrammer +ut anot&er else clause after line 1I so t&at errors #ould be caug&t and a message +rinted/ N$T+: %&e +rograms s&o#n in t&is boo. are #ritten to demonstrate t&e +articular issues being discussed/ %&ey are .e+t intentionally sim+leB t&ere is no attem+t to 9bullet+roof9 t&e code to +rotect against user error/ In +rofessional"8uality code, every +ossible user error is antici+ated and &andled gracefully/

-ogica $0erators

ften you #ant to as. more t&an one relational 8uestion at a time/ 9Is it true t&at - is greater t&an y, and also true t&at y is greater t&an 4*9 A +rogram mig&t need to determine t&at bot& of t&ese conditions are true, or t&at some ot&er condition is true, in order to ta.e an action/ Imagine a so+&isticated alarm system t&at &as t&is logic7 9If t&e door alarm sounds A'D it is after si- +/m/ A'D it is ' % a &oliday, ; if it is a #ee.end, t&en call t&e +olice/9 C++6s t&ree logical o+erators are used to ma.e t&is .ind of evaluation/ %&ese o+erators are listed in %able I/1/

Ta" e *'(' T,e -ogica $0erators'


Operator Symbol Example AND `` e-+ression1 `` e-+ression1 OR ^^ e-+ression1 ^^ e-+ression1 NOE 5 5e-+ression -ogica AND A logical AND statement evaluates t#o e-+ressions, and if bot& e-+ressions are true, t&e logical AND statement is true as #ell/ If it is true t&at you are &ungry, A'D it is true t&at you &ave money, %H$' it is true t&at you can buy lunc&/ %&us,
i / /@ == 30 `` /y == 30 0

#ould evaluate ERU< if bot& @ and y are e8ual to E, and it #ould evaluate KALM< if eit&er one is not e8ual to E/ 'ote t&at bot& sides must be true for t&e entire e-+ression to be true/ 'ote t&at t&e logical AND is t#o `` symbols/ A single ` symbol is a different o+erator, discussed on Day 11, 90&at6s 'e-t/9 -ogica $5 A logical OR statement evaluates t#o e-+ressions/ If eit&er one is true, t&e e-+ression is true/ If you &ave money ; you &ave a credit card, you can +ay t&e bill/ ,ou don6t need bot& money and a credit cardB you need only one, alt&oug& &aving bot& #ould be fine as #ell/ %&us,
i / /@ == 30 ^^ /y == 30 0

evaluates ERU< if eit&er @ or y is e8ual to E, or if bot& are/ 'ote t&at t&e logical OR is t#o ^^ symbols/ A single ^ symbol is a different o+erator, discussed on Day 11/ -ogica N$T

A logical NOE statement evaluates tr*e if t&e e-+ression being tested is false/ Again, if t&e e-+ression being tested is false, t&e value of t&e test is ERU<5 %&us
i / 5/@ == 30 0

is true only if @ is not e8ual to E/ %&is is e-actly t&e same as #riting


i /@ 5= 30

5e ationa Precedence
;elational o+erators and logical o+erators, being C++ e-+ressions, eac& return a value7 1 ?ERU<@ or 0 ?KALM<@/ (i.e all e-+ressions, t&ey &ave a +recedence order ?see A++endi- A@ t&at determines #&ic& relations are evaluated first/ %&is fact is im+ortant #&en determining t&e value of t&e statement
i / @ " 3 `` y " 3 ^^ N " 30

It mig&t be t&at t&e +rogrammer #anted t&is e-+ression to evaluate ERU< if bot& @ and y are greater t&an E or if N is greater t&an E/ n t&e ot&er &and, t&e +rogrammer mig&t &ave #anted t&is e-+ression to evaluate ERU< only if @ is greater t&an E and if it is also true t&at eit&er y is greater t&an E or N is greater t&an E/ If @ is F, and y and N are bot& 1>, t&e first inter+retation #ill be true ?N is greater t&an E, so ignore @ and y@, but t&e second #ill be false ?it isn6t true t&at bot& @ and y are greater t&an E nor is it true t&at N is greater t&an E@/ Alt&oug& +recedence #ill determine #&ic& relation is evaluated first, +arent&eses can bot& c&ange t&e order and ma.e t&e statement clearer7
i / /@ " 30 `` /y " 3 ^^ N " 30 0

:sing t&e values from earlier, t&is statement is false/ Because it is not true t&at @ is greater t&an E, t&e left side of t&e AND statement fails, and t&us t&e entire statement is false/ ;emember t&at an AND statement re8uires t&at bot& sides be true""somet&ing isn6t bot& 9good tasting9 A'D 9good for you9 if it isn6t good tasting/ N$T+: It is often a good idea to use e-tra +arent&eses to clarify #&at you #ant to grou+/ ;emember, t&e goal is to #rite +rograms t&at #or. and t&at are easy to read and understand/

@ore A"out Trut, and .a se,ood


In C++, 4ero is false, and any ot&er value is true/ Because an e-+ression al#ays &as a value, many C++ +rogrammers ta.e advantage of t&is feature in t&eir i statements/ A statement suc& as

/@0 @ = 07

DD i

@ is tr*e /!o!Nero0

can be read as 9If @ &as a non4ero value, set it to >/9 %&is is a bit of a c&eatB it #ould be clearer if #ritten
i /@ 5= 00 @ = 07 DD i @ is !o!Nero

Bot& statements are legal, but t&e latter is clearer/ It is good +rogramming +ractice to reserve t&e former met&od for true tests of logic, rat&er t&an for testing for non4ero values/ %&ese t#o statements also are e8uivalent7
i i /5@0 /@ == 00 DD i DD i @ is alse /Nero0 @ is Nero

%&e second statement, &o#ever, is some#&at easier to understand and is more e-+licit/ D$ +ut +arent&eses around your logical tests to ma.e t&em clearer and to ma.e t&e +recedence e-+licit/ D$ use braces in nested i statements to ma.e t&e else statements clearer and to avoid bugs/ D$N:T use i /@0 as a synonym for i /@ 5= 00B t&e latter is clearer/ D$N:T use i /5@0 as a synonym for i /@ == 00B t&e latter is clearer/ N$T+: It is common to define your o#n enumerated Boolean ?logical@ ty+e #it& e!*m $ool 2KALM<> ERU<:7/ %&is serves to set KALM< to 0 and ERU< to 1/

Conditiona FTernaryG $0erator


%&e conditional o+erator ?O,@ is C++6s only ternary o+eratorB t&at is, it is t&e only o+erator to ta.e t&ree terms/ %&e conditional o+erator ta.es t&ree e-+ressions and returns a value7
/e@#ressio!10 O /e@#ressio!-0 , /e@#ressio!.0

%&is line is read as 9If e-+ression1 is true, return t&e value of e-+ression1B ot&er#ise, return t&e value of e-+ressionF/9 %y+ically, t&is value #ould be assigned to a variable/ (isting I/< s&o#s an i statement re#ritten using t&e conditional o+erator/

-isting *'H' A demonstration of t,e conditiona o0erator'


1, -, ., DD Listi!? 1.C I (emo!strates t+e co!(itio!al o#erator DD )i!cl*(e <iostream.+"

1, i!t mai!/0 3, 2 8, i!t @> y> N7 9, co*t << 4<!ter two !*mbers.6!47 ;, co*t << 4Kirst, 47 C, ci! "" @7 10, co*t << 46!Meco!(, 47 11, ci! "" y7 1-, co*t << 46!47 1., 11, i /@ " y0 13, N = @7 18, else 19, N = y7 1;, 1C, co*t << 4N, 4 << N7 -0, co*t << 46!47 -1, --, N = /@ " y0 O @ , y7 -., -1, co*t << 4N, 4 << N7 -3, co*t << 46!47 -8, ret*r! 07 -9, : O*t#*t, <!ter two !*mbers. Kirst, 3 Meco!(, ; N, ; N, ;

Ana ysis: %&ree integer variables are created7 @, y, and N/ %&e first t#o are given values by t&e user/ %&e i statement on line 1I tests to see #&ic& is larger and assigns t&e larger value to N/ %&is value is +rinted on line 1</ %&e conditional o+erator on line 11 ma.es t&e same test and assigns N t&e larger value/ It is read li.e t&is7 9If @ is greater t&an y, return t&e value of @B ot&er#ise, return t&e value of y/9 %&e value returned is assigned to N/ %&at value is +rinted on line 1I/ As you can see, t&e conditional statement is a s&orter e8uivalent to t&e i ...else statement/

Summary
%&is c&a+ter &as covered a lot of material/ ,ou &ave learned #&at C++ statements and e-+ressions are, #&at C++ o+erators do, and &o# C++ i statements #or./ ,ou &ave seen t&at a bloc. of statements enclosed by a +air of braces can be used any#&ere a single statement can be used/ ,ou &ave learned t&at every e-+ression evaluates to a value, and t&at value can be tested in an i statement or by using t&e conditional o+erator/ ,ou6ve also seen &o# to evaluate multi+le statements using t&e logical o+erator, &o# to com+are values using t&e relational o+erators, and &o# to assign values using t&e assignment o+erator/

,ou &ave e-+lored o+erator +recedence/ And you &ave seen &o# +arent&eses can be used to c&ange t&e +recedence and to ma.e +recedence e-+licit and t&us easier to manage/

67A
6' 4,y use unnecessary 0arent,eses w,en 0recedence wi determine w,ic, o0erators are acted on first/ A' Alt&oug& it is true t&at t&e com+iler #ill .no# t&e +recedence and t&at a +rogrammer can loo. u+ t&e +recedence order, code t&at is easy to understand is easier to maintain/ 6' If t,e re ationa o0erators a ways return 1 or I# w,y are ot,er !a ues considered true/ A' %&e relational o+erators return 1 or >, but every e-+ression returns a value, and t&ose values can also be evaluated in an i statement/ Here6s an e-am+le7 %&is is a +erfectly legal C++ statement/ It evaluates to a value even if t&e sum of a and b is not e8ual to FE/ Also note t&at @ is assigned t&e value t&at is t&e sum of a and b in any case/ 6' 4,at effect do ta"s# s0aces# and new ines ,a!e on t,e 0rogram/ A/ %abs, s+aces, and ne# lines ?.no#n as #&ites+ace@ &ave no effect on t&e +rogram, alt&oug& !udicious use of #&ites+ace can ma.e t&e +rogram easier to read/ 6' Are negati!e num"ers true or fa se/ A' All non4ero numbers, +ositive and negative, are true/

/ /@ = a A b0 == .3 0

4or3s,o0
%&e 0or.s&o+ +rovides 8ui4 8uestions to &el+ you solidify your understanding of t&e material covered, and e-ercises to +rovide you #it& e-+erience in using #&at you6ve learned/ %ry to ans#er t&e 8ui4 and e-ercise 8uestions before c&ec.ing t&e ans#ers in A++endi- D, and ma.e sure t&at you understand t&e ans#ers before continuing to t&e ne-t c&a+ter/ 6ui8 1' 0&at is an e-+ression* (' Is @ = 3 A 9 an e-+ression* 0&at is its value*

)' 0&at is t&e value of -01 D 1* *' 0&at is t&e value of -01 V 1* ;' If myA?e, a, myA?e = .C7 a = myA?eAA7 b = AAmyA?e7 and b are all i!t variables, #&at are t&eir values after7

B' 0&at is t&e value of ;A-B.* C' 0&at is t&e difference bet#een @ = . and @ == .* E' Do t&e follo#ing values evaluate to ERU< or KALM<* a/ 0 "' 1 c' I1 d' @ = 0 e/ @ == 0 DD ass*me t+at @ +as t+e Gal*e o +2ercises 1' 0rite a single i statement t&at e-amines t#o integer variables and c&anges t&e larger to t&e smaller, using only one else clause/ (' $-amine t&e follo#ing +rogram/ Imagine entering t&ree numbers, and #rite #&at out+ut you e-+ect/

1, )i!cl*(e <iostream.+" -, i!t mai!/0 ., 2 1, i!t a> b> c7 3, co*t << 4Please e!ter t+ree !*mbers6!47 8, co*t << 4a, 47 9, ci! "" a7 ;, co*t << 46!b, 47 C, ci! "" b7 10, co*t << 46!c, 47 11, ci! "" c7 1-, 1., i /c = /aIb00 11, 2co*t << 4a, 47 13, co*t << a7 18, co*t << 4mi!*s b, 47 19, co*t << b7 1;, co*t << 4eP*als c, 47 1C, co*t << c << e!(l7: -0, else -1, co*t << 4aIb (oes !ot eP*al c, 4 << e!(l7 --, ret*r! 07 -., :

)' $nter t&e +rogram from $-ercise 1B com+ile, lin., and run it/ $nter t&e numbers 1>, 1>, and E>/ Did you get t&e out+ut you e-+ected* 0&y not* *' $-amine t&is +rogram and antici+ate t&e out+ut7
1, -, ., 1, 3, 8, 9, ;, )i!cl*(e <iostream.+" i!t mai!/0 2 i!t a = 1> b = 1> c7 i /c = /aIb00 co*t << 4E+e Gal*e o c is, 4 << c7 ret*r! 07 :

;' $nter, com+ile, lin., and run t&e +rogram from $-ercise I/ 0&at #as t&e out+ut* 0&y*

You might also like