资源描述:
《C Traps and Pitfalls. Andrew Koenig. Addison-Wesley.pdf》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、CTrapsandPitfalls*AndrewKoenigAT&TBellLaboratoriesMurrayHill,NewJersey07974ABSTRACTTheClanguageislikeacarvingknife:simple,sharp,andextremelyusefulinskilledhands.Likeanysharptool,Ccaninjurepeoplewhodon'tknowhowtohandleit.ThispapershowssomeofthewaysCcaninjuretheunwary,andhowto
2、avoidinjury.0.IntroductionTheClanguageanditstypicalimplementationsaredesignedtobeusedeasilybyexperts.Thelan-guageisterseandexpressive.Therearefewrestrictionstokeeptheuserfromblundering.Auserwhohasblunderedisoftenrewardedbyaneffectthatisnotobviouslyrelatedtothecause.Inthispap
3、er,wewilllookatsomeoftheseunexpectedrewards.Becausetheyareunexpected,itmaywellbeimpossibletoclassifythemcompletely.Nevertheless,wehavemadearoughefforttodosobylookingatwhathastohappeninordertorunaCprogram.WeassumethereaderhasatleastapassingacquaintancewiththeClanguage.Section
4、1looksatproblemsthatoccurwhiletheprogramisbeingbrokenintotokens.Section2fol-lowstheprogramasthecompilergroupsitstokensintodeclarations,expressions,andstatements.Section3recognizesthataCprogramisoftenmadeoutofseveralpartsthatarecompiledseparatelyandboundtogether.Section4deals
5、withmisconceptionsofmeaning:thingsthathappenwhiletheprogramisactuallyrunning.Section5examinestherelationshipbetweenourprogramsandthelibraryroutinestheyuse.Insection6wenotethattheprogramwewriteisnotreallytheprogramwerun;thepreprocessorhasgottenatitfirst.Finally,section7discus
6、sesportabilityproblems:reasonsaprogrammightrunononeimplementa-tionandnotanother.1.LexicalPitfallsThefirstpartofacompilerisusuallycalledalexicalanalyzer.Thislooksatthesequenceofcharac-tersthatmakeuptheprogramandbreaksthemupintotokens.Atokenisasequenceofoneormorechar-acterstha
7、thavea(relatively)uniformmeaninginthelanguagebeingcompiled.InC,forinstance,thetoken->hasameaningthatisquitedistinctfromthatofeitherofthecharactersthatmakeitup,andthatisindependentofthecontextinwhichthe->appears.Foranotherexample,considerthestatement:if(x>big)big=x;Eachnon-bl
8、ankcharacterinthisstatementisaseparatetoken,exceptforthekeywordifandthetwoi