Massachusetts Institute of Technology John Marrero Lecture 2 Notes: Flow of Control 1 Motivation or!ally, a "rogra! e#ecutes state!ents fro! first to last. The first state!ent is e#ecuted, then the second, then the third, and so on, until the "rogra! reaches its end and ter!inates. $ co!"uter "rogra! li%ely &ouldn't (e )ery useful if it ran the sa!e se*uence of state!ents e)ery ti!e it &as run. It &ould (e nice to (e a(le to change &hich state!ents ran and &hen, de"ending on the circu!stances. +or e#a!"le, if a "rogra! chec%s a file for the nu!(er of ti!es a certain &ord a""ears, it should (e a(le to gi)e the correct count no !atter &hat file and &ord are gi)en to it. ,r, a co!"uter ga!e should !o)e the "layer's character around &hen the "layer &ants. -e need to (e a(le to alter the order in &hich a "rogra!'s state!ents are e#ecuted, the control flow. 2 Control Structures Control structures are "ortions of "rogra! code that contain state!ents &ithin the! and, de"ending on the circu!stances, e#ecute these state!ents in a certain &ay. There are ty"ically t&o %inds. conditionals and loops. 2.1 Conditionals In order for a "rogra! to change its (eha)ior de"ending on the in"ut, there !ust a &ay to test that in"ut. Conditionals allo& the "rogra! to chec% the )alues of )aria(les and to e#ecute /or not e#ecute0 certain state!ents. C++ has if and switch-case conditional structures. 2.1.1 Operators Conditionals use t&o %inds of s"ecial o"erators. relational and logical. These are used to deter!ine &hether so!e condition is true or false. The relational o"erators are used to test a relation (et&een t&o e#"ressions. Operator Meaning > 1reater than >= 1reater than or e*ual to < 2ess than <= 2ess than or e*ual to == 3*ual to != ot e*ual to They &or% the sa!e as the arith!etic o"erators /e.g., a 4 (0 (ut return a 5oolean )alue of either true or false, indicating &hether the relation tested for holds. /$n e#"ression that returns this %ind of )alue is called a 5oolean e#"ression.0 +or e#a!"le, if the )aria(les x and y ha)e (een set to 6 and 2, res"ecti)ely, then x > y returns true. 6i!ilarly, x < 5 returns false. The logical o"erators are often used to co!(ine relational e#"ressions into !ore co!"licated 5oolean e#"ressions. Operator Meaning && and || or ! not The o"erators return true or false, according to the rules of logic. a b a && b true true true true false false false true false false false false a b a b true true true true false true false true true false false false The ! o"erator is a unary o"erator, ta%ing only one argu!ent and negating its )alue. a !a true false false true 3#a!"les using logical o"erators /assu!e # 7 6 and y 7 20. !(x > 2) false (x > y) && (y > 0) true (x < y) && (y > 0) false (x < y) || (y > 0) true ,f course, 5oolean )aria(les can (e used directly in these e#"ressions, since they hold true and false )alues. In fact, any %ind of )alue can (e used in a 5oolean e#"ression due to a *uir% C++ has. false is re"resented (y a )alue of 0 and anything that is not 0 is true. 6o, Hello, world! is true, 2 is true, and any it )aria(le holding a non89ero )alue is true. This !eans !x returns false and x && y returns true: 2.1.2 if, if-else and else if The if conditional has the for!. if(!oditio) " state#et$ state#et2 % & The condition is so!e e#"ression &hose )alue is (eing tested. If the condition resol)es to a )alue of true, then the state!ents are e#ecuted (efore the "rogra! continues on. ,ther&ise, the state!ents are ignored. If there is only one state!ent, the curly (races !ay (e o!itted, gi)ing the for!. if(!oditio) state#et The if-else for! is used to decide (et&een t&o se*uences of state!ents referred to as blocks. if(!oditio) " state#et'$ state#et'2 % & else " state#et($ state#et(2 % & If the condition is !et, the (loc% corres"onding to the if is e#ecuted. ,ther&ise, the (loc% corres"onding to the else is e#ecuted. 5ecause the condition is either satisfied or not, one of the (loc%s in an if8else must e#ecute. If there is only one state!ent for any of the (loc%s, the curly (races for that (loc% !ay (e o!itted. if(!oditio) state#et'$ else state#et($ The else if is used to decide (et&een t&o or !ore (loc%s (ased on multiple conditions. if(!oditio$) " state#et'$ state#et'2 % & else if(!oditio2) " state#et($ state#et(2 % & If !oditio$ is !et, the (loc% corres"onding to the if is e#ecuted. If not, then only if !oditio2 is !et is the (loc% corres"onding to the else if e#ecuted. There !ay (e !ore than one else if, each &ith its o&n condition. ,nce a (loc% &hose condition &as !et is e#ecuted, any else ifs after it are ignored. Therefore, in an if-else-if structure, either one or no (loc% is e#ecuted. $n else !ay (e added to the end of an if8else8if. If none of the "re)ious conditions are !et, the else (loc% is e#ecuted. In this structure, one of the (loc%s must e#ecute, as in a nor!al if8 else. ;ere is an e#a!"le using these control structures. $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 it x = /, / it y = 2, 0 1 if(x > y) 2 !out << x is *reater t3a y4, $0 else if(y > x) $$ !out << y is *reater t3a x4, $2 else $- !out << x ad y are e5ual4, $. $5 retur 0, $/ & The out"ut of this "rogra! is x is *reater t3a y. If &e re"lace lines 5 and 6 &ith it x = 2, it y = /, then the out"ut is y is *reater t3a x. If &e re"lace the lines &ith it x = 2, it y = 2, then the out"ut is x ad y are e5ual. 2.1." switch-case The switch-case is another conditional structure that !ay or !ay not e#ecute certain state!ents. ;o&e)er, the s&itch8case has "eculiar synta# and (eha)ior. swit!3(ex+ressio) " !ase !ostat$6 state#et'$ state#et'2 ... 7rea8, !ase !ostat26 state#et($ state#et(2 ... 7rea8, ... default6 state#et9$ state#et92 ... & The swit!3 e)aluates ex+ressio and, if ex+ressio is e*ual to !ostat$, then the state!ents (eneath !ase !ostat $6 are e#ecuted until a 7rea8 is encountered. If ex+ressio is not e*ual to !ostat$, then it is co!"ared to !ostat2. If these are e*ual, then the state!ents (eneath !ase !ostat 26 are e#ecuted until a 7rea8 is encountered. If not, then the sa!e "rocess re"eats for each of the constants, in turn. If none of the constants !atch, then the state!ents (eneath default6 are e#ecuted. <ue to the "eculiar (eha)ior of swit!3:!ases, curly (races are not necessary for cases &here $ 2 - . 5 / 0 1 there is !ore than one state!ent /(ut they are necessary to enclose the entire swit!3:!ase0. swit!3:!ases generally ha)e if:else e*ui)alents (ut can often (e a cleaner &ay of e#"ressing the sa!e (eha)ior. ;ere is an e#a!"le using swit!3:!ase. $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 / it x = /, 0 1 swit!3(x) " !ase $6 2 $0 $$ !out << x is $4, 7rea8, !ase 26 $2 !ase -6 $- $. $5 !out << ;x is 2 or -;, 7rea8, default6 $/ $0 $1 & !out << ;x is ot $, 2, or -;, $2 20 & retur 0, This "rogra! &ill "rint x is ot $, 2, or -. If &e re"lace line 5 &ith it x = 2, then the "rogra! &ill "rint x is 2 or -. 2.2 Loops Conditionals e#ecute certain state!ents if certain conditions are !et= loo"s e#ecute certain state!ents while certain conditions are !et. C++ has three %inds of loo"s. while, do-while, and for. 2.2.1 while and do-while The while loo" has a for! si!ilar to the if conditional. w3ile(!oditio) " state#et$ state#et2 % & $s long as condition holds, the (loc% of state!ents &ill (e re"eatedly e#ecuted. If there is only one state!ent, the curly (races !ay (e o!itted. ;ere is an e#a!"le. )i!lude <iostrea#> usi* a#es+a!e std, it #ai() " it x = 0, w3ile(x < $0) x = x < $, 2 $0 $$ !out << x is << x << 4, $2 $- & retur 0, This "rogra! &ill "rint x is $0. The do-while loo" is a )ariation that guarantees the (loc% of state!ents &ill (e e#ecuted at least once: do " state#et$ state#et2 % & w3ile(!oditio), The (loc% of state!ents is e#ecuted and then, if the condition holds, the "rogra! returns to the to" of the (loc%. Curly (races are always re*uired. $lso note the se!icolon after the w3ile condition. 2.2.2 for The for loo" &or%s li%e the &hile loo" (ut &ith so!e change in synta#. for(iitiali=atio, !oditio, i!re#etatio) " state#et$ state#et2 % & The for loo" is designed to allo& a counter )aria(le that is initiali9ed at the (eginning of the loo" and incre!ented /or decre!ented0 on each iteration of the loo". Curly (races !ay (e o!itted if there is only one state!ent. ;ere is an e#a!"le. $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 / for(it x = 0, x < $0, x = x < $) 0 !out << x << 4, 1 2 retur 0, $0 & This "rogra! &ill "rint out the )alues 0 through 2, each on its o&n line. If the counter )aria(le is already defined, there is no need to define a ne& one in the initiali9ation "ortion of the for loo". Therefore, it is )alid to ha)e the follo&ing. $ 2 - . 5 / 0 1 2 $0 $$ $2 $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 / it x = 0, 0 for(, x < $0, x = x < $) 1 !out << x << 4, 2 $0 retur 0, $$ & ote that the first se!icolon inside the for loo"'s "arentheses is still re*uired. $ for loo" can (e e#"ressed as a &hile loo" and )ice8)ersa. >ecalling that a for loo" has the for! for(iitiali=atio, !oditio, i!re#etatio) " state#et$ state#et2 % & &e can &rite an e*ui)alent &hile loo" as iitiali=atio w3ile(!oditio) " state#et$ state#et2 % i!re#etatio & ?sing our e#a!"le a(o)e, $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 / for(it x = 0, x < $0, x = x < $) 0 !out << x << 4, 1 2 retur 0, $0 & is con)erted to )i!lude <iostrea#> usi* a#es+a!e std, it #ai() " it x = 0, w3ile(x < $0) " !out << x << 4, x = x < $, & retur 0, $- & The incre!entation ste" can technically (e any&here inside the state!ent (loc%, (ut it is good "ractice to "lace it as the last ste", "articularly if the "re)ious state!ents use the current )alue of the counter )aria(le. 2." Nested Control Structures It is "ossi(le to "lace ifs inside of ifs and loo"s inside of loo"s (y si!"ly "lacing these structures inside the state!ent (loc%s. This allo&s for !ore co!"licated "rogra! (eha)ior. ;ere is an e#a!"le using nesting if conditionals. $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 it x = /, / it y = 0, 0 1 if(x > y) " 2 !out << x is *reater t3a y4, $0 if(x == /) $$ !out << x is e5ual to /4, $2 else $- !out << x is ot e5ualt to /4, $. & else $5 !out << x is ot *reater t3a y4, $/ $0 retur 0, $1 & This "rogra! &ill "rint x is *reater t3a y on one line and then x is e5ual to / on the ne#t line. ;ere is an e#a!"le using nested loo"s. $ )i!lude <iostrea#> 2 usi* a#es+a!e std, - . it #ai() " 5 for(it x = 0, x < ., x = x < $) " / for(it y = 0, y < ., y = y < $) 0 !out << y, 1 !out << 4, 2 & $0 $$ retur 0, $2 & This "rogra! &ill "rint four lines of 0$2-. MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2011 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.