Professional Documents
Culture Documents
C++ Notes - Braces
C++ Notes - Braces
History
ThefirstpopularuseofbracestoindicatescopewastheAlgolprogramminglanguagefromabout1960.
Manynewerlanguageshavechosenbetteralternativestothisparticularlyawkwardanderrorprone
notation.Forexample,VisualBasicuseskeywordstoindicatetheendofstatementscopeandPythonuses
indentation,buttheC/C++/Java/C#familycontinuestousebraces.
Onestatementbody
Forif,while,andforstatementstheruleisthatthebodyconsistsofonestatement.Ifyouwantmorethan
onestatementinthebody,youcanenclosethestatementsincurlybraces.Rememberthatexcesswhite
space,blanks,tabs,andnewlines,don'tchangetheinterpretationofaprogram'ssyntax.Forexample,
if(x==1)n++;
isthesameas
if(x==1)
x++;
isthesameas
if(x==1){
x++;
}
asaremanyothervariations.Thebracesarenecessarywhenthereismorethanonestatementinthe
body.
if(x==1){
n++;
p++;
}
Thiswillincrementbothnandpifxisone.Incontrast,
if(x==1)
n++;
p++;
willincrementonlynifxisone,thenalwaysincrementp,despitethemisleadingindentation.
Whatis"one"statement?
Inadditiontotheobvioussinglestatements,eganassignmentstatement,anif,while,orotherstatement
thatmaycontainabodyisonestatement.
while(cin>>x)
if(x==1)
n++;
else
n;
Theifstatementcountsasonlyonestatement,eventhoitcontainsotherstatements.
Rule:Alwaysindent
Regardlessoftheuseofbraces,alwaysindentstatementsthatareinthebodyofanotherstatement.
Commonrule:Alwaysusebraces
Althothelanguagedoesn'trequireit,someprogrammingstylestandardsrequiretheuseofthebraces,
evenifthereisonlyonestatementinthebodyofanotherstatement.Why?(1)Becauseitimprovesthe
uniformityandthereforereadability,and(2)becauseinsertinganadditionalstatementinthebodywhere
thereisonlyonestatementislesserrorpronebecauseit'seasytoforgettoaddbraceswhenthe
indentationgivessuchastrong(butpossiblymisleading)guidetothestructure.
Copyleft2003FredSwartzLastupdate20170415,URL=undefined
https://www.uow.edu.au/~lukes/TEXTBOOK/notescpp/basics/braces.html 1/1