View
2
Download
0
Category
Preview:
Citation preview
CITS2002SystemsProgramming
1 next→ CITS2002 CITS2002schedule
ThestructureofCprogramsLet'slooksatthehigh-levelstructureofashortCprogram,rotate.c(usingellipsistoomitsomestatementsfornow).Atthisstageit'snotimportantwhattheprogramissupposedtodo.
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>
/* Compile this program with: cc -std=c99 -Wall -Werror -pedantic -o rotate rotate.c */
#define ROT 13
static char rotate(char c){ c = c + ROT; ..... return c;}
int main(int argcount, char *argvalue[]){ // check the number of arguments if(argcount != 2) { .... exit(EXIT_FAILURE); } else { .... exit(EXIT_SUCCESS); } return 0;}
Ofnoteinthisexample:
Characterssuchasaspace,tab,ornewline,mayappearalmostanywhere-theyarestrippedoutandignoredbytheCcompiler.
Weusesuchwhitespacecharacterstoprovidealayouttoourprograms.Whiletheexactlayoutisnotimportant,usingaconsistentlayoutisverygoodpractice.
Keywords,inbold,meanveryspecificthingstotheCcompiler.
Linescommencingwitha'#'inblueareprocessedbyaseparateprogram,namedtheCpreprocessor.
Inpractice,ourprogramisprovidedasinputtothepreprocessor,
preprocessor,andthepreprocessor'soutputisgiventotheCcompiler.
Linesingreenarecomments.TheyareignoredbytheCcompiler,andmaycontain(almost)anycharacters.
C99providestwotypesofcomments-
/*blockcomments*/and//commentstotheendofaline
CITS2002SystemsProgramming,Lecture2,p1,27thJuly2021.
CITS2002SystemsProgramming
←prev 2 next→ CITS2002 CITS2002schedule
ThestructureofCprograms,continued
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>
/* Compile this program with: cc -std=c99 -Wall -Werror -pedantic -o rotate rotate.c */
#define ROT 13
static char rotate(char c){ c = c + ROT; ..... return c;}
int main(int argcount, char *argvalue[]){ // check the number of arguments if(argcount != 2) { .... exit(EXIT_FAILURE); } else { .... exit(EXIT_SUCCESS); } return 0;}
Sameprogram,butmoretonote:
Avarietyofbracketsareemployed,inpairs,togrouptogetheritemstobeconsideredinthesameway.Here:
anglebracketsencloseafilenameina#includedirective,roundbracketsgroupitemsinarithmeticexpressionsandfunctioncalls,squarebracketsenclosetheindexwhenaccessarrays(vectorsandmatrices...)ofdata,andcurlybracketsgrouptogethersequencesofoneormorestatementsinC.Wetermagroupofstatementsablockof
ablockofstatements.
FunctionsinC,maybethoughtofasablockofstatementstowhichwegiveaname.Inourexample,wehavetwofunctions-rotate()andmain().
Whenourprogramsarerunbytheoperatingsystem,theoperatingsystemalwaysstartsourprogramfrommain().Thus,everycompleteCprogramrequiresamain()function.
Theoperatingsystempassessomespecialinformationtoourmain()function,command-linearguments,andmain()needsaspecialsyntaxtoreceivethese.
MostCprogramsyoureadwillnamemain()'sparametersasargcandargv.
Whenourprogramfinishesitsexecution,itreturnssomeinformationtotheoperatingsystem.Ourexamplehereexitsbyannouncingeitheritsfailureorsuccess.
CITS2002SystemsProgramming,Lecture2,p2,27thJuly2021.
CITS2002SystemsProgramming
←prev 3 next→ CITS2002 CITS2002schedule
CompilingandlinkingourCprogramsCprogramsarehuman-readabletextfiles,thatwetermsource-codefiles.
Thismakesthemveryeasytocopy,read,andeditondifferentcomputersanddifferentoperatingsystems.Cisoftendescribedasbeingportableatthesource-codelevel.
Beforewecanrun(execute)ourCprograms,wemusttranslate,orcompile,theirsource-codefilestofilesthattheoperatingsystemcanbettermanage.Aprogramknownasacompilertranslates(compiles)source-codefilesintoobject-codefiles.
Finally,wetranslateorlinkoneormoreobject-codefilestoproduceanexecutableprogram,oftentermeda'binary',an'executable',oran'exe'file.Aprogramknownasalinkerperformsthistranslation,alsolinkingourobject-codefile(s)withstandardlibrariesand(optionally)3rd-partylibraries.
Dependingonhowweinvokethecompiler,sometimeswecan'move'straightfromthesource-codefilestotheexecutableprogram,allinonestep.Inrealitythecompileris'silently'executingthelinkerprogramforus,andthenremovinganyunwantedobject-files.
CITS2002SystemsProgramming,Lecture2,p3,27thJuly2021.
CITS2002SystemsProgramming
←prev 4 next→ CITS2002 CITS2002schedule
VariablesVariablesarelocationsinacomputer'smemory.Atypicaldesktoporlaptopcomputerwillhave4-16GBofmemory,orfour-sixteenbillionaddressablememorylocations,
AtypicalCprogramwilluse4bytestoholdasingleintegervalue,or8bytestoholdasinglefloating-pointvalue.
Anyvariablecanonlyholdasinglevalueatanytime-theydonotmaintainahistoryofpastvaluestheyoncehad.
NamingourvariablesTomakeprogramsmorereadable,weprovidevariableswithsimplenames.Weshouldcarefullychoosenamestoreflecttheroleofthevariableinourprograms.
Whilevariablenamescanbealmostanything(butnotthesameasthekeywordsinC)there'sasimplerestrictiononthepermittedcharactersinaname-
theymustcommencewithanalphabeticortheunderscorecharacter(_A-Za-z),andbefollowedbyzeroormorealphabetic,underscoreordigitcharacters(_A-Za-z0-9).
Cvariablenamesarecasesensitive,thus:
MYLIMIT,mylimit,MylimitandMyLimit
arefourdifferentvariablenames.
Whilenotrequired,it'spreferredthatvariablenamesdonotconsistentirelyofuppercasecharacters.We'llconsistentlyuseuppercase-onlynamesforconstantsprovidedbytheCpreprocessor,oruser-definedtypenames:
MAXLENGTH, AVATAR, BUFSIZ, and ROT
OlderCcompilerslimitedvariablenamesto,say,8uniquecharacters.Thus,forthem,
turn_nuclear_reactor_coolant_onandturn_nuclear_reactor_coolant_off
arethesamevariable!Keepthisinmindifeverdevelopingportablecodeforoldenvironments.
CITS2002SystemsProgramming,Lecture2,p4,27thJuly2021.
CITS2002SystemsProgramming
←prev 5 next→ CITS2002 CITS2002schedule
BasicdatatypesVariablesaredeclaredtobeofacertaindatatype,orjusttype.
Weusedifferenttypestorepresentthepermissiblevaluesthataprogram'svariablehas.
Forexample,ifwe'reusingavariabletojustcountthings,we'lluseanintegervariabletoholdthecount;ifperformingtrigonometryonanglesexpressedinradians,we'llusefloating-pointvariablestoholdvalueswithbothanintegralandafractionalpart.
Cprovidesanumberofstandard,orbasetypestoholdcommonlyrequiredvalues,andlaterwe'llseehowwecanalsodefineourownuser-definedtypestomeetourneeds.
Let'slookquicklyatsomeofC'sbasedatatypes:
typename description,andanexampleofvariableinitialization
bool Boolean(truthvalues),whichmayonlyholdthevaluesofeithertrueorfalsee.g.boolfinished=false;
charcharactervalues,toeachholdasinglevaluessuchasanalphabeticcharacter,adigitcharacter,aspace,atab...e.g.charinitial='C';
int integervalues,negative,positive,andzeroe.g.intyear=2006;
floatfloatingpointvalues,withatypicalprecisionof10decimaldigits(onourlabmachines)e.g.floatinflation=4.1;
double"bigger"floatingpointvalues,withatypicalprecisionof17decimaldigits(onourlabmachines)e.g.doublepi=3.1415926535897932;
Sometextbookswill(tooquickly)focusontheactualstoragesizeofthesebasictypes,andemphasisetherangesofpermissiblevalues.Whenwritingtrulyportableprograms-thatcanexecuteconsistentlyacrossdifferenthardwarearchitecturesandoperatingsystems-it'simportanttobeawareof,andavoid,theirdifferences.We'llexaminethisissuelater,butfornowwe'llfocusonusingthesebasictypesintheirmostobviousways.
Fromwheredoesthebooldatatypegetitsname?-the19thcenturymathematicianandphilosopher,GeorgeBoole.
CITS2002SystemsProgramming,Lecture2,p5,27thJuly2021.
CITS2002SystemsProgramming
←prev 6 next→ CITS2002 CITS2002schedule
TheSignificanceofIntegersinCThroughoutthe1950s,60s,and70s,thereweremanymorecomputerhardwaremanufacturersthantherearetoday.Eachcompanyneededtopromoteitsownproductsbydistinguishingthemfromtheircompetitors.
Atalowlevel,differentmanufacturersemployeddifferentmemorysizesforabasiccharacter-somejust6bits,some8bits,9,and10.Theunfortunateoutcomewastheincompatabilityofcomputerprogramsanddatastorageformats.
TheCprogramminglanguage,developedintheearly1970s,addressedthisissuebynotdefiningtherequiredsizeofitsdatatypes.Thus,Cprogramsareportableattheleveloftheirsourcecode-portingaprogramtoadifferentcomputerarchitectureispossible,providedthattheprogramsarecompiledon(orfor)eacharchitecture.Theonlyrequirementwasthat:
sizeof(char)≤sizeof(short)≤sizeof(int)≤sizeof(long)
Sincethe1980s,fortunately,theindustryhasagreedon8-bitcharactersorbytes.But(compilingand)runningtheCprogramondifferentarchitectures:
#include <stdio.h>
int main(void){ printf("char %lu\n", sizeof(char)); printf("short %lu\n", sizeof(short)); printf("int %lu\n", sizeof(int)); printf("long %lu\n", sizeof(long)); return 0;}
mayproducedifferent(thoughstillcorrect)results:
char 1short 2int 4long 8
It'spermissiblefordifferentCcompilersondifferentarchitecturestoemploydifferentsizedintegers.
Whydoesthismatter?Differentsizedintegerscanstoredifferentmaximumvalues-theabovedatatypesaresigned(supportingpositiveandnegativevalues)soa4-byteintegercanonlyrepresentthevalues-2,147,483,648to2,147,483,647.
Ifemployingintegersfor'simple'counting,orloopingoveraknownrangeofvalues,there'srarelyaproblem.Butifusingintegerstocountmany(small)values,suchasmilli-ormicro-seconds,itmatters:
Funfact:GPSuses10bitstostoretheweek.Thatmeansitrunsout...ohheck?April6,2019AirlinesHaveToRebootTheirAirbusA350PlanesAfterEvery149HoursTokeepaBoeingDreamlinerflying,rebootonceevery248days
CITS2002SystemsProgramming,Lecture2,p6,27thJuly2021.
CITS2002SystemsProgramming
←prev 7 next→ CITS2002 CITS2002schedule
ThescopeofvariablesThescopeofavariabledescribestherangeoflinesinwhichthevariablemaybeused.Sometextbooksmayalsotermthisthevisibilityorlexicalrangeofavariable.
Chasonly2primarytypesofscope:
globalscope(sometimestermedfilescope)inwhichvariablesaredeclaredoutsideofallfunctionsandstatementblocks,and
blockscopeinwhichvariablesaredeclaredwithinafunctionorstatementblock.
01 #include <stdio.h>02 #include <stdlib.h>03 #include <string.h>04 #include <ctype.h>0506 static int count = 0;0708 int main(int argcount, char *argvalue[])09 {10 int nfound = 0;1112 // check the number of arguments13 if(argcount != 2) {14 int nerrors = 1;1516 ....17 exit(EXIT_FAILURE);18 }19 else {20 int ntimes = 100;2122 ....23 exit(EXIT_SUCCESS);24 }25 return 0;26 }
Thevariablecounthasglobalscope.
Itisdefinedonline06,andmaybeusedanywherefromline06untiltheendofthefile(line26).
Thevariablecountisalsoprecededbythekeywordstatic,whichpreventsitfrombeing'seen'(readorwritten)fromoutsideofthisfilerotate.c
Thevariablenfoundhasblockscope.
Itisdefinedonline10,andmaybeusedanywherefromline10untiltheendoftheblockinwhichitwasdefined(untilline26).
Thevariablenerrorshasblockscope.
Itisdefinedonline14,andmaybeusedanywherefromline14untilline18.
Thevariablentimeshasblockscope.
Itisdefinedonline20,andmaybeusedanywherefromline20untilline24.
Wecoulddefineadifferentvariablenamednerrorsintheblockoflines20-24-withoutproblems.
Wecoulddefineadifferentvariablenamednfoundintheblockoflines20-24-butthiswouldbeaverybadpractice!
CITS2002SystemsProgramming,Lecture2,p7,27thJuly2021.
CITS2002SystemsProgramming
←prev 8 next→ CITS2002 CITS2002schedule
FlowofcontrolinaCprogramAprogram'scontrolflowdescribeshowsequencesofstatementsareexecuted.FlowcontrolinaCprogramisverysimilartomostotherimperativeandobject-orientedlanguages.
Cprogramscommencetheirexecutionattheirmain()function,executetheirstatements,andexit(returntheflowofcontrol)totheoperatingsystem.
It'sfairlyobviousthatstatementsneedtobeexecutedinawell-definedorder,asweexpectprogramstoalwaysbehavethesameway(unlesssomerandomdatadirectstheexecutionpath,asincomputergames,simulations,andheuristicalgorithms).
Defaultflowofcontrolexecuteseachstatementinorder,top-to-bottom.
Programsthatonlyexecutefromtop-to-bottomareprettyboring,andweneedtocontroltheirflowwithavarietyofconditionalstatements,loops,andfunction-calls.
CITS2002SystemsProgramming,Lecture2,p8,27thJuly2021.
CITS2002SystemsProgramming
←prev 9 next→ CITS2002 CITS2002schedule
ConditionalexecutionConditionalstatementsfirstevaluateaBooleanconditionandthen,basedonwhetherit'strueorfalse,executeotherstatements.
Themostcommonformis: Sometimes,theelseclauseisomitted: Often,theelseclauseprovidesfurtherifstatements:
if(condition) { // more statements; .....}else{ // more statements; .....}
if(condition) { // more statements; .....}
if(condition1) { // more statements; .....}else if(condition2){ // more statements; .....}else{ // more statements; .....}
Notethatintheexamples,above,eachblockofstatementstobeexecutedhasbeenwrittenwithincurly-brackets.
Thecurly-bracketsarenotrequired(wecouldjustwriteasinglestatementforeitheriforelseclause).However,addingcurly-bracketsisconsideredagoodpractice.Theyprovideasafeguardforwhenadditionalstatementsareaddedlater.
CITS2002SystemsProgramming,Lecture2,p9,27thJuly2021.
CITS2002SystemsProgramming
←prev 10 next→ CITS2002 CITS2002schedule
BooleanvaluesOfsignificance,andaverycommoncauseoferrorsinCprograms,isthatCstandards,priortoISO-C99,hadnoBooleandatatype.
Historically,anintegervalueofzeroevaluatedequivalenttoaBooleanvalueoffalse;anynon-zerointegervalueevaluatedastrue.
YoumayreadsomeolderCcode: whichmaybebadlyandaccidentlycodedas: so,employdefensiveprogramming:
int initialised = 0; // set to false....
if(! initialised) { // initialisation statements; ..... initialised = 1; // set to true}
int initialised = 0; // set to false....
if(initialised = 0) { // initialisation statements; ..... initialised = 1; // set to true}
int initialised = 0; // set to false....
if(0 = initialised) // invalid syntax!{ // initialisation statements; ..... initialised = 1; // set to true}
Inthesecondexample,theconditionaltestalwaysevaluatestofalse,asthesingleequalscharacterrequestsanassignment,notacomparison.
Itispossible(andoccassionallyreasonable)toperformanassignmentaspartofaBooleancondition-you'lloftensee:
while((nextch=getc(file))!=EOF){....
Wheneverrequiringthetrueandfalseconstants(introducedinC99),weneedtoprovidetheline:
#include <stdbool.h>
CITS2002SystemsProgramming,Lecture2,p10,27thJuly2021.
CITS2002SystemsProgramming
←prev 11 next→ CITS2002 CITS2002schedule
SwitchstatementsWhenthesame(integer)expressioniscomparedagainstanumberofdistinctvalues,it'spreferredtoevaluatetheexpressiononce,andcompareitwithpossiblevalues:
Cascadingif..else..if..statements: Theequivalentswitchstatement:
Less-commonfeaturesoftheswitchstatement:
if(expression == value1){ // more statements; .....}else if(expression == value2){ // more statements; .....}else{ // more statements; .....}
switch(expression){ case value1 : { // more statements; ..... break; } case value2 : { // more statements; ..... break; } default : { // more statements; ..... break; }}
switch(expression){ case value1 : case value2 : { // handle either value1 or value2 ..... break; } case value3 : { // more statements; ..... // no 'break' statement, drop through } default : { // more statements; ..... break; }}
Typicallythe'expression'issimplyanidentifier,butitmaybearbitrarilycomplex-suchasanarithmeticexpression,orafunctioncall.Thedatatypeofthe'expression'mustbeaninteger(whichincludescharacters,Booleans,andenumeratedtypes),butitcannotbearealorfloating-pointdatatype.Thebreakstatementattheendofeachcaseindicatesthatwehavefinishedwiththe'current'value,andcontrol-flowleavestheswitchstatement.Withoutabreakstatement,control-flowcontinues"downwards",flowingintothenextcasebranch(eventhoughtheexpressiondoesnothavethatcase'svalue!).switchstatementswith'dense'values(none,orfewintegermissing)providegoodopportunitiesforoptimisedcode.
CITS2002SystemsProgramming,Lecture2,p11,27thJuly2021.
CITS2002SystemsProgramming
←prev 12 next→ CITS2002 CITS2002schedule
FlowofcontrolinaCprogram-boundedloopsOneofthemostpowerfulfeaturesofcomputers,ingeneral,istoperformthousands,millions,ofrepetitivetasksquickly
(infact,oneofthemotivatingfirstusesofcomputersinthe1940swastocalculatetrigonometrictablesforthefiringofartilleryshells).
Cprovidesitsforcontrolstatementtoloopthroughasequenceofstatements,ablockofstatements,aknownnumberoftimes:
Themostcommonformappearsbelow,inwhichweintroducealoopcontrolvariable,i,tocounthowmanytimeswegothroughtheloop:
Theloopcontrolvariabledoesnotalwayshavetobeaninteger:
// here, variable i holds the values 1,2,...10
for(int i = 1 ; i <= 10 ; i = i+1){// the above introduced a loop-control variable, i ..... printf("loop number %i\n", i); .....// variable i is available down to here}
// but variable i is not available from here
// here, variable ch holds each lowercase value
for(char ch = 'a' ; ch <= 'z' ; ch = ch+1){ ..... printf("loop using character '%c'\n", ch); .....}
Noticethatinbothcases,above,wehaveintroducednewvariables,hereiandch,tospecificallycontroltheloop.
Thevariablesmaybeusedinsideeachloop,inthestatementblock,butthen"disappear"oncetheblockisfinished(afteritsbottomcurlybracket).
It'salsopossibletouseanyothervariableastheloopcontrolvariable,evenifdefinedoutsideoftheforloop.Ingeneral,we'lltrytoavoidthispractice-unlessthevalueofthevariableisrequiredoutsideoftheloop.
CITS2002SystemsProgramming,Lecture2,p12,27thJuly2021.
CITS2002SystemsProgramming
←prev 13 next→ CITS2002 CITS2002schedule
FlowofcontrolinaCprogram-unboundedloopsTheforloopsthatwe'vejustseenshouldbeusedwhenweknow,aheadoftime,howmanytimesweneedtoloop(i.e.10times,orovertherange'a'..'z').
Suchloopsaretermedboundedloopsand,unlesswe'vemadeanunseencodingerror,alwaysterminateafterafixednumberofiterations.
Therearealsomanyoccasionswhenwedon'tknow,aheadoftime,howmanyiterationsmayberequired.Suchoccasionsrequireunboundedloops.
Cprovidestwotypesofunboundedloop:Themostcommonisthewhileloop,wherezeroormoreiterationsaremadethroughtheloop:
Lesscommonisthedo....whileloop,whereatleastoneiterationismadethroughtheloop:
#define NLOOPS 20
int i = 1;int n = 0; .....
while(i <= NLOOPS){ printf("iteration number %i\n", i); ..... ..... i = some_calculation_setting_i; n = n + 1;}
printf("loop was traversed %i times\n", n);
#define NLOOPS 20
int i = 1;int n = 0; .....
do{ printf("iteration number %i\n", i); ..... ..... i = some_calculation_setting_i; n = n + 1;} while(i <= NLOOPS);
printf("loop was traversed %i times\n", n);
Noticethatinbothcaseswestilluseavariable,i,tocontrolthenumberofiterationsofeachloop,andthatthechangingvalueofthevariableisusedtodetermineiftheloopshould"keepgoing".
However,thestatementsusedtomodifythecontrolvariablemayappearalmostanywhereintheloops.Theyprovideflexibility,butcanalsobeconfusingwhenloopsbecomeseveralstensorhundredsoflineslong.
Noticealsothatwhile,anddo....whileloopscannotintroducenewvariablestocontroltheiriterations,andsowehavetouseexistingvariablesfromanouterlexicalscope.
CITS2002SystemsProgramming,Lecture2,p13,27thJuly2021.
CITS2002SystemsProgramming
←prev 14 next→ CITS2002 CITS2002schedule
WritingloopswithinloopsThere'sanumberofoccassionswhenwewishtoloopanumberoftimes(andsoweuseaforloop)andwithinthatloopwewishtoperformanotherloop.Whilealittleconfusing,thisconstructisoftenquitecommon.Itistermedanestedloop.
#define NROWS 6#define NCOLS 4
for(int row = 1 ; row <= NROWS ; row = row+1) // the 'outer' loop{ for(int col = 1 ; col <= NCOLS ; col = col+1) // the 'inner' loop { printf("(%i,%i) ", row, col); // print row and col as if "coordinates" } printf("\n"); // finish printing on this line}
Theresultingoutputwillbe:
(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (3,4) (4,1) (4,2) (4,3) (4,4) (5,1) (5,2) (5,3) (5,4) (6,1) (6,2) (6,3) (6,4)
Noticethatwehavetwodistinctloop-controlvariables,rowandcol.
Eachtimethattheinnerloop(col'sloop)starts,col'svalueisinitializedto1,andadvancesto4(NCOLS).
Asprogramsbecomemorecomplex,wewillseetheneedfor,andwrite,allcombinationsof:
forloopswithinforloops,whileloopswithinwhileloops,forloopswithinwhileloops,andsoon....
CITS2002SystemsProgramming,Lecture2,p14,27thJuly2021.
CITS2002SystemsProgramming
←prev 15 next→ CITS2002 CITS2002schedule
ChangingtheregularflowofcontrolwithinloopsTherearemanyoccasionswhenthedefaultflowofcontrolinloopsneedstobemodified.
Sometimesweneedtoleavealoopearly,usingthebreakstatement,possiblyskippingsomeiterationsandsomestatements:
Sometimesweneedtostartthenextiterationofaloop,evenbeforeexecutingallstatementsintheloop:
for(int i = 1 ; i <= 10 ; i = i+1){ // Read an input character from the keyboard ..... if(input_char == 'Q') // Should we quit? break; ..... .....}// Come here after the 'break'. i is unavailable
for(char ch = 'a' ; ch <= 'z' ; ch = ch+1){ if(ch == 'm') // skip over the character 'm' continue; ..... ..... statements that will never see ch == 'm' ..... .....}
Inthefirstexample,weiteratethroughtheloopatmost10times,eachtimereadingalineofinputfromthekeyboard.Iftheuserindicatestheywishtoquit,webreakoutoftheboundedloop.
Inthesecondexample,wewishtoperformsomeworkforalllowercasecharacters,except'm'.Weusecontinuetoignorethefollowingstatements,andtostartthenextloop(withch=='n').
CITS2002SystemsProgramming,Lecture2,p15,27thJuly2021.
CITS2002SystemsProgramming
←prev 16 next→ CITS2002 CITS2002schedule
TheequivalenceofboundedandunboundedloopsWeshouldnowbeabletoseethatthefor,while,anddo...whilecontrolflowstatementsareeachcloselyrelated.
Tofullyunderstandthis,however,weneedtoaccept(fornow),thatthethree"pieces"oftheforconstruct,arenotalwaysinitialization,condition,modification.
Moregenerally,thethreepiecesmaybeCexpressions-forthemomentwe'llconsidertheseasCstatementswhich,iftheyproduceavalue,thevalueisoftenignored.
Thefollowingloopsareactuallyequivalent:
for( expression1 ; expression2 ; expression3 ){ statement1; ....}
expression1; while(expression2){ statement1; .... expression3;}
Inbothcases,we'reexpectingexpression2toproduceaBooleanvalue,eithertrueorfalse,asweneedthattruthvaluetodetermineifourloopsshould"keepgoing".
Youshouldthinkaboutthesecarefully,perhapsperformsomeexperiments,todeterminewherecontrolflowreallygoeswhenweintroducebreakandcontinuestatements.
CITS2002SystemsProgramming,Lecture2,p16,27thJuly2021.
CITS2002SystemsProgramming
←prev 17 CITS2002 CITS2002schedule
SomeunusualloopsyouwillencounterAsyoureadmoreCprogramswrittenbyothers,you'llseesomestatementsthatlooklikefororwhileloops,butappeartohavesomethingmissing.Infact,any(orall!)ofthe3"parts"ofaforloopmaybeomitted.
Forexample,thefollowingloopinitiallysetsito1,andincrementsiteachiteration,butitdoesn'thavea"middle"conditionaltesttoseeiftheloophasfinished.Themissingconditionconstantlyevaluatestotrue:
for(int i = 1 ; /* condition is missing */ ; i = i+1){ ..... .....}
Someloopsdon'tevenhavealoop-controlvariable,anddon'ttestfortheirtermination.Thisloopwillrunforever,untilweinterruptorterminatetheoperatingsystemprocessrunningtheCprogram.Wetermtheseinfiniteloops:
// cryptic - avoid this mechanismfor( ; ; ){ ..... .....}
#include <stdbool.h>
// clearer - use this mechanismwhile( true ){ ..... .....}
Whileweoftenseeandwritesuchloops,wedon'tusuallywantthemtorunforever!
Wewilltypicallyuseanenclosedconditionandabreakstatementtoterminatetheloop,eitherbasedonsomeuserinput,orthestateofsomecalculation.
CITS2002SystemsProgramming,Lecture2,p17,27thJuly2021.
Recommended