c.texi 419 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008
  1. \input texinfo
  2. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  3. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Intro and Reference Manual}
  34. @sp 4
  35. @c @center @value{EDITION} Edition
  36. @sp 5
  37. @center Richard Stallman
  38. @center and
  39. @center Trevis Rothwell
  40. @center plus Nelson Beebe
  41. @center on floating point
  42. @page
  43. @vskip 0pt plus 1filll
  44. @insertcopying
  45. @sp 2
  46. @ignore
  47. WILL BE Published by the Free Software Foundation @*
  48. 51 Franklin Street, Fifth Floor @*
  49. Boston, MA 02110-1301 USA @*
  50. ISBN ?-??????-??-?
  51. @ignore
  52. @ignore
  53. @sp 1
  54. Cover art by J. Random Artist
  55. @end ignore
  56. @end titlepage
  57. @summarycontents
  58. @contents
  59. @node Top
  60. @ifnottex
  61. @top GNU C Manual
  62. @end ifnottex
  63. @iftex
  64. @top Preface
  65. @end iftex
  66. This manual explains the C language for use with the GNU Compiler
  67. Collection (GCC) on the GNU/Linux system and other systems. We refer
  68. to this dialect as GNU C. If you already know C, you can use this as
  69. a reference manual.
  70. If you understand basic concepts of programming but know nothing about
  71. C, you can read this manual sequentially from the beginning to learn
  72. the C language.
  73. If you are a beginner to programming, we recommend you first learn a
  74. language with automatic garbage collection and no explicit pointers,
  75. rather than starting with C@. Good choices include Lisp, Scheme,
  76. Python and Java. C's explicit pointers mean that programmers must be
  77. careful to avoid certain kinds of errors.
  78. C is a venerable language; it was first used in 1973. The GNU C
  79. Compiler, which was subsequently extended into the GNU Compiler
  80. Collection, was first released in 1987. Other important languages
  81. were designed based on C: once you know C, it gives you a useful base
  82. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  83. The special advantage of C is that it is fairly simple while allowing
  84. close access to the computer's hardware, which previously required
  85. writing in assembler language to describe the individual machine
  86. instructions. Some have called C a ``high-level assembler language''
  87. because of its explicit pointers and lack of automatic management of
  88. storage. As one wag put it, ``C combines the power of assembler
  89. language with the convenience of assembler language.'' However, C is
  90. far more portable, and much easier to read and write, than assembler
  91. language.
  92. This manual focuses on the GNU C language supported by the GNU
  93. Compiler Collection, version ???. When a construct may be absent or
  94. work differently in other C compilers, we say so. When it is not part
  95. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  96. useful to know that; however, other dialects and standards are not the
  97. focus of this manual. We keep those notes short, unless it is vital
  98. to say more. For the same reason, we hardly mention C@t{++} or other
  99. languages that the GNU Compiler Collection supports.
  100. Some aspects of the meaning of C programs depend on the target
  101. platform: which computer, and which operating system, the compiled
  102. code will run on. Where this is the case, we say so.
  103. The C language provides no built-in facilities for performing such
  104. common operations as input/output, memory management, string
  105. manipulation, and the like. Instead, these facilities are defined in
  106. a standard library, which is automatically available in every C
  107. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  108. Reference Manual}.
  109. This manual incorporates the former GNU C Preprocessor Manual, which
  110. was among the earliest GNU Manuals. It also uses some text from the
  111. earlier GNU C Manual that was written by Trevis Rothwell and James
  112. Youngman.
  113. GNU C has many obscure features, each one either for historical
  114. compatibility or meant for very special situations. We have left them
  115. to a companion manual, the GNU C Obscurities Manual, which will be
  116. published digitally later.
  117. @menu
  118. * The First Example:: Getting started with basic C code.
  119. * Complete Program:: A whole example program
  120. that can be compiled and run.
  121. * Storage:: Basic layout of storage; bytes.
  122. * Beyond Integers:: Exploring different numeric types.
  123. * Lexical Syntax:: The various lexical components of C programs.
  124. * Arithmetic:: Numeric computations.
  125. * Assignment Expressions:: Storing values in variables.
  126. * Execution Control Expressions:: Expressions combining values in various ways.
  127. * Binary Operator Grammar:: An overview of operator precedence.
  128. * Order of Execution:: The order of program execution.
  129. * Primitive Types:: More details about primitive data types.
  130. * Constants:: Explicit constant values:
  131. details and examples.
  132. * Type Size:: The memory space occupied by a type.
  133. * Pointers:: Creating and manipulating memory pointers.
  134. * Structures:: Compound data types built
  135. by grouping other types.
  136. * Arrays:: Creating and manipulating arrays.
  137. * Enumeration Types:: Sets of integers with named values.
  138. * Defining Typedef Names:: Using @code{typedef} to define type names.
  139. * Statements:: Controling program flow.
  140. * Variables:: Details about declaring, initializing,
  141. and using variables.
  142. * Type Qualifiers:: Mark variables for certain intended uses.
  143. * Functions:: Declaring, defining, and calling functions.
  144. * Compatible Types:: How to tell if two types are compatible
  145. with each other.
  146. * Type Conversions:: Converting between types.
  147. * Scope:: Different categories of identifier scope.
  148. * Preprocessing:: Using the GNU C preprocessor.
  149. * Integers in Depth:: How integer numbers are represented.
  150. * Floating Point in Depth:: How floating-point numbers are represented.
  151. * Compilation:: How to compile multi-file programs.
  152. * Directing Compilation:: Operations that affect compilation
  153. but don't change the program.
  154. Appendices
  155. * Type Alignment:: Where in memory a type can validly start.
  156. * Aliasing:: Accessing the same data in two types.
  157. * Digraphs:: Two-character aliases for some characters.
  158. * Attributes:: Specifying additional information
  159. in a declaration.
  160. * Signals:: Fatal errors triggered in various scenarios.
  161. * GNU Free Documentation License:: The license for this manual.
  162. * Symbol Index:: Keyword and symbol index.
  163. * Concept Index:: Detailed topical index.
  164. @detailmenu
  165. --- The Detailed Node Listing ---
  166. * Recursive Fibonacci:: Writing a simple function recursively.
  167. * Stack:: Each function call uses space in the stack.
  168. * Iterative Fibonacci:: Writing the same function iteratively.
  169. * Complete Example:: Turn the simple function into a full program.
  170. * Complete Explanation:: Explanation of each part of the example.
  171. * Complete Line-by-Line:: Explaining each line of the example.
  172. * Compile Example:: Using GCC to compile the example.
  173. * Float Example:: A function that uses floating-point numbers.
  174. * Array Example:: A function that works with arrays.
  175. * Array Example Call:: How to call that function.
  176. * Array Example Variations:: Different ways to write the call example.
  177. Lexical Syntax
  178. * English:: Write programs in English!
  179. * Characters:: The characters allowed in C programs.
  180. * Whitespace:: The particulars of whitespace characters.
  181. * Comments:: How to include comments in C code.
  182. * Identifiers:: How to form identifiers (names).
  183. * Operators/Punctuation:: Characters used as operators or punctuation.
  184. * Line Continuation:: Splitting one line into multiple lines.
  185. * Digraphs:: Two-character substitutes for some characters.
  186. Arithmetic
  187. * Basic Arithmetic:: Addition, subtraction, multiplication,
  188. and division.
  189. * Integer Arithmetic:: How C performs arithmetic with integer values.
  190. * Integer Overflow:: When an integer value exceeds the range
  191. of its type.
  192. * Mixed Mode:: Calculating with both integer values
  193. and floating-point values.
  194. * Division and Remainder:: How integer division works.
  195. * Numeric Comparisons:: Comparing numeric values for
  196. equality or order.
  197. * Shift Operations:: Shift integer bits left or right.
  198. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  199. Assignment Expressions
  200. * Simple Assignment:: The basics of storing a value.
  201. * Lvalues:: Expressions into which a value can be stored.
  202. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  203. * Increment/Decrement:: Shorthand for incrementing and decrementing
  204. an lvalue's contents.
  205. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  206. * Assignment in Subexpressions:: How to avoid ambiguity.
  207. * Write Assignments Separately:: Write assignments as separate statements.
  208. Execution Control Expressions
  209. * Logical Operators:: Logical conjunction, disjunction, negation.
  210. * Logicals and Comparison:: Logical operators with comparison operators.
  211. * Logicals and Assignments:: Assignments with logical operators.
  212. * Conditional Expression:: An if/else construct inside expressions.
  213. * Comma Operator:: Build a sequence of subexpressions.
  214. Order of Execution
  215. * Reordering of Operands:: Operations in C are not necessarily computed
  216. in the order they are written.
  217. * Associativity and Ordering:: Some associative operations are performed
  218. in a particular order; others are not.
  219. * Sequence Points:: Some guarantees about the order of operations.
  220. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  221. * Ordering of Operands:: Evaluation order of operands
  222. and function arguments.
  223. * Optimization and Ordering:: Compiler optimizations can reorder operations
  224. only if it has no impact on program results.
  225. Primitive Data Types
  226. * Integer Types:: Description of integer types.
  227. * Floating-Point Data Types:: Description of floating-point types.
  228. * Complex Data Types:: Description of complex number types.
  229. * The Void Type:: A type indicating no value at all.
  230. * Other Data Types:: A brief summary of other types.
  231. Constants
  232. * Integer Constants:: Literal integer values.
  233. * Integer Const Type:: Types of literal integer values.
  234. * Floating Constants:: Literal floating-point values.
  235. * Imaginary Constants:: Literal imaginary number values.
  236. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  237. * Character Constants:: Literal character values.
  238. * Unicode Character Codes:: Unicode characters represented
  239. in either UTF-16 or UTF-32.
  240. * Wide Character Constants:: Literal characters values larger than 8 bits.
  241. * String Constants:: Literal string values.
  242. * UTF-8 String Constants:: Literal UTF-8 string values.
  243. * Wide String Constants:: Literal string values made up of
  244. 16- or 32-bit characters.
  245. Pointers
  246. * Address of Data:: Using the ``address-of'' operator.
  247. * Pointer Types:: For each type, there is a pointer type.
  248. * Pointer Declarations:: Declaring variables with pointer types.
  249. * Pointer Type Designators:: Designators for pointer types.
  250. * Pointer Dereference:: Accessing what a pointer points at.
  251. * Null Pointers:: Pointers which do not point to any object.
  252. * Invalid Dereference:: Dereferencing null or invalid pointers.
  253. * Void Pointers:: Totally generic pointers, can cast to any.
  254. * Pointer Comparison:: Comparing memory address values.
  255. * Pointer Arithmetic:: Computing memory address values.
  256. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  257. * Pointer Arithmetic Low Level:: More about computing memory address values.
  258. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  259. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  260. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  261. * Printing Pointers:: Using @code{printf} for a pointer's value.
  262. Structures
  263. * Referencing Fields:: Accessing field values in a structure object.
  264. * Dynamic Memory Allocation:: Allocating space for objects
  265. while the program is running.
  266. * Field Offset:: Memory layout of fields within a structure.
  267. * Structure Layout:: Planning the memory layout of fields.
  268. * Packed Structures:: Packing structure fields as close as possible.
  269. * Bit Fields:: Dividing integer fields
  270. into fields with fewer bits.
  271. * Bit Field Packing:: How bit fields pack together in integers.
  272. * const Fields:: Making structure fields immutable.
  273. * Zero Length:: Zero-length array as a variable-length object.
  274. * Flexible Array Fields:: Another approach to variable-length objects.
  275. * Overlaying Structures:: Casting one structure type
  276. over an object of another structure type.
  277. * Structure Assignment:: Assigning values to structure objects.
  278. * Unions:: Viewing the same object in different types.
  279. * Packing With Unions:: Using a union type to pack various types into
  280. the same memory space.
  281. * Cast to Union:: Casting a value one of the union's alternative
  282. types to the type of the union itself.
  283. * Structure Constructors:: Building new structure objects.
  284. * Unnamed Types as Fields:: Fields' types do not always need names.
  285. * Incomplete Types:: Types which have not been fully defined.
  286. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  287. * Type Tags:: Scope of structure and union type tags.
  288. Arrays
  289. * Accessing Array Elements:: How to access individual elements of an array.
  290. * Declaring an Array:: How to name and reserve space for a new array.
  291. * Strings:: A string in C is a special case of array.
  292. * Incomplete Array Types:: Naming, but not allocating, a new array.
  293. * Limitations of C Arrays:: Arrays are not first-class objects.
  294. * Multidimensional Arrays:: Arrays of arrays.
  295. * Constructing Array Values:: Assigning values to an entire array at once.
  296. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  297. Statements
  298. * Expression Statement:: Evaluate an expression, as a statement,
  299. usually done for a side effect.
  300. * if Statement:: Basic conditional execution.
  301. * if-else Statement:: Multiple branches for conditional execution.
  302. * Blocks:: Grouping multiple statements together.
  303. * return Statement:: Return a value from a function.
  304. * Loop Statements:: Repeatedly executing a statement or block.
  305. * switch Statement:: Multi-way conditional choices.
  306. * switch Example:: A plausible example of using @code{switch}.
  307. * Duffs Device:: A special way to use @code{switch}.
  308. * Case Ranges:: Ranges of values for @code{switch} cases.
  309. * Null Statement:: A statement that does nothing.
  310. * goto Statement:: Jump to another point in the source code,
  311. identified by a label.
  312. * Local Labels:: Labels with limited scope.
  313. * Labels as Values:: Getting the address of a label.
  314. * Statement Exprs:: A series of statements used as an expression.
  315. Variables
  316. * Variable Declarations:: Name a variable and and reserve space for it.
  317. * Initializers:: Assigning inital values to variables.
  318. * Designated Inits:: Assigning initial values to array elements
  319. at particular array indices.
  320. * Auto Type:: Obtaining the type of a variable.
  321. * Local Variables:: Variables declared in function definitions.
  322. * File-Scope Variables:: Variables declared outside of
  323. function definitions.
  324. * Static Local Variables:: Variables declared within functions,
  325. but with permanent storage allocation.
  326. * Extern Declarations:: Declaring a variable
  327. which is allocated somewhere else.
  328. * Allocating File-Scope:: When is space allocated
  329. for file-scope variables?
  330. * auto and register:: Historically used storage directions.
  331. * Omitting Types:: The bad practice of declaring variables
  332. with implicit type.
  333. Type Qualifiers
  334. * const:: Variables whose values don't change.
  335. * volatile:: Variables whose values may be accessed
  336. or changed outside of the control of
  337. this program.
  338. * restrict Pointers:: Restricted pointers for code optimization.
  339. * restrict Pointer Example:: Example of how that works.
  340. Functions
  341. * Function Definitions:: Writing the body of a function.
  342. * Function Declarations:: Declaring the interface of a function.
  343. * Function Calls:: Using functions.
  344. * Function Call Semantics:: Call-by-value argument passing.
  345. * Function Pointers:: Using references to functions.
  346. * The main Function:: Where execution of a GNU C program begins.
  347. Type Conversions
  348. * Explicit Type Conversion:: Casting a value from one type to another.
  349. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  350. * Argument Promotions:: Automatic conversion of function parameters.
  351. * Operand Promotions:: Automatic conversion of arithmetic operands.
  352. * Common Type:: When operand types differ, which one is used?
  353. Scope
  354. * Scope:: Different categories of identifier scope.
  355. Preprocessing
  356. * Preproc Overview:: Introduction to the C preprocessor.
  357. * Directives:: The form of preprocessor directives.
  358. * Preprocessing Tokens:: The lexical elements of preprocessing.
  359. * Header Files:: Including one source file in another.
  360. * Macros:: Macro expansion by the preprocessor.
  361. * Conditionals:: Controling whether to compile some lines
  362. or ignore them.
  363. * Diagnostics:: Reporting warnings and errors.
  364. * Line Control:: Reporting source line numbers.
  365. * Null Directive:: A preprocessing no-op.
  366. Integers in Depth
  367. * Integer Representations:: How integer values appear in memory.
  368. * Maximum and Minimum Values:: Value ranges of integer types.
  369. Floating Point in Depth
  370. * Floating Representations:: How floating-point values appear in memory.
  371. * Floating Type Specs:: Precise details of memory representations.
  372. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  373. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  374. * Exception Flags:: Handling certain conditions in floating point.
  375. * Exact Floating-Point:: Not all floating calculations lose precision.
  376. * Rounding:: When a floating result can't be represented
  377. exactly in the floating-point type in use.
  378. * Rounding Issues:: Avoid magnifying rounding errors.
  379. * Significance Loss:: Subtracting numbers that are almost equal.
  380. * Fused Multiply-Add:: Taking advantage of a special floating-point
  381. instruction for faster execution.
  382. * Error Recovery:: Determining rounding errors.
  383. * Exact Floating Constants:: Precisely specified floating-point numbers.
  384. * Handling Infinity:: When floating calculation is out of range.
  385. * Handling NaN:: What floating calculation is undefined.
  386. * Signed Zeros:: Positive zero vs. negative zero.
  387. * Scaling by the Base:: A useful exact floating-point operation.
  388. * Rounding Control:: Specifying some rounding behaviors.
  389. * Machine Epsilon:: The smallest number you can add to 1.0
  390. and get a sum which is larger than 1.0.
  391. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  392. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  393. * Further Reading:: References for floating-point numbers.
  394. Directing Compilation
  395. * Pragmas:: Controling compilation of some constructs.
  396. * Static Assertions:: Compile-time tests for conditions.
  397. @end detailmenu
  398. @end menu
  399. @node The First Example
  400. @chapter The First Example
  401. This chapter presents the source code for a very simple C program and
  402. uses it to explain a few features of the language. If you already
  403. know the basic points of C presented in this chapter, you can skim it
  404. or skip it.
  405. @menu
  406. * Recursive Fibonacci:: Writing a simple function recursively.
  407. * Stack:: Each function call uses space in the stack.
  408. * Iterative Fibonacci:: Writing the same function iteratively.
  409. @end menu
  410. @node Recursive Fibonacci
  411. @section Example: Recursive Fibonacci
  412. @cindex recursive Fibonacci function
  413. @cindex Fibonacci function, recursive
  414. To introduce the most basic features of C, let's look at code for a
  415. simple mathematical function that does calculations on integers. This
  416. function calculates the @var{n}th number in the Fibonacci series, in
  417. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  418. 13, 21, 34, 55, @dots{}.
  419. @example
  420. int
  421. fib (int n)
  422. @{
  423. if (n <= 2) /* @r{This avoids infinite recursion.} */
  424. return 1;
  425. else
  426. return fib (n - 1) + fib (n - 2);
  427. @}
  428. @end example
  429. This very simple program illustrates several features of C:
  430. @itemize @bullet
  431. @item
  432. A function definition, whose first two lines constitute the function
  433. header. @xref{Function Definitions}.
  434. @item
  435. A function parameter @code{n}, referred to as the variable @code{n}
  436. inside the function body. @xref{Function Parameter Variables}.
  437. A function definition uses parameters to refer to the argument
  438. values provided in a call to that function.
  439. @item
  440. Arithmetic. C programs add with @samp{+} and subtract with
  441. @samp{-}. @xref{Arithmetic}.
  442. @item
  443. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  444. equal.'' @xref{Numeric Comparisons}.
  445. @item
  446. Integer constants written in base 10.
  447. @xref{Integer Constants}.
  448. @item
  449. A function call. The function call @code{fib (n - 1)} calls the
  450. function @code{fib}, passing as its argument the value @code{n - 1}.
  451. @xref{Function Calls}.
  452. @item
  453. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  454. comment has no effect on the execution of the program. Its purpose is
  455. to provide explanations to people reading the source code. Including
  456. comments in the code is tremendously important---they provide
  457. background information so others can understand the code more quickly.
  458. @xref{Comments}.
  459. @item
  460. Two kinds of statements, the @code{return} statement and the
  461. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  462. @item
  463. Recursion. The function @code{fib} calls itself; that is called a
  464. @dfn{recursive call}. These are valid in C, and quite common.
  465. The @code{fib} function would not be useful if it didn't return.
  466. Thus, recursive definitions, to be of any use, must avoid infinite
  467. recursion.
  468. This function definition prevents infinite recursion by specially
  469. handling the case where @code{n} is two or less. Thus the maximum
  470. depth of recursive calls is less than @code{n}.
  471. @end itemize
  472. @menu
  473. * Function Header:: The function's name and how it is called.
  474. * Function Body:: Declarations and statements that implement the function.
  475. @end menu
  476. @node Function Header
  477. @subsection Function Header
  478. @cindex function header
  479. In our example, the first two lines of the function definition are the
  480. @dfn{header}. Its purpose is to state the function's name and say how
  481. it is called:
  482. @example
  483. int
  484. fib (int n)
  485. @end example
  486. @noindent
  487. says that the function returns an integer (type @code{int}), its name is
  488. @code{fib}, and it takes one argument named @code{n} which is also an
  489. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  490. @node Function Body
  491. @subsection Function Body
  492. @cindex function body
  493. @cindex recursion
  494. The rest of the function definition is called the @dfn{function body}.
  495. Like every function body, this one starts with @samp{@{}, ends with
  496. @samp{@}}, and contains zero or more @dfn{statements} and
  497. @dfn{declarations}. Statements specify actions to take, whereas
  498. declarations define names of variables, functions, and so on. Each
  499. statement and each declaration ends with a semicolon (@samp{;}).
  500. Statements and declarations often contain @dfn{expressions}; an
  501. expression is a construct whose execution produces a @dfn{value} of
  502. some data type, but may also take actions through ``side effects''
  503. that alter subsequent execution. A statement, by contrast, does not
  504. have a value; it affects further execution of the program only through
  505. the actions it takes.
  506. This function body contains no declarations, and just one statement,
  507. but that one is a complex statement in that it contains nested
  508. statements. This function uses two kinds of statements:
  509. @table @code
  510. @item return
  511. The @code{return} statement makes the function return immediately.
  512. It looks like this:
  513. @example
  514. return @var{value};
  515. @end example
  516. Its meaning is to compute the expression @var{value} and exit the
  517. function, making it return whatever value that expression produced.
  518. For instance,
  519. @example
  520. return 1;
  521. @end example
  522. @noindent
  523. returns the integer 1 from the function, and
  524. @example
  525. return fib (n - 1) + fib (n - 2);
  526. @end example
  527. @noindent
  528. returns a value computed by performing two function calls
  529. as specified and adding their results.
  530. @item @code{if}@dots{}@code{else}
  531. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  532. Each time it executes, it chooses one of its two substatements to execute
  533. and ignores the other. It looks like this:
  534. @example
  535. if (@var{condition})
  536. @var{if-true-statement}
  537. else
  538. @var{if-false-statement}
  539. @end example
  540. Its meaning is to compute the expression @var{condition} and, if it's
  541. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  542. @var{if-false-statement}. @xref{if-else Statement}.
  543. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  544. simply an expression. It's considered ``true'' if its value is
  545. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  546. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  547. Comparisons}.) Thus,
  548. @example
  549. if (n <= 2)
  550. return 1;
  551. else
  552. return fib (n - 1) + fib (n - 2);
  553. @end example
  554. @noindent
  555. first tests whether the value of @code{n} is less than or equal to 2.
  556. If so, the expression @code{n <= 2} has the value 1. So execution
  557. continues with the statement
  558. @example
  559. return 1;
  560. @end example
  561. @noindent
  562. Otherwise, execution continues with this statement:
  563. @example
  564. return fib (n - 1) + fib (n - 2);
  565. @end example
  566. Each of these statements ends the execution of the function and
  567. provides a value for it to return. @xref{return Statement}.
  568. @end table
  569. Calculating @code{fib} using ordinary integers in C works only for
  570. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  571. in type @code{int}. The addition operation that tries to add
  572. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  573. This occurrence is called @dfn{integer overflow}.
  574. Overflow can manifest itself in various ways, but one thing that can't
  575. possibly happen is to produce the correct value, since that can't fit
  576. in the space for the value. @xref{Integer Overflow}.
  577. @xref{Functions}, for a full explanation about functions.
  578. @node Stack
  579. @section The Stack, And Stack Overflow
  580. @cindex stack
  581. @cindex stack frame
  582. @cindex stack overflow
  583. @cindex recursion, drawbacks of
  584. @cindex stack frame
  585. Recursion has a drawback: there are limits to how many nested function
  586. calls a program can make. In C, each function call allocates a block
  587. of memory which it uses until the call returns. C allocates these
  588. blocks consecutively within a large area of memory known as the
  589. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  590. The size of the stack is limited; if the program tries to use too
  591. much, that causes the program to fail because the stack is full. This
  592. is called @dfn{stack overflow}.
  593. @cindex crash
  594. @cindex segmentation fault
  595. Stack overflow on GNU/Linux typically manifests itself as the
  596. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  597. fault.'' By default, this signal terminates the program immediately,
  598. rather than letting the program try to recover, or reach an expected
  599. ending point. (We commonly say in this case that the program
  600. ``crashes''). @xref{Signals}.
  601. It is inconvenient to observe a crash by passing too large
  602. an argument to recursive Fibonacci, because the program would run a
  603. long time before it crashes. This algorithm is simple but
  604. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  605. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  606. the final result.
  607. However, you can observe stack overflow very quickly if you use
  608. this function instead:
  609. @example
  610. int
  611. fill_stack (int n)
  612. @{
  613. if (n <= 1) /* @r{This limits the depth of recursion.} */
  614. return 1;
  615. else
  616. return fill_stack (n - 1);
  617. @}
  618. @end example
  619. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  620. and using the default configuration, an experiment showed there is
  621. enough stack space to do 261906 nested calls to that function. One
  622. more, and the stack overflows and the program crashes. On another
  623. platform, with a different configuration, or with a different
  624. function, the limit might be bigger or smaller.
  625. @node Iterative Fibonacci
  626. @section Example: Iterative Fibonacci
  627. @cindex iterative Fibonacci function
  628. @cindex Fibonacci function, iterative
  629. Here's a much faster algorithm for computing the same Fibonacci
  630. series. It is faster for two reasons. First, it uses @dfn{iteration}
  631. (that is, repetition or looping) rather than recursion, so it doesn't
  632. take time for a large number of function calls. But mainly, it is
  633. faster because the number of repetitions is small---only @code{@var{n}}.
  634. @c If you change this, change the duplicate in node Example of for.
  635. @example
  636. int
  637. fib (int n)
  638. @{
  639. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  640. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  641. int i;
  642. for (i = 1; i < n; ++i)
  643. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  644. /* @r{since @code{i < n} is false the first time.} */
  645. @{
  646. /* @r{Now @code{last} is @code{fib (@code{i})}}
  647. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  648. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  649. int next = prev + last;
  650. /* @r{Shift the values down.} */
  651. prev = last;
  652. last = next;
  653. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  654. @r{and @code{prev} is @code{fib (@code{i})}.}
  655. @r{But that won't stay true for long,}
  656. @r{because we are about to increment @code{i}.} */
  657. @}
  658. return last;
  659. @}
  660. @end example
  661. This definition computes @code{fib (@var{n})} in a time proportional
  662. to @code{@var{n}}. The comments in the definition explain how it works: it
  663. advances through the series, always keeps the last two values in
  664. @code{last} and @code{prev}, and adds them to get the next value.
  665. Here are the additional C features that this definition uses:
  666. @table @asis
  667. @item Internal blocks
  668. Within a function, wherever a statement is called for, you can write a
  669. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  670. more statements and declarations. (You can also use additional
  671. blocks as statements in a block.)
  672. The function body also counts as a block, which is why it can contain
  673. statements and declarations.
  674. @xref{Blocks}.
  675. @item Declarations of local variables
  676. This function body contains declarations as well as statements. There
  677. are three declarations directly in the function body, as well as a
  678. fourth declaration in an internal block. Each starts with @code{int}
  679. because it declares a variable whose type is integer. One declaration
  680. can declare several variables, but each of these declarations is
  681. simple and declares just one variable.
  682. Variables declared inside a block (either a function body or an
  683. internal block) are @dfn{local variables}. These variables exist only
  684. within that block; their names are not defined outside the block, and
  685. exiting the block deallocates their storage. This example declares
  686. four local variables: @code{last}, @code{prev}, @code{i}, and
  687. @code{next}.
  688. The most basic local variable declaration looks like this:
  689. @example
  690. @var{type} @var{variablename};
  691. @end example
  692. For instance,
  693. @example
  694. int i;
  695. @end example
  696. @noindent
  697. declares the local variable @code{i} as an integer.
  698. @xref{Variable Declarations}.
  699. @item Initializers
  700. When you declare a variable, you can also specify its initial value,
  701. like this:
  702. @example
  703. @var{type} @var{variablename} = @var{value};
  704. @end example
  705. For instance,
  706. @example
  707. int last = 1;
  708. @end example
  709. @noindent
  710. declares the local variable @code{last} as an integer (type
  711. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  712. @item Assignment
  713. Assignment: a specific kind of expression, written with the @samp{=}
  714. operator, that stores a new value in a variable or other place. Thus,
  715. @example
  716. @var{variable} = @var{value}
  717. @end example
  718. @noindent
  719. is an expression that computes @code{@var{value}} and stores the value in
  720. @code{@var{variable}}. @xref{Assignment Expressions}.
  721. @item Expression statements
  722. An expression statement is an expression followed by a semicolon.
  723. That computes the value of the expression, then ignores the value.
  724. An expression statement is useful when the expression changes some
  725. data or has other side effects---for instance, with function calls, or
  726. with assignments as in this example. @xref{Expression Statement}.
  727. Using an expression with no side effects in an expression statement is
  728. pointless except in very special cases. For instance, the expression
  729. statement @code{x;} would examine the value of @code{x} and ignore it.
  730. That is not useful.
  731. @item Increment operator
  732. The increment operator is @samp{++}. @code{++i} is an
  733. expression that is short for @code{i = i + 1}.
  734. @xref{Increment/Decrement}.
  735. @item @code{for} statements
  736. A @code{for} statement is a clean way of executing a statement
  737. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  738. @example
  739. for (i = 1; i < n; ++i)
  740. @var{body}
  741. @end example
  742. @noindent
  743. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  744. for the loop. The loop itself consists of
  745. @itemize @bullet
  746. @item
  747. Testing @code{i < n} and exiting the loop if that's false.
  748. @item
  749. Executing @var{body}.
  750. @item
  751. Advancing the loop (executing @code{++i}, which increments @code{i}).
  752. @end itemize
  753. The net result is to execute @var{body} with 0 in @code{i},
  754. then with 1 in @code{i}, and so on, stopping just before the repetition
  755. where @code{i} would equal @code{n}.
  756. The body of the @code{for} statement must be one and only one
  757. statement. You can't write two statements in a row there; if you try
  758. to, only the first of them will be treated as part of the loop.
  759. The way to put multiple statements in those places is to group them
  760. with a block, and that's what we do in this example.
  761. @end table
  762. @node Complete Program
  763. @chapter A Complete Program
  764. @cindex complete example program
  765. @cindex example program, complete
  766. It's all very well to write a Fibonacci function, but you cannot run
  767. it by itself. It is a useful program, but it is not a complete
  768. program.
  769. In this chapter we present a complete program that contains the
  770. @code{fib} function. This example shows how to make the program
  771. start, how to make it finish, how to do computation, and how to print
  772. a result.
  773. @menu
  774. * Complete Example:: Turn the simple function into a full program.
  775. * Complete Explanation:: Explanation of each part of the example.
  776. * Complete Line-by-Line:: Explaining each line of the example.
  777. * Compile Example:: Using GCC to compile the example.
  778. @end menu
  779. @node Complete Example
  780. @section Complete Program Example
  781. Here is the complete program that uses the simple, recursive version
  782. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  783. @example
  784. #include <stdio.h>
  785. int
  786. fib (int n)
  787. @{
  788. if (n <= 2) /* @r{This avoids infinite recursion.} */
  789. return 1;
  790. else
  791. return fib (n - 1) + fib (n - 2);
  792. @}
  793. int
  794. main (void)
  795. @{
  796. printf ("Fibonacci series item %d is %d\n",
  797. 20, fib (20));
  798. return 0;
  799. @}
  800. @end example
  801. @noindent
  802. This program prints a message that shows the value of @code{fib (20)}.
  803. Now for an explanation of what that code means.
  804. @node Complete Explanation
  805. @section Complete Program Explanation
  806. @ifnottex
  807. Here's the explanation of the code of the example in the
  808. previous section.
  809. @end ifnottex
  810. This sample program prints a message that shows the value of @code{fib
  811. (20)}, and exits with code 0 (which stands for successful execution).
  812. Every C program is started by running the function named @code{main}.
  813. Therefore, the example program defines a function named @code{main} to
  814. provide a way to start it. Whatever that function does is what the
  815. program does. @xref{The main Function}.
  816. The @code{main} function is the first one called when the program
  817. runs, but it doesn't come first in the example code. The order of the
  818. function definitions in the source code makes no difference to the
  819. program's meaning.
  820. The initial call to @code{main} always passes certain arguments, but
  821. @code{main} does not have to pay attention to them. To ignore those
  822. arguments, define @code{main} with @code{void} as the parameter list.
  823. (@code{void} as a function's parameter list normally means ``call with
  824. no arguments,'' but @code{main} is a special case.)
  825. The function @code{main} returns 0 because that is
  826. the conventional way for @code{main} to indicate successful execution.
  827. It could instead return a positive integer to indicate failure, and
  828. some utility programs have specific conventions for the meaning of
  829. certain numeric @dfn{failure codes}. @xref{Values from main}.
  830. @cindex @code{printf}
  831. The simplest way to print text in C is by calling the @code{printf}
  832. function, so here we explain what that does.
  833. @cindex standard output
  834. The first argument to @code{printf} is a @dfn{string constant}
  835. (@pxref{String Constants}) that is a template for output. The
  836. function @code{printf} copies most of that string directly as output,
  837. including the newline character at the end of the string, which is
  838. written as @samp{\n}. The output goes to the program's @dfn{standard
  839. output} destination, which in the usual case is the terminal.
  840. @samp{%} in the template introduces a code that substitutes other text
  841. into the output. Specifically, @samp{%d} means to take the next
  842. argument to @code{printf} and substitute it into the text as a decimal
  843. number. (The argument for @samp{%d} must be of type @code{int}; if it
  844. isn't, @code{printf} will malfunction.) So the output is a line that
  845. looks like this:
  846. @example
  847. Fibonacci series item 20 is 6765
  848. @end example
  849. This program does not contain a definition for @code{printf} because
  850. it is defined by the C library, which makes it available in all C
  851. programs. However, each program does need to @dfn{declare}
  852. @code{printf} so it will be called correctly. The @code{#include}
  853. line takes care of that; it includes a @dfn{header file} called
  854. @file{stdio.h} into the program's code. That file is provided by the
  855. operating system and it contains declarations for the many standard
  856. input/output functions in the C library, one of which is
  857. @code{printf}.
  858. Don't worry about header files for now; we'll explain them later in
  859. @ref{Header Files}.
  860. The first argument of @code{printf} does not have to be a string
  861. constant; it can be any string (@pxref{Strings}). However, using a
  862. constant is the most common case.
  863. To learn more about @code{printf} and other facilities of the C
  864. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  865. Reference Manual}.
  866. @node Complete Line-by-Line
  867. @section Complete Program, Line by Line
  868. Here's the same example, explained line by line.
  869. @strong{Beginners, do you find this helpful or not?
  870. Would you prefer a different layout for the example?
  871. Please tell rms@@gnu.org.}
  872. @example
  873. #include <stdio.h> /* @r{Include declaration of usual} */
  874. /* @r{I/O functions such as @code{printf}.} */
  875. /* @r{Most programs need these.} */
  876. int /* @r{This function returns an @code{int}.} */
  877. fib (int n) /* @r{Its name is @code{fib};} */
  878. /* @r{its argument is called @code{n}.} */
  879. @{ /* @r{Start of function body.} */
  880. /* @r{This stops the recursion from being infinite.} */
  881. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  882. return 1; /* @r{make @code{fib} return 1.} */
  883. else /* @r{otherwise, add the two previous} */
  884. /* @r{fibonacci numbers.} */
  885. return fib (n - 1) + fib (n - 2);
  886. @}
  887. int /* @r{This function returns an @code{int}.} */
  888. main (void) /* @r{Start here; ignore arguments.} */
  889. @{ /* @r{Print message with numbers in it.} */
  890. printf ("Fibonacci series item %d is %d\n",
  891. 20, fib (20));
  892. return 0; /* @r{Terminate program, report success.} */
  893. @}
  894. @end example
  895. @node Compile Example
  896. @section Compiling the Example Program
  897. @cindex compiling
  898. @cindex executable file
  899. To run a C program requires converting the source code into an
  900. @dfn{executable file}. This is called @dfn{compiling} the program,
  901. and the command to do that using GNU C is @command{gcc}.
  902. This example program consists of a single source file. If we
  903. call that file @file{fib1.c}, the complete command to compile it is
  904. this:
  905. @example
  906. gcc -g -O -o fib1 fib1.c
  907. @end example
  908. @noindent
  909. Here, @option{-g} says to generate debugging information, @option{-O}
  910. says to optimize at the basic level, and @option{-o fib1} says to put
  911. the executable program in the file @file{fib1}.
  912. To run the program, use its file name as a shell command.
  913. For instance,
  914. @example
  915. ./fib1
  916. @end example
  917. @noindent
  918. However, unless you are sure the program is correct, you should
  919. expect to need to debug it. So use this command,
  920. @example
  921. gdb fib1
  922. @end example
  923. @noindent
  924. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  925. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  926. debug the executable program @code{fib1}.
  927. @xref{Compilation}, for an introduction to compiling more complex
  928. programs which consist of more than one source file.
  929. @node Storage
  930. @chapter Storage and Data
  931. @cindex bytes
  932. @cindex storage organization
  933. @cindex memory organization
  934. Storage in C programs is made up of units called @dfn{bytes}. On
  935. nearly all computers, a byte consists of 8 bits, but there are a few
  936. peculiar computers (mostly ``embedded controllers'' for very small
  937. systems) where a byte is longer than that. This manual does not try
  938. to explain the peculiarity of those computers; we assume that a byte
  939. is 8 bits.
  940. Every C data type is made up of a certain number of bytes; that number
  941. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  942. types @code{signed char} and @code{unsigned char} are one byte long;
  943. use those types to operate on data byte by byte. @xref{Signed and
  944. Unsigned Types}. You can refer to a series of consecutive bytes as an
  945. array of @code{char} elements; that's what an ASCII string looks like
  946. in memory. @xref{String Constants}.
  947. @node Beyond Integers
  948. @chapter Beyond Integers
  949. So far we've presented programs that operate on integers. In this
  950. chapter we'll present examples of handling non-integral numbers and
  951. arrays of numbers.
  952. @menu
  953. * Float Example:: A function that uses floating-point numbers.
  954. * Array Example:: A function that works with arrays.
  955. * Array Example Call:: How to call that function.
  956. * Array Example Variations:: Different ways to write the call example.
  957. @end menu
  958. @node Float Example
  959. @section An Example with Non-Integer Numbers
  960. @cindex floating point example
  961. Here's a function that operates on and returns @dfn{floating point}
  962. numbers that don't have to be integers. Floating point represents a
  963. number as a fraction together with a power of 2. (For more detail,
  964. @pxref{Floating-Point Data Types}.) This example calculates the
  965. average of three floating point numbers that are passed to it as
  966. arguments:
  967. @example
  968. double
  969. average_of_three (double a, double b, double c)
  970. @{
  971. return (a + b + c) / 3;
  972. @}
  973. @end example
  974. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  975. integers, and even when they happen to be integers, most likely their
  976. average is not an integer.
  977. @code{double} is the usual data type in C for calculations on
  978. floating-point numbers.
  979. To print a @code{double} with @code{printf}, we must use @samp{%f}
  980. instead of @samp{%d}:
  981. @example
  982. printf ("Average is %f\n",
  983. average_of_three (1.1, 9.8, 3.62));
  984. @end example
  985. The code that calls @code{printf} must pass a @code{double} for
  986. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  987. If the argument has the wrong type, @code{printf} will produce garbage
  988. output.
  989. Here's a complete program that computes the average of three
  990. specific numbers and prints the result:
  991. @example
  992. double
  993. average_of_three (double a, double b, double c)
  994. @{
  995. return (a + b + c) / 3;
  996. @}
  997. int
  998. main (void)
  999. @{
  1000. printf ("Average is %f\n",
  1001. average_of_three (1.1, 9.8, 3.62));
  1002. return 0;
  1003. @}
  1004. @end example
  1005. From now on we will not present examples of calls to @code{main}.
  1006. Instead we encourage you to write them for yourself when you want
  1007. to test executing some code.
  1008. @node Array Example
  1009. @section An Example with Arrays
  1010. @cindex array example
  1011. A function to take the average of three numbers is very specific and
  1012. limited. A more general function would take the average of any number
  1013. of numbers. That requires passing the numbers in an array. An array
  1014. is an object in memory that contains a series of values of the same
  1015. data type. This chapter presents the basic concepts and use of arrays
  1016. through an example; for the full explanation, see @ref{Arrays}.
  1017. Here's a function definition to take the average of several
  1018. floating-point numbers, passed as type @code{double}. The first
  1019. parameter, @code{length}, specifies how many numbers are passed. The
  1020. second parameter, @code{input_data}, is an array that holds those
  1021. numbers.
  1022. @example
  1023. double
  1024. avg_of_double (int length, double input_data[])
  1025. @{
  1026. double sum = 0;
  1027. int i;
  1028. for (i = 0; i < length; i++)
  1029. sum = sum + input_data[i];
  1030. return sum / length;
  1031. @}
  1032. @end example
  1033. This introduces the expression to refer to an element of an array:
  1034. @code{input_data[i]} means the element at index @code{i} in
  1035. @code{input_data}. The index of the element can be any expression
  1036. with an integer value; in this case, the expression is @code{i}.
  1037. @xref{Accessing Array Elements}.
  1038. @cindex zero-origin indexing
  1039. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1040. valid index is one less than the number of elements. (This is known
  1041. as @dfn{zero-origin indexing}.)
  1042. This example also introduces the way to declare that a function
  1043. parameter is an array. Such declarations are modeled after the syntax
  1044. for an element of the array. Just as @code{double foo} declares that
  1045. @code{foo} is of type @code{double}, @code{double input_data[]}
  1046. declares that each element of @code{input_data} is of type
  1047. @code{double}. Therefore, @code{input_data} itself has type ``array
  1048. of @code{double}.''
  1049. When declaring an array parameter, it's not necessary to say how long
  1050. the array is. In this case, the parameter @code{input_data} has no
  1051. length information. That's why the function needs another parameter,
  1052. @code{length}, for the caller to provide that information to the
  1053. function @code{avg_of_double}.
  1054. @node Array Example Call
  1055. @section Calling the Array Example
  1056. To call the function @code{avg_of_double} requires making an
  1057. array and then passing it as an argument. Here is an example.
  1058. @example
  1059. @{
  1060. /* @r{The array of values to average.} */
  1061. double nums_to_average[5];
  1062. /* @r{The average, once we compute it.} */
  1063. double average;
  1064. /* @r{Fill in elements of @code{nums_to_average}.} */
  1065. nums_to_average[0] = 58.7;
  1066. nums_to_average[1] = 5.1;
  1067. nums_to_average[2] = 7.7;
  1068. nums_to_average[3] = 105.2;
  1069. nums_to_average[4] = -3.14159;
  1070. average = avg_of_double (5, nums_to_average);
  1071. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1072. @}
  1073. @end example
  1074. This shows an array subscripting expression again, this time
  1075. on the left side of an assignment, storing a value into an
  1076. element of an array.
  1077. It also shows how to declare a local variable that is an array:
  1078. @code{double nums_to_average[5];}. Since this declaration allocates the
  1079. space for the array, it needs to know the array's length. You can
  1080. specify the length with any expression whose value is an integer, but
  1081. in this declaration the length is a constant, the integer 5.
  1082. The name of the array, when used by itself as an expression, stands
  1083. for the address of the array's data, and that's what gets passed to
  1084. the function @code{avg_of_double} in @code{avg_of_double (5,
  1085. nums_to_average)}.
  1086. We can make the code easier to maintain by avoiding the need to write
  1087. 5, the array length, when calling @code{avg_of_double}. That way, if
  1088. we change the array to include more elements, we won't have to change
  1089. that call. One way to do this is with the @code{sizeof} operator:
  1090. @example
  1091. average = avg_of_double ((sizeof (nums_to_average)
  1092. / sizeof (nums_to_average[0])),
  1093. nums_to_average);
  1094. @end example
  1095. This computes the number of elements in @code{nums_to_average} by dividing
  1096. its total size by the size of one element. @xref{Type Size}, for more
  1097. details of using @code{sizeof}.
  1098. We don't show in this example what happens after storing the result of
  1099. @code{avg_of_double} in the variable @code{average}. Presumably
  1100. more code would follow that uses that result somehow. (Why compute
  1101. the average and not use it?) But that isn't part of this topic.
  1102. @node Array Example Variations
  1103. @section Variations for Array Example
  1104. The code to call @code{avg_of_double} has two declarations that
  1105. start with the same data type:
  1106. @example
  1107. /* @r{The array of values to average.} */
  1108. double nums_to_average[5];
  1109. /* @r{The average, once we compute it.} */
  1110. double average;
  1111. @end example
  1112. In C, you can combine the two, like this:
  1113. @example
  1114. double nums_to_average[5], average;
  1115. @end example
  1116. This declares @code{nums_to_average} so each of its elements is a
  1117. @code{double}, and @code{average} so that it simply is a
  1118. @code{double}.
  1119. However, while you @emph{can} combine them, that doesn't mean you
  1120. @emph{should}. If it is useful to write comments about the variables,
  1121. and usually it is, then it's clearer to keep the declarations separate
  1122. so you can put a comment on each one.
  1123. We set all of the elements of the array @code{nums_to_average} with
  1124. assignments, but it is more convenient to use an initializer in the
  1125. declaration:
  1126. @example
  1127. @{
  1128. /* @r{The array of values to average.} */
  1129. double nums_to_average[]
  1130. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1131. /* @r{The average, once we compute it.} */
  1132. average = avg_of_double ((sizeof (nums_to_average)
  1133. / sizeof (nums_to_average[0])),
  1134. nums_to_average);
  1135. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1136. @}
  1137. @end example
  1138. The array initializer is a comma-separated list of values, delimited
  1139. by braces. @xref{Initializers}.
  1140. Note that the declaration does not specify a size for
  1141. @code{nums_to_average}, so the size is determined from the
  1142. initializer. There are five values in the initializer, so
  1143. @code{nums_to_average} gets length 5. If we add another element to
  1144. the initializer, @code{nums_to_average} will have six elements.
  1145. Because the code computes the number of elements from the size of
  1146. the array, using @code{sizeof}, the program will operate on all the
  1147. elements in the initializer, regardless of how many those are.
  1148. @node Lexical Syntax
  1149. @chapter Lexical Syntax
  1150. @cindex lexical syntax
  1151. @cindex token
  1152. To start the full description of the C language, we explain the
  1153. lexical syntax and lexical units of C code. The lexical units of a
  1154. programming language are known as @dfn{tokens}. This chapter covers
  1155. all the tokens of C except for constants, which are covered in a later
  1156. chapter (@pxref{Constants}). One vital kind of token is the
  1157. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1158. kind.
  1159. @menu
  1160. * English:: Write programs in English!
  1161. * Characters:: The characters allowed in C programs.
  1162. * Whitespace:: The particulars of whitespace characters.
  1163. * Comments:: How to include comments in C code.
  1164. * Identifiers:: How to form identifiers (names).
  1165. * Operators/Punctuation:: Characters used as operators or punctuation.
  1166. * Line Continuation:: Splitting one line into multiple lines.
  1167. @end menu
  1168. @node English
  1169. @section Write Programs in English!
  1170. In principle, you can write the function and variable names in a
  1171. program, and the comments, in any human language. C allows any kinds
  1172. of characters in comments, and you can put non-ASCII characters into
  1173. identifiers with a special prefix. However, to enable programmers in
  1174. all countries to understand and develop the program, it is best given
  1175. today's circumstances to write identifiers and comments in
  1176. English.
  1177. English is the one language that programmers in all countries
  1178. generally study. If a program's names are in English, most
  1179. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1180. understand them. Most programmers in those countries can speak
  1181. English, or at least read it, but they do not read each other's
  1182. languages at all. In India, with so many languages, two programmers
  1183. may have no common language other than English.
  1184. If you don't feel confident in writing English, do the best you can,
  1185. and follow each English comment with a version in a language you
  1186. write better; add a note asking others to translate that to English.
  1187. Someone will eventually do that.
  1188. The program's user interface is a different matter. We don't need to
  1189. choose one language for that; it is easy to support multiple languages
  1190. and let each user choose the language to use. This requires writing
  1191. the program to support localization of its interface. (The
  1192. @code{gettext} package exists to support this; @pxref{Message
  1193. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1194. Manual}.) Then a community-based translation effort can provide
  1195. support for all the languages users want to use.
  1196. @node Characters
  1197. @section Characters
  1198. @cindex character set
  1199. @cindex Unicode
  1200. @c ??? How to express ¶?
  1201. GNU C source files are usually written in the
  1202. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1203. was defined in the 1960s for English. However, they can also include
  1204. Unicode characters represented in the
  1205. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1206. This makes it possible to represent accented letters such as @samp{á},
  1207. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1208. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1209. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1210. manual.}
  1211. In C source code, non-ASCII characters are valid in comments, in wide
  1212. character constants (@pxref{Wide Character Constants}), and in string
  1213. constants (@pxref{String Constants}).
  1214. @c ??? valid in identifiers?
  1215. Another way to specify non-ASCII characters in constants (character or
  1216. string) and identifiers is with an escape sequence starting with
  1217. backslash, specifying the intended Unicode character. (@xref{Unicode
  1218. Character Codes}.) This specifies non-ASCII characters without
  1219. putting a real non-ASCII character in the source file itself.
  1220. C accepts two-character aliases called @dfn{digraphs} for certain
  1221. characters. @xref{Digraphs}.
  1222. @node Whitespace
  1223. @section Whitespace
  1224. @cindex whitespace characters in source files
  1225. @cindex space character in source
  1226. @cindex tab character in source
  1227. @cindex formfeed in source
  1228. @cindex linefeed in source
  1229. @cindex newline in source
  1230. @cindex carriage return in source
  1231. @cindex vertical tab in source
  1232. Whitespace means characters that exist in a file but appear blank in a
  1233. printed listing of a file (or traditionally did appear blank, several
  1234. decades ago). The C language requires whitespace in order to separate
  1235. two consecutive identifiers, or to separate an identifier from a
  1236. numeric constant. Other than that, and a few special situations
  1237. described later, whitespace is optional; you can put it in when you
  1238. wish, to make the code easier to read.
  1239. Space and tab in C code are treated as whitespace characters. So are
  1240. line breaks. You can represent a line break with the newline
  1241. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1242. the CRLF sequence (two characters: carriage return followed by a
  1243. newline character).
  1244. The @dfn{formfeed} character, Control-L, was traditionally used to
  1245. divide a file into pages. It is still used this way in source code,
  1246. and the tools that generate nice printouts of source code still start
  1247. a new page after each ``formfeed'' character. Dividing code into
  1248. pages separated by formfeed characters is a good way to break it up
  1249. into comprehensible pieces and show other programmers where they start
  1250. and end.
  1251. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1252. make printing advance down to the next section of a page. We know of
  1253. no particular reason to use it in source code, but it is still
  1254. accepted as whitespace in C.
  1255. Comments are also syntactically equivalent to whitespace.
  1256. @ifinfo
  1257. @xref{Comments}.
  1258. @end ifinfo
  1259. @node Comments
  1260. @section Comments
  1261. @cindex comments
  1262. A comment encapsulates text that has no effect on the program's
  1263. execution or meaning.
  1264. The purpose of comments is to explain the code to people that read it.
  1265. Writing good comments for your code is tremendously important---they
  1266. should provide background information that helps programmers
  1267. understand the reasons why the code is written the way it is. You,
  1268. returning to the code six months from now, will need the help of these
  1269. comments to remember why you wrote it this way.
  1270. Outdated comments that become incorrect are counterproductive, so part
  1271. of the software developer's responsibility is to update comments as
  1272. needed to correspond with changes to the program code.
  1273. C allows two kinds of comment syntax, the traditional style and the
  1274. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1275. with @samp{*/}. For instance,
  1276. @example
  1277. /* @r{This is a comment in traditional C syntax.} */
  1278. @end example
  1279. A traditional comment can contain @samp{/*}, but these delimiters do
  1280. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1281. whether it contains @samp{/*} sequences.
  1282. @example
  1283. /* @r{This} /* @r{is a comment} */ But this is not! */
  1284. @end example
  1285. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1286. For instance,
  1287. @example
  1288. // @r{This is a comment in C@t{++} style.}
  1289. @end example
  1290. Line comments do nest, in effect, because @samp{//} inside a line
  1291. comment is part of that comment:
  1292. @example
  1293. // @r{this whole line is} // @r{one comment}
  1294. This is code, not comment.
  1295. @end example
  1296. It is safe to put line comments inside block comments, or vice versa.
  1297. @example
  1298. @group
  1299. /* @r{traditional comment}
  1300. // @r{contains line comment}
  1301. @r{more traditional comment}
  1302. */ text here is not a comment
  1303. // @r{line comment} /* @r{contains traditional comment} */
  1304. @end group
  1305. @end example
  1306. But beware of commenting out one end of a traditional comment with a line
  1307. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1308. inside an already-started comment.
  1309. @example
  1310. @group
  1311. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1312. Oops! The line comment has ended;
  1313. this isn't a comment any more. */
  1314. @end group
  1315. @end example
  1316. Comments are not recognized within string constants. @t{@w{"/* blah
  1317. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1318. string.
  1319. In this manual we show the text in comments in a variable-width font,
  1320. for readability, but this font distinction does not exist in source
  1321. files.
  1322. A comment is syntactically equivalent to whitespace, so it always
  1323. separates tokens. Thus,
  1324. @example
  1325. @group
  1326. int/* @r{comment} */foo;
  1327. @r{is equivalent to}
  1328. int foo;
  1329. @end group
  1330. @end example
  1331. @noindent
  1332. but clean code always uses real whitespace to separate the comment
  1333. visually from surrounding code.
  1334. @node Identifiers
  1335. @section Identifiers
  1336. @cindex identifiers
  1337. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1338. as well as @samp{_}, that does not start with a digit. Most compilers
  1339. also allow @samp{$}. An identifier can be as long as you like; for
  1340. example,
  1341. @example
  1342. int anti_dis_establishment_arian_ism;
  1343. @end example
  1344. @cindex case of letters in identifiers
  1345. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1346. and @code{A} are two different identifiers.
  1347. @cindex keyword
  1348. @cindex reserved words
  1349. Identifiers in C are used as variable names, function names, typedef
  1350. names, enumeration constants, type tags, field names, and labels.
  1351. Certain identifiers in C are @dfn{keywords}, which means they have
  1352. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1353. meaning you cannot use them in any other way. For instance, you can't
  1354. define a variable or function named @code{return} or @code{if}.
  1355. You can also include other characters, even non-ASCII characters, in
  1356. identifiers by writing their Unicode character names, which start with
  1357. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1358. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1359. characters in identifiers, and when they are written in English, they
  1360. never need non-ASCII characters. @xref{English}.
  1361. Whitespace is required to separate two consecutive identifiers, or to
  1362. separate an identifier from a preceding or following numeric
  1363. constant.
  1364. @node Operators/Punctuation
  1365. @section Operators and Punctuation
  1366. @cindex operators
  1367. @cindex punctuation
  1368. Here we describe the lexical syntax of operators and punctuation in C.
  1369. The specific operators of C and their meanings are presented in
  1370. subsequent chapters.
  1371. Most operators in C consist of one or two characters that can't be
  1372. used in identifiers. The characters used for operators in C are
  1373. @samp{!~^&|*/%+-=<>,.?:}.
  1374. Some operators are a single character. For instance, @samp{-} is the
  1375. operator for negation (with one operand) and the operator for
  1376. subtraction (with two operands).
  1377. Some operators are two characters. For example, @samp{++} is the
  1378. increment operator. Recognition of multicharacter operators works by
  1379. grouping together as many consecutive characters as can constitute one
  1380. operator.
  1381. For instance, the character sequence @samp{++} is always interpreted
  1382. as the increment operator; therefore, if we want to write two
  1383. consecutive instances of the operator @samp{+}, we must separate them
  1384. with a space so that they do not combine as one token. Applying the
  1385. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1386. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1387. of a valid C program and the former could not (since @code{a++}
  1388. is not an lvalue and thus can't be the operand of @code{++}).
  1389. A few C operators are keywords rather than special characters. They
  1390. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1391. (@pxref{Type Alignment}).
  1392. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1393. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1394. @samp{@}}) begin and end a block at the statement level
  1395. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1396. for a variable with multiple elements or components (such as arrays or
  1397. structures).
  1398. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1399. @code{array[5]}.
  1400. Parentheses are used in expressions for explicit nesting of
  1401. expressions (@pxref{Basic Arithmetic}), around the parameter
  1402. declarations in a function declaration or definition, and around the
  1403. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1404. (@pxref{Function Calls}). Several kinds of statements also use
  1405. parentheses as part of their syntax---for instance, @code{if}
  1406. statements, @code{for} statements, @code{while} statements, and
  1407. @code{switch} statements. @xref{if Statement}, and following
  1408. sections.
  1409. Parentheses are also required around the operand of the operator
  1410. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1411. type rather than a value. @xref{Type Size}.
  1412. @node Line Continuation
  1413. @section Line Continuation
  1414. @cindex line continuation
  1415. @cindex continuation of lines
  1416. The sequence of a backslash and a newline is ignored absolutely
  1417. anywhere in a C program. This makes it possible to split a single
  1418. source line into multiple lines in the source file. GNU C tolerates
  1419. and ignores other whitespace between the backslash and the newline.
  1420. In particular, it always ignores a CR (carriage return) character
  1421. there, in case some text editor decided to end the line with the CRLF
  1422. sequence.
  1423. The main use of line continuation in C is for macro definitions that
  1424. would be inconveniently long for a single line (@pxref{Macros}).
  1425. It is possible to continue a line comment onto another line with
  1426. backslash-newline. You can put backslash-newline in the middle of an
  1427. identifier, even a keyword, or an operator. You can even split
  1428. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1429. backslash-newline. Here's an ugly example:
  1430. @example
  1431. @group
  1432. /\
  1433. *
  1434. */ fo\
  1435. o +\
  1436. = 1\
  1437. 0;
  1438. @end group
  1439. @end example
  1440. @noindent
  1441. That's equivalent to @samp{/* */ foo += 10;}.
  1442. Don't do those things in real programs, since they make code hard to
  1443. read.
  1444. @strong{Note:} For the sake of using certain tools on the source code, it is
  1445. wise to end every source file with a newline character which is not
  1446. preceded by a backslash, so that it really ends the last line.
  1447. @node Arithmetic
  1448. @chapter Arithmetic
  1449. @cindex arithmetic operators
  1450. @cindex operators, arithmetic
  1451. @c ??? Duplication with other sections -- get rid of that?
  1452. Arithmetic operators in C attempt to be as similar as possible to the
  1453. abstract arithmetic operations, but it is impossible to do this
  1454. perfectly. Numbers in a computer have a finite range of possible
  1455. values, and non-integer values have a limit on their possible
  1456. accuracy. Nonetheless, in most cases you will encounter no surprises
  1457. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1458. for multiplication.
  1459. Each C operator has a @dfn{precedence}, which is its rank in the
  1460. grammatical order of the various operators. The operators with the
  1461. highest precedence grab adjoining operands first; these expressions
  1462. then become operands for operators of lower precedence. We give some
  1463. information about precedence of operators in this chapter where we
  1464. describe the operators; for the full explanation, see @ref{Binary
  1465. Operator Grammar}.
  1466. The arithmetic operators always @dfn{promote} their operands before
  1467. operating on them. This means converting narrow integer data types to
  1468. a wider data type (@pxref{Operand Promotions}). If you are just
  1469. learning C, don't worry about this yet.
  1470. Given two operands that have different types, most arithmetic
  1471. operations convert them both to their @dfn{common type}. For
  1472. instance, if one is @code{int} and the other is @code{double}, the
  1473. common type is @code{double}. (That's because @code{double} can
  1474. represent all the values that an @code{int} can hold, but not vice
  1475. versa.) For the full details, see @ref{Common Type}.
  1476. @menu
  1477. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1478. and division.
  1479. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1480. * Integer Overflow:: When an integer value exceeds the range
  1481. of its type.
  1482. * Mixed Mode:: Calculating with both integer values
  1483. and floating-point values.
  1484. * Division and Remainder:: How integer division works.
  1485. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1486. * Shift Operations:: Shift integer bits left or right.
  1487. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1488. @end menu
  1489. @node Basic Arithmetic
  1490. @section Basic Arithmetic
  1491. @cindex addition operator
  1492. @cindex subtraction operator
  1493. @cindex multiplication operator
  1494. @cindex division operator
  1495. @cindex negation operator
  1496. @cindex operator, addition
  1497. @cindex operator, subtraction
  1498. @cindex operator, multiplication
  1499. @cindex operator, division
  1500. @cindex operator, negation
  1501. Basic arithmetic in C is done with the usual binary operators of
  1502. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1503. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1504. used to change the sign of a number. The unary @code{+} operator also
  1505. exists; it yields its operand unaltered.
  1506. @samp{/} is the division operator, but dividing integers may not give
  1507. the result you expect. Its value is an integer, which is not equal to
  1508. the mathematical quotient when that is a fraction. Use @samp{%} to
  1509. get the corresponding integer remainder when necessary.
  1510. @xref{Division and Remainder}. Floating point division yields value
  1511. as close as possible to the mathematical quotient.
  1512. These operators use algebraic syntax with the usual algebraic
  1513. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1514. and division are done before addition and subtraction, but you can use
  1515. parentheses to explicitly specify how the operators nest. They are
  1516. left-associative (@pxref{Associativity and Ordering}). Thus,
  1517. @example
  1518. -a + b - c + d * e / f
  1519. @end example
  1520. @noindent
  1521. is equivalent to
  1522. @example
  1523. (((-a) + b) - c) + ((d * e) / f)
  1524. @end example
  1525. @node Integer Arithmetic
  1526. @section Integer Arithmetic
  1527. @cindex integer arithmetic
  1528. Each of the basic arithmetic operations in C has two variants for
  1529. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1530. by the data types of their operands.
  1531. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1532. A signed type can hold a range of positive and negative numbers, with
  1533. zero near the middle of the range. An unsigned type can hold only
  1534. nonnegative numbers; its range starts with zero and runs upward.
  1535. The most basic integer types are @code{int}, which normally can hold
  1536. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1537. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1538. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1539. computers but not always on embedded controllers.) @xref{Integer
  1540. Types}, for full information about integer types.
  1541. When a basic arithmetic operation is given two signed operands, it
  1542. does signed arithmetic. Given two unsigned operands, it does
  1543. unsigned arithmetic.
  1544. If one operand is @code{unsigned int} and the other is @code{int}, the
  1545. operator treats them both as unsigned. More generally, the common
  1546. type of the operands determines whether the operation is signed or
  1547. not. @xref{Common Type}.
  1548. Printing the results of unsigned arithmetic with @code{printf} using
  1549. @samp{%d} can produce surprising results for values far away from
  1550. zero. Even though the rules above say that the computation was done
  1551. with unsigned arithmetic, the printed result may appear to be signed!
  1552. The explanation is that the bit pattern resulting from addition,
  1553. subtraction or multiplication is actually the same for signed and
  1554. unsigned operations. The difference is only in the data type of the
  1555. result, which affects the @emph{interpretation} of the result bit pattern,
  1556. and whether the arithmetic operation can overflow (see the next section).
  1557. But @samp{%d} doesn't know its argument's data type. It sees only the
  1558. value's bit pattern, and it is defined to interpret that as
  1559. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1560. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1561. libc, The GNU C Library Reference Manual}.
  1562. Arithmetic in C never operates directly on narrow integer types (those
  1563. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1564. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1565. @node Integer Overflow
  1566. @section Integer Overflow
  1567. @cindex integer overflow
  1568. @cindex overflow, integer
  1569. When the mathematical value of an arithmetic operation doesn't fit in
  1570. the range of the data type in use, that's called @dfn{overflow}.
  1571. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1572. Integer overflow happens only in arithmetic operations. Type conversion
  1573. operations, by definition, do not cause overflow, not even when the
  1574. result can't fit in its new type. @xref{Integer Conversion}.
  1575. Signed numbers use two's-complement representation, in which the most
  1576. negative number lacks a positive counterpart (@pxref{Integers in
  1577. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1578. overflow.
  1579. @menu
  1580. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1581. * Signed Overflow:: Overlow in signed integer arithmetic.
  1582. @end menu
  1583. @node Unsigned Overflow
  1584. @subsection Overflow with Unsigned Integers
  1585. Unsigned arithmetic in C ignores overflow; it produces the true result
  1586. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1587. in the data type. We say it ``truncates'' the true result to the
  1588. lowest @var{n} bits.
  1589. A true result that is negative, when taken modulo the @var{n}th power
  1590. of 2, yields a positive number. For instance,
  1591. @example
  1592. unsigned int x = 1;
  1593. unsigned int y;
  1594. y = -x;
  1595. @end example
  1596. @noindent
  1597. causes overflow because the negative number @minus{}1 can't be stored
  1598. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1599. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1600. is the largest value that the unsigned data type can store. For a
  1601. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1602. and Minimum Values}.
  1603. Adding that number to itself, as here,
  1604. @example
  1605. unsigned int z;
  1606. z = y + y;
  1607. @end example
  1608. @noindent
  1609. ought to yield 8,489,934,590; however, that is again too large to fit,
  1610. so overflow truncates the value to 4,294,967,294. If that were a
  1611. signed integer, it would mean @minus{}2, which (not by coincidence)
  1612. equals @minus{}1 + @minus{}1.
  1613. @node Signed Overflow
  1614. @subsection Overflow with Signed Integers
  1615. @cindex compiler options for integer overflow
  1616. @cindex integer overflow, compiler options
  1617. @cindex overflow, compiler options
  1618. For signed integers, the result of overflow in C is @emph{in
  1619. principle} undefined, meaning that anything whatsoever could happen.
  1620. Therefore, C compilers can do optimizations that treat the overflow
  1621. case with total unconcern. (Since the result of overflow is undefined
  1622. in principle, one cannot claim that these optimizations are
  1623. erroneous.)
  1624. @strong{Watch out:} These optimizations can do surprising things. For
  1625. instance,
  1626. @example
  1627. int i;
  1628. @r{@dots{}}
  1629. if (i < i + 1)
  1630. x = 5;
  1631. @end example
  1632. @noindent
  1633. could be optimized to do the assignment unconditionally, because the
  1634. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1635. GCC offers compiler options to control handling signed integer
  1636. overflow. These options operate per module; that is, each module
  1637. behaves according to the options it was compiled with.
  1638. These two options specify particular ways to handle signed integer
  1639. overflow, other than the default way:
  1640. @table @option
  1641. @item -fwrapv
  1642. Make signed integer operations well-defined, like unsigned integer
  1643. operations: they produce the @var{n} low-order bits of the true
  1644. result. The highest of those @var{n} bits is the sign bit of the
  1645. result. With @option{-fwrapv}, these out-of-range operations are not
  1646. considered overflow, so (strictly speaking) integer overflow never
  1647. happens.
  1648. The option @option{-fwrapv} enables some optimizations based on the
  1649. defined values of out-of-range results. In GCC 8, it disables
  1650. optimizations that are based on assuming signed integer operations
  1651. will not overflow.
  1652. @item -ftrapv
  1653. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1654. This terminates the program unless the program handles the signal.
  1655. @xref{Signals}.
  1656. @end table
  1657. One other option is useful for finding where overflow occurs:
  1658. @ignore
  1659. @item -fno-strict-overflow
  1660. Disable optimizations that are based on assuming signed integer
  1661. operations will not overflow.
  1662. @end ignore
  1663. @table @option
  1664. @item -fsanitize=signed-integer-overflow
  1665. Output a warning message at run time when signed integer overflow
  1666. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1667. This takes priority over @option{-ftrapv}.
  1668. @end table
  1669. @node Mixed Mode
  1670. @section Mixed-Mode Arithmetic
  1671. Mixing integers and floating-point numbers in a basic arithmetic
  1672. operation converts the integers automatically to floating point.
  1673. In most cases, this gives exactly the desired results.
  1674. But sometimes it matters precisely where the conversion occurs.
  1675. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1676. as an integer, then converts the sum to floating point for the
  1677. multiplication. If the addition gets an overflow, that is not
  1678. equivalent to converting both integers to floating point and then
  1679. adding them. You can get the latter result by explicitly converting
  1680. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1681. @xref{Explicit Type Conversion}.
  1682. @c Eggert's report
  1683. Adding or multiplying several values, including some integers and some
  1684. floating point, does the operations left to right. Thus, @code{3.0 +
  1685. i + j} converts @code{i} to floating point, then adds 3.0, then
  1686. converts @code{j} to floating point and adds that. You can specify a
  1687. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1688. and @code{j} first and then adds that result (converting to floating
  1689. point) to 3.0. In this respect, C differs from other languages, such
  1690. as Fortran.
  1691. @node Division and Remainder
  1692. @section Division and Remainder
  1693. @cindex remainder operator
  1694. @cindex modulus
  1695. @cindex operator, remainder
  1696. Division of integers in C rounds the result to an integer. The result
  1697. is always rounded towards zero.
  1698. @example
  1699. 16 / 3 @result{} 5
  1700. -16 / 3 @result{} -5
  1701. 16 / -3 @result{} -5
  1702. -16 / -3 @result{} 5
  1703. @end example
  1704. @noindent
  1705. To get the corresponding remainder, use the @samp{%} operator:
  1706. @example
  1707. 16 % 3 @result{} 1
  1708. -16 % 3 @result{} -1
  1709. 16 % -3 @result{} 1
  1710. -16 % -3 @result{} -1
  1711. @end example
  1712. @noindent
  1713. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1714. From the rounded quotient and the remainder, you can reconstruct
  1715. the dividend, like this:
  1716. @example
  1717. int
  1718. original_dividend (int divisor, int quotient, int remainder)
  1719. @{
  1720. return divisor * quotient + remainder;
  1721. @}
  1722. @end example
  1723. To do unrounded division, use floating point. If only one operand is
  1724. floating point, @samp{/} converts the other operand to floating
  1725. point.
  1726. @example
  1727. 16.0 / 3 @result{} 5.333333333333333
  1728. 16 / 3.0 @result{} 5.333333333333333
  1729. 16.0 / 3.0 @result{} 5.333333333333333
  1730. 16 / 3 @result{} 5
  1731. @end example
  1732. The remainder operator @samp{%} is not allowed for floating-point
  1733. operands, because it is not needed. The concept of remainder makes
  1734. sense for integers because the result of division of integers has to
  1735. be an integer. For floating point, the result of division is a
  1736. floating-point number, in other words a fraction, which will differ
  1737. from the exact result only by a very small amount.
  1738. There are functions in the standard C library to calculate remainders
  1739. from integral-values division of floating-point numbers.
  1740. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1741. Reference Manual}.
  1742. Integer division overflows in one specific case: dividing the smallest
  1743. negative value for the data type (@pxref{Maximum and Minimum Values})
  1744. by @minus{}1. That's because the correct result, which is the
  1745. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1746. in the same number of bits. On some computers now in use, this always
  1747. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1748. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1749. Division by zero leads to unpredictable results---depending on the
  1750. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1751. produce a numeric result.
  1752. @cindex division by zero
  1753. @cindex zero, division by
  1754. @strong{Watch out:} Make sure the program does not divide by zero. If
  1755. you can't prove that the divisor is not zero, test whether it is zero,
  1756. and skip the division if so.
  1757. @node Numeric Comparisons
  1758. @section Numeric Comparisons
  1759. @cindex numeric comparisons
  1760. @cindex comparisons
  1761. @cindex operators, comparison
  1762. @cindex equal operator
  1763. @cindex not-equal operator
  1764. @cindex less-than operator
  1765. @cindex greater-than operator
  1766. @cindex less-or-equal operator
  1767. @cindex greater-or-equal operator
  1768. @cindex operator, equal
  1769. @cindex operator, not-equal
  1770. @cindex operator, less-than
  1771. @cindex operator, greater-than
  1772. @cindex operator, less-or-equal
  1773. @cindex operator, greater-or-equal
  1774. @cindex truth value
  1775. There are two kinds of comparison operators: @dfn{equality} and
  1776. @dfn{ordering}. Equality comparisons test whether two expressions
  1777. have the same value. The result is a @dfn{truth value}: a number that
  1778. is 1 for ``true'' and 0 for ``false.''
  1779. @example
  1780. a == b /* @r{Test for equal.} */
  1781. a != b /* @r{Test for not equal.} */
  1782. @end example
  1783. The equality comparison is written @code{==} because plain @code{=}
  1784. is the assignment operator.
  1785. Ordering comparisons test which operand is greater or less. Their
  1786. results are truth values. These are the ordering comparisons of C:
  1787. @example
  1788. a < b /* @r{Test for less-than.} */
  1789. a > b /* @r{Test for greater-than.} */
  1790. a <= b /* @r{Test for less-than-or-equal.} */
  1791. a >= b /* @r{Test for greater-than-or-equal.} */
  1792. @end example
  1793. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1794. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1795. mathematics. However, if @code{a} and @code{b} are special floating
  1796. point values (not ordinary numbers), all three can be false.
  1797. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1798. @node Shift Operations
  1799. @section Shift Operations
  1800. @cindex shift operators
  1801. @cindex operators, shift
  1802. @cindex operators, shift
  1803. @cindex shift count
  1804. @dfn{Shifting} an integer means moving the bit values to the left or
  1805. right within the bits of the data type. Shifting is defined only for
  1806. integers. Here's the way to write it:
  1807. @example
  1808. /* @r{Left shift.} */
  1809. 5 << 2 @result{} 20
  1810. /* @r{Right shift.} */
  1811. 5 >> 2 @result{} 1
  1812. @end example
  1813. @noindent
  1814. The left operand is the value to be shifted, and the right operand
  1815. says how many bits to shift it (the @dfn{shift count}). The left
  1816. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1817. operates on a narrow integer type; it's always either @code{int} or
  1818. wider. The value of the shift operator has the same type as the
  1819. promoted left operand.
  1820. @menu
  1821. * Bits Shifted In:: How shifting makes new bits to shift in.
  1822. * Shift Caveats:: Caveats of shift operations.
  1823. * Shift Hacks:: Clever tricks with shift operations.
  1824. @end menu
  1825. @node Bits Shifted In
  1826. @subsection Shifting Makes New Bits
  1827. A shift operation shifts towards one end of the number and has to
  1828. generate new bits at the other end.
  1829. Shifting left one bit must generate a new least significant bit. It
  1830. always brings in zero there. It is equivalent to multiplying by the
  1831. appropriate power of 2. For example,
  1832. @example
  1833. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1834. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1835. @end example
  1836. The meaning of shifting right depends on whether the data type is
  1837. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1838. data type, it performs ``arithmetic shift,'' which keeps the number's
  1839. sign unchanged by duplicating the sign bit. For an unsigned data
  1840. type, it performs ``logical shift,'' which always shifts in zeros at
  1841. the most significant bit.
  1842. In both cases, shifting right one bit is division by two, rounding
  1843. towards negative infinity. For example,
  1844. @example
  1845. (unsigned) 19 >> 2 @result{} 4
  1846. (unsigned) 20 >> 2 @result{} 5
  1847. (unsigned) 21 >> 2 @result{} 5
  1848. @end example
  1849. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1850. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1851. zero.
  1852. The shift count must be zero or greater. Shifting by a negative
  1853. number of bits gives machine-dependent results.
  1854. @node Shift Caveats
  1855. @subsection Caveats for Shift Operations
  1856. @strong{Warning:} If the shift count is greater than or equal to the
  1857. width in bits of the first operand, the results are machine-dependent.
  1858. Logically speaking, the ``correct'' value would be either -1 (for
  1859. right shift of a negative number) or 0 (in all other cases), but what
  1860. it really generates is whatever the machine's shift instruction does in
  1861. that case. So unless you can prove that the second operand is not too
  1862. large, write code to check it at run time.
  1863. @strong{Warning:} Never rely on how the shift operators relate in
  1864. precedence to other arithmetic binary operators. Programmers don't
  1865. remember these precedences, and won't understand the code. Always use
  1866. parentheses to explicitly specify the nesting, like this:
  1867. @example
  1868. a + (b << 5) /* @r{Shift first, then add.} */
  1869. (a + b) << 5 /* @r{Add first, then shift.} */
  1870. @end example
  1871. Note: according to the C standard, shifting of signed values isn't
  1872. guaranteed to work properly when the value shifted is negative, or
  1873. becomes negative during the operation of shifting left. However, only
  1874. pedants have a reason to be concerned about this; only computers with
  1875. strange shift instructions could plausibly do this wrong. In GNU C,
  1876. the operation always works as expected,
  1877. @node Shift Hacks
  1878. @subsection Shift Hacks
  1879. You can use the shift operators for various useful hacks. For
  1880. example, given a date specified by day of the month @code{d}, month
  1881. @code{m}, and year @code{y}, you can store the entire date in a single
  1882. integer @code{date}:
  1883. @example
  1884. unsigned int d = 12;
  1885. unsigned int m = 6;
  1886. unsigned int y = 1983;
  1887. unsigned int date = ((y << 4) + m) << 5) + d;
  1888. @end example
  1889. @noindent
  1890. To extract the original day, month, and year out of
  1891. @code{date}, use a combination of shift and remainder.
  1892. @example
  1893. d = date % 32;
  1894. m = (date >> 5) % 16;
  1895. y = date >> 9;
  1896. @end example
  1897. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1898. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1899. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1900. multiplication, since negating a value is equivalent to multiplying it
  1901. by @minus{}1.
  1902. @node Bitwise Operations
  1903. @section Bitwise Operations
  1904. @cindex bitwise operators
  1905. @cindex operators, bitwise
  1906. @cindex negation, bitwise
  1907. @cindex conjunction, bitwise
  1908. @cindex disjunction, bitwise
  1909. Bitwise operators operate on integers, treating each bit independently.
  1910. They are not allowed for floating-point types.
  1911. The examples in this section use binary constants, starting with
  1912. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1913. of type @code{int}.
  1914. @table @code
  1915. @item ~@code{a}
  1916. Unary operator for bitwise negation; this changes each bit of
  1917. @code{a} from 1 to 0 or from 0 to 1.
  1918. @example
  1919. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1920. ~0 @result{} 0b11111111111111111111111111111111
  1921. ~0b11111111111111111111111111111111 @result{} 0
  1922. ~ (-1) @result{} 0
  1923. @end example
  1924. It is useful to remember that @code{~@var{x} + 1} equals
  1925. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1926. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1927. as @var{x}.
  1928. @item @code{a} & @code{b}
  1929. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1930. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1931. @example
  1932. 0b10101010 & 0b11001100 @result{} 0b10001000
  1933. @end example
  1934. @item @code{a} | @code{b}
  1935. Binary operator for bitwise ``or'' (``inclusive or'' or
  1936. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1937. either @code{a} or @code{b}.
  1938. @example
  1939. 0b10101010 | 0b11001100 @result{} 0b11101110
  1940. @end example
  1941. @item @code{a} ^ @code{b}
  1942. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1943. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1944. @example
  1945. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1946. @end example
  1947. @end table
  1948. To understand the effect of these operators on signed integers, keep
  1949. in mind that all modern computers use two's-complement representation
  1950. (@pxref{Integer Representations}) for negative integers. This means
  1951. that the highest bit of the number indicates the sign; it is 1 for a
  1952. negative number and 0 for a positive number. In a negative number,
  1953. the value in the other bits @emph{increases} as the number gets closer
  1954. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1955. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1956. @strong{Warning:} C defines a precedence ordering for the bitwise
  1957. binary operators, but you should never rely on it. You should
  1958. never rely on how bitwise binary operators relate in precedence to the
  1959. arithmetic and shift binary operators. Other programmers don't
  1960. remember this precedence ordering, so always use parentheses to
  1961. explicitly specify the nesting.
  1962. For example, suppose @code{offset} is an integer that specifies
  1963. the offset within shared memory of a table, except that its bottom few
  1964. bits (@code{LOWBITS} says how many) are special flags. Here's
  1965. how to get just that offset and add it to the base address.
  1966. @example
  1967. shared_mem_base + (offset & (-1 << LOWBITS))
  1968. @end example
  1969. Thanks to the outer set of parentheses, we don't need to know whether
  1970. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1971. set, we don't need to know whether @samp{&} has higher precedence than
  1972. @samp{<<}. But we can rely on all unary operators to have higher
  1973. precedence than any binary operator, so we don't need parentheses
  1974. around the left operand of @samp{<<}.
  1975. @node Assignment Expressions
  1976. @chapter Assignment Expressions
  1977. @cindex assignment expressions
  1978. @cindex operators, assignment
  1979. As a general concept in programming, an @dfn{assignment} is a
  1980. construct that stores a new value into a place where values can be
  1981. stored---for instance, in a variable. Such places are called
  1982. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1983. An assignment in C is an expression because it has a value; we call
  1984. it an @dfn{assignment expression}. A simple assignment looks like
  1985. @example
  1986. @var{lvalue} = @var{value-to-store}
  1987. @end example
  1988. @noindent
  1989. We say it assigns the value of the expression @var{value-to-store} to
  1990. the location @var{lvalue}, or that it stores @var{value-to-store}
  1991. there. You can think of the ``l'' in ``lvalue'' as standing for
  1992. ``left,'' since that's what you put on the left side of the assignment
  1993. operator.
  1994. However, that's not the only way to use an lvalue, and not all lvalues
  1995. can be assigned to. To use the lvalue in the left side of an
  1996. assignment, it has to be @dfn{modifiable}. In C, that means it was
  1997. not declared with the type qualifier @code{const} (@pxref{const}).
  1998. The value of the assignment expression is that of @var{lvalue} after
  1999. the new value is stored in it. This means you can use an assignment
  2000. inside other expressions. Assignment operators are right-associative
  2001. so that
  2002. @example
  2003. x = y = z = 0;
  2004. @end example
  2005. @noindent
  2006. is equivalent to
  2007. @example
  2008. x = (y = (z = 0));
  2009. @end example
  2010. This is the only useful way for them to associate;
  2011. the other way,
  2012. @example
  2013. ((x = y) = z) = 0;
  2014. @end example
  2015. @noindent
  2016. would be invalid since an assignment expression such as @code{x = y}
  2017. is not valid as an lvalue.
  2018. @strong{Warning:} Write parentheses around an assignment if you nest
  2019. it inside another expression, unless that is a conditional expression,
  2020. or comma-separated series, or another assignment.
  2021. @menu
  2022. * Simple Assignment:: The basics of storing a value.
  2023. * Lvalues:: Expressions into which a value can be stored.
  2024. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2025. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2026. an lvalue's contents.
  2027. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2028. * Assignment in Subexpressions:: How to avoid ambiguity.
  2029. * Write Assignments Separately:: Write assignments as separate statements.
  2030. @end menu
  2031. @node Simple Assignment
  2032. @section Simple Assignment
  2033. @cindex simple assignment
  2034. @cindex assignment, simple
  2035. A @dfn{simple assignment expression} computes the value of the right
  2036. operand and stores it into the lvalue on the left. Here is a simple
  2037. assignment expression that stores 5 in @code{i}:
  2038. @example
  2039. i = 5
  2040. @end example
  2041. @noindent
  2042. We say that this is an @dfn{assignment to} the variable @code{i} and
  2043. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2044. because it is an expression (so it has a value). Adding a semicolon
  2045. at the end would make it a statement (@pxref{Expression Statement}).
  2046. Here is another example of a simple assignment expression. Its
  2047. operands are not simple, but the kind of assignment done here is
  2048. simple assignment.
  2049. @example
  2050. x[foo ()] = y + 6
  2051. @end example
  2052. A simple assignment with two different numeric data types converts the
  2053. right operand value to the lvalue's type, if possible. It can convert
  2054. any numeric type to any other numeric type.
  2055. Simple assignment is also allowed on some non-numeric types: pointers
  2056. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2057. unions (@pxref{Unions}).
  2058. @strong{Warning:} Assignment is not allowed on arrays because
  2059. there are no array values in C; C variables can be arrays, but these
  2060. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2061. Arrays}.
  2062. @xref{Assignment Type Conversions}, for the complete rules about data
  2063. types used in assignments.
  2064. @node Lvalues
  2065. @section Lvalues
  2066. @cindex lvalues
  2067. An expression that identifies a memory space that holds a value is
  2068. called an @dfn{lvalue}, because it is a location that can hold a value.
  2069. The standard kinds of lvalues are:
  2070. @itemize @bullet
  2071. @item
  2072. A variable.
  2073. @item
  2074. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2075. unary @samp{*}.
  2076. @item
  2077. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2078. the structure value is an lvalue.
  2079. @item
  2080. A structure field reference using @samp{->}. This is always an lvalue
  2081. since @samp{->} implies pointer dereference.
  2082. @item
  2083. A union alternative reference (@pxref{Unions}), on the same conditions
  2084. as for structure fields.
  2085. @item
  2086. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2087. is an lvalue.
  2088. @end itemize
  2089. If an expression's outermost operation is any other operator, that
  2090. expression is not an lvalue. Thus, the variable @code{x} is an
  2091. lvalue, but @code{x + 0} is not, even though these two expressions
  2092. compute the same value (assuming @code{x} is a number).
  2093. An array can be an lvalue (the rules above determine whether it is
  2094. one), but using the array in an expression converts it automatically
  2095. to a pointer to the first element. The result of this conversion is
  2096. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2097. use @code{a} by itself as the left operand of an assignment. But you
  2098. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2099. lvalue since @code{a} is an lvalue.
  2100. @node Modifying Assignment
  2101. @section Modifying Assignment
  2102. @cindex modifying assignment
  2103. @cindex assignment, modifying
  2104. You can abbreviate the common construct
  2105. @example
  2106. @var{lvalue} = @var{lvalue} + @var{expression}
  2107. @end example
  2108. @noindent
  2109. as
  2110. @example
  2111. @var{lvalue} += @var{expression}
  2112. @end example
  2113. This is known as a @dfn{modifying assignment}. For instance,
  2114. @example
  2115. i = i + 5;
  2116. i += 5;
  2117. @end example
  2118. @noindent
  2119. shows two statements that are equivalent. The first uses
  2120. simple assignment; the second uses modifying assignment.
  2121. Modifying assignment works with any binary arithmetic operator. For
  2122. instance, you can subtract something from an lvalue like this,
  2123. @example
  2124. @var{lvalue} -= @var{expression}
  2125. @end example
  2126. @noindent
  2127. or multiply it by a certain amount like this,
  2128. @example
  2129. @var{lvalue} *= @var{expression}
  2130. @end example
  2131. @noindent
  2132. or shift it by a certain amount like this.
  2133. @example
  2134. @var{lvalue} <<= @var{expression}
  2135. @var{lvalue} >>= @var{expression}
  2136. @end example
  2137. In most cases, this feature adds no power to the language, but it
  2138. provides substantial convenience. Also, when @var{lvalue} contains
  2139. code that has side effects, the simple assignment performs those side
  2140. effects twice, while the modifying assignment performs them once. For
  2141. instance,
  2142. @example
  2143. x[foo ()] = x[foo ()] + 5;
  2144. @end example
  2145. @noindent
  2146. calls @code{foo} twice, and it could return different values each
  2147. time. If @code{foo ()} returns 1 the first time and 3 the second
  2148. time, then the effect could be to add @code{x[3]} and 5 and store the
  2149. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2150. result in @code{x[3]}. We don't know which of the two it will do,
  2151. because C does not specify which call to @code{foo} is computed first.
  2152. Such a statement is not well defined, and shouldn't be used.
  2153. By contrast,
  2154. @example
  2155. x[foo ()] += 5;
  2156. @end example
  2157. @noindent
  2158. is well defined: it calls @code{foo} only once to determine which
  2159. element of @code{x} to adjust, and it adjusts that element by adding 5
  2160. to it.
  2161. @node Increment/Decrement
  2162. @section Increment and Decrement Operators
  2163. @cindex increment operator
  2164. @cindex decrement operator
  2165. @cindex operator, increment
  2166. @cindex operator, decrement
  2167. @cindex preincrement expression
  2168. @cindex predecrement expression
  2169. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2170. @dfn{decrement} operators. When used on a numeric value, they add or
  2171. subtract 1. We don't consider them assignments, but they are
  2172. equivalent to assignments.
  2173. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2174. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2175. and the result becomes the expression's value. For instance,
  2176. @example
  2177. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2178. int
  2179. main (void)
  2180. @{
  2181. int i = 5;
  2182. printf ("%d\n", i);
  2183. printf ("%d\n", ++i);
  2184. printf ("%d\n", i);
  2185. return 0;
  2186. @}
  2187. @end example
  2188. @noindent
  2189. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2190. increments @code{i} from 5 to 6, and has the value 6, so the output
  2191. from @code{printf} on that line says @samp{6}.
  2192. Using @samp{--} instead, for predecrement,
  2193. @example
  2194. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2195. int
  2196. main (void)
  2197. @{
  2198. int i = 5;
  2199. printf ("%d\n", i);
  2200. printf ("%d\n", --i);
  2201. printf ("%d\n", i);
  2202. return 0;
  2203. @}
  2204. @end example
  2205. @noindent
  2206. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2207. again @samp{4}.
  2208. @node Postincrement/Postdecrement
  2209. @section Postincrement and Postdecrement
  2210. @cindex postincrement expression
  2211. @cindex postdecrement expression
  2212. @cindex operator, postincrement
  2213. @cindex operator, postdecrement
  2214. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2215. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2216. increments or decrement it. Thus, the value of @code{i++} is the same
  2217. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2218. little later.'' This is called @dfn{postincrement} or
  2219. @dfn{postdecrement}.
  2220. For example,
  2221. @example
  2222. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2223. int
  2224. main (void)
  2225. @{
  2226. int i = 5;
  2227. printf ("%d\n", i);
  2228. printf ("%d\n", i++);
  2229. printf ("%d\n", i);
  2230. return 0;
  2231. @}
  2232. @end example
  2233. @noindent
  2234. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2235. has the value 5, which is the value of @code{i} at the time,
  2236. but it increments @code{i} from 5 to 6 just a little later.
  2237. How much later is ``just a little later''? That is flexible. The
  2238. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2239. that means by the end of the statement. @xref{Sequence Points}.
  2240. If a unary operator precedes a postincrement or postincrement expression,
  2241. the increment nests inside:
  2242. @example
  2243. -a++ @r{is equivalent to} -(a++)
  2244. @end example
  2245. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2246. it can't be incremented.
  2247. @node Assignment in Subexpressions
  2248. @section Pitfall: Assignment in Subexpressions
  2249. @cindex assignment in subexpressions
  2250. @cindex subexpressions, assignment in
  2251. In C, the order of computing parts of an expression is not fixed.
  2252. Aside from a few special cases, the operations can be computed in any
  2253. order. If one part of the expression has an assignment to @code{x}
  2254. and another part of the expression uses @code{x}, the result is
  2255. unpredictable because that use might be computed before or after the
  2256. assignment.
  2257. Here's an example of ambiguous code:
  2258. @example
  2259. x = 20;
  2260. printf ("%d %d\n", x, x = 4);
  2261. @end example
  2262. @noindent
  2263. If the second argument, @code{x}, is computed before the third argument,
  2264. @code{x = 4}, the second argument's value will be 20. If they are
  2265. computed in the other order, the second argument's value will be 4.
  2266. Here's one way to make that code unambiguous:
  2267. @example
  2268. y = 20;
  2269. printf ("%d %d\n", y, x = 4);
  2270. @end example
  2271. Here's another way, with the other meaning:
  2272. @example
  2273. x = 4;
  2274. printf ("%d %d\n", x, x);
  2275. @end example
  2276. This issue applies to all kinds of assignments, and to the increment
  2277. and decrement operators, which are equivalent to assignments.
  2278. @xref{Order of Execution}, for more information about this.
  2279. However, it can be useful to write assignments inside an
  2280. @code{if}-condition or @code{while}-test along with logical operators.
  2281. @xref{Logicals and Assignments}.
  2282. @node Write Assignments Separately
  2283. @section Write Assignments in Separate Statements
  2284. It is often convenient to write an assignment inside an
  2285. @code{if}-condition, but that can reduce the readability of the
  2286. program. Here's an example of what to avoid:
  2287. @example
  2288. if (x = advance (x))
  2289. @r{@dots{}}
  2290. @end example
  2291. The idea here is to advance @code{x} and test if the value is nonzero.
  2292. However, readers might miss the fact that it uses @samp{=} and not
  2293. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2294. inside a condition is a common error, so GNU C can give warnings when
  2295. @samp{=} appears in a way that suggests it's an error.
  2296. It is much clearer to write the assignment as a separate statement, like this:
  2297. @example
  2298. x = advance (x);
  2299. if (x != 0)
  2300. @r{@dots{}}
  2301. @end example
  2302. @noindent
  2303. This makes it unmistakably clear that @code{x} is assigned a new value.
  2304. Another method is to use the comma operator (@pxref{Comma Operator}),
  2305. like this:
  2306. @example
  2307. if (x = advance (x), x != 0)
  2308. @r{@dots{}}
  2309. @end example
  2310. @noindent
  2311. However, putting the assignment in a separate statement is usually clearer
  2312. unless the assignment is very short, because it reduces nesting.
  2313. @node Execution Control Expressions
  2314. @chapter Execution Control Expressions
  2315. @cindex execution control expressions
  2316. @cindex expressions, execution control
  2317. This chapter describes the C operators that combine expressions to
  2318. control which of those expressions execute, or in which order.
  2319. @menu
  2320. * Logical Operators:: Logical conjunction, disjunction, negation.
  2321. * Logicals and Comparison:: Logical operators with comparison operators.
  2322. * Logicals and Assignments:: Assignments with logical operators.
  2323. * Conditional Expression:: An if/else construct inside expressions.
  2324. * Comma Operator:: Build a sequence of subexpressions.
  2325. @end menu
  2326. @node Logical Operators
  2327. @section Logical Operators
  2328. @cindex logical operators
  2329. @cindex operators, logical
  2330. @cindex conjunction operator
  2331. @cindex disjunction operator
  2332. @cindex negation operator, logical
  2333. The @dfn{logical operators} combine truth values, which are normally
  2334. represented in C as numbers. Any expression with a numeric value is a
  2335. valid truth value: zero means false, and any other value means true.
  2336. A pointer type is also meaningful as a truth value; a null pointer
  2337. (which is zero) means false, and a non-null pointer means true
  2338. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2339. or 0 and has type @code{int} (@pxref{Integer Types}).
  2340. The logical operators are used mainly in the condition of an @code{if}
  2341. statement, or in the end test in a @code{for} statement or
  2342. @code{while} statement (@pxref{Statements}). However, they are valid
  2343. in any context where an integer-valued expression is allowed.
  2344. @table @samp
  2345. @item ! @var{exp}
  2346. Unary operator for logical ``not.'' The value is 1 (true) if
  2347. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2348. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2349. function call, you should write parentheses around it.
  2350. @item @var{left} && @var{right}
  2351. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2352. @var{right}. If both of the operands are true, the @samp{&&} expression
  2353. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2354. gives the value 0 (false). If @var{left} yields a false value,
  2355. that determines the overall result, so @var{right} is not computed.
  2356. @item @var{left} || @var{right}
  2357. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2358. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2359. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2360. gives the value 0 (false). If @var{left} yields a true value,
  2361. that determines the overall result, so @var{right} is not computed.
  2362. @end table
  2363. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2364. and @samp{||}. When you use them together, always use parentheses to
  2365. specify explicitly how they nest, as shown here:
  2366. @example
  2367. if ((r != 0 && x % r == 0)
  2368. ||
  2369. (s != 0 && x % s == 0))
  2370. @end example
  2371. @node Logicals and Comparison
  2372. @section Logical Operators and Comparisons
  2373. The most common thing to use inside the logical operators is a
  2374. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2375. precedence than comparison operators and arithmetic operators, so we
  2376. can write expressions like this without parentheses and get the
  2377. nesting that is natural: two comparison operations that must both be
  2378. true.
  2379. @example
  2380. if (r != 0 && x % r == 0)
  2381. @end example
  2382. @noindent
  2383. This example also shows how it is useful that @samp{&&} guarantees to
  2384. skip the right operand if the left one turns out false. Because of
  2385. that, this code never tries to divide by zero.
  2386. This is equivalent:
  2387. @example
  2388. if (r && x % r == 0)
  2389. @end example
  2390. @noindent
  2391. A truth value is simply a number, so @code{r}
  2392. as a truth value tests whether it is nonzero.
  2393. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2394. So it is better style to write the explicit @code{!= 0}.
  2395. Here's another equivalent way to write it:
  2396. @example
  2397. if (!(r == 0) && x % r == 0)
  2398. @end example
  2399. @noindent
  2400. This illustrates the unary @samp{!} operator, and the need to
  2401. write parentheses around its operand.
  2402. @node Logicals and Assignments
  2403. @section Logical Operators and Assignments
  2404. There are cases where assignments nested inside the condition can
  2405. actually make a program @emph{easier} to read. Here is an example
  2406. using a hypothetical type @code{list} which represents a list; it
  2407. tests whether the list has at least two links, using hypothetical
  2408. functions, @code{nonempty} which is true of the argument is a nonempty
  2409. list, and @code{list_next} which advances from one list link to the
  2410. next. We assume that a list is never a null pointer, so that the
  2411. assignment expressions are always ``true.''
  2412. @example
  2413. if (nonempty (list)
  2414. && (temp1 = list_next (list))
  2415. && nonempty (temp1)
  2416. && (temp2 = list_next (temp1)))
  2417. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2418. @end example
  2419. @noindent
  2420. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2421. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2422. only natural place to put the assignments is among those calls.
  2423. It would be possible to rewrite this as several statements, but that
  2424. could make it much more cumbersome. On the other hand, when the test
  2425. is even more complex than this one, splitting it into multiple
  2426. statements might be necessary for clarity.
  2427. If an empty list is a null pointer, we can dispense with calling
  2428. @code{nonempty}:
  2429. @example
  2430. if ((temp1 = list_next (list))
  2431. && (temp2 = list_next (temp1)))
  2432. @r{@dots{}}
  2433. @end example
  2434. @node Conditional Expression
  2435. @section Conditional Expression
  2436. @cindex conditional expression
  2437. @cindex expression, conditional
  2438. C has a conditional expression that selects one of two expressions
  2439. to compute and get the value from. It looks like this:
  2440. @example
  2441. @var{condition} ? @var{iftrue} : @var{iffalse}
  2442. @end example
  2443. @menu
  2444. * Conditional Rules:: Rules for the conditional operator.
  2445. * Conditional Branches:: About the two branches in a conditional.
  2446. @end menu
  2447. @node Conditional Rules
  2448. @subsection Rules for Conditional Operator
  2449. The first operand, @var{condition}, should be a value that can be
  2450. compared with zero---a number or a pointer. If it is true (nonzero),
  2451. then the conditional expression computes @var{iftrue} and its value
  2452. becomes the value of the conditional expression. Otherwise the
  2453. conditional expression computes @var{iffalse} and its value becomes
  2454. the value of the conditional expression. The conditional expression
  2455. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2456. of them.
  2457. Here's an example: the absolute value of a number @code{x}
  2458. can be written as @code{(x >= 0 ? x : -x)}.
  2459. @strong{Warning:} The conditional expression operators have rather low
  2460. syntactic precedence. Except when the conditional expression is used
  2461. as an argument in a function call, write parentheses around it. For
  2462. clarity, always write parentheses around it if it extends across more
  2463. than one line.
  2464. Assignment operators and the comma operator (@pxref{Comma Operator})
  2465. have lower precedence than conditional expression operators, so write
  2466. parentheses around those when they appear inside a conditional
  2467. expression. @xref{Order of Execution}.
  2468. @node Conditional Branches
  2469. @subsection Conditional Operator Branches
  2470. @cindex branches of conditional expression
  2471. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2472. conditional.
  2473. The two branches should normally have the same type, but a few
  2474. exceptions are allowed. If they are both numeric types, the
  2475. conditional converts both to their common type (@pxref{Common Type}).
  2476. With pointers (@pxref{Pointers}), the two values can be pointers to
  2477. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2478. result type is a similar pointer whose target type combines all the
  2479. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2480. If one branch has type @code{void *} and the other is a pointer to an
  2481. object (not to a function), the conditional converts the @code{void *}
  2482. branch to the type of the other.
  2483. If one branch is an integer constant with value zero and the other is
  2484. a pointer, the conditional converts zero to the pointer's type.
  2485. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2486. that case, if @var{condition} is nonzero, its value becomes the value of
  2487. the conditional expression, after conversion to the common type.
  2488. Thus,
  2489. @example
  2490. x ? : y
  2491. @end example
  2492. @noindent
  2493. has the value of @code{x} if that is nonzero; otherwise, the value of
  2494. @code{y}.
  2495. @cindex side effect in ?:
  2496. @cindex ?: side effect
  2497. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2498. In that case, writing that expression twice would carry out the side
  2499. effects twice, but writing it once does them just once. For example,
  2500. if we suppose that the function @code{next_element} advances a pointer
  2501. variable to point to the next element in a list and returns the new
  2502. pointer,
  2503. @example
  2504. next_element () ? : default_pointer
  2505. @end example
  2506. @noindent
  2507. is a way to advance the pointer and use its new value if it isn't
  2508. null, but use @code{default_pointer} if that is null. We must not do
  2509. it this way,
  2510. @example
  2511. next_element () ? next_element () : default_pointer
  2512. @end example
  2513. @noindent
  2514. because it would advance the pointer a second time.
  2515. @node Comma Operator
  2516. @section Comma Operator
  2517. @cindex comma operator
  2518. @cindex operator, comma
  2519. The comma operator stands for sequential execution of expressions.
  2520. The value of the comma expression comes from the last expression in
  2521. the sequence; the previous expressions are computed only for their
  2522. side effects. It looks like this:
  2523. @example
  2524. @var{exp1}, @var{exp2} @r{@dots{}}
  2525. @end example
  2526. @noindent
  2527. You can bundle any number of expressions together this way, by putting
  2528. commas between them.
  2529. @menu
  2530. * Uses of Comma:: When to use the comma operator.
  2531. * Clean Comma:: Clean use of the comma operator.
  2532. * Avoid Comma:: When to not use the comma operator.
  2533. @end menu
  2534. @node Uses of Comma
  2535. @subsection The Uses of the Comma Operator
  2536. With commas, you can put several expressions into a place that
  2537. requires just one expression---for example, in the header of a
  2538. @code{for} statement. This statement
  2539. @example
  2540. for (i = 0, j = 10, k = 20; i < n; i++)
  2541. @end example
  2542. @noindent
  2543. contains three assignment expressions, to initialize @code{i}, @code{j}
  2544. and @code{k}. The syntax of @code{for} requires just one expression
  2545. for initialization; to include three assignments, we use commas to
  2546. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2547. 20}. This technique is also useful in the loop-advance expression,
  2548. the last of the three inside the @code{for} parentheses.
  2549. In the @code{for} statement and the @code{while} statement
  2550. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2551. effect before the loop-exit test. For example,
  2552. @example
  2553. while (printf ("At the test, x = %d\n", x), x != 0)
  2554. @end example
  2555. @node Clean Comma
  2556. @subsection Clean Use of the Comma Operator
  2557. Always write parentheses around a series of comma operators, except
  2558. when it is at top level in an expression statement, or within the
  2559. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2560. statement (@pxref{Statements}). For instance, in
  2561. @example
  2562. for (i = 0, j = 10, k = 20; i < n; i++)
  2563. @end example
  2564. @noindent
  2565. the commas between the assignments are clear because they are between
  2566. a parenthesis and a semicolon.
  2567. The arguments in a function call are also separated by commas, but that is
  2568. not an instance of the comma operator. Note the difference between
  2569. @example
  2570. foo (4, 5, 6)
  2571. @end example
  2572. @noindent
  2573. which passes three arguments to @code{foo} and
  2574. @example
  2575. foo ((4, 5, 6))
  2576. @end example
  2577. @noindent
  2578. which uses the comma operator and passes just one argument
  2579. (with value 6).
  2580. @strong{Warning:} don't use the comma operator around an argument
  2581. of a function unless it helps understand the code. When you do so,
  2582. don't put part of another argument on the same line. Instead, add a
  2583. line break to make the parentheses around the comma operator easier to
  2584. see, like this.
  2585. @example
  2586. foo ((mumble (x, y), frob (z)),
  2587. *p)
  2588. @end example
  2589. @node Avoid Comma
  2590. @subsection When Not to Use the Comma Operator
  2591. You can use a comma in any subexpression, but in most cases it only
  2592. makes the code confusing, and it is clearer to raise all but the last
  2593. of the comma-separated expressions to a higher level. Thus, instead
  2594. of this:
  2595. @example
  2596. x = (y += 4, 8);
  2597. @end example
  2598. @noindent
  2599. it is much clearer to write this:
  2600. @example
  2601. y += 4, x = 8;
  2602. @end example
  2603. @noindent
  2604. or this:
  2605. @example
  2606. y += 4;
  2607. x = 8;
  2608. @end example
  2609. Use commas only in the cases where there is no clearer alternative
  2610. involving multiple statements.
  2611. By contrast, don't hesitate to use commas in the expansion in a macro
  2612. definition. The trade-offs of code clarity are different in that
  2613. case, because the @emph{use} of the macro may improve overall clarity
  2614. so much that the ugliness of the macro's @emph{definition} is a small
  2615. price to pay. @xref{Macros}.
  2616. @node Binary Operator Grammar
  2617. @chapter Binary Operator Grammar
  2618. @cindex binary operator grammar
  2619. @cindex grammar, binary operator
  2620. @cindex operator precedence
  2621. @cindex precedence, operator
  2622. @cindex left-associative
  2623. @dfn{Binary operators} are those that take two operands, one
  2624. on the left and one on the right.
  2625. All the binary operators in C are syntactically left-associative.
  2626. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2627. @var{op} b) @var{op} c}}. However, you should only write repeated
  2628. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2629. @samp{/}, because those cases are clear from algebra. So it is ok to
  2630. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2631. c} or @code{a % b % c}.
  2632. Each C operator has a @dfn{precedence}, which is its rank in the
  2633. grammatical order of the various operators. The operators with the
  2634. highest precedence grab adjoining operands first; these expressions
  2635. then become operands for operators of lower precedence.
  2636. The precedence order of operators in C is fully specified, so any
  2637. combination of operations leads to a well-defined nesting. We state
  2638. only part of the full precedence ordering here because it is bad
  2639. practice for C code to depend on the other cases. For cases not
  2640. specified in this chapter, always use parentheses to make the nesting
  2641. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2642. remembering anything about the C precedence order beyond what's stated
  2643. here. I studied the full precedence table to write the parser, and
  2644. promptly forgot it again. If you need to look up the full precedence order
  2645. to understand some C code, fix the code with parentheses so nobody else
  2646. needs to do that.}
  2647. You can depend on this subsequence of the precedence ordering
  2648. (stated from highest precedence to lowest):
  2649. @enumerate
  2650. @item
  2651. Component access (@samp{.} and @samp{->}).
  2652. @item
  2653. Unary prefix operators.
  2654. @item
  2655. Unary postfix operators.
  2656. @item
  2657. Multiplication, division, and remainder (they have the same precedence).
  2658. @item
  2659. Addition and subtraction (they have the same precedence).
  2660. @item
  2661. Comparisons---but watch out!
  2662. @item
  2663. Logical operators @samp{&&} and @samp{||}---but watch out!
  2664. @item
  2665. Conditional expression with @samp{?} and @samp{:}.
  2666. @item
  2667. Assignments.
  2668. @item
  2669. Sequential execution (the comma operator, @samp{,}).
  2670. @end enumerate
  2671. Two of the lines in the above list say ``but watch out!'' That means
  2672. that the line covers operators with subtly different precedence.
  2673. Never depend on the grammar of C to decide how two comparisons nest;
  2674. instead, always use parentheses to specify their nesting.
  2675. You can let several @samp{&&} operators associate, or several
  2676. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2677. and @samp{||} nest with each other. @xref{Logical Operators}.
  2678. There is one other precedence ordering that code can depend on:
  2679. @enumerate
  2680. @item
  2681. Unary postfix operators.
  2682. @item
  2683. Bitwise and shift operators---but watch out!
  2684. @item
  2685. Conditional expression with @samp{?} and @samp{:}.
  2686. @end enumerate
  2687. The caveat for bitwise and shift operators is like that for logical
  2688. operators: you can let multiple uses of one bitwise operator
  2689. associate, but always use parentheses to control nesting of dissimilar
  2690. operators.
  2691. These lists do not specify any precedence ordering between the bitwise
  2692. and shift operators of the second list and the binary operators above
  2693. conditional expressions in the first list. When they come together,
  2694. parenthesize them. @xref{Bitwise Operations}.
  2695. @node Order of Execution
  2696. @chapter Order of Execution
  2697. @cindex order of execution
  2698. The order of execution of a C program is not always obvious, and not
  2699. necessarily predictable. This chapter describes what you can count on.
  2700. @menu
  2701. * Reordering of Operands:: Operations in C are not necessarily computed
  2702. in the order they are written.
  2703. * Associativity and Ordering:: Some associative operations are performed
  2704. in a particular order; others are not.
  2705. * Sequence Points:: Some guarantees about the order of operations.
  2706. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2707. * Ordering of Operands:: Evaluation order of operands
  2708. and function arguments.
  2709. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2710. only if it has no impact on program results.
  2711. @end menu
  2712. @node Reordering of Operands
  2713. @section Reordering of Operands
  2714. @cindex ordering of operands
  2715. @cindex reordering of operands
  2716. @cindex operand execution ordering
  2717. The C language does not necessarily carry out operations within an
  2718. expression in the order they appear in the code. For instance, in
  2719. this expression,
  2720. @example
  2721. foo () + bar ()
  2722. @end example
  2723. @noindent
  2724. @code{foo} might be called first or @code{bar} might be called first.
  2725. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2726. results can be unpredictable.
  2727. The unpredictable order of computation of subexpressions also makes a
  2728. difference when one of them contains an assignment. We already saw
  2729. this example of bad code,
  2730. @example
  2731. x = 20;
  2732. printf ("%d %d\n", x, x = 4);
  2733. @end example
  2734. @noindent
  2735. in which the second argument, @code{x}, has a different value
  2736. depending on whether it is computed before or after the assignment in
  2737. the third argument.
  2738. @node Associativity and Ordering
  2739. @section Associativity and Ordering
  2740. @cindex associativity and ordering
  2741. An associative binary operator, such as @code{+}, when used repeatedly
  2742. can combine any number of operands. The operands' values may be
  2743. computed in any order.
  2744. If the values are integers and overflow can be ignored, they may be
  2745. combined in any order. Thus, given four functions that return
  2746. @code{unsigned int}, calling them and adding their results as here
  2747. @example
  2748. (foo () + bar ()) + (baz () + quux ())
  2749. @end example
  2750. @noindent
  2751. may add up the results in any order.
  2752. By contrast, arithmetic on signed integers, with overflow significant,
  2753. is not really associative (@pxref{Integer Overflow}). Thus, the
  2754. additions must be done in the order specified, obeying parentheses and
  2755. left-association. That means computing @code{(foo () + bar ())} and
  2756. @code{(baz () + quux ())} first (in either order), then adding the
  2757. two.
  2758. The same applies to arithmetic on floating-point values, since that
  2759. too is not really associative. However, the GCC option
  2760. @option{-funsafe-math-optimizations} allows the compiler to change the
  2761. order of calculation when an associative operation (associative in
  2762. exact mathematics) combines several operands. The option takes effect
  2763. when compiling a module (@pxref{Compilation}). Changing the order
  2764. of association can enable the program to pipeline the floating point
  2765. operations.
  2766. In all these cases, the four function calls can be done in any order.
  2767. There is no right or wrong about that.
  2768. @node Sequence Points
  2769. @section Sequence Points
  2770. @cindex sequence points
  2771. @cindex full expression
  2772. There are some points in the code where C makes limited guarantees
  2773. about the order of operations. These are called @dfn{sequence
  2774. points}. Here is where they occur:
  2775. @itemize @bullet
  2776. @item
  2777. At the end of a @dfn{full expression}; that is to say, an expression
  2778. that is not part of a larger expression. All side effects specified
  2779. by that expression are carried out before execution moves
  2780. on to subsequent code.
  2781. @item
  2782. At the end of the first operand of certain operators: @samp{,},
  2783. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2784. that expression are carried out before any execution of the
  2785. next operand.
  2786. The commas that separate arguments in a function call are @emph{not}
  2787. comma operators, and they do not create sequence points. The rule
  2788. for function arguments and the rule for operands are different
  2789. (@pxref{Ordering of Operands}).
  2790. @item
  2791. Just before calling a function. All side effects specified by the
  2792. argument expressions are carried out before calling the function.
  2793. If the function to be called is not constant---that is, if it is
  2794. computed by an expression---all side effects in that expression are
  2795. carried out before calling the function.
  2796. @end itemize
  2797. The ordering imposed by a sequence point applies locally to a limited
  2798. range of code, as stated above in each case. For instance, the
  2799. ordering imposed by the comma operator does not apply to code outside
  2800. that comma operator. Thus, in this code,
  2801. @example
  2802. (x = 5, foo (x)) + x * x
  2803. @end example
  2804. @noindent
  2805. the sequence point of the comma operator orders @code{x = 5} before
  2806. @code{foo (x)}, but @code{x * x} could be computed before or after
  2807. them.
  2808. @node Postincrement and Ordering
  2809. @section Postincrement and Ordering
  2810. @cindex postincrement and ordering
  2811. @cindex ordering and postincrement
  2812. Ordering requirements are loose with the postincrement and
  2813. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2814. specify side effects to happen ``a little later.'' They must happen
  2815. before the next sequence point, but that still leaves room for various
  2816. meanings. In this expression,
  2817. @example
  2818. z = x++ - foo ()
  2819. @end example
  2820. @noindent
  2821. it's unpredictable whether @code{x} gets incremented before or after
  2822. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2823. it might see the old value or it might see the incremented value.
  2824. In this perverse expression,
  2825. @example
  2826. x = x++
  2827. @end example
  2828. @noindent
  2829. @code{x} will certainly be incremented but the incremented value may
  2830. not stick. If the incrementation of @code{x} happens after the
  2831. assignment to @code{x}, the incremented value will remain in place.
  2832. But if the incrementation happens first, the assignment will overwrite
  2833. that with the not-yet-incremented value, so the expression as a whole
  2834. will leave @code{x} unchanged.
  2835. @node Ordering of Operands
  2836. @section Ordering of Operands
  2837. @cindex ordering of operands
  2838. @cindex operand ordering
  2839. Operands and arguments can be computed in any order, but there are limits to
  2840. this intermixing in GNU C:
  2841. @itemize @bullet
  2842. @item
  2843. The operands of a binary arithmetic operator can be computed in either
  2844. order, but they can't be intermixed: one of them has to come first,
  2845. followed by the other. Any side effects in the operand that's computed
  2846. first are executed before the other operand is computed.
  2847. @item
  2848. That applies to assignment operators too, except that in simple assignment
  2849. the previous value of the left operand is unused.
  2850. @item
  2851. The arguments in a function call can be computed in any order, but
  2852. they can't be intermixed. Thus, one argument is fully computed, then
  2853. another, and so on until they are all done. Any side effects in one argument
  2854. are executed before computation of another argument begins.
  2855. @end itemize
  2856. These rules don't cover side effects caused by postincrement and
  2857. postdecrement operators---those can be deferred up to the next
  2858. sequence point.
  2859. If you want to get pedantic, the fact is that GCC can reorder the
  2860. computations in many other ways provided that doesn't alter the result
  2861. of running the program. However, because they don't alter the result
  2862. of running the program, they are negligible, unless you are concerned
  2863. with the values in certain variables at various times as seen by other
  2864. processes. In those cases, you can use @code{volatile} to prevent
  2865. optimizations that would make them behave strangely. @xref{volatile}.
  2866. @node Optimization and Ordering
  2867. @section Optimization and Ordering
  2868. @cindex optimization and ordering
  2869. @cindex ordering and optimization
  2870. Sequence points limit the compiler's freedom to reorder operations
  2871. arbitrarily, but optimizations can still reorder them if the compiler
  2872. concludes that this won't alter the results. Thus, in this code,
  2873. @example
  2874. x++;
  2875. y = z;
  2876. x++;
  2877. @end example
  2878. @noindent
  2879. there is a sequence point after each statement, so the code is
  2880. supposed to increment @code{x} once before the assignment to @code{y}
  2881. and once after. However, incrementing @code{x} has no effect on
  2882. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2883. the code could be optimized into this:
  2884. @example
  2885. y = z;
  2886. x += 2;
  2887. @end example
  2888. Normally that has no effect except to make the program faster. But
  2889. there are special situations where it can cause trouble due to things
  2890. that the compiler cannot know about, such as shared memory. To limit
  2891. optimization in those places, use the @code{volatile} type qualifier
  2892. (@pxref{volatile}).
  2893. @node Primitive Types
  2894. @chapter Primitive Data Types
  2895. @cindex primitive types
  2896. @cindex types, primitive
  2897. This chapter describes all the primitive data types of C---that is,
  2898. all the data types that aren't built up from other types. They
  2899. include the types @code{int} and @code{double} that we've already covered.
  2900. @menu
  2901. * Integer Types:: Description of integer types.
  2902. * Floating-Point Data Types:: Description of floating-point types.
  2903. * Complex Data Types:: Description of complex number types.
  2904. * The Void Type:: A type indicating no value at all.
  2905. * Other Data Types:: A brief summary of other types.
  2906. * Type Designators:: Referring to a data type abstractly.
  2907. @end menu
  2908. These types are all made up of bytes (@pxref{Storage}).
  2909. @node Integer Types
  2910. @section Integer Data Types
  2911. @cindex integer types
  2912. @cindex types, integer
  2913. Here we describe all the integer types and their basic
  2914. characteristics. @xref{Integers in Depth}, for more information about
  2915. the bit-level integer data representations and arithmetic.
  2916. @menu
  2917. * Basic Integers:: Overview of the various kinds of integers.
  2918. * Signed and Unsigned Types:: Integers can either hold both negative and
  2919. non-negative values, or only non-negative.
  2920. * Narrow Integers:: When to use smaller integer types.
  2921. * Integer Conversion:: Casting a value from one integer type
  2922. to another.
  2923. * Boolean Type:: An integer type for boolean values.
  2924. * Integer Variations:: Sizes of integer types can vary
  2925. across platforms.
  2926. @end menu
  2927. @node Basic Integers
  2928. @subsection Basic Integers
  2929. @findex char
  2930. @findex int
  2931. @findex short int
  2932. @findex long int
  2933. @findex long long int
  2934. Integer data types in C can be signed or unsigned. An unsigned type
  2935. can represent only positive numbers and zero. A signed type can
  2936. represent both positive and negative numbers, in a range spread almost
  2937. equally on both sides of zero.
  2938. Aside from signedness, the integer data types vary in size: how many
  2939. bytes long they are. The size determines how many different integer
  2940. values the type can hold.
  2941. Here's a list of the signed integer data types, with the sizes they
  2942. have on most computers. Each has a corresponding unsigned type; see
  2943. @ref{Signed and Unsigned Types}.
  2944. @table @code
  2945. @item signed char
  2946. One byte (8 bits). This integer type is used mainly for integers that
  2947. represent characters, as part of arrays or other data structures.
  2948. @item short
  2949. @itemx short int
  2950. Two bytes (16 bits).
  2951. @item int
  2952. Four bytes (32 bits).
  2953. @item long
  2954. @itemx long int
  2955. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2956. platform. Typically it is 32 bits on 32-bit computers
  2957. and 64 bits on 64-bit computers, but there are exceptions.
  2958. @item long long
  2959. @itemx long long int
  2960. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2961. incorporated into standard C as of ISO C99.
  2962. @end table
  2963. You can omit @code{int} when you use @code{long} or @code{short}.
  2964. This is harmless and customary.
  2965. @node Signed and Unsigned Types
  2966. @subsection Signed and Unsigned Types
  2967. @cindex signed types
  2968. @cindex unsigned types
  2969. @cindex types, signed
  2970. @cindex types, unsigned
  2971. @findex signed
  2972. @findex unsigned
  2973. An unsigned integer type can represent only positive numbers and zero.
  2974. A signed type can represent both positive and negative number, in a
  2975. range spread almost equally on both sides of zero. For instance,
  2976. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2977. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2978. these types holds 256 different possible values, since they are both 8
  2979. bits wide.
  2980. Write @code{signed} or @code{unsigned} before the type keyword to
  2981. specify a signed or an unsigned type. However, the integer types
  2982. other than @code{char} are signed by default; with them, @code{signed}
  2983. is a no-op.
  2984. Plain @code{char} may be signed or unsigned; this depends on the
  2985. compiler, the machine in use, and its operating system.
  2986. In many programs, it makes no difference whether @code{char} is
  2987. signed. When it does matter, don't leave it to chance; write
  2988. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2989. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2990. Arctic Char. When my meal arrived, I noted that the chef had not
  2991. signed it. So I complained, ``This char is unsigned---I wanted a
  2992. signed char!'' Or rather, I would have said this if I had thought of
  2993. it fast enough.}
  2994. @node Narrow Integers
  2995. @subsection Narrow Integers
  2996. The types that are narrower than @code{int} are rarely used for
  2997. ordinary variables---we declare them @code{int} instead. This is
  2998. because C converts those narrower types to @code{int} for any
  2999. arithmetic. There is literally no reason to declare a local variable
  3000. @code{char}, for instance.
  3001. In particular, if the value is really a character, you should declare
  3002. the variable @code{int}. Not @code{char}! Using that narrow type can
  3003. force the compiler to truncate values for conversion, which is a
  3004. waste. Furthermore, some functions return either a character value,
  3005. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3006. values distinct.
  3007. The narrow integer types are useful as parts of other objects, such as
  3008. arrays and structures. Compare these array declarations, whose sizes
  3009. on 32-bit processors are shown:
  3010. @example
  3011. signed char ac[1000]; /* @r{1000 bytes} */
  3012. short as[1000]; /* @r{2000 bytes} */
  3013. int ai[1000]; /* @r{4000 bytes} */
  3014. long long all[1000]; /* @r{8000 bytes} */
  3015. @end example
  3016. In addition, character strings must be made up of @code{char}s,
  3017. because that's what all the standard library string functions expect.
  3018. Thus, array @code{ac} could be used as a character string, but the
  3019. others could not be.
  3020. @node Integer Conversion
  3021. @subsection Conversion among Integer Types
  3022. C converts between integer types implicitly in many situations. It
  3023. converts the narrow integer types, @code{char} and @code{short}, to
  3024. @code{int} whenever they are used in arithmetic. Assigning a new
  3025. value to an integer variable (or other lvalue) converts the value to
  3026. the variable's type.
  3027. You can also convert one integer type to another explicitly with a
  3028. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3029. The process of conversion to a wider type is straightforward: the
  3030. value is unchanged. The only exception is when converting a negative
  3031. value (in a signed type, obviously) to a wider unsigned type. In that
  3032. case, the result is a positive value with the same bits
  3033. (@pxref{Integers in Depth}).
  3034. @cindex truncation
  3035. Converting to a narrower type, also called @dfn{truncation}, involves
  3036. discarding some of the value's bits. This is not considered overflow
  3037. (@pxref{Integer Overflow}) because loss of significant bits is a
  3038. normal consequence of truncation. Likewise for conversion between
  3039. signed and unsigned types of the same width.
  3040. More information about conversion for assignment is in
  3041. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3042. see @ref{Argument Promotions}.
  3043. @node Boolean Type
  3044. @subsection Boolean Type
  3045. @cindex boolean type
  3046. @cindex type, boolean
  3047. @findex bool
  3048. The unsigned integer type @code{bool} holds truth values: its possible
  3049. values are 0 and 1. Converting any nonzero value to @code{bool}
  3050. results in 1. For example:
  3051. @example
  3052. bool a = 0;
  3053. bool b = 1;
  3054. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3055. @end example
  3056. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3057. the header file @file{stdbool.h}.
  3058. @node Integer Variations
  3059. @subsection Integer Variations
  3060. The integer types of C have standard @emph{names}, but what they
  3061. @emph{mean} varies depending on the kind of platform in use:
  3062. which kind of computer, which operating system, and which compiler.
  3063. It may even depend on the compiler options used.
  3064. Plain @code{char} may be signed or unsigned; this depends on the
  3065. platform, too. Even for GNU C, there is no general rule.
  3066. In theory, all of the integer types' sizes can vary. @code{char} is
  3067. always considered one ``byte'' for C, but it is not necessarily an
  3068. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3069. specifies only that none of these types is narrower than the ones
  3070. above it in the list in @ref{Basic Integers}, and that @code{short}
  3071. has at least 16 bits.
  3072. It is possible that in the future GNU C will support platforms where
  3073. @code{int} is 64 bits long. In practice, however, on today's real
  3074. computers, there is little variation; you can rely on the table
  3075. given previously (@pxref{Basic Integers}).
  3076. To be completely sure of the size of an integer type,
  3077. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3078. Their corresponding unsigned types add @samp{u} at the front.
  3079. To define these, include the header file @file{stdint.h}.
  3080. The GNU C Compiler compiles for some embedded controllers that use two
  3081. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3082. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3083. 32 bits. These processors can't support an ordinary operating system
  3084. (they may have their own specialized operating systems), and most C
  3085. programs do not try to support them.
  3086. @node Floating-Point Data Types
  3087. @section Floating-Point Data Types
  3088. @cindex floating-point types
  3089. @cindex types, floating-point
  3090. @findex double
  3091. @findex float
  3092. @findex long double
  3093. @dfn{Floating point} is the binary analogue of scientific notation:
  3094. internally it represents a number as a fraction and a binary exponent; the
  3095. value is that fraction multiplied by the specified power of 2.
  3096. For instance, to represent 6, the fraction would be 0.75 and the
  3097. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3098. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3099. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3100. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3101. -1 as the exponent.
  3102. These binary exponents are used by machine instructions. You can
  3103. write a floating-point constant this way if you wish, using
  3104. hexadecimal; but normally we write floating-point numbers in decimal.
  3105. @xref{Floating Constants}.
  3106. C has three floating-point data types:
  3107. @table @code
  3108. @item double
  3109. ``Double-precision'' floating point, which uses 64 bits. This is the
  3110. normal floating-point type, and modern computers normally do
  3111. their floating-point computations in this type, or some wider type.
  3112. Except when there is a special reason to do otherwise, this is the
  3113. type to use for floating-point values.
  3114. @item float
  3115. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3116. for floating-point values stored in structures and arrays, to save
  3117. space when the full precision of @code{double} is not needed. In
  3118. addition, single-precision arithmetic is faster on some computers, and
  3119. occasionally that is useful. But not often---most programs don't use
  3120. the type @code{float}.
  3121. C would be cleaner if @code{float} were the name of the type we
  3122. use for most floating-point values; however, for historical reasons,
  3123. that's not so.
  3124. @item long double
  3125. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3126. precision, depending on the machine in use. On some machines, which
  3127. have no floating-point format wider than @code{double}, this is
  3128. equivalent to @code{double}.
  3129. @end table
  3130. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3131. Point in Depth}, for more information.
  3132. @node Complex Data Types
  3133. @section Complex Data Types
  3134. @cindex complex numbers
  3135. @cindex types, complex
  3136. @cindex @code{_Complex} keyword
  3137. @cindex @code{__complex__} keyword
  3138. @findex _Complex
  3139. @findex __complex__
  3140. Complex numbers can include both a real part and an imaginary part.
  3141. The numeric constants covered above have real-numbered values. An
  3142. imaginary-valued constant is an ordinary real-valued constant followed
  3143. by @samp{i}.
  3144. To declare numeric variables as complex, use the @code{_Complex}
  3145. keyword.@footnote{For compatibility with older versions of GNU C, the
  3146. keyword @code{__complex__} is also allowed. Going forward, however,
  3147. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3148. standard C complex data types are floating point,
  3149. @example
  3150. _Complex float foo;
  3151. _Complex double bar;
  3152. _Complex long double quux;
  3153. @end example
  3154. @noindent
  3155. but GNU C supports integer complex types as well.
  3156. Since @code{_Complex} is a keyword just like @code{float} and
  3157. @code{double} and @code{long}, the keywords can appear in any order,
  3158. but the order shown above seems most logical.
  3159. GNU C supports constants for complex values; for instance, @code{4.0 +
  3160. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3161. @xref{Imaginary Constants}.
  3162. To pull the real and imaginary parts of the number back out, GNU C
  3163. provides the keywords @code{__real__} and @code{__imag__}:
  3164. @example
  3165. _Complex double foo = 4.0 + 3.0i;
  3166. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3167. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3168. @end example
  3169. @noindent
  3170. Standard C does not include these keywords, and instead relies on
  3171. functions defined in @code{complex.h} for accessing the real and
  3172. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3173. @code{creall} extract the real part of a float, double, or long double
  3174. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3175. @code{cimagl} extract the imaginary part.
  3176. @cindex complex conjugation
  3177. GNU C also defines @samp{~} as an operator for complex conjugation,
  3178. which means negating the imaginary part of a complex number:
  3179. @example
  3180. _Complex double foo = 4.0 + 3.0i;
  3181. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3182. @end example
  3183. @noindent
  3184. For standard C compatibility, you can use the appropriate library
  3185. function: @code{conjf}, @code{conj}, or @code{confl}.
  3186. @node The Void Type
  3187. @section The Void Type
  3188. @cindex void type
  3189. @cindex type, void
  3190. @findex void
  3191. The data type @code{void} is a dummy---it allows no operations. It
  3192. really means ``no value at all.'' When a function is meant to return
  3193. no value, we write @code{void} for its return type. Then
  3194. @code{return} statements in that function should not specify a value
  3195. (@pxref{return Statement}). Here's an example:
  3196. @example
  3197. void
  3198. print_if_positive (double x, double y)
  3199. @{
  3200. if (x <= 0)
  3201. return;
  3202. if (y <= 0)
  3203. return;
  3204. printf ("Next point is (%f,%f)\n", x, y);
  3205. @}
  3206. @end example
  3207. A @code{void}-returning function is comparable to what some other languages
  3208. call a ``procedure'' instead of a ``function.''
  3209. @c ??? Already presented
  3210. @c @samp{%f} in an output template specifies to format a @code{double} value
  3211. @c as a decimal number, using a decimal point if needed.
  3212. @node Other Data Types
  3213. @section Other Data Types
  3214. Beyond the primitive types, C provides several ways to construct new
  3215. data types. For instance, you can define @dfn{pointers}, values that
  3216. represent the addresses of other data (@pxref{Pointers}). You can
  3217. define @dfn{structures}, as in many other languages
  3218. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3219. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3220. are collections of named integer codes (@pxref{Enumeration Types}).
  3221. @dfn{Array types} in C are used for allocating space for objects,
  3222. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3223. @node Type Designators
  3224. @section Type Designators
  3225. @cindex type designator
  3226. Some C constructs require a way to designate a specific data type
  3227. independent of any particular variable or expression which has that
  3228. type. The way to do this is with a @dfn{type designator}. The
  3229. constucts that need one include casts (@pxref{Explicit Type
  3230. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3231. We also use type designators to talk about the type of a value in C,
  3232. so you will see many type designators in this manual. When we say,
  3233. ``The value has type @code{int},'' @code{int} is a type designator.
  3234. To make the designator for any type, imagine a variable declaration
  3235. for a variable of that type and delete the variable name and the final
  3236. semicolon.
  3237. For example, to designate the type of full-word integers, we start
  3238. with the declaration for a variable @code{foo} with that type,
  3239. which is this:
  3240. @example
  3241. int foo;
  3242. @end example
  3243. @noindent
  3244. Then we delete the variable name @code{foo} and the semicolon, leaving
  3245. @code{int}---exactly the keyword used in such a declaration.
  3246. Therefore, the type designator for this type is @code{int}.
  3247. What about long unsigned integers? From the declaration
  3248. @example
  3249. unsigned long int foo;
  3250. @end example
  3251. @noindent
  3252. we determine that the designator is @code{unsigned long int}.
  3253. Following this procedure, the designator for any primitive type is
  3254. simply the set of keywords which specifies that type in a declaration.
  3255. The same is true for compound types such as structures, unions, and
  3256. enumerations.
  3257. Designators for pointer types do follow the rule of deleting the
  3258. variable name and semicolon, but the result is not so simple.
  3259. @xref{Pointer Type Designators}, as part of the chapter about
  3260. pointers. @xref{Array Type Designators}), for designators for array
  3261. types.
  3262. To understand what type a designator stands for, imagine a variable
  3263. name inserted into the right place in the designator to make a valid
  3264. declaration. What type would that variable be declared as? That is the
  3265. type the designator designates.
  3266. @node Constants
  3267. @chapter Constants
  3268. @cindex constants
  3269. A @dfn{constant} is an expression that stands for a specific value by
  3270. explicitly representing the desired value. C allows constants for
  3271. numbers, characters, and strings. We have already seen numeric and
  3272. string constants in the examples.
  3273. @menu
  3274. * Integer Constants:: Literal integer values.
  3275. * Integer Const Type:: Types of literal integer values.
  3276. * Floating Constants:: Literal floating-point values.
  3277. * Imaginary Constants:: Literal imaginary number values.
  3278. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3279. * Character Constants:: Literal character values.
  3280. * String Constants:: Literal string values.
  3281. * UTF-8 String Constants:: Literal UTF-8 string values.
  3282. * Unicode Character Codes:: Unicode characters represented
  3283. in either UTF-16 or UTF-32.
  3284. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3285. * Wide String Constants:: Literal string values made up of
  3286. 16- or 32-bit characters.
  3287. @end menu
  3288. @node Integer Constants
  3289. @section Integer Constants
  3290. @cindex integer constants
  3291. @cindex constants, integer
  3292. An integer constant consists of a number to specify the value,
  3293. followed optionally by suffix letters to specify the data type.
  3294. The simplest integer constants are numbers written in base 10
  3295. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3296. constant cannot start with the character @samp{0} (zero) because
  3297. that makes the constant octal.
  3298. You can get the effect of a negative integer constant by putting a
  3299. minus sign at the beginning. Grammatically speaking, that is an
  3300. arithmetic expression rather than a constant, but it behaves just like
  3301. a true constant.
  3302. Integer constants can also be written in octal (base 8), hexadecimal
  3303. (base 16), or binary (base 2). An octal constant starts with the
  3304. character @samp{0} (zero), followed by any number of octal digits
  3305. (@samp{0} to @samp{7}):
  3306. @example
  3307. 0 // @r{zero}
  3308. 077 // @r{63}
  3309. 0403 // @r{259}
  3310. @end example
  3311. @noindent
  3312. Pedantically speaking, the constant @code{0} is an octal constant, but
  3313. we can think of it as decimal; it has the same value either way.
  3314. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3315. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3316. through @samp{f} in upper or lower case):
  3317. @example
  3318. 0xff // @r{255}
  3319. 0XA0 // @r{160}
  3320. 0xffFF // @r{65535}
  3321. @end example
  3322. @cindex binary integer constants
  3323. A binary constant starts with @samp{0b} (upper or lower case) followed
  3324. by bits (each represented by the characters @samp{0} or @samp{1}):
  3325. @example
  3326. 0b101 // @r{5}
  3327. @end example
  3328. Binary constants are a GNU C extension, not part of the C standard.
  3329. Sometimes a space is needed after an integer constant to avoid
  3330. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3331. @node Integer Const Type
  3332. @section Integer Constant Data Types
  3333. @cindex integer constant data types
  3334. @cindex constant data types, integer
  3335. @cindex types of integer constants
  3336. The type of an integer constant is normally @code{int}, if the value
  3337. fits in that type, but here are the complete rules. The type
  3338. of an integer constant is the first one in this sequence that can
  3339. properly represent the value,
  3340. @enumerate
  3341. @item
  3342. @code{int}
  3343. @item
  3344. @code{unsigned int}
  3345. @item
  3346. @code{long int}
  3347. @item
  3348. @code{unsigned long int}
  3349. @item
  3350. @code{long long int}
  3351. @item
  3352. @code{unsigned long long int}
  3353. @end enumerate
  3354. @noindent
  3355. and that isn't excluded by the following rules.
  3356. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3357. first two types (non-@code{long}).
  3358. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3359. first four types (non-@code{long long}).
  3360. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3361. the signed types.
  3362. Otherwise, if the constant is decimal, that excludes the unsigned
  3363. types.
  3364. @c ### This said @code{unsigned int} is excluded.
  3365. @c ### See 17 April 2016
  3366. Here are some examples of the suffixes.
  3367. @example
  3368. 3000000000u // @r{three billion as @code{unsigned int}.}
  3369. 0LL // @r{zero as a @code{long long int}.}
  3370. 0403l // @r{259 as a @code{long int}.}
  3371. @end example
  3372. Suffixes in integer constants are rarely used. When the precise type
  3373. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3374. Type Conversion}).
  3375. @xref{Integer Types}.
  3376. @node Floating Constants
  3377. @section Floating-Point Constants
  3378. @cindex floating-point constants
  3379. @cindex constants, floating-point
  3380. A floating-point constant must have either a decimal point, an
  3381. exponent-of-ten, or both; they distinguish it from an integer
  3382. constant.
  3383. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3384. value follows. It is always written as a decimal number; it can
  3385. optionally start with a sign. The exponent @var{n} means to multiply
  3386. the constant's value by ten to the @var{n}th power.
  3387. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3388. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3389. writing a floating-point number whose value is 1500. They are all
  3390. equivalent.
  3391. Here are more examples with decimal points:
  3392. @example
  3393. 1.0
  3394. 1000.
  3395. 3.14159
  3396. .05
  3397. .0005
  3398. @end example
  3399. For each of them, here are some equivalent constants written with
  3400. exponents:
  3401. @example
  3402. 1e0, 1.0000e0
  3403. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3404. 3.14159e0
  3405. 5e-2, .0005e+2, 5E-2, .0005E2
  3406. .05e-2
  3407. @end example
  3408. A floating-point constant normally has type @code{double}. You can
  3409. force it to type @code{float} by adding @samp{f} or @samp{F}
  3410. at the end. For example,
  3411. @example
  3412. 3.14159f
  3413. 3.14159e0f
  3414. 1000.f
  3415. 100E1F
  3416. .0005f
  3417. .05e-2f
  3418. @end example
  3419. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3420. to type @code{long double}.
  3421. You can use exponents in hexadecimal floating constants, but since
  3422. @samp{e} would be interpreted as a hexadecimal digit, the character
  3423. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3424. The exponent in a hexadecimal floating constant is a possibly-signed
  3425. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3426. multiply into the number.
  3427. Here are some examples:
  3428. @example
  3429. @group
  3430. 0xAp2 // @r{40 in decimal}
  3431. 0xAp-1 // @r{5 in decimal}
  3432. 0x2.0Bp4 // @r{16.75 decimal}
  3433. 0xE.2p3 // @r{121 decimal}
  3434. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3435. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3436. 0x100p-8 // @r{1}
  3437. 0x10p-4 // @r{1}
  3438. 0x1p+4 // @r{16}
  3439. 0x1p+8 // @r{256}
  3440. @end group
  3441. @end example
  3442. @xref{Floating-Point Data Types}.
  3443. @node Imaginary Constants
  3444. @section Imaginary Constants
  3445. @cindex imaginary constants
  3446. @cindex complex constants
  3447. @cindex constants, imaginary
  3448. A complex number consists of a real part plus an imaginary part.
  3449. (Either or both parts may be zero.) This section explains how to
  3450. write numeric constants with imaginary values. By adding these to
  3451. ordinary real-valued numeric constants, we can make constants with
  3452. complex values.
  3453. The simple way to write an imaginary-number constant is to attach the
  3454. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3455. floating-point constant. For example, @code{2.5fi} has type
  3456. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3457. The four alternative suffix letters are all equivalent.
  3458. @cindex _Complex_I
  3459. The other way to write an imaginary constant is to multiply a real
  3460. constant by @code{_Complex_I}, which represents the imaginary number
  3461. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3462. this clunky way is needed.
  3463. To write a complex constant with a nonzero real part and a nonzero
  3464. imaginary part, write the two separately and add them, like this:
  3465. @example
  3466. 4.0 + 3.0i
  3467. @end example
  3468. @noindent
  3469. That gives the value 4 + 3i, with type @code{_Complex double}.
  3470. Such a sum can include multiple real constants, or none. Likewise, it
  3471. can include multiple imaginary constants, or none. For example:
  3472. @example
  3473. _Complex double foo, bar, quux;
  3474. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3475. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3476. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3477. @end example
  3478. @xref{Complex Data Types}.
  3479. @node Invalid Numbers
  3480. @section Invalid Numbers
  3481. Some number-like constructs which are not really valid as numeric
  3482. constants are treated as numbers in preprocessing directives. If
  3483. these constructs appear outside of preprocessing, they are erroneous.
  3484. @xref{Preprocessing Tokens}.
  3485. Sometimes we need to insert spaces to separate tokens so that they
  3486. won't be combined into a single number-like construct. For example,
  3487. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3488. constant, so it is a syntax error. If what we want is the three
  3489. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3490. @node Character Constants
  3491. @section Character Constants
  3492. @cindex character constants
  3493. @cindex constants, character
  3494. @cindex escape sequence
  3495. A @dfn{character constant} is written with single quotes, as in
  3496. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3497. character that the constant should represent. The constant has type
  3498. @code{int}, and its value is the character code of that character.
  3499. For instance, @code{'a'} represents the character code for the letter
  3500. @samp{a}: 97, that is.
  3501. To put the @samp{'} character (single quote) in the character
  3502. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3503. constant looks like @code{'\''}. This sort of sequence, starting with
  3504. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3505. here functions as a kind of @dfn{escape character}.
  3506. To put the @samp{\} character (backslash) in the character constant,
  3507. quote it likewise with @samp{\} (another backslash). This character
  3508. constant looks like @code{'\\'}.
  3509. @cindex bell character
  3510. @cindex @samp{\a}
  3511. @cindex backspace
  3512. @cindex @samp{\b}
  3513. @cindex tab (ASCII character)
  3514. @cindex @samp{\t}
  3515. @cindex vertical tab
  3516. @cindex @samp{\v}
  3517. @cindex formfeed
  3518. @cindex @samp{\f}
  3519. @cindex newline
  3520. @cindex @samp{\n}
  3521. @cindex return (ASCII character)
  3522. @cindex @samp{\r}
  3523. @cindex escape (ASCII character)
  3524. @cindex @samp{\e}
  3525. Here are all the escape sequences that represent specific
  3526. characters in a character constant. The numeric values shown are
  3527. the corresponding ASCII character codes, as decimal numbers.
  3528. @example
  3529. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3530. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3531. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3532. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3533. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3534. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3535. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3536. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3537. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3538. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3539. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3540. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3541. @end example
  3542. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3543. You can also write octal and hex character codes as
  3544. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3545. option here, so octal codes do not need to start with @samp{0}.
  3546. The character constant's value has type @code{int}. However, the
  3547. character code is treated initially as a @code{char} value, which is
  3548. then converted to @code{int}. If the character code is greater than
  3549. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3550. on a platform where the type @code{char} is 8 bits long and signed.
  3551. @node String Constants
  3552. @section String Constants
  3553. @cindex string constants
  3554. @cindex constants, string
  3555. A @dfn{string constant} represents a series of characters. It starts
  3556. with @samp{"} and ends with @samp{"}; in between are the contents of
  3557. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3558. newline in the contents works in string constants as in character
  3559. constants. In a string constant, @samp{'} does not need to be quoted.
  3560. A string constant defines an array of characters which contains the
  3561. specified characters followed by the null character (code 0). Using
  3562. the string constant is equivalent to using the name of an array with
  3563. those contents. In simple cases, the length in bytes of the string
  3564. constant is one greater than the number of characters written in it.
  3565. As with any array in C, using the string constant in an expression
  3566. converts the array to a pointer (@pxref{Pointers}) to the array's
  3567. first element (@pxref{Accessing Array Elements}). This pointer will
  3568. have type @code{char *} because it points to an element of type
  3569. @code{char}. @code{char *} is an example of a type designator for a
  3570. pointer type (@pxref{Pointer Type Designators}). That type is used
  3571. for strings generally, not just the strings expressed as constants
  3572. in a program.
  3573. Thus, the string constant @code{"Foo!"} is almost
  3574. equivalent to declaring an array like this
  3575. @example
  3576. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3577. @end example
  3578. @noindent
  3579. and then using @code{string_array_1} in the program. There
  3580. are two differences, however:
  3581. @itemize @bullet
  3582. @item
  3583. The string constant doesn't define a name for the array.
  3584. @item
  3585. The string constant is probably stored in a read-only area of memory.
  3586. @end itemize
  3587. Newlines are not allowed in the text of a string constant. The motive
  3588. for this prohibition is to catch the error of omitting the closing
  3589. @samp{"}. To put a newline in a constant string, write it as
  3590. @samp{\n} in the string constant.
  3591. A real null character in the source code inside a string constant
  3592. causes a warning. To put a null character in the middle of a string
  3593. constant, write @samp{\0} or @samp{\000}.
  3594. Consecutive string constants are effectively concatenated. Thus,
  3595. @example
  3596. "Fo" "o!" @r{is equivalent to} "Foo!"
  3597. @end example
  3598. This is useful for writing a string containing multiple lines,
  3599. like this:
  3600. @example
  3601. "This message is so long that it needs more than\n"
  3602. "a single line of text. C does not allow a newline\n"
  3603. "to represent itself in a string constant, so we have to\n"
  3604. "write \\n to put it in the string. For readability of\n"
  3605. "the source code, it is advisable to put line breaks in\n"
  3606. "the source where they occur in the contents of the\n"
  3607. "constant.\n"
  3608. @end example
  3609. The sequence of a backslash and a newline is ignored anywhere
  3610. in a C program, and that includes inside a string constant.
  3611. Thus, you can write multi-line string constants this way:
  3612. @example
  3613. "This is another way to put newlines in a string constant\n\
  3614. and break the line after them in the source code."
  3615. @end example
  3616. @noindent
  3617. However, concatenation is the recommended way to do this.
  3618. You can also write perverse string constants like this,
  3619. @example
  3620. "Fo\
  3621. o!"
  3622. @end example
  3623. @noindent
  3624. but don't do that---write it like this instead:
  3625. @example
  3626. "Foo!"
  3627. @end example
  3628. Be careful to avoid passing a string constant to a function that
  3629. modifies the string it receives. The memory where the string constant
  3630. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3631. signal that normally terminates the function (@pxref{Signals}. Even
  3632. worse, the memory may not be read-only. Then the function might
  3633. modify the string constant, thus spoiling the contents of other string
  3634. constants that are supposed to contain the same value and are unified
  3635. by the compiler.
  3636. @node UTF-8 String Constants
  3637. @section UTF-8 String Constants
  3638. @cindex UTF-8 String Constants
  3639. Writing @samp{u8} immediately before a string constant, with no
  3640. intervening space, means to represent that string in UTF-8 encoding as
  3641. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3642. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3643. as multibyte sequences. Here is an example of a UTF-8 constant:
  3644. @example
  3645. u8"A cónstàñt"
  3646. @end example
  3647. This constant occupies 13 bytes plus the terminating null,
  3648. because each of the accented letters is a two-byte sequence.
  3649. Concatenating an ordinary string with a UTF-8 string conceptually
  3650. produces another UTF-8 string. However, if the ordinary string
  3651. contains character codes 128 and up, the results cannot be relied on.
  3652. @node Unicode Character Codes
  3653. @section Unicode Character Codes
  3654. @cindex Unicode character codes
  3655. @cindex universal character names
  3656. You can specify Unicode characters, for individual character constants
  3657. or as part of string constants (@pxref{String Constants}), using
  3658. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3659. hexadecimal Unicode character code. If the code value is too big for
  3660. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3661. Unicode character code. (These codes are called @dfn{universal
  3662. character names}.) For example,
  3663. @example
  3664. \u6C34 /* @r{16-bit code (UTF-16)} */
  3665. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3666. @end example
  3667. @noindent
  3668. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3669. Constants}). For instance,
  3670. @example
  3671. u8"fóó \u6C34 \U0010ABCD"
  3672. @end example
  3673. You can also use them in wide character constants (@pxref{Wide
  3674. Character Constants}), like this:
  3675. @example
  3676. u'\u6C34' /* @r{16-bit code} */
  3677. U'\U0010ABCD' /* @r{32-bit code} */
  3678. @end example
  3679. @noindent
  3680. and in wide string constants (@pxref{Wide String Constants}), like
  3681. this:
  3682. @example
  3683. u"\u6C34\u6C33" /* @r{16-bit code} */
  3684. U"\U0010ABCD" /* @r{32-bit code} */
  3685. @end example
  3686. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3687. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3688. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3689. actually ASCII control characters, and you can specify them with other
  3690. escape sequences (@pxref{Character Constants}).
  3691. @node Wide Character Constants
  3692. @section Wide Character Constants
  3693. @cindex wide character constants
  3694. @cindex constants, wide character
  3695. A @dfn{wide character constant} represents characters with more than 8
  3696. bits of character code. This is an obscure feature that we need to
  3697. document but that you probably won't ever use. If you're just
  3698. learning C, you may as well skip this section.
  3699. The original C wide character constant looks like @samp{L} (upper
  3700. case!) followed immediately by an ordinary character constant (with no
  3701. intervening space). Its data type is @code{wchar_t}, which is an
  3702. alias defined in @file{stddef.h} for one of the standard integer
  3703. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3704. it is 16 bits, these character constants use the UTF-16 form of
  3705. Unicode; if 32 bits, UTF-32.
  3706. There are also Unicode wide character constants which explicitly
  3707. specify the width. These constants start with @samp{u} or @samp{U}
  3708. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3709. character constant, and @samp{U} a 32-bit Unicode wide character
  3710. constant. Their types are, respectively, @code{char16_t} and
  3711. @w{@code{char32_t}}; they are declared in the header file
  3712. @file{uchar.h}. These character constants are valid even if
  3713. @file{uchar.h} is not included, but some uses of them may be
  3714. inconvenient without including it to declare those type names.
  3715. The character represented in a wide character constant can be an
  3716. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3717. are all valid, and they are all equal to @code{'a'}.
  3718. In all three kinds of wide character constants, you can write a
  3719. non-ASCII Unicode character in the constant itself; the constant's
  3720. value is the character's Unicode character code. Or you can specify
  3721. the Unicode character with an escape sequence (@pxref{Unicode
  3722. Character Codes}).
  3723. @node Wide String Constants
  3724. @section Wide String Constants
  3725. @cindex wide string constants
  3726. @cindex constants, wide string
  3727. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3728. characters. They are rarely used; if you're just
  3729. learning C, you may as well skip this section.
  3730. There are three kinds of wide string constants, which differ in the
  3731. data type used for each character in the string. Each wide string
  3732. constant is equivalent to an array of integers, but the data type of
  3733. those integers depends on the kind of wide string. Using the constant
  3734. in an expression will convert the array to a pointer to its first
  3735. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3736. For each kind of wide string constant, we state here what type that
  3737. pointer will be.
  3738. @table @code
  3739. @item char16_t
  3740. This is a 16-bit Unicode wide string constant: each element is a
  3741. 16-bit Unicode character code with type @code{char16_t}, so the string
  3742. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3743. @pxref{Pointer Type Designators}.) The constant is written as
  3744. @samp{u} (which must be lower case) followed (with no intervening
  3745. space) by a string constant with the usual syntax.
  3746. @item char32_t
  3747. This is a 32-bit Unicode wide string constant: each element is a
  3748. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3749. It's written as @samp{U} (which must be upper case) followed (with no
  3750. intervening space) by a string constant with the usual syntax.
  3751. @item wchar_t
  3752. This is the original kind of wide string constant. It's written as
  3753. @samp{L} (which must be upper case) followed (with no intervening
  3754. space) by a string constant with the usual syntax, and the string has
  3755. type @code{wchar_t@ *}.
  3756. The width of the data type @code{wchar_t} depends on the target
  3757. platform, which makes this kind of wide string somewhat less useful
  3758. than the newer kinds.
  3759. @end table
  3760. @code{char16_t} and @code{char32_t} are declared in the header file
  3761. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3762. Consecutive wide string constants of the same kind concatenate, just
  3763. like ordinary string constants. A wide string constant concatenated
  3764. with an ordinary string constant results in a wide string constant.
  3765. You can't concatenate two wide string constants of different kinds.
  3766. You also can't concatenate a wide string constant (of any kind) with a
  3767. UTF-8 string constant.
  3768. @node Type Size
  3769. @chapter Type Size
  3770. @cindex type size
  3771. @cindex size of type
  3772. @findex sizeof
  3773. Each data type has a @dfn{size}, which is the number of bytes
  3774. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3775. a C program, use @code{sizeof}. There are two ways to use it:
  3776. @table @code
  3777. @item sizeof @var{expression}
  3778. This gives the size of @var{expression}, based on its data type. It
  3779. does not calculate the value of @var{expression}, only its size, so if
  3780. @var{expression} includes side effects or function calls, they do not
  3781. happen. Therefore, @code{sizeof} is always a compile-time operation
  3782. that has zero run-time cost.
  3783. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3784. operand of @code{sizeof}.
  3785. For example,
  3786. @example
  3787. double a;
  3788. i = sizeof a + 10;
  3789. @end example
  3790. @noindent
  3791. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3792. Here's how to determine the number of elements in an array
  3793. @code{array}:
  3794. @example
  3795. (sizeof array / sizeof array[0])
  3796. @end example
  3797. @noindent
  3798. The expression @code{sizeof array} gives the size of the array, not
  3799. the size of a pointer to an element. However, if @var{expression} is
  3800. a function parameter that was declared as an array, that
  3801. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3802. the result is the size of that pointer.
  3803. @item sizeof (@var{type})
  3804. This gives the size of @var{type}.
  3805. For example,
  3806. @example
  3807. i = sizeof (double) + 10;
  3808. @end example
  3809. @noindent
  3810. is equivalent to the previous example.
  3811. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3812. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3813. C, which makes adding an integer to a function pointer work as desired
  3814. (@pxref{Pointer Arithmetic}).
  3815. @end table
  3816. @strong{Warning}: When you use @code{sizeof} with a type
  3817. instead of an expression, you must write parentheses around the type.
  3818. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3819. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3820. the cast expression to avoid an ambiguity in the grammar of C@.
  3821. Specifically,
  3822. @example
  3823. sizeof (int) -x
  3824. @end example
  3825. @noindent
  3826. parses as
  3827. @example
  3828. (sizeof (int)) - x
  3829. @end example
  3830. @noindent
  3831. If what you want is
  3832. @example
  3833. sizeof ((int) -x)
  3834. @end example
  3835. @noindent
  3836. you must write it that way, with parentheses.
  3837. The data type of the value of the @code{sizeof} operator is always one
  3838. of the unsigned integer types; which one of those types depends on the
  3839. machine. The header file @code{stddef.h} defines the typedef name
  3840. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3841. Names}.
  3842. @node Pointers
  3843. @chapter Pointers
  3844. @cindex pointers
  3845. Among high-level languages, C is rather low level, close to the
  3846. machine. This is mainly because it has explicit @dfn{pointers}. A
  3847. pointer value is the numeric address of data in memory. The type of
  3848. data to be found at that address is specified by the data type of the
  3849. pointer itself. The unary operator @samp{*} gets the data that a
  3850. pointer points to---this is called @dfn{dereferencing the pointer}.
  3851. C also allows pointers to functions, but since there are some
  3852. differences in how they work, we treat them later. @xref{Function
  3853. Pointers}.
  3854. @menu
  3855. * Address of Data:: Using the ``address-of'' operator.
  3856. * Pointer Types:: For each type, there is a pointer type.
  3857. * Pointer Declarations:: Declaring variables with pointer types.
  3858. * Pointer Type Designators:: Designators for pointer types.
  3859. * Pointer Dereference:: Accessing what a pointer points at.
  3860. * Null Pointers:: Pointers which do not point to any object.
  3861. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3862. * Void Pointers:: Totally generic pointers, can cast to any.
  3863. * Pointer Comparison:: Comparing memory address values.
  3864. * Pointer Arithmetic:: Computing memory address values.
  3865. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3866. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3867. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3868. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3869. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3870. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3871. @end menu
  3872. @node Address of Data
  3873. @section Address of Data
  3874. @cindex address-of operator
  3875. The most basic way to make a pointer is with the ``address-of''
  3876. operator, @samp{&}. Let's suppose we have these variables available:
  3877. @example
  3878. int i;
  3879. double a[5];
  3880. @end example
  3881. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3882. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3883. address of the element 3 of @code{a}. (It is actually the fourth
  3884. element in the array, since the first element has index 0.)
  3885. The address-of operator is unusual because it operates on a place to
  3886. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3887. stored there. (The left argument of a simple assignment is unusual in
  3888. the same way.) You can use it on any lvalue except a bit field
  3889. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3890. Constructors}).
  3891. @node Pointer Types
  3892. @section Pointer Types
  3893. For each data type @var{t}, there is a type for pointers to type
  3894. @var{t}. For these variables,
  3895. @example
  3896. int i;
  3897. double a[5];
  3898. @end example
  3899. @itemize @bullet
  3900. @item
  3901. @code{i} has type @code{int}; we say
  3902. @code{&i} is a ``pointer to @code{int}.''
  3903. @item
  3904. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3905. arrays of five @code{double}s.''
  3906. @item
  3907. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3908. to @code{double}.''
  3909. @end itemize
  3910. @node Pointer Declarations
  3911. @section Pointer-Variable Declarations
  3912. The way to declare that a variable @code{foo} points to type @var{t} is
  3913. @example
  3914. @var{t} *foo;
  3915. @end example
  3916. To remember this syntax, think ``if you dereference @code{foo}, using
  3917. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3918. points to type @var{t}.''
  3919. Thus, we can declare variables that hold pointers to these three
  3920. types, like this:
  3921. @example
  3922. int *ptri; /* @r{Pointer to @code{int}.} */
  3923. double *ptrd; /* @r{Pointer to @code{double}.} */
  3924. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3925. @end example
  3926. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3927. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3928. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3929. @code{double}.'' The parentheses express the point that you would
  3930. dereference it first, then subscript it.
  3931. Contrast the last one with this:
  3932. @example
  3933. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3934. @end example
  3935. @noindent
  3936. Because @samp{*} has higher syntactic precedence than subscripting,
  3937. you would subscript @code{aptrd} then dereference it. Therefore, it
  3938. declares an array of pointers, not a pointer.
  3939. @node Pointer Type Designators
  3940. @section Pointer-Type Designators
  3941. Every type in C has a designator; you make it by deleting the variable
  3942. name and the semicolon from a declaration (@pxref{Type
  3943. Designators}). Here are the designators for the pointer
  3944. types of the example declarations in the previous section:
  3945. @example
  3946. int * /* @r{Pointer to @code{int}.} */
  3947. double * /* @r{Pointer to @code{double}.} */
  3948. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3949. @end example
  3950. Remember, to understand what type a designator stands for, imagine the
  3951. variable name that would be in the declaration, and figure out what
  3952. type it would declare that variable with. @code{double (*)[5]} can
  3953. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3954. which, when dereferenced, gives an array of 5 @code{double}s.
  3955. @node Pointer Dereference
  3956. @section Dereferencing Pointers
  3957. @cindex dereferencing pointers
  3958. @cindex pointer dereferencing
  3959. The main use of a pointer value is to @dfn{dereference it} (access the
  3960. data it points at) with the unary @samp{*} operator. For instance,
  3961. @code{*&i} is the value at @code{i}'s address---which is just
  3962. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3963. valid.
  3964. A pointer-dereference expression whose type is data (not a function)
  3965. is an lvalue.
  3966. Pointers become really useful when we store them somewhere and use
  3967. them later. Here's a simple example to illustrate the practice:
  3968. @example
  3969. @{
  3970. int i;
  3971. int *ptr;
  3972. ptr = &i;
  3973. i = 5;
  3974. @r{@dots{}}
  3975. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3976. @}
  3977. @end example
  3978. This shows how to declare the variable @code{ptr} as type
  3979. @code{int *} (pointer to @code{int}), store a pointer value into it
  3980. (pointing at @code{i}), and use it later to get the value of the
  3981. object it points at (the value in @code{i}).
  3982. If anyone can provide a useful example which is this basic,
  3983. I would be grateful.
  3984. @node Null Pointers
  3985. @section Null Pointers
  3986. @cindex null pointers
  3987. @cindex pointers, null
  3988. @c ???stdio loads sttddef
  3989. A pointer value can be @dfn{null}, which means it does not point to
  3990. any object. The cleanest way to get a null pointer is by writing
  3991. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3992. also do it by casting 0 to the desired pointer type, as in
  3993. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  3994. @xref{Explicit Type Conversion}.)
  3995. You can store a null pointer in any lvalue whose data type
  3996. is a pointer type:
  3997. @example
  3998. char *foo;
  3999. foo = NULL;
  4000. @end example
  4001. These two, if consecutive, can be combined into a declaration with
  4002. initializer,
  4003. @example
  4004. char *foo = NULL;
  4005. @end example
  4006. You can also explicitly cast @code{NULL} to the specific pointer type
  4007. you want---it makes no difference.
  4008. @example
  4009. char *foo;
  4010. foo = (char *) NULL;
  4011. @end example
  4012. To test whether a pointer is null, compare it with zero or
  4013. @code{NULL}, as shown here:
  4014. @example
  4015. if (p != NULL)
  4016. /* @r{@code{p} is not null.} */
  4017. operate (p);
  4018. @end example
  4019. Since testing a pointer for not being null is basic and frequent, all
  4020. but beginners in C will understand the conditional without need for
  4021. @code{!= NULL}:
  4022. @example
  4023. if (p)
  4024. /* @r{@code{p} is not null.} */
  4025. operate (p);
  4026. @end example
  4027. @node Invalid Dereference
  4028. @section Dereferencing Null or Invalid Pointers
  4029. Trying to dereference a null pointer is an error. On most platforms,
  4030. it generally causes a signal, usually @code{SIGSEGV}
  4031. (@pxref{Signals}).
  4032. @example
  4033. char *foo = NULL;
  4034. c = *foo; /* @r{This causes a signal and terminates.} */
  4035. @end example
  4036. @noindent
  4037. Likewise a pointer that has the wrong alignment for the target data type
  4038. (on most types of computer), or points to a part of memory that has
  4039. not been allocated in the process's address space.
  4040. The signal terminates the program, unless the program has arranged to
  4041. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4042. The GNU C Library Reference Manual}).
  4043. However, the signal might not happen if the dereference is optimized
  4044. away. In the example above, if you don't subsequently use the value
  4045. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4046. can prevent such optimization using the @code{volatile} qualifier, as
  4047. shown here:
  4048. @example
  4049. volatile char *p;
  4050. volatile char c;
  4051. c = *p;
  4052. @end example
  4053. You can use this to test whether @code{p} points to unallocated
  4054. memory. Set up a signal handler first, so the signal won't terminate
  4055. the program.
  4056. @node Void Pointers
  4057. @section Void Pointers
  4058. @cindex void pointers
  4059. @cindex pointers, void
  4060. The peculiar type @code{void *}, a pointer whose target type is
  4061. @code{void}, is used often in C@. It represents a pointer to
  4062. we-don't-say-what. Thus,
  4063. @example
  4064. void *numbered_slot_pointer (int);
  4065. @end example
  4066. @noindent
  4067. declares a function @code{numbered_slot_pointer} that takes an
  4068. integer parameter and returns a pointer, but we don't say what type of
  4069. data it points to.
  4070. With type @code{void *}, you can pass the pointer around and test
  4071. whether it is null. However, dereferencing it gives a @code{void}
  4072. value that can't be used (@pxref{The Void Type}). To dereference the
  4073. pointer, first convert it to some other pointer type.
  4074. Assignments convert @code{void *} automatically to any other pointer
  4075. type, if the left operand has a pointer type; for instance,
  4076. @example
  4077. @{
  4078. int *p;
  4079. /* @r{Converts return value to @code{int *}.} */
  4080. p = numbered_slot_pointer (5);
  4081. @r{@dots{}}
  4082. @}
  4083. @end example
  4084. Passing an argument of type @code{void *} for a parameter that has a
  4085. pointer type also converts. For example, supposing the function
  4086. @code{hack} is declared to require type @code{float *} for its
  4087. argument, this will convert the null pointer to that type.
  4088. @example
  4089. /* @r{Declare @code{hack} that way.}
  4090. @r{We assume it is defined somewhere else.} */
  4091. void hack (float *);
  4092. @dots{}
  4093. /* @r{Now call @code{hack}.} */
  4094. @{
  4095. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4096. @r{to @code{float *} to pass it to @code{hack}.} */
  4097. hack (numbered_slot_pointer (5));
  4098. @r{@dots{}}
  4099. @}
  4100. @end example
  4101. You can also convert to another pointer type with an explicit cast
  4102. (@pxref{Explicit Type Conversion}), like this:
  4103. @example
  4104. (int *) numbered_slot_pointer (5)
  4105. @end example
  4106. Here is an example which decides at run time which pointer
  4107. type to convert to:
  4108. @example
  4109. void
  4110. extract_int_or_double (void *ptr, bool its_an_int)
  4111. @{
  4112. if (its_an_int)
  4113. handle_an_int (*(int *)ptr);
  4114. else
  4115. handle_a_double (*(double *)ptr);
  4116. @}
  4117. @end example
  4118. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4119. to type @code{int *}, then dereference it.
  4120. @node Pointer Comparison
  4121. @section Pointer Comparison
  4122. @cindex pointer comparison
  4123. @cindex comparison, pointer
  4124. Two pointer values are equal if they point to the same location, or if
  4125. they are both null. You can test for this with @code{==} and
  4126. @code{!=}. Here's a trivial example:
  4127. @example
  4128. @{
  4129. int i;
  4130. int *p, *q;
  4131. p = &i;
  4132. q = &i;
  4133. if (p == q)
  4134. printf ("This will be printed.\n");
  4135. if (p != q)
  4136. printf ("This won't be printed.\n");
  4137. @}
  4138. @end example
  4139. Ordering comparisons such as @code{>} and @code{>=} operate on
  4140. pointers by converting them to unsigned integers. The C standard says
  4141. the two pointers must point within the same object in memory, but on
  4142. GNU/Linux systems these operations simply compare the numeric values
  4143. of the pointers.
  4144. The pointer values to be compared should in principle have the same type, but
  4145. they are allowed to differ in limited cases. First of all, if the two
  4146. pointers' target types are nearly compatible (@pxref{Compatible
  4147. Types}), the comparison is allowed.
  4148. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4149. the other is another pointer type, the comparison operator converts
  4150. the @code{void *} pointer to the other type so as to compare them.
  4151. (In standard C, this is not allowed if the other type is a function
  4152. pointer type, but that works in GNU C@.)
  4153. Comparison operators also allow comparing the integer 0 with a pointer
  4154. value. Thus works by converting 0 to a null pointer of the same type
  4155. as the other operand.
  4156. @node Pointer Arithmetic
  4157. @section Pointer Arithmetic
  4158. @cindex pointer arithmetic
  4159. @cindex arithmetic, pointer
  4160. Adding an integer (positive or negative) to a pointer is valid in C@.
  4161. It assumes that the pointer points to an element in an array, and
  4162. advances or retracts the pointer across as many array elements as the
  4163. integer specifies. Here is an example, in which adding a positive
  4164. integer advances the pointer to a later element in the same array.
  4165. @example
  4166. void
  4167. incrementing_pointers ()
  4168. @{
  4169. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4170. int elt0, elt1, elt4;
  4171. int *p = &array[0];
  4172. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4173. elt0 = *p;
  4174. ++p;
  4175. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4176. elt1 = *p;
  4177. p += 3;
  4178. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4179. elt4 = *p;
  4180. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4181. elt0, elt1, elt4);
  4182. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4183. @}
  4184. @end example
  4185. Here's an example where adding a negative integer retracts the pointer
  4186. to an earlier element in the same array.
  4187. @example
  4188. void
  4189. decrementing_pointers ()
  4190. @{
  4191. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4192. int elt0, elt3, elt4;
  4193. int *p = &array[4];
  4194. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4195. elt4 = *p;
  4196. --p;
  4197. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4198. elt3 = *p;
  4199. p -= 3;
  4200. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4201. elt0 = *p;
  4202. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4203. elt0, elt3, elt4);
  4204. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4205. @}
  4206. @end example
  4207. If one pointer value was made by adding an integer to another
  4208. pointer value, it should be possible to subtract the pointer values
  4209. and recover that integer. That works too in C@.
  4210. @example
  4211. void
  4212. subtract_pointers ()
  4213. @{
  4214. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4215. int *p0, *p3, *p4;
  4216. int *p = &array[4];
  4217. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4218. p4 = p;
  4219. --p;
  4220. /* @r{Now @code{p} points at element 3. Save the value.} */
  4221. p3 = p;
  4222. p -= 3;
  4223. /* @r{Now @code{p} points at element 0. Save the value.} */
  4224. p0 = p;
  4225. printf ("%d, %d, %d, %d\n",
  4226. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4227. /* @r{Prints 4, 0, 3, -3.} */
  4228. @}
  4229. @end example
  4230. The addition operation does not know where arrays are. All it does is
  4231. add the integer (multiplied by object size) to the value of the
  4232. pointer. When the initial pointer and the result point into a single
  4233. array, the result is well-defined.
  4234. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4235. into different memory objects.
  4236. The difference between two pointers has type @code{int}, or
  4237. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4238. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4239. file @file{stddef.h}.
  4240. This definition of pointer subtraction is consistent with
  4241. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4242. @code{p3}, as in ordinary algebra.
  4243. In standard C, addition and subtraction are not allowed on @code{void
  4244. *}, since the target type's size is not defined in that case.
  4245. Likewise, they are not allowed on pointers to function types.
  4246. However, these operations work in GNU C, and the ``size of the target
  4247. type'' is taken as 1.
  4248. @node Pointers and Arrays
  4249. @section Pointers and Arrays
  4250. @cindex pointers and arrays
  4251. @cindex arrays and pointers
  4252. The clean way to refer to an array element is
  4253. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4254. same job is to get the address of that element as a pointer, then
  4255. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4256. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4257. pointer to element zero, then increments it with @code{+} to point to
  4258. the desired element, then gets the value from there.
  4259. That pointer-arithmetic construct is the @emph{definition} of square
  4260. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4261. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4262. symmetrically, so one must be a pointer and the other an integer; it
  4263. does not matter which comes first.
  4264. Since indexing with square brackets is defined in terms of addition
  4265. and dereference, that too is symmetrical. Thus, you can write
  4266. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4267. would be foolish to write @code{3[array]}, since it has no advantage
  4268. and could confuse people who read the code.
  4269. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4270. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4271. instead. Why is this valid? The name of the array, when used by
  4272. itself as an expression (other than in @code{sizeof}), stands for a
  4273. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4274. converts @code{array} implicitly to @code{&array[0]}, and the result
  4275. is a pointer to element 3, equivalent to @code{&array[3]}.
  4276. Since square brackets are defined in terms of such addition,
  4277. @code{array[3]} first converts @code{array} to a pointer. That's why
  4278. it works to use an array directly in that construct.
  4279. @node Pointer Arithmetic Low Level
  4280. @section Pointer Arithmetic at Low Level
  4281. @cindex pointer arithmetic, low level
  4282. @cindex low level pointer arithmetic
  4283. The behavior of pointer arithmetic is theoretically defined only when
  4284. the pointer values all point within one object allocated in memory.
  4285. But the addition and subtraction operators can't tell whether the
  4286. pointer values are all within one object. They don't know where
  4287. objects start and end. So what do they really do?
  4288. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4289. address, which is in fact an integer---call it @var{pint}. It treats
  4290. @var{i} as a number of elements of the type that @var{p} points to.
  4291. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4292. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4293. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4294. If the starting pointer value @var{p} and the result do not point at
  4295. parts of the same object, the operation is not officially legitimate,
  4296. and C code is not ``supposed'' to do it. But you can do it anyway,
  4297. and it gives precisely the results described by the procedure above.
  4298. In some special situations it can do something useful, but non-wizards
  4299. should avoid it.
  4300. Here's a function to offset a pointer value @emph{as if} it pointed to
  4301. an object of any given size, by explicitly performing that calculation:
  4302. @example
  4303. #include <stdint.h>
  4304. void *
  4305. ptr_add (void *p, int i, int objsize)
  4306. @{
  4307. intptr_t p_address = (long) p;
  4308. intptr_t totalsize = i * objsize;
  4309. intptr_t new_address = p_address + totalsize;
  4310. return (void *) new_address;
  4311. @}
  4312. @end example
  4313. @noindent
  4314. @cindex @code{intptr_t}
  4315. This does the same job as @code{@var{p} + @var{i}} with the proper
  4316. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4317. defined in the header file @file{stdint.h}. (In practice, @code{long
  4318. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4319. @node Pointer Increment/Decrement
  4320. @section Pointer Increment and Decrement
  4321. @cindex pointer increment and decrement
  4322. @cindex incrementing pointers
  4323. @cindex decrementing pointers
  4324. The @samp{++} operator adds 1 to a variable. We have seen it for
  4325. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4326. For instance, suppose we have a series of positive integers,
  4327. terminated by a zero, and we want to add them all up.
  4328. @example
  4329. int
  4330. sum_array_till_0 (int *p)
  4331. @{
  4332. int sum = 0;
  4333. for (;;)
  4334. @{
  4335. /* @r{Fetch the next integer.} */
  4336. int next = *p++;
  4337. /* @r{Exit the loop if it's 0.} */
  4338. if (next == 0)
  4339. break;
  4340. /* @r{Add it into running total.} */
  4341. sum += next;
  4342. @}
  4343. return sum;
  4344. @}
  4345. @end example
  4346. @noindent
  4347. The statement @samp{break;} will be explained further on (@pxref{break
  4348. Statement}). Used in this way, it immediately exits the surrounding
  4349. @code{for} statement.
  4350. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4351. takes precedence over a prefix operator. Therefore, it dereferences
  4352. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4353. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4354. pointer, adding 1 to it advances it by the width of the datum it
  4355. points to---in this case, one @code{int}. Therefore, each iteration
  4356. of the loop picks up the next integer from the series and puts it into
  4357. @code{next}.
  4358. This @code{for}-loop has no initialization expression since @code{p}
  4359. and @code{sum} are already initialized, it has no end-test since the
  4360. @samp{break;} statement will exit it, and needs no expression to
  4361. advance it since that's done within the loop by incrementing @code{p}
  4362. and @code{sum}. Thus, those three expressions after @code{for} are
  4363. left empty.
  4364. Another way to write this function is by keeping the parameter value unchanged
  4365. and using indexing to access the integers in the table.
  4366. @example
  4367. int
  4368. sum_array_till_0_indexing (int *p)
  4369. @{
  4370. int i;
  4371. int sum = 0;
  4372. for (i = 0; ; i++)
  4373. @{
  4374. /* @r{Fetch the next integer.} */
  4375. int next = p[i];
  4376. /* @r{Exit the loop if it's 0.} */
  4377. if (next == 0)
  4378. break;
  4379. /* @r{Add it into running total.} */
  4380. sum += next;
  4381. @}
  4382. return sum;
  4383. @}
  4384. @end example
  4385. In this program, instead of advancing @code{p}, we advance @code{i}
  4386. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4387. i)}.) Either way, it uses the same address to get the next integer.
  4388. It makes no difference in this program whether we write @code{i++} or
  4389. @code{++i}, because the value is not used. All that matters is the
  4390. effect, to increment @code{i}.
  4391. The @samp{--} operator also works on pointers; it can be used
  4392. to scan backwards through an array, like this:
  4393. @example
  4394. int
  4395. after_last_nonzero (int *p, int len)
  4396. @{
  4397. /* @r{Set up @code{q} to point just after the last array element.} */
  4398. int *q = p + len;
  4399. while (q != p)
  4400. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4401. if (*--q != 0)
  4402. /* @r{Return the index of the element after that nonzero.} */
  4403. return q - p + 1;
  4404. return 0;
  4405. @}
  4406. @end example
  4407. That function returns the length of the nonzero part of the
  4408. array specified by its arguments; that is, the index of the
  4409. first zero of the run of zeros at the end.
  4410. @node Pointer Arithmetic Drawbacks
  4411. @section Drawbacks of Pointer Arithmetic
  4412. @cindex drawbacks of pointer arithmetic
  4413. @cindex pointer arithmetic, drawbacks
  4414. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4415. major security flaw in the C language. Theoretically, it is only
  4416. valid to adjust a pointer within one object allocated as a unit in
  4417. memory. However, if you unintentionally adjust a pointer across the
  4418. bounds of the object and into some other object, the system has no way
  4419. to detect this error.
  4420. A bug which does that can easily result in clobbering part of another
  4421. object. For example, with @code{array[-1]} you can read or write the
  4422. nonexistent element before the beginning of an array---probably part
  4423. of some other data.
  4424. Combining pointer arithmetic with casts between pointer types, you can
  4425. create a pointer that fails to be properly aligned for its type. For
  4426. example,
  4427. @example
  4428. int a[2];
  4429. char *pa = (char *)a;
  4430. int *p = (int *)(pa + 1);
  4431. @end example
  4432. @noindent
  4433. gives @code{p} a value pointing to an ``integer'' that includes part
  4434. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4435. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4436. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4437. ``works,'' it may be quite slow. It can also cause aliasing
  4438. confusions (@pxref{Aliasing}).
  4439. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4440. unless it is really necessary.
  4441. @node Pointer-Integer Conversion
  4442. @section Pointer-Integer Conversion
  4443. @cindex pointer-integer conversion
  4444. @cindex conversion between pointers and integers
  4445. @cindex @code{uintptr_t}
  4446. On modern computers, an address is simply a number. It occupies the
  4447. same space as some size of integer. In C, you can convert a pointer
  4448. to the appropriate integer types and vice versa, without losing
  4449. information. The appropriate integer types are @code{uintptr_t} (an
  4450. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4451. in @file{stdint.h}.
  4452. For instance,
  4453. @example
  4454. #include <stdint.h>
  4455. #include <stdio.h>
  4456. void
  4457. print_pointer (void *ptr)
  4458. @{
  4459. uintptr_t converted = (uintptr_t) ptr;
  4460. printf ("Pointer value is 0x%x\n",
  4461. (unsigned int) converted);
  4462. @}
  4463. @end example
  4464. @noindent
  4465. The specification @samp{%x} in the template (the first argument) for
  4466. @code{printf} means to represent this argument using hexadecimal
  4467. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4468. printing treats the number as unsigned, but it won't actually matter:
  4469. all @code{printf} gets to see is the series of bits in the number.
  4470. @strong{Warning:} Converting pointers to integers is risky---don't do
  4471. it unless it is really necessary.
  4472. @node Printing Pointers
  4473. @section Printing Pointers
  4474. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4475. For example:
  4476. @example
  4477. void
  4478. print_pointer (void *ptr)
  4479. @{
  4480. printf ("Pointer value is %p\n", ptr);
  4481. @}
  4482. @end example
  4483. The specification @samp{%p} works with any pointer type. It prints
  4484. @samp{0x} followed by the address in hexadecimal, printed as the
  4485. appropriate unsigned integer type.
  4486. @node Structures
  4487. @chapter Structures
  4488. @cindex structures
  4489. @findex struct
  4490. @cindex fields in structures
  4491. A @dfn{structure} is a user-defined data type that holds various
  4492. @dfn{fields} of data. Each field has a name and a data type specified
  4493. in the structure's definition.
  4494. Here we define a structure suitable for storing a linked list of
  4495. integers. Each list item will hold one integer, plus a pointer
  4496. to the next item.
  4497. @example
  4498. struct intlistlink
  4499. @{
  4500. int datum;
  4501. struct intlistlink *next;
  4502. @};
  4503. @end example
  4504. The structure definition has a @dfn{type tag} so that the code can
  4505. refer to this structure. The type tag here is @code{intlistlink}.
  4506. The definition refers recursively to the same structure through that
  4507. tag.
  4508. You can define a structure without a type tag, but then you can't
  4509. refer to it again. That is useful only in some special contexts, such
  4510. as inside a @code{typedef} or a @code{union}.
  4511. The contents of the structure are specified by the @dfn{field
  4512. declarations} inside the braces. Each field in the structure needs a
  4513. declaration there. The fields in one structure definition must have
  4514. distinct names, but these names do not conflict with any other names
  4515. in the program.
  4516. A field declaration looks just like a variable declaration. You can
  4517. combine field declarations with the same beginning, just as you can
  4518. combine variable declarations.
  4519. This structure has two fields. One, named @code{datum}, has type
  4520. @code{int} and will hold one integer in the list. The other, named
  4521. @code{next}, is a pointer to another @code{struct intlistlink}
  4522. which would be the rest of the list. In the last list item, it would
  4523. be @code{NULL}.
  4524. This structure definition is recursive, since the type of the
  4525. @code{next} field refers to the structure type. Such recursion is not
  4526. a problem; in fact, you can use the type @code{struct intlistlink *}
  4527. before the definition of the type @code{struct intlistlink} itself.
  4528. That works because pointers to all kinds of structures really look the
  4529. same at the machine level.
  4530. After defining the structure, you can declare a variable of type
  4531. @code{struct intlistlink} like this:
  4532. @example
  4533. struct intlistlink foo;
  4534. @end example
  4535. The structure definition itself can serve as the beginning of a
  4536. variable declaration, so you can declare variables immediately after,
  4537. like this:
  4538. @example
  4539. struct intlistlink
  4540. @{
  4541. int datum;
  4542. struct intlistlink *next;
  4543. @} foo;
  4544. @end example
  4545. @noindent
  4546. But that is ugly. It is almost always clearer to separate the
  4547. definition of the structure from its uses.
  4548. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4549. the scope of the structure type name to that block. That means the
  4550. structure type is recognized only within that block. Declaring it in
  4551. a function parameter list, as here,
  4552. @example
  4553. int f (struct foo @{int a, b@} parm);
  4554. @end example
  4555. @noindent
  4556. (assuming that @code{struct foo} is not already defined) limits the
  4557. scope of the structure type @code{struct foo} to that parameter list;
  4558. that is basically useless, so it triggers a warning.
  4559. Standard C requires at least one field in a structure.
  4560. GNU C does not require this.
  4561. @menu
  4562. * Referencing Fields:: Accessing field values in a structure object.
  4563. * Dynamic Memory Allocation:: Allocating space for objects
  4564. while the program is running.
  4565. * Field Offset:: Memory layout of fields within a structure.
  4566. * Structure Layout:: Planning the memory layout of fields.
  4567. * Packed Structures:: Packing structure fields as close as possible.
  4568. * Bit Fields:: Dividing integer fields
  4569. into fields with fewer bits.
  4570. * Bit Field Packing:: How bit fields pack together in integers.
  4571. * const Fields:: Making structure fields immutable.
  4572. * Zero Length:: Zero-length array as a variable-length object.
  4573. * Flexible Array Fields:: Another approach to variable-length objects.
  4574. * Overlaying Structures:: Casting one structure type
  4575. over an object of another structure type.
  4576. * Structure Assignment:: Assigning values to structure objects.
  4577. * Unions:: Viewing the same object in different types.
  4578. * Packing With Unions:: Using a union type to pack various types into
  4579. the same memory space.
  4580. * Cast to Union:: Casting a value one of the union's alternative
  4581. types to the type of the union itself.
  4582. * Structure Constructors:: Building new structure objects.
  4583. * Unnamed Types as Fields:: Fields' types do not always need names.
  4584. * Incomplete Types:: Types which have not been fully defined.
  4585. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4586. * Type Tags:: Scope of structure and union type tags.
  4587. @end menu
  4588. @node Referencing Fields
  4589. @section Referencing Structure Fields
  4590. @cindex referencing structure fields
  4591. @cindex structure fields, referencing
  4592. To make a structure useful, there has to be a way to examine and store
  4593. its fields. The @samp{.} (period) operator does that; its use looks
  4594. like @code{@var{object}.@var{field}}.
  4595. Given this structure and variable,
  4596. @example
  4597. struct intlistlink
  4598. @{
  4599. int datum;
  4600. struct intlistlink *next;
  4601. @};
  4602. struct intlistlink foo;
  4603. @end example
  4604. @noindent
  4605. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4606. fields in the value of @code{foo}. These fields are lvalues, so you
  4607. can store values into them, and read the values out again.
  4608. Most often, structures are dynamically allocated (see the next
  4609. section), and we refer to the objects via pointers.
  4610. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4611. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4612. contains this declaration:
  4613. @example
  4614. struct intlistlink *ptr;
  4615. @end example
  4616. @noindent
  4617. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4618. to the two fields in the object that @code{ptr} points to.
  4619. If a unary operator precedes an expression using @samp{->},
  4620. the @samp{->} nests inside:
  4621. @example
  4622. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4623. @end example
  4624. You can intermix @samp{->} and @samp{.} without parentheses,
  4625. as shown here:
  4626. @example
  4627. struct @{ double d; struct intlistlink l; @} foo;
  4628. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4629. @end example
  4630. @node Dynamic Memory Allocation
  4631. @section Dynamic Memory Allocation
  4632. @cindex dynamic memory allocation
  4633. @cindex memory allocation, dynamic
  4634. @cindex allocating memory dynamically
  4635. To allocate an object dynamically, call the library function
  4636. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4637. Reference Manual}). Here is how to allocate an object of type
  4638. @code{struct intlistlink}. To make this code work, include the file
  4639. @file{stdlib.h}, like this:
  4640. @example
  4641. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4642. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4643. @dots{}
  4644. struct intlistlink *
  4645. alloc_intlistlink ()
  4646. @{
  4647. struct intlistlink *p;
  4648. p = malloc (sizeof (struct intlistlink));
  4649. if (p == NULL)
  4650. fatal ("Ran out of storage");
  4651. /* @r{Initialize the contents.} */
  4652. p->datum = 0;
  4653. p->next = NULL;
  4654. return p;
  4655. @}
  4656. @end example
  4657. @noindent
  4658. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4659. will automatically convert it to type @code{struct intlistlink *}.
  4660. The return value of @code{malloc} is always sufficiently aligned
  4661. (@pxref{Type Alignment}) that it is valid for any data type.
  4662. The test for @code{p == NULL} is necessary because @code{malloc}
  4663. returns a null pointer if it cannot get any storage. We assume that
  4664. the program defines the function @code{fatal} to report a fatal error
  4665. to the user.
  4666. Here's how to add one more integer to the front of such a list:
  4667. @example
  4668. struct intlistlink *my_list = NULL;
  4669. void
  4670. add_to_mylist (int my_int)
  4671. @{
  4672. struct intlistlink *p = alloc_intlistlink ();
  4673. p->datum = my_int;
  4674. p->next = mylist;
  4675. mylist = p;
  4676. @}
  4677. @end example
  4678. The way to free the objects is by calling @code{free}. Here's
  4679. a function to free all the links in one of these lists:
  4680. @example
  4681. void
  4682. free_intlist (struct intlistlink *p)
  4683. @{
  4684. while (p)
  4685. @{
  4686. struct intlistlink *q = p;
  4687. p = p->next;
  4688. free (q);
  4689. @}
  4690. @}
  4691. @end example
  4692. We must extract the @code{next} pointer from the object before freeing
  4693. it, because @code{free} can clobber the data that was in the object.
  4694. For the same reason, the program must not use the list any more after
  4695. freeing its elements. To make sure it won't, it is best to clear out
  4696. the variable where the list was stored, like this:
  4697. @example
  4698. free_intlist (mylist);
  4699. mylist = NULL;
  4700. @end example
  4701. @node Field Offset
  4702. @section Field Offset
  4703. @cindex field offset
  4704. @cindex structure field offset
  4705. @cindex offset of structure fields
  4706. To determine the offset of a given field @var{field} in a structure
  4707. type @var{type}, use the macro @code{offsetof}, which is defined in
  4708. the file @file{stddef.h}. It is used like this:
  4709. @example
  4710. offsetof (@var{type}, @var{field})
  4711. @end example
  4712. Here is an example:
  4713. @example
  4714. struct foo
  4715. @{
  4716. int element;
  4717. struct foo *next;
  4718. @};
  4719. offsetof (struct foo, next)
  4720. /* @r{On most machines that is 4. It may be 8.} */
  4721. @end example
  4722. @node Structure Layout
  4723. @section Structure Layout
  4724. @cindex structure layout
  4725. @cindex layout of structures
  4726. The rest of this chapter covers advanced topics about structures. If
  4727. you are just learning C, you can skip it.
  4728. The precise layout of a @code{struct} type is crucial when using it to
  4729. overlay hardware registers, to access data structures in shared
  4730. memory, or to assemble and disassemble packets for network
  4731. communication. It is also important for avoiding memory waste when
  4732. the program makes many objects of that type. However, the layout
  4733. depends on the target platform. Each platform has conventions for
  4734. structure layout, which compilers need to follow.
  4735. Here are the conventions used on most platforms.
  4736. The structure's fields appear in the structure layout in the order
  4737. they are declared. When possible, consecutive fields occupy
  4738. consecutive bytes within the structure. However, if a field's type
  4739. demands more alignment than it would get that way, C gives it the
  4740. alignment it requires by leaving a gap after the previous field.
  4741. Once all the fields have been laid out, it is possible to determine
  4742. the structure's alignment and size. The structure's alignment is the
  4743. maximum alignment of any of the fields in it. Then the structure's
  4744. size is rounded up to a multiple of its alignment. That may require
  4745. leaving a gap at the end of the structure.
  4746. Here are some examples, where we assume that @code{char} has size and
  4747. alignment 1 (always true), and @code{int} has size and alignment 4
  4748. (true on most kinds of computers):
  4749. @example
  4750. struct foo
  4751. @{
  4752. char a, b;
  4753. int c;
  4754. @};
  4755. @end example
  4756. @noindent
  4757. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4758. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4759. There is a gap of 2 bytes before @code{c}.
  4760. Contrast that with this structure:
  4761. @example
  4762. struct foo
  4763. @{
  4764. char a;
  4765. int c;
  4766. char b;
  4767. @};
  4768. @end example
  4769. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4770. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4771. gaps: three bytes before @code{c}, and three bytes at the end.
  4772. These two structures have the same contents at the C level, but one
  4773. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4774. fields. A reliable way to avoid this sort of wastage is to order the
  4775. fields by size, biggest fields first.
  4776. @node Packed Structures
  4777. @section Packed Structures
  4778. @cindex packed structures
  4779. @cindex @code{__attribute__((packed))}
  4780. In GNU C you can force a structure to be laid out with no gaps by
  4781. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4782. end of the structure type declaration). Here's an example:
  4783. @example
  4784. struct __attribute__((packed)) foo
  4785. @{
  4786. char a;
  4787. int c;
  4788. char b;
  4789. @};
  4790. @end example
  4791. Without @code{__attribute__((packed))}, this structure occupies 12
  4792. bytes (as described in the previous section), assuming 4-byte
  4793. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4794. only 6 bytes long---the sum of the lengths of its fields.
  4795. Use of @code{__attribute__((packed))} often results in fields that
  4796. don't have the normal alignment for their types. Taking the address
  4797. of such a field can result in an invalid pointer because of its
  4798. improper alignment. Dereferencing such a pointer can cause a
  4799. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4800. unaligned pointers.
  4801. @xref{Attributes}.
  4802. @node Bit Fields
  4803. @section Bit Fields
  4804. @cindex bit fields
  4805. A structure field declaration with an integer type can specify the
  4806. number of bits the field should occupy. We call that a @dfn{bit
  4807. field}. These are useful because consecutive bit fields are packed
  4808. into a larger storage unit. For instance,
  4809. @example
  4810. unsigned char opcode: 4;
  4811. @end example
  4812. @noindent
  4813. specifies that this field takes just 4 bits.
  4814. Since it is unsigned, its possible values range
  4815. from 0 to 15. A signed field with 4 bits, such as this,
  4816. @example
  4817. signed char small: 4;
  4818. @end example
  4819. @noindent
  4820. can hold values from -8 to 7.
  4821. You can subdivide a single byte into those two parts by writing
  4822. @example
  4823. unsigned char opcode: 4;
  4824. signed char small: 4;
  4825. @end example
  4826. @noindent
  4827. in the structure. With bit fields, these two numbers fit into
  4828. a single @code{char}.
  4829. Here's how to declare a one-bit field that can hold either 0 or 1:
  4830. @example
  4831. unsigned char special_flag: 1;
  4832. @end example
  4833. You can also use the @code{bool} type for bit fields:
  4834. @example
  4835. bool special_flag: 1;
  4836. @end example
  4837. Except when using @code{bool} (which is always unsigned,
  4838. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4839. for a bit field. There is a default, if that's not specified: the bit
  4840. field is signed if plain @code{char} is signed, except that the option
  4841. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4842. is cleaner not to depend on this default.
  4843. Bit fields are special in that you cannot take their address with
  4844. @samp{&}. They are not stored with the size and alignment appropriate
  4845. for the specified type, so they cannot be addressed through pointers
  4846. to that type.
  4847. @node Bit Field Packing
  4848. @section Bit Field Packing
  4849. Programs to communicate with low-level hardware interfaces need to
  4850. define bit fields laid out to match the hardware data. This section
  4851. explains how to do that.
  4852. Consecutive bit fields are packed together, but each bit field must
  4853. fit within a single object of its specified type. In this example,
  4854. @example
  4855. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4856. @end example
  4857. @noindent
  4858. all five fields fit consecutively into one two-byte @code{short}.
  4859. They need 15 bits, and one @code{short} provides 16. By contrast,
  4860. @example
  4861. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4862. @end example
  4863. @noindent
  4864. needs three bytes. It fits @code{a} and @code{b} into one
  4865. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4866. add up to 9 bits). So @code{c} and @code{d} go into a second
  4867. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4868. Then @code{e} needs a third @code{char}. By contrast,
  4869. @example
  4870. unsigned char a : 3, b : 3;
  4871. unsigned int c : 3;
  4872. unsigned char d : 3, e : 3;
  4873. @end example
  4874. @noindent
  4875. needs only two bytes: the type @code{unsigned int}
  4876. allows @code{c} to straddle bytes that are in the same word.
  4877. You can leave a gap of a specified number of bits by defining a
  4878. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4879. It is allocated space in the structure just as a named bit field would
  4880. be allocated.
  4881. You can force the following bit field to advance to the following
  4882. aligned memory object with @code{@var{type} : 0;}.
  4883. Both of these constructs can syntactically share @var{type} with
  4884. ordinary bit fields. This example illustrates both:
  4885. @example
  4886. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4887. @end example
  4888. @noindent
  4889. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4890. between them. Then @code{: 0} advances to the next @code{int},
  4891. so @code{c} and @code{d} fit into that one.
  4892. These rules for packing bit fields apply to most target platforms,
  4893. including all the usual real computers. A few embedded controllers
  4894. have special layout rules.
  4895. @node const Fields
  4896. @section @code{const} Fields
  4897. @cindex const fields
  4898. @cindex structure fields, constant
  4899. @c ??? Is this a C standard feature?
  4900. A structure field declared @code{const} cannot be assigned to
  4901. (@pxref{const}). For instance, let's define this modified version of
  4902. @code{struct intlistlink}:
  4903. @example
  4904. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4905. @{
  4906. const int datum;
  4907. struct intlistlink *next;
  4908. @};
  4909. @end example
  4910. This structure can be used to prevent part of the code from modifying
  4911. the @code{datum} field:
  4912. @example
  4913. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4914. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4915. struct intlistlink_ro *q
  4916. = (struct intlistlink_ro *) p;
  4917. q->datum = 5; /* @r{Error!} */
  4918. p->datum = 5; /* @r{Valid since @code{*p} is}
  4919. @r{not a @code{struct intlistlink_ro}.} */
  4920. @end example
  4921. A @code{const} field can get a value in two ways: by initialization of
  4922. the whole structure, and by making a pointer-to-structure point to an object
  4923. in which that field already has a value.
  4924. Any @code{const} field in a structure type makes assignment impossible
  4925. for structures of that type (@pxref{Structure Assignment}). That is
  4926. because structure assignment works by assigning the structure's
  4927. fields, one by one.
  4928. @node Zero Length
  4929. @section Arrays of Length Zero
  4930. @cindex array of length zero
  4931. @cindex zero-length arrays
  4932. @cindex length-zero arrays
  4933. GNU C allows zero-length arrays. They are useful as the last element
  4934. of a structure that is really a header for a variable-length object.
  4935. Here's an example, where we construct a variable-size structure
  4936. to hold a line which is @code{this_length} characters long:
  4937. @example
  4938. struct line @{
  4939. int length;
  4940. char contents[0];
  4941. @};
  4942. struct line *thisline
  4943. = ((struct line *)
  4944. malloc (sizeof (struct line)
  4945. + this_length));
  4946. thisline->length = this_length;
  4947. @end example
  4948. In ISO C90, we would have to give @code{contents} a length of 1, which
  4949. means either wasting space or complicating the argument to @code{malloc}.
  4950. @node Flexible Array Fields
  4951. @section Flexible Array Fields
  4952. @cindex flexible array fields
  4953. @cindex array fields, flexible
  4954. The C99 standard adopted a more complex equivalent of zero-length
  4955. array fields. It's called a @dfn{flexible array}, and it's indicated
  4956. by omitting the length, like this:
  4957. @example
  4958. struct line
  4959. @{
  4960. int length;
  4961. char contents[];
  4962. @};
  4963. @end example
  4964. The flexible array has to be the last field in the structure, and there
  4965. must be other fields before it.
  4966. Under the C standard, a structure with a flexible array can't be part
  4967. of another structure, and can't be an element of an array.
  4968. GNU C allows static initialization of flexible array fields. The effect
  4969. is to ``make the array long enough'' for the initializer.
  4970. @example
  4971. struct f1 @{ int x; int y[]; @} f1
  4972. = @{ 1, @{ 2, 3, 4 @} @};
  4973. @end example
  4974. @noindent
  4975. This defines a structure variable named @code{f1}
  4976. whose type is @code{struct f1}. In C, a variable name or function name
  4977. never conflicts with a structure type tag.
  4978. Omitting the flexible array field's size lets the initializer
  4979. determine it. This is allowed only when the flexible array is defined
  4980. in the outermost structure and you declare a variable of that
  4981. structure type. For example:
  4982. @example
  4983. struct foo @{ int x; int y[]; @};
  4984. struct bar @{ struct foo z; @};
  4985. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4986. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4987. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4988. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4989. @end example
  4990. @node Overlaying Structures
  4991. @section Overlaying Different Structures
  4992. @cindex overlaying structures
  4993. @cindex structures, overlaying
  4994. Be careful about using different structure types to refer to the same
  4995. memory within one function, because GNU C can optimize code assuming
  4996. it never does that. @xref{Aliasing}. Here's an example of the kind of
  4997. aliasing that can cause the problem:
  4998. @example
  4999. struct a @{ int size; char *data; @};
  5000. struct b @{ int size; char *data; @};
  5001. struct a foo;
  5002. struct b *q = (struct b *) &foo;
  5003. @end example
  5004. Here @code{q} points to the same memory that the variable @code{foo}
  5005. occupies, but they have two different types. The two types
  5006. @code{struct a} and @code{struct b} are defined alike, but they are
  5007. not the same type. Interspersing references using the two types,
  5008. like this,
  5009. @example
  5010. p->size = 0;
  5011. q->size = 1;
  5012. x = p->size;
  5013. @end example
  5014. @noindent
  5015. allows GNU C to assume that @code{p->size} is still zero when it is
  5016. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5017. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5018. Other compilers might also do this optimization. The ISO C standard
  5019. considers such code erroneous, precisely so that this optimization
  5020. will be valid.
  5021. @node Structure Assignment
  5022. @section Structure Assignment
  5023. @cindex structure assignment
  5024. @cindex assigning structures
  5025. Assignment operating on a structure type copies the structure. The
  5026. left and right operands must have the same type. Here is an example:
  5027. @example
  5028. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5029. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5030. @r{@dots{}}
  5031. struct point @{ double x, y; @};
  5032. struct point *
  5033. copy_point (struct point point)
  5034. @{
  5035. struct point *p
  5036. = (struct point *) malloc (sizeof (struct point));
  5037. if (p == NULL)
  5038. fatal ("Out of memory");
  5039. *p = point;
  5040. return p;
  5041. @}
  5042. @end example
  5043. Notionally, assignment on a structure type works by copying each of
  5044. the fields. Thus, if any of the fields has the @code{const}
  5045. qualifier, that structure type does not allow assignment:
  5046. @example
  5047. struct point @{ const double x, y; @};
  5048. struct point a, b;
  5049. a = b; /* @r{Error!} */
  5050. @end example
  5051. @xref{Assignment Expressions}.
  5052. @node Unions
  5053. @section Unions
  5054. @cindex unions
  5055. @findex union
  5056. A @dfn{union type} defines alternative ways of looking at the same
  5057. piece of memory. Each alternative view is defined with a data type,
  5058. and identified by a name. A union definition looks like this:
  5059. @example
  5060. union @var{name}
  5061. @{
  5062. @var{alternative declarations}@r{@dots{}}
  5063. @};
  5064. @end example
  5065. Each alternative declaration looks like a structure field declaration,
  5066. except that it can't be a bit field. For instance,
  5067. @example
  5068. union number
  5069. @{
  5070. long int integer;
  5071. double float;
  5072. @}
  5073. @end example
  5074. @noindent
  5075. lets you store either an integer (type @code{long int}) or a floating
  5076. point number (type @code{double}) in the same place in memory. The
  5077. length and alignment of the union type are the maximum of all the
  5078. alternatives---they do not have to be the same. In this union
  5079. example, @code{double} probably takes more space than @code{long int},
  5080. but that doesn't cause a problem in programs that use the union in the
  5081. normal way.
  5082. The members don't have to be different in data type. Sometimes
  5083. each member pertains to a way the data will be used. For instance,
  5084. @example
  5085. union datum
  5086. @{
  5087. double latitude;
  5088. double longitude;
  5089. double height;
  5090. double weight;
  5091. int continent;
  5092. @}
  5093. @end example
  5094. This union holds one of several kinds of data; most kinds are floating
  5095. points, but the value can also be a code for a continent which is an
  5096. integer. You @emph{could} use one member of type @code{double} to
  5097. access all the values which have that type, but the different member
  5098. names will make the program clearer.
  5099. The alignment of a union type is the maximum of the alignments of the
  5100. alternatives. The size of the union type is the maximum of the sizes
  5101. of the alternatives, rounded up to a multiple of the alignment
  5102. (because every type's size must be a multiple of its alignment).
  5103. All the union alternatives start at the address of the union itself.
  5104. If an alternative is shorter than the union as a whole, it occupies
  5105. the first part of the union's storage, leaving the last part unused
  5106. @emph{for that alternative}.
  5107. @strong{Warning:} if the code stores data using one union alternative
  5108. and accesses it with another, the results depend on the kind of
  5109. computer in use. Only wizards should try to do this. However, when
  5110. you need to do this, a union is a clean way to do it.
  5111. Assignment works on any union type by copying the entire value.
  5112. @node Packing With Unions
  5113. @section Packing With Unions
  5114. Sometimes we design a union with the intention of packing various
  5115. kinds of objects into a certain amount of memory space. For example.
  5116. @example
  5117. union bytes8
  5118. @{
  5119. long long big_int_elt;
  5120. double double_elt;
  5121. struct @{ int first, second; @} two_ints;
  5122. struct @{ void *first, *second; @} two_ptrs;
  5123. @};
  5124. union bytes8 *p;
  5125. @end example
  5126. This union makes it possible to look at 8 bytes of data that @code{p}
  5127. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5128. single floating-point number (@code{p->double_elt}), as a pair of
  5129. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5130. as a pair of pointers (@code{p->two_ptrs.first} and
  5131. @code{p->two_ptrs.second}).
  5132. To pack storage with such a union makes assumptions about the sizes of
  5133. all the types involved. This particular union was written expecting a
  5134. pointer to have the same size as @code{int}. On a machine where one
  5135. pointer takes 8 bytes, the code using this union probably won't work
  5136. as expected. The union, as such, will function correctly---if you
  5137. store two values through @code{two_ints} and extract them through
  5138. @code{two_ints}, you will get the same integers back---but the part of
  5139. the program that expects the union to be 8 bytes long could
  5140. malfunction, or at least use too much space.
  5141. The above example shows one case where a @code{struct} type with no
  5142. tag can be useful. Another way to get effectively the same result
  5143. is with arrays as members of the union:
  5144. @example
  5145. union eight_bytes
  5146. @{
  5147. long long big_int_elt;
  5148. double double_elt;
  5149. int two_ints[2];
  5150. void *two_ptrs[2];
  5151. @};
  5152. @end example
  5153. @node Cast to Union
  5154. @section Cast to a Union Type
  5155. @cindex cast to a union
  5156. @cindex union, casting to a
  5157. In GNU C, you can explicitly cast any of the alternative types to the
  5158. union type; for instance,
  5159. @example
  5160. (union eight_bytes) (long long) 5
  5161. @end example
  5162. @noindent
  5163. makes a value of type @code{union eight_bytes} which gets its contents
  5164. through the alternative named @code{big_int_elt}.
  5165. The value being cast must exactly match the type of the alternative,
  5166. so this is not valid:
  5167. @example
  5168. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5169. @end example
  5170. A cast to union type looks like any other cast, except that the type
  5171. specified is a union type. You can specify the type either with
  5172. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5173. Typedef Names}).
  5174. Using the cast as the right-hand side of an assignment to a variable of
  5175. union type is equivalent to storing in an alternative of the union:
  5176. @example
  5177. union foo u;
  5178. u = (union foo) x @r{means} u.i = x
  5179. u = (union foo) y @r{means} u.d = y
  5180. @end example
  5181. You can also use the union cast as a function argument:
  5182. @example
  5183. void hack (union foo);
  5184. @r{@dots{}}
  5185. hack ((union foo) x);
  5186. @end example
  5187. @node Structure Constructors
  5188. @section Structure Constructors
  5189. @cindex structure constructors
  5190. @cindex constructors, structure
  5191. You can construct a structure value by writing its type in
  5192. parentheses, followed by an initializer that would be valid in a
  5193. declaration for that type. For instance, given this declaration,
  5194. @example
  5195. struct foo @{int a; char b[2];@} structure;
  5196. @end example
  5197. @noindent
  5198. you can create a @code{struct foo} value as follows:
  5199. @example
  5200. ((struct foo) @{x + y, 'a', 0@})
  5201. @end example
  5202. @noindent
  5203. This specifies @code{x + y} for field @code{a},
  5204. the character @samp{a} for field @code{b}'s element 0,
  5205. and the null character for field @code{b}'s element 1.
  5206. The parentheses around that constructor are to necessary, but we
  5207. recommend writing them to make the nesting of the containing
  5208. expression clearer.
  5209. You can also show the nesting of the two by writing it like
  5210. this:
  5211. @example
  5212. ((struct foo) @{x + y, @{'a', 0@} @})
  5213. @end example
  5214. Each of those is equivalent to writing the following statement
  5215. expression (@pxref{Statement Exprs}):
  5216. @example
  5217. (@{
  5218. struct foo temp = @{x + y, 'a', 0@};
  5219. temp;
  5220. @})
  5221. @end example
  5222. You can also create a union value this way, but it is not especially
  5223. useful since that is equivalent to doing a cast:
  5224. @example
  5225. ((union whosis) @{@var{value}@})
  5226. @r{is equivalent to}
  5227. ((union whosis) (@var{value}))
  5228. @end example
  5229. @node Unnamed Types as Fields
  5230. @section Unnamed Types as Fields
  5231. @cindex unnamed structures
  5232. @cindex unnamed unions
  5233. @cindex structures, unnamed
  5234. @cindex unions, unnamed
  5235. A structure or a union can contain, as fields,
  5236. unnamed structures and unions. Here's an example:
  5237. @example
  5238. struct
  5239. @{
  5240. int a;
  5241. union
  5242. @{
  5243. int b;
  5244. float c;
  5245. @};
  5246. int d;
  5247. @} foo;
  5248. @end example
  5249. @noindent
  5250. You can access the fields of the unnamed union within @code{foo} as if they
  5251. were individual fields at the same level as the union definition:
  5252. @example
  5253. foo.a = 42;
  5254. foo.b = 47;
  5255. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5256. foo.d = 314;
  5257. @end example
  5258. Avoid using field names that could cause ambiguity. For example, with
  5259. this definition:
  5260. @example
  5261. struct
  5262. @{
  5263. int a;
  5264. struct
  5265. @{
  5266. int a;
  5267. float b;
  5268. @};
  5269. @} foo;
  5270. @end example
  5271. @noindent
  5272. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5273. an error when a definition is ambiguous in this way.
  5274. @node Incomplete Types
  5275. @section Incomplete Types
  5276. @cindex incomplete types
  5277. @cindex types, incomplete
  5278. A type that has not been fully defined is called an @dfn{incomplete
  5279. type}. Structure and union types are incomplete when the code makes a
  5280. forward reference, such as @code{struct foo}, before defining the
  5281. type. An array type is incomplete when its length is unspecified.
  5282. You can't use an incomplete type to declare a variable or field, or
  5283. use it for a function parameter or return type. The operators
  5284. @code{sizeof} and @code{_Alignof} give errors when used on an
  5285. incomplete type.
  5286. However, you can define a pointer to an incomplete type, and declare a
  5287. variable or field with such a pointer type. In general, you can do
  5288. everything with such pointers except dereference them. For example:
  5289. @example
  5290. extern void bar (struct mysterious_value *);
  5291. void
  5292. foo (struct mysterious_value *arg)
  5293. @{
  5294. bar (arg);
  5295. @}
  5296. @r{@dots{}}
  5297. @{
  5298. struct mysterious_value *p, **q;
  5299. p = *q;
  5300. foo (p);
  5301. @}
  5302. @end example
  5303. @noindent
  5304. These examples are valid because the code doesn't try to understand
  5305. what @code{p} points to; it just passes the pointer around.
  5306. (Presumably @code{bar} is defined in some other file that really does
  5307. have a definition for @code{struct mysterious_value}.) However,
  5308. dereferencing the pointer would get an error; that requires a
  5309. definition for the structure type.
  5310. @node Intertwined Incomplete Types
  5311. @section Intertwined Incomplete Types
  5312. When several structure types contain pointers to each other, you can
  5313. define the types in any order because pointers to types that come
  5314. later are incomplete types. Thus,
  5315. Here is an example.
  5316. @example
  5317. /* @r{An employee record points to a group.} */
  5318. struct employee
  5319. @{
  5320. char *name;
  5321. @r{@dots{}}
  5322. struct group *group; /* @r{incomplete type.} */
  5323. @r{@dots{}}
  5324. @};
  5325. /* @r{An employee list points to employees.} */
  5326. struct employee_list
  5327. @{
  5328. struct employee *this_one;
  5329. struct employee_list *next; /* @r{incomplete type.} */
  5330. @r{@dots{}}
  5331. @};
  5332. /* @r{A group points to one employee_list.} */
  5333. struct group
  5334. @{
  5335. char *name;
  5336. @r{@dots{}}
  5337. struct employee_list *employees;
  5338. @r{@dots{}}
  5339. @};
  5340. @end example
  5341. @node Type Tags
  5342. @section Type Tags
  5343. @cindex type tags
  5344. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5345. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5346. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5347. name or function name; the type tags have a separate @dfn{name space}.
  5348. Thus, there is no name conflict in this code:
  5349. @example
  5350. struct pair @{ int a, b; @};
  5351. int pair = 1;
  5352. @end example
  5353. @noindent
  5354. nor in this one:
  5355. @example
  5356. struct pair @{ int a, b; @} pair;
  5357. @end example
  5358. @noindent
  5359. where @code{pair} is both a structure type tag and a variable name.
  5360. However, @code{struct}, @code{union}, and @code{enum} share the same
  5361. name space of tags, so this is a conflict:
  5362. @example
  5363. struct pair @{ int a, b; @};
  5364. enum pair @{ c, d @};
  5365. @end example
  5366. @noindent
  5367. and so is this:
  5368. @example
  5369. struct pair @{ int a, b; @};
  5370. struct pair @{ int c, d; @};
  5371. @end example
  5372. When the code defines a type tag inside a block, the tag's scope is
  5373. limited to that block (as for local variables). Two definitions for
  5374. one type tag do not conflict if they are in different scopes; rather,
  5375. each is valid in its scope. For example,
  5376. @example
  5377. struct pair @{ int a, b; @};
  5378. void
  5379. pair_up_doubles (int len, double array[])
  5380. @{
  5381. struct pair @{ double a, b; @};
  5382. @r{@dots{}}
  5383. @}
  5384. @end example
  5385. @noindent
  5386. has two definitions for @code{struct pair} which do not conflict. The
  5387. one inside the function applies only within the definition of
  5388. @code{pair_up_doubles}. Within its scope, that definition
  5389. @dfn{shadows} the outer definition.
  5390. If @code{struct pair} appears inside the function body, before the
  5391. inner definition, it refers to the outer definition---the only one
  5392. that has been seen at that point. Thus, in this code,
  5393. @example
  5394. struct pair @{ int a, b; @};
  5395. void
  5396. pair_up_doubles (int len, double array[])
  5397. @{
  5398. struct two_pairs @{ struct pair *p, *q; @};
  5399. struct pair @{ double a, b; @};
  5400. @r{@dots{}}
  5401. @}
  5402. @end example
  5403. @noindent
  5404. the structure @code{two_pairs} has pointers to the outer definition of
  5405. @code{struct pair}, which is probably not desirable.
  5406. To prevent that, you can write @code{struct pair;} inside the function
  5407. body as a variable declaration with no variables. This is a
  5408. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5409. type tag local to the current block, with the details of the type to
  5410. come later. Here's an example:
  5411. @example
  5412. void
  5413. pair_up_doubles (int len, double array[])
  5414. @{
  5415. /* @r{Forward declaration for @code{pair}.} */
  5416. struct pair;
  5417. struct two_pairs @{ struct pair *p, *q; @};
  5418. /* @r{Give the details.} */
  5419. struct pair @{ double a, b; @};
  5420. @r{@dots{}}
  5421. @}
  5422. @end example
  5423. However, the cleanest practice is to avoid shadowing type tags.
  5424. @node Arrays
  5425. @chapter Arrays
  5426. @cindex array
  5427. @cindex elements of arrays
  5428. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5429. all of the same data type. Each element is identified by its numeric
  5430. @var{index} within the array.
  5431. We presented arrays of numbers in the sample programs early in this
  5432. manual (@pxref{Array Example}). However, arrays can have elements of
  5433. any data type, including pointers, structures, unions, and other
  5434. arrays.
  5435. If you know another programming language, you may suppose that you know all
  5436. about arrays, but C arrays have special quirks, so in this chapter we
  5437. collect all the information about arrays in C@.
  5438. The elements of a C array are allocated consecutively in memory,
  5439. with no gaps between them. Each element is aligned as required
  5440. for its data type (@pxref{Type Alignment}).
  5441. @menu
  5442. * Accessing Array Elements:: How to access individual elements of an array.
  5443. * Declaring an Array:: How to name and reserve space for a new array.
  5444. * Strings:: A string in C is a special case of array.
  5445. * Array Type Designators:: Referring to a specific array type.
  5446. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5447. * Limitations of C Arrays:: Arrays are not first-class objects.
  5448. * Multidimensional Arrays:: Arrays of arrays.
  5449. * Constructing Array Values:: Assigning values to an entire array at once.
  5450. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5451. @end menu
  5452. @node Accessing Array Elements
  5453. @section Accessing Array Elements
  5454. @cindex accessing array elements
  5455. @cindex array elements, accessing
  5456. If the variable @code{a} is an array, the @var{n}th element of
  5457. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5458. an element's value or to assign to it:
  5459. @example
  5460. x = a[5];
  5461. a[6] = 1;
  5462. @end example
  5463. @noindent
  5464. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5465. lvalue.
  5466. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5467. valid index is one less than the number of elements.
  5468. The C language does not check whether array indices are in bounds, so
  5469. if the code uses an out-of-range index, it will access memory outside the
  5470. array.
  5471. @strong{Warning:} Using only valid index values in C is the
  5472. programmer's responsibility.
  5473. Array indexing in C is not a primitive operation: it is defined in
  5474. terms of pointer arithmetic and dereferencing. Now that we know
  5475. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5476. its job.
  5477. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5478. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5479. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5480. When an expression with array type (such as @code{a}) appears as part
  5481. of a larger C expression, it is converted automatically to a pointer
  5482. to element zero of that array. For instance, @code{a} in an
  5483. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5484. computed as @code{*(&a[0]+i)}.
  5485. Now we can analyze how that expression gives us the desired element of
  5486. the array. It makes a pointer to element 0 of @code{a}, advances it
  5487. by the value of @code{i}, and dereferences that pointer.
  5488. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5489. @node Declaring an Array
  5490. @section Declaring an Array
  5491. @cindex declaring an array
  5492. @cindex array, declaring
  5493. To make an array declaration, write @code{[@var{length}]} after the
  5494. name being declared. This construct is valid in the declaration of a
  5495. variable, a function parameter, a function value type (the value can't
  5496. be an array, but it can be a pointer to one), a structure field, or a
  5497. union alternative.
  5498. The surrounding declaration specifies the element type of the array;
  5499. that can be any type of data, but not @code{void} or a function type.
  5500. For instance,
  5501. @example
  5502. double a[5];
  5503. @end example
  5504. @noindent
  5505. declares @code{a} as an array of 5 @code{double}s.
  5506. @example
  5507. struct foo bstruct[length];
  5508. @end example
  5509. @noindent
  5510. declares @code{bstruct} as an array of @code{length} objects of type
  5511. @code{struct foo}. A variable array size like this is allowed when
  5512. the array is not file-scope.
  5513. Other declaration constructs can nest within the array declaration
  5514. construct. For instance:
  5515. @example
  5516. struct foo *b[length];
  5517. @end example
  5518. @noindent
  5519. declares @code{b} as an array of @code{length} pointers to
  5520. @code{struct foo}. This shows that the length need not be a constant
  5521. (@pxref{Arrays of Variable Length}).
  5522. @example
  5523. double (*c)[5];
  5524. @end example
  5525. @noindent
  5526. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5527. @example
  5528. char *(*f (int))[5];
  5529. @end example
  5530. @noindent
  5531. declares @code{f} as a function taking an @code{int} argument and
  5532. returning a pointer to an array of 5 strings (pointers to
  5533. @code{char}s).
  5534. @example
  5535. double aa[5][10];
  5536. @end example
  5537. @noindent
  5538. declares @code{aa} as an array of 5 elements, each of which is an
  5539. array of 10 @code{double}s. This shows how to declare a
  5540. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5541. All these declarations specify the array's length, which is needed in
  5542. these cases in order to allocate storage for the array.
  5543. @node Strings
  5544. @section Strings
  5545. @cindex string
  5546. A string in C is a sequence of elements of type @code{char},
  5547. terminated with the null character, the character with code zero.
  5548. Programs often need to use strings with specific, fixed contents. To
  5549. write one in a C program, use a @dfn{string constant} such as
  5550. @code{"Take me to your leader!"}. The data type of a string constant
  5551. is @code{char *}. For the full syntactic details of writing string
  5552. constants, @ref{String Constants}.
  5553. To declare a place to store a non-constant string, declare an array of
  5554. @code{char}. Keep in mind that it must include one extra @code{char}
  5555. for the terminating null. For instance,
  5556. @example
  5557. char text = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5558. @end example
  5559. @noindent
  5560. declares an array named @samp{text} with six elements---five letters
  5561. and the terminating null character. An equivalent way to get the same
  5562. result is this,
  5563. @example
  5564. char text = "Hello";
  5565. @end example
  5566. @noindent
  5567. which copies the elements of the string constant, including @emph{its}
  5568. terminating null character.
  5569. @example
  5570. char message[200];
  5571. @end example
  5572. @noindent
  5573. declares an array long enough to hold a string of 199 ASCII characters
  5574. plus the terminating null character.
  5575. When you store a string into @code{message} be sure to check or prove
  5576. that the length does not exceed its size. For example,
  5577. @example
  5578. void
  5579. set_message (char *text)
  5580. @{
  5581. int i;
  5582. for (i = 0; i < sizeof (message); i++)
  5583. @{
  5584. message[i] = text[i];
  5585. if (text[i] == 0)
  5586. return;
  5587. @}
  5588. fatal_error ("Message is too long for `message');
  5589. @}
  5590. @end example
  5591. It's easy to do this with the standard library function
  5592. @code{strncpy}, which fills out the whole destination array (up to a
  5593. specified length) with null characters. Thus, if the last character
  5594. of the destination is not null, the string did not fit. Many system
  5595. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5596. to run faster than an explicit @code{for}-loop.
  5597. Here's what the code looks like:
  5598. @example
  5599. void
  5600. set_message (char *text)
  5601. @{
  5602. strncpy (message, text, sizeof (message));
  5603. if (message[sizeof (message) - 1] != 0)
  5604. fatal_error ("Message is too long for `message');
  5605. @}
  5606. @end example
  5607. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5608. Library Reference Manual}, for more information about the standard
  5609. library functions for operating on strings.
  5610. You can avoid putting a fixed length limit on strings you construct or
  5611. operate on by allocating the space for them dynamically.
  5612. @xref{Dynamic Memory Allocation}.
  5613. @node Array Type Designators
  5614. @section Array Type Designators
  5615. Every C type has a type designator, which you make by deleting the
  5616. variable name and the semicolon from a declaration (@pxref{Type
  5617. Designators}). The designators for array types follow this rule, but
  5618. they may appear surprising.
  5619. @example
  5620. @r{type} int a[5]; @r{designator} int [5]
  5621. @r{type} double a[5][3]; @r{designator} double [5][3]
  5622. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5623. @end example
  5624. @node Incomplete Array Types
  5625. @section Incomplete Array Types
  5626. @cindex incomplete array types
  5627. @cindex array types, incomplete
  5628. An array is equivalent, for most purposes, to a pointer to its zeroth
  5629. element. When that is true, the length of the array is irrelevant.
  5630. The length needs to be known only for allocating space for the array, or
  5631. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5632. contexts C allows
  5633. @itemize @bullet
  5634. @item
  5635. An @code{extern} declaration says how to refer to a variable allocated
  5636. elsewhere. It does not need to allocate space for the variable,
  5637. so if it is an array, you can omit the length. For example,
  5638. @example
  5639. extern int foo[];
  5640. @end example
  5641. @item
  5642. When declaring a function parameter as an array, the argument value
  5643. passed to the function is really a pointer to the array's zeroth
  5644. element. This value does not say how long the array really is, there
  5645. is no need to declare it. For example,
  5646. @example
  5647. int
  5648. func (int foo[])
  5649. @end example
  5650. @end itemize
  5651. These declarations are examples of @dfn{incomplete} array types, types
  5652. that are not fully specified. The incompleteness makes no difference
  5653. for accessing elements of the array, but it matters for some other
  5654. things. For instance, @code{sizeof} is not allowed on an incomplete
  5655. type.
  5656. With multidimensional arrays, only the first dimension can be omitted:
  5657. @example
  5658. extern struct chesspiece *funnyboard foo[][8];
  5659. @end example
  5660. In other words, the code doesn't have to say how many rows there are,
  5661. but it must state how big each row is.
  5662. @node Limitations of C Arrays
  5663. @section Limitations of C Arrays
  5664. @cindex limitations of C arrays
  5665. @cindex first-class object
  5666. Arrays have quirks in C because they are not ``first-class objects'':
  5667. there is no way in C to operate on an array as a unit.
  5668. The other composite objects in C, structures and unions, are
  5669. first-class objects: a C program can copy a structure or union value
  5670. in an assignment, or pass one as an argument to a function, or make a
  5671. function return one. You can't do those things with an array in C@.
  5672. That is because a value you can operate on never has an array type.
  5673. An expression in C can have an array type, but that doesn't produce
  5674. the array as a value. Instead it is converted automatically to a
  5675. pointer to the array's element at index zero. The code can operate
  5676. on the pointer, and through that on individual elements of the array,
  5677. but it can't get and operate on the array as a unit.
  5678. There are three exceptions to this conversion rule, but none of them
  5679. offers a way to operate on the array as a whole.
  5680. First, @samp{&} applied to an expression with array type gives you the
  5681. address of the array, as an array type. However, you can't operate on the
  5682. whole array that way---if you apply @samp{*} to get the array back,
  5683. that expression converts, as usual, to a pointer to its zeroth
  5684. element.
  5685. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5686. @code{typeof} do not convert the array to a pointer; they leave it as
  5687. an array. But they don't operate on the array's data---they only give
  5688. information about its type.
  5689. Third, a string constant used as an initializer for an array is not
  5690. converted to a pointer---rather, the declaration copies the
  5691. @emph{contents} of that string in that one special case.
  5692. You @emph{can} copy the contents of an array, just not with an
  5693. assignment operator. You can do it by calling the library function
  5694. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5695. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5696. when a structure contains just an array, you can copy that structure.
  5697. An array itself is an lvalue if it is a declared variable, or part of
  5698. a structure or union that is an lvalue. When you construct an array
  5699. from elements (@pxref{Constructing Array Values}), that array is not
  5700. an lvalue.
  5701. @node Multidimensional Arrays
  5702. @section Multidimensional Arrays
  5703. @cindex multidimensional arrays
  5704. @cindex array, multidimensional
  5705. Strictly speaking, all arrays in C are unidimensional. However, you
  5706. can create an array of arrays, which is more or less equivalent to a
  5707. multidimensional array. For example,
  5708. @example
  5709. struct chesspiece *board[8][8];
  5710. @end example
  5711. @noindent
  5712. declares an array of 8 arrays of 8 pointers to @code{struct
  5713. chesspiece}. This data type could represent the state of a chess
  5714. game. To access one square's contents requires two array index
  5715. operations, one for each dimension. For instance, you can write
  5716. @code{board[row][column]}, assuming @code{row} and @code{column}
  5717. are variables with integer values in the proper range.
  5718. How does C understand @code{board[row][column]}? First of all,
  5719. @code{board} is converted automatically to a pointer to the zeroth
  5720. element (at index zero) of @code{board}. Adding @code{row} to that
  5721. makes it point to the desired element. Thus, @code{board[row]}'s
  5722. value is an element of @code{board}---an array of 8 pointers.
  5723. However, as an expression with array type, it is converted
  5724. automatically to a pointer to the array's zeroth element. The second
  5725. array index operation, @code{[column]}, accesses the chosen element
  5726. from that array.
  5727. As this shows, pointer-to-array types are meaningful in C@.
  5728. You can declare a variable that points to a row in a chess board
  5729. like this:
  5730. @example
  5731. struct chesspiece *(*rowptr)[8];
  5732. @end example
  5733. @noindent
  5734. This points to an array of 8 pointers to @code{struct chesspiece}.
  5735. You can assign to it as follows:
  5736. @example
  5737. rowptr = &board[5];
  5738. @end example
  5739. The dimensions don't have to be equal in length. Here we declare
  5740. @code{statepop} as an array to hold the population of each state in
  5741. the United States for each year since 1900:
  5742. @example
  5743. #define NSTATES 50
  5744. @{
  5745. int nyears = current_year - 1900 + 1;
  5746. int statepop[NSTATES][nyears];
  5747. @r{@dots{}}
  5748. @}
  5749. @end example
  5750. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5751. each indexed by the year (counting from 1900). Thus, to get the
  5752. element for a particular state and year, we must subscript it first
  5753. by the number that indicates the state, and second by the index for
  5754. the year:
  5755. @example
  5756. statepop[state][year - 1900]
  5757. @end example
  5758. @cindex array, layout in memory
  5759. The subarrays within the multidimensional array are allocated
  5760. consecutively in memory, and within each subarray, its elements are
  5761. allocated consecutively in memory. The most efficient way to process
  5762. all the elements in the array is to scan the last subscript in the
  5763. innermost loop. This means consecutive accesses go to consecutive
  5764. memory locations, which optimizes use of the processor's memory cache.
  5765. For example:
  5766. @example
  5767. int total = 0;
  5768. float average;
  5769. for (int state = 0; state < NSTATES, ++state)
  5770. @{
  5771. for (int year = 0; year < nyears; ++year)
  5772. @{
  5773. total += statepop[state][year];
  5774. @}
  5775. @}
  5776. average = total / nyears;
  5777. @end example
  5778. C's layout for multidimensional arrays is different from Fortran's
  5779. layout. In Fortran, a multidimensional array is not an array of
  5780. arrays; rather, multidimensional arrays are a primitive feature, and
  5781. it is the first index that varies most rapidly between consecutive
  5782. memory locations. Thus, the memory layout of a 50x114 array in C
  5783. matches that of a 114x50 array in Fortran.
  5784. @node Constructing Array Values
  5785. @section Constructing Array Values
  5786. @cindex constructing array values
  5787. @cindex array values, constructing
  5788. You can construct an array from elements by writing them inside
  5789. braces, and preceding all that with the array type's designator in
  5790. parentheses. There is no need to specify the array length, since the
  5791. number of elements determines that. The constructor looks like this:
  5792. @example
  5793. (@var{elttype}[]) @{ @var{elements} @};
  5794. @end example
  5795. Here is an example, which constructs an array of string pointers:
  5796. @example
  5797. (char *[]) @{ "x", "y", "z" @};
  5798. @end example
  5799. That's equivalent in effect to declaring an array with the same
  5800. initializer, like this:
  5801. @example
  5802. char *array[] = @{ "x", "y", "z" @};
  5803. @end example
  5804. and then using the array.
  5805. If all the elements are simple constant expressions, or made up of
  5806. such, then the compound literal can be coerced to a pointer to its
  5807. zeroth element and used to initialize a file-scope variable
  5808. (@pxref{File-Scope Variables}), as shown here:
  5809. @example
  5810. char **foo = (char *[]) @{ "x", "y", "z" @};
  5811. @end example
  5812. @noindent
  5813. The data type of @code{foo} is @code{char **}, which is a pointer
  5814. type, not an array type. The declaration is equivalent to defining
  5815. and then using an array-type variable:
  5816. @example
  5817. char *nameless_array[] = @{ "x", "y", "z" @};
  5818. char **foo = &nameless_array[0];
  5819. @end example
  5820. @node Arrays of Variable Length
  5821. @section Arrays of Variable Length
  5822. @cindex array of variable length
  5823. @cindex variable-length arrays
  5824. In GNU C, you can declare variable-length arrays like any other
  5825. arrays, but with a length that is not a constant expression. The
  5826. storage is allocated at the point of declaration and deallocated when
  5827. the block scope containing the declaration exits. For example:
  5828. @example
  5829. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5830. #include <string.h> /* @r{Declares @code{str}.} */
  5831. FILE *
  5832. concat_fopen (char *s1, char *s2, char *mode)
  5833. @{
  5834. char str[strlen (s1) + strlen (s2) + 1];
  5835. strcpy (str, s1);
  5836. strcat (str, s2);
  5837. return fopen (str, mode);
  5838. @}
  5839. @end example
  5840. @noindent
  5841. (This uses some standard library functions; see @ref{String and Array
  5842. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5843. The length of an array is computed once when the storage is allocated
  5844. and is remembered for the scope of the array in case it is used in
  5845. @code{sizeof}.
  5846. @strong{Warning:} don't allocate a variable-length array if the size
  5847. might be very large (more than 100,000), or in a recursive function,
  5848. because that is likely to cause stack overflow. Allocate the array
  5849. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5850. Jumping or breaking out of the scope of the array name deallocates the
  5851. storage. Jumping into the scope is not allowed; that gives an error
  5852. message.
  5853. You can also use variable-length arrays as arguments to functions:
  5854. @example
  5855. struct entry
  5856. tester (int len, char data[len][len])
  5857. @{
  5858. @r{@dots{}}
  5859. @}
  5860. @end example
  5861. As usual, a function argument declared with an array type
  5862. is really a pointer to an array that already exists.
  5863. Calling the function does not allocate the array, so there's no
  5864. particular danger of stack overflow in using this construct.
  5865. To pass the array first and the length afterward, use a forward
  5866. declaration in the function's parameter list (another GNU extension).
  5867. For example,
  5868. @example
  5869. struct entry
  5870. tester (int len; char data[len][len], int len)
  5871. @{
  5872. @r{@dots{}}
  5873. @}
  5874. @end example
  5875. The @code{int len} before the semicolon is a @dfn{parameter forward
  5876. declaration}, and it serves the purpose of making the name @code{len}
  5877. known when the declaration of @code{data} is parsed.
  5878. You can write any number of such parameter forward declarations in the
  5879. parameter list. They can be separated by commas or semicolons, but
  5880. the last one must end with a semicolon, which is followed by the
  5881. ``real'' parameter declarations. Each forward declaration must match
  5882. a ``real'' declaration in parameter name and data type. ISO C11 does
  5883. not support parameter forward declarations.
  5884. @node Enumeration Types
  5885. @chapter Enumeration Types
  5886. @cindex enumeration types
  5887. @cindex types, enumeration
  5888. @cindex enumerator
  5889. An @dfn{enumeration type} represents a limited set of integer values,
  5890. each with a name. It is effectively equivalent to a primitive integer
  5891. type.
  5892. Suppose we have a list of possible emotional states to store in an
  5893. integer variable. We can give names to these alternative values with
  5894. an enumeration:
  5895. @example
  5896. enum emotion_state @{ neutral, happy, sad, worried,
  5897. calm, nervous @};
  5898. @end example
  5899. @noindent
  5900. (Never mind that this is a simplistic way to classify emotional states;
  5901. it's just a code example.)
  5902. The names inside the enumeration are called @dfn{enumerators}. The
  5903. enumeration type defines them as constants, and their values are
  5904. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5905. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5906. the enumerators explicitly like this:
  5907. @example
  5908. enum emotion_state @{ neutral = 2, happy = 5,
  5909. sad = 20, worried = 10,
  5910. calm = -5, nervous = -300 @};
  5911. @end example
  5912. Each enumerator which does not specify a value gets value zero
  5913. (if it is at the beginning) or the next consecutive integer.
  5914. @example
  5915. /* @r{@code{neutral} is 0 by default,}
  5916. @r{and @code{worried} is 21 by default.} */
  5917. enum emotion_state @{ neutral,
  5918. happy = 5, sad = 20, worried,
  5919. calm = -5, nervous = -300 @};
  5920. @end example
  5921. If an enumerator is obsolete, you can specify that using it should
  5922. cause a warning, by including an attribute in the enumerator's
  5923. declaration. Here is how @code{happy} would look with this
  5924. attribute:
  5925. @example
  5926. happy __attribute__
  5927. ((deprecated
  5928. ("impossible under plutocratic rule")))
  5929. = 5,
  5930. @end example
  5931. @xref{Attributes}.
  5932. You can declare variables with the enumeration type:
  5933. @example
  5934. enum emotion_state feelings_now;
  5935. @end example
  5936. In the C code itself, this is equivalent to declaring the variable
  5937. @code{int}. (If all the enumeration values are positive, it is
  5938. equivalent to @code{unsigned int}.) However, declaring it with the
  5939. enumeration type has an advantage in debugging, because GDB knows it
  5940. should display the current value of the variable using the
  5941. corresponding name. If the variable's type is @code{int}, GDB can
  5942. only show the value as a number.
  5943. The identifier that follows @code{enum} is called a @dfn{type tag}
  5944. since it distinguishes different enumeration types. Type tags are in
  5945. a separate name space and belong to scopes like most other names in C@.
  5946. @xref{Type Tags}, for explanation.
  5947. You can predeclare an @code{enum} type tag like a structure or union
  5948. type tag, like this:
  5949. @example
  5950. enum foo;
  5951. @end example
  5952. @noindent
  5953. The @code{enum} type is incomplete until you finish defining it.
  5954. You can optionally include a trailing comma at the end of a list of
  5955. enumeration values:
  5956. @example
  5957. enum emotion_state @{ neutral, happy, sad, worried,
  5958. calm, nervous, @};
  5959. @end example
  5960. @noindent
  5961. This is useful in some macro definitions, since it enables you to
  5962. assemble the list of enumerators without knowing which one is last.
  5963. The extra comma does not change the meaning of the enumeration in any
  5964. way.
  5965. @node Defining Typedef Names
  5966. @chapter Defining Typedef Names
  5967. @cindex typedef names
  5968. @findex typedef
  5969. You can define a data type keyword as an alias for any type, and then
  5970. use the alias syntactically like a built-in type keyword such as
  5971. @code{int}. You do this using @code{typedef}, so these aliases are
  5972. also called @dfn{typedef names}.
  5973. @code{typedef} is followed by text that looks just like a variable
  5974. declaration, but instead of declaring variables it defines data type
  5975. keywords.
  5976. Here's how to define @code{fooptr} as a typedef alias for the type
  5977. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5978. with that type:
  5979. @example
  5980. typedef struct foo *fooptr;
  5981. fooptr x, y;
  5982. @end example
  5983. @noindent
  5984. That declaration is equivalent to the following one:
  5985. @example
  5986. struct foo *x, *y;
  5987. @end example
  5988. You can define a typedef alias for any type. For instance, this makes
  5989. @code{frobcount} an alias for type @code{int}:
  5990. @example
  5991. typedef int frobcount;
  5992. @end example
  5993. @noindent
  5994. This doesn't define a new type distinct from @code{int}. Rather,
  5995. @code{frobcount} is another name for the type @code{int}. Once the
  5996. variable is declared, it makes no difference which name the
  5997. declaration used.
  5998. There is a syntactic difference, however, between @code{frobcount} and
  5999. @code{int}: A typedef name cannot be used with
  6000. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6001. to specify the type all by itself. So you can't write this:
  6002. @example
  6003. unsigned frobcount f1; /* @r{Error!} */
  6004. @end example
  6005. But you can write this:
  6006. @example
  6007. typedef unsigned int unsigned_frobcount;
  6008. unsigned_frobcount f1;
  6009. @end example
  6010. In other words, a typedef name is not an alias for @emph{a keyword}
  6011. such as @code{int}. It stands for a @emph{type}, and that could be
  6012. the type @code{int}.
  6013. Typedef names are in the same namespace as functions and variables, so
  6014. you can't use the same name for a typedef and a function, or a typedef
  6015. and a variable. When a typedef is declared inside a code block, it is
  6016. in scope only in that block.
  6017. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6018. because many of these have standard meanings.
  6019. You can redefine a typedef name to the exact same type as its first
  6020. definition, but you cannot redefine a typedef name to a
  6021. different type, even if the two types are compatible. For example, this
  6022. is valid:
  6023. @example
  6024. typedef int frobcount;
  6025. typedef int frotzcount;
  6026. typedef frotzcount frobcount;
  6027. typedef frobcount frotzcount;
  6028. @end example
  6029. @noindent
  6030. because each typedef name is always defined with the same type
  6031. (@code{int}), but this is not valid:
  6032. @example
  6033. enum foo @{f1, f2, f3@};
  6034. typedef enum foo frobcount;
  6035. typedef int frobcount;
  6036. @end example
  6037. @noindent
  6038. Even though the type @code{enum foo} is compatible with @code{int},
  6039. they are not the @emph{same} type.
  6040. @node Statements
  6041. @chapter Statements
  6042. @cindex statements
  6043. A @dfn{statement} specifies computations to be done for effect; it
  6044. does not produce a value, as an expression would. In general a
  6045. statement ends with a semicolon (@samp{;}), but blocks (which are
  6046. statements, more or less) are an exception to that rule.
  6047. @ifnottex
  6048. @xref{Blocks}.
  6049. @end ifnottex
  6050. The places to use statements are inside a block, and inside a
  6051. complex statement. A @dfn{complex statement} contains one or two
  6052. components that are nested statements. Each such component must
  6053. consist of one and only one statement. The way to put multiple
  6054. statements in such a component is to group them into a @dfn{block}
  6055. (@pxref{Blocks}), which counts as one statement.
  6056. The following sections describe the various kinds of statement.
  6057. @menu
  6058. * Expression Statement:: Evaluate an expression, as a statement,
  6059. usually done for a side effect.
  6060. * if Statement:: Basic conditional execution.
  6061. * if-else Statement:: Multiple branches for conditional execution.
  6062. * Blocks:: Grouping multiple statements together.
  6063. * return Statement:: Return a value from a function.
  6064. * Loop Statements:: Repeatedly executing a statement or block.
  6065. * switch Statement:: Multi-way conditional choices.
  6066. * switch Example:: A plausible example of using @code{switch}.
  6067. * Duffs Device:: A special way to use @code{switch}.
  6068. * Case Ranges:: Ranges of values for @code{switch} cases.
  6069. * Null Statement:: A statement that does nothing.
  6070. * goto Statement:: Jump to another point in the source code,
  6071. identified by a label.
  6072. * Local Labels:: Labels with limited scope.
  6073. * Labels as Values:: Getting the address of a label.
  6074. * Statement Exprs:: A series of statements used as an expression.
  6075. @end menu
  6076. @node Expression Statement
  6077. @section Expression Statement
  6078. @cindex expression statement
  6079. @cindex statement, expression
  6080. The most common kind of statement in C is an @dfn{expression statement}.
  6081. It consists of an expression followed by a
  6082. semicolon. The expression's value is discarded, so the expressions
  6083. that are useful are those that have side effects: assignment
  6084. expressions, increment and decrement expressions, and function calls.
  6085. Here are examples of expression statements:
  6086. @smallexample
  6087. x = 5; /* @r{Assignment expression.} */
  6088. p++; /* @r{Increment expression.} */
  6089. printf ("Done\n"); /* @r{Function call expression.} */
  6090. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6091. x + y; /* @r{Useless statement without effect.} */
  6092. @end smallexample
  6093. In very unusual circumstances we use an expression statement
  6094. whose purpose is to get a fault if an address is invalid:
  6095. @smallexample
  6096. volatile char *p;
  6097. @r{@dots{}}
  6098. *p; /* @r{Cause signal if @code{p} is null.} */
  6099. @end smallexample
  6100. If the target of @code{p} is not declared @code{volatile}, the
  6101. compiler might optimize away the memory access, since it knows that
  6102. the value isn't really used. @xref{volatile}.
  6103. @node if Statement
  6104. @section @code{if} Statement
  6105. @cindex @code{if} statement
  6106. @cindex statement, @code{if}
  6107. @findex if
  6108. An @code{if} statement computes an expression to decide
  6109. whether to execute the following statement or not.
  6110. It looks like this:
  6111. @example
  6112. if (@var{condition})
  6113. @var{execute-if-true}
  6114. @end example
  6115. The first thing this does is compute the value of @var{condition}. If
  6116. that is true (nonzero), then it executes the statement
  6117. @var{execute-if-true}. If the value of @var{condition} is false
  6118. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6119. nothing.
  6120. This is a @dfn{complex statement} because it contains a component
  6121. @var{if-true-substatement} that is a nested statement. It must be one
  6122. and only one statement. The way to put multiple statements there is
  6123. to group them into a @dfn{block} (@pxref{Blocks}).
  6124. @node if-else Statement
  6125. @section @code{if-else} Statement
  6126. @cindex @code{if}@dots{}@code{else} statement
  6127. @cindex statement, @code{if}@dots{}@code{else}
  6128. @findex else
  6129. An @code{if}-@code{else} statement computes an expression to decide
  6130. which of two nested statements to execute.
  6131. It looks like this:
  6132. @example
  6133. if (@var{condition})
  6134. @var{if-true-substatement}
  6135. else
  6136. @var{if-false-substatement}
  6137. @end example
  6138. The first thing this does is compute the value of @var{condition}. If
  6139. that is true (nonzero), then it executes the statement
  6140. @var{if-true-substatement}. If the value of @var{condition} is false
  6141. (zero), then it executes the statement @var{if-false-substatement} instead.
  6142. This is a @dfn{complex statement} because it contains components
  6143. @var{if-true-substatement} and @var{if-else-substatement} that are
  6144. nested statements. Each must be one and only one statement. The way
  6145. to put multiple statements in such a component is to group them into a
  6146. @dfn{block} (@pxref{Blocks}).
  6147. @node Blocks
  6148. @section Blocks
  6149. @cindex block
  6150. @cindex compound statement
  6151. A @dfn{block} is a construct that contains multiple statements of any
  6152. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6153. series of statements and declarations in between. Another name for
  6154. blocks is @dfn{compound statements}.
  6155. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6156. normal statement---it does not end with a semicolon. But you can
  6157. @emph{use} it like a statement; anywhere that a statement is required
  6158. or allowed, you can write a block and consider that block a statement.
  6159. So far it seems that a block is a kind of statement with an unusual
  6160. syntax. But that is not entirely true: a function body is also a
  6161. block, and that block is definitely not a statement. The text after a
  6162. function header is not treated as a statement; only a function body is
  6163. allowed there, and nothing else would be meaningful there.
  6164. In a formal grammar we would have to choose---either a block is a kind
  6165. of statement or it is not. But this manual is meant for humans, not
  6166. for parser generators. The clearest answer for humans is, ``a block
  6167. is a statement, in some ways.''
  6168. @cindex nested block
  6169. @cindex internal block
  6170. A block that isn't a function body is called an @dfn{internal block}
  6171. or a @dfn{nested block}. You can put a nested block directly inside
  6172. another block, but more often the nested block is inside some complex
  6173. statement, such as a @code{for} statement or an @code{if} statement.
  6174. There are two uses for nested blocks in C:
  6175. @itemize @bullet
  6176. @item
  6177. To specify the scope for local declarations. For instance, a local
  6178. variable's scope is the rest of the innermost containing block.
  6179. @item
  6180. To write a series of statements where, syntactically, one statement is
  6181. called for. For instance, the @var{execute-if-true} of an @code{if}
  6182. statement is one statement. To put multiple statements there, they
  6183. have to be wrapped in a block, like this:
  6184. @example
  6185. if (x < 0)
  6186. @{
  6187. printf ("x was negative\n");
  6188. x = -x;
  6189. @}
  6190. @end example
  6191. @end itemize
  6192. This example (repeated from above) shows a nested block which serves
  6193. both purposes: it includes two statements (plus a declaration) in the
  6194. body of a @code{while} statement, and it provides the scope for the
  6195. declaration of @code{q}.
  6196. @example
  6197. void
  6198. free_intlist (struct intlistlink *p)
  6199. @{
  6200. while (p)
  6201. @{
  6202. struct intlistlink *q = p;
  6203. p = p->next;
  6204. free (q);
  6205. @}
  6206. @}
  6207. @end example
  6208. @node return Statement
  6209. @section @code{return} Statement
  6210. @cindex @code{return} statement
  6211. @cindex statement, @code{return}
  6212. @findex return
  6213. The @code{return} statement makes the containing function return
  6214. immediately. It has two forms. This one specifies no value to
  6215. return:
  6216. @example
  6217. return;
  6218. @end example
  6219. @noindent
  6220. That form is meant for functions whose return type is @code{void}
  6221. (@pxref{The Void Type}). You can also use it in a function that
  6222. returns nonvoid data, but that's a bad idea, since it makes the
  6223. function return garbage.
  6224. The form that specifies a value looks like this:
  6225. @example
  6226. return @var{value};
  6227. @end example
  6228. @noindent
  6229. which computes the expression @var{value} and makes the function
  6230. return that. If necessary, the value undergoes type conversion to
  6231. the function's declared return value type, which works like
  6232. assigning the value to a variable of that type.
  6233. @node Loop Statements
  6234. @section Loop Statements
  6235. @cindex loop statements
  6236. @cindex statements, loop
  6237. @cindex iteration
  6238. You can use a loop statement when you need to execute a series of
  6239. statements repeatedly, making an @dfn{iteration}. C provides several
  6240. different kinds of loop statements, described in the following
  6241. subsections.
  6242. Every kind of loop statement is a complex statement because contains a
  6243. component, here called @var{body}, which is a nested statement.
  6244. Most often the body is a block.
  6245. @menu
  6246. * while Statement:: Loop as long as a test expression is true.
  6247. * do-while Statement:: Execute a loop once, with further looping
  6248. as long as a test expression is true.
  6249. * break Statement:: End a loop immediately.
  6250. * for Statement:: Iterative looping.
  6251. * Example of for:: An example of iterative looping.
  6252. * Omitted for-Expressions:: for-loop expression options.
  6253. * for-Index Declarations:: for-loop declaration options.
  6254. * continue Statement:: Begin the next cycle of a loop.
  6255. @end menu
  6256. @node while Statement
  6257. @subsection @code{while} Statement
  6258. @cindex @code{while} statement
  6259. @cindex statement, @code{while}
  6260. @findex while
  6261. The @code{while} statement is the simplest loop construct.
  6262. It looks like this:
  6263. @example
  6264. while (@var{test})
  6265. @var{body}
  6266. @end example
  6267. Here, @var{body} is a statement (often a nested block) to repeat, and
  6268. @var{test} is the test expression that controls whether to repeat it again.
  6269. Each iteration of the loop starts by computing @var{test} and, if it
  6270. is true (nonzero), that means the loop should execute @var{body} again
  6271. and then start over.
  6272. Here's an example of advancing to the last structure in a chain of
  6273. structures chained through the @code{next} field:
  6274. @example
  6275. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6276. @r{@dots{}}
  6277. while (chain->next != NULL)
  6278. chain = chain->next;
  6279. @end example
  6280. @noindent
  6281. This code assumes the chain isn't empty to start with; if the chain is
  6282. empty (that is, if @code{chain} is a null pointer), the code gets a
  6283. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6284. @node do-while Statement
  6285. @subsection @code{do-while} Statement
  6286. @cindex @code{do}--@code{while} statement
  6287. @cindex statement, @code{do}--@code{while}
  6288. @findex do
  6289. The @code{do}--@code{while} statement is a simple loop construct that
  6290. performs the test at the end of the iteration.
  6291. @example
  6292. do
  6293. @var{body}
  6294. while (@var{test});
  6295. @end example
  6296. Here, @var{body} is a statement (possibly a block) to repeat, and
  6297. @var{test} is an expression that controls whether to repeat it again.
  6298. Each iteration of the loop starts by executing @var{body}. Then it
  6299. computes @var{test} and, if it is true (nonzero), that means to go
  6300. back and start over with @var{body}. If @var{test} is false (zero),
  6301. then the loop stops repeating and execution moves on past it.
  6302. @node break Statement
  6303. @subsection @code{break} Statement
  6304. @cindex @code{break} statement
  6305. @cindex statement, @code{break}
  6306. @findex break
  6307. The @code{break} statement looks like @samp{break;}. Its effect is to
  6308. exit immediately from the innermost loop construct or @code{switch}
  6309. statement (@pxref{switch Statement}).
  6310. For example, this loop advances @code{p} until the next null
  6311. character or newline.
  6312. @example
  6313. while (*p)
  6314. @{
  6315. /* @r{End loop if we have reached a newline.} */
  6316. if (*p == '\n')
  6317. break;
  6318. p++
  6319. @}
  6320. @end example
  6321. When there are nested loops, the @code{break} statement exits from the
  6322. innermost loop containing it.
  6323. @example
  6324. struct list_if_tuples
  6325. @{
  6326. struct list_if_tuples next;
  6327. int length;
  6328. data *contents;
  6329. @};
  6330. void
  6331. process_all_elements (struct list_if_tuples *list)
  6332. @{
  6333. while (list)
  6334. @{
  6335. /* @r{Process all the elements in this node's vector,}
  6336. @r{stopping when we reach one that is null.} */
  6337. for (i = 0; i < list->length; i++
  6338. @{
  6339. /* @r{Null element terminates this node's vector.} */
  6340. if (list->contents[i] == NULL)
  6341. /* @r{Exit the @code{for} loop.} */
  6342. break;
  6343. /* @r{Operate on the next element.} */
  6344. process_element (list->contents[i]);
  6345. @}
  6346. list = list->next;
  6347. @}
  6348. @}
  6349. @end example
  6350. The only way in C to exit from an outer loop is with
  6351. @code{goto} (@pxref{goto Statement}).
  6352. @node for Statement
  6353. @subsection @code{for} Statement
  6354. @cindex @code{for} statement
  6355. @cindex statement, @code{for}
  6356. @findex for
  6357. A @code{for} statement uses three expressions written inside a
  6358. parenthetical group to define the repetition of the loop. The first
  6359. expression says how to prepare to start the loop. The second says how
  6360. to test, before each iteration, whether to continue looping. The
  6361. third says how to advance, at the end of an iteration, for the next
  6362. iteration. All together, it looks like this:
  6363. @example
  6364. for (@var{start}; @var{continue-test}; @var{advance})
  6365. @var{body}
  6366. @end example
  6367. The first thing the @code{for} statement does is compute @var{start}.
  6368. The next thing it does is compute the expression @var{continue-test}.
  6369. If that expression is false (zero), the @code{for} statement finishes
  6370. immediately, so @var{body} is executed zero times.
  6371. However, if @var{continue-test} is true (nonzero), the @code{for}
  6372. statement executes @var{body}, then @var{advance}. Then it loops back
  6373. to the not-quite-top to test @var{continue-test} again. But it does
  6374. not compute @var{start} again.
  6375. @node Example of for
  6376. @subsection Example of @code{for}
  6377. Here is the @code{for} statement from the iterative Fibonacci
  6378. function:
  6379. @example
  6380. int i;
  6381. for (i = 1; i < n; ++i)
  6382. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6383. /* @r{since @code{i < n} is false the first time.} */
  6384. @{
  6385. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6386. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6387. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6388. int next = prev + last;
  6389. /* @r{Shift the values down.} */
  6390. prev = last;
  6391. last = next;
  6392. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6393. @r{and @var{prev} is @code{fib (@var{i})}.}
  6394. @r{But that won't stay true for long,}
  6395. @r{because we are about to increment @var{i}.} */
  6396. @}
  6397. @end example
  6398. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6399. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6400. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6401. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6402. that contains a declaration and two statements.
  6403. @node Omitted for-Expressions
  6404. @subsection Omitted @code{for}-Expressions
  6405. A fully-fleshed @code{for} statement contains all these parts,
  6406. @example
  6407. for (@var{start}; @var{continue-test}; @var{advance})
  6408. @var{body}
  6409. @end example
  6410. @noindent
  6411. but you can omit any of the three expressions inside the parentheses.
  6412. The parentheses and the two semicolons are required syntactically, but
  6413. the expressions between them may be missing. A missing expression
  6414. means this loop doesn't use that particular feature of the @code{for}
  6415. statement.
  6416. Instead of using @var{start}, you can do the loop preparation
  6417. before the @code{for} statement: the effect is the same. So we
  6418. could have written the beginning of the previous example this way:
  6419. @example
  6420. int i = 0;
  6421. for (; i < n; ++i)
  6422. @end example
  6423. @noindent
  6424. instead of this way:
  6425. @example
  6426. int i;
  6427. for (i = 0; i < n; ++i)
  6428. @end example
  6429. Omitting @var{continue-test} means the loop runs forever (or until
  6430. something else causes exit from it). Statements inside the loop can
  6431. test conditions for termination and use @samp{break;} to exit. This
  6432. is more flexible since you can put those tests anywhere in the loop,
  6433. not solely at the beginning.
  6434. Putting an expression in @var{advance} is almost equivalent to writing
  6435. it at the end of the loop body; it does almost the same thing. The
  6436. only difference is for the @code{continue} statement (@pxref{continue
  6437. Statement}). So we could have written this:
  6438. @example
  6439. for (i = 0; i < n;)
  6440. @{
  6441. @r{@dots{}}
  6442. ++i;
  6443. @}
  6444. @end example
  6445. @noindent
  6446. instead of this:
  6447. @example
  6448. for (i = 0; i < n; ++i)
  6449. @{
  6450. @r{@dots{}}
  6451. @}
  6452. @end example
  6453. The choice is mainly a matter of what is more readable for
  6454. programmers. However, there is also a syntactic difference:
  6455. @var{advance} is an expression, not a statement. It can't include
  6456. loops, blocks, declarations, etc.
  6457. @node for-Index Declarations
  6458. @subsection @code{for}-Index Declarations
  6459. You can declare loop-index variables directly in the @var{start}
  6460. portion of the @code{for}-loop, like this:
  6461. @example
  6462. for (int i = 0; i < n; ++i)
  6463. @{
  6464. @r{@dots{}}
  6465. @}
  6466. @end example
  6467. This kind of @var{start} is limited to a single declaration; it can
  6468. declare one or more variables, separated by commas, all of which are
  6469. the same @var{basetype} (@code{int}, in this example):
  6470. @example
  6471. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6472. @{
  6473. @r{@dots{}}
  6474. @}
  6475. @end example
  6476. @noindent
  6477. The scope of these variables is the @code{for} statement as a whole.
  6478. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6479. Variables declared in @code{for} statements should have initializers.
  6480. Omitting the initialization gives the variables unpredictable initial
  6481. values, so this code is erroneous.
  6482. @example
  6483. for (int i; i < n; ++i)
  6484. @{
  6485. @r{@dots{}}
  6486. @}
  6487. @end example
  6488. @node continue Statement
  6489. @subsection @code{continue} Statement
  6490. @cindex @code{continue} statement
  6491. @cindex statement, @code{continue}
  6492. @findex continue
  6493. The @code{continue} statement looks like @samp{continue;}, and its
  6494. effect is to jump immediately to the end of the innermost loop
  6495. construct. If it is a @code{for}-loop, the next thing that happens
  6496. is to execute the loop's @var{advance} expression.
  6497. For example, this loop increments @code{p} until the next null character
  6498. or newline, and operates (in some way not shown) on all the characters
  6499. in the line except for spaces. All it does with spaces is skip them.
  6500. @example
  6501. for (;*p; ++p)
  6502. @{
  6503. /* @r{End loop if we have reached a newline.} */
  6504. if (*p == '\n')
  6505. break;
  6506. /* @r{Pay no attention to spaces.} */
  6507. if (*p == ' ')
  6508. continue;
  6509. /* @r{Operate on the next character.} */
  6510. @r{@dots{}}
  6511. @}
  6512. @end example
  6513. @noindent
  6514. Executing @samp{continue;} skips the loop body but it does not
  6515. skip the @var{advance} expression, @code{p++}.
  6516. We could also write it like this:
  6517. @example
  6518. for (;*p; ++p)
  6519. @{
  6520. /* @r{Exit if we have reached a newline.} */
  6521. if (*p == '\n')
  6522. break;
  6523. /* @r{Pay no attention to spaces.} */
  6524. if (*p != ' ')
  6525. @{
  6526. /* @r{Operate on the next character.} */
  6527. @r{@dots{}}
  6528. @}
  6529. @}
  6530. @end example
  6531. The advantage of using @code{continue} is that it reduces the
  6532. depth of nesting.
  6533. Contrast @code{continue} with the @code{break} statement. @xref{break
  6534. Statement}.
  6535. @node switch Statement
  6536. @section @code{switch} Statement
  6537. @cindex @code{switch} statement
  6538. @cindex statement, @code{switch}
  6539. @findex switch
  6540. @findex case
  6541. @findex default
  6542. The @code{switch} statement selects code to run according to the value
  6543. of an expression. The expression, in parentheses, follows the keyword
  6544. @code{switch}. After that come all the cases to select among,
  6545. inside braces. It looks like this:
  6546. @example
  6547. switch (@var{selector})
  6548. @{
  6549. @var{cases}@r{@dots{}}
  6550. @}
  6551. @end example
  6552. A case can look like this:
  6553. @example
  6554. case @var{value}:
  6555. @var{statements}
  6556. break;
  6557. @end example
  6558. @noindent
  6559. which means ``come here if @var{selector} happens to have the value
  6560. @var{value},'' or like this (a GNU C extension):
  6561. @example
  6562. case @var{rangestart} ... @var{rangeend}:
  6563. @var{statements}
  6564. break;
  6565. @end example
  6566. @noindent
  6567. which means ``come here if @var{selector} happens to have a value
  6568. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6569. Ranges}.
  6570. The values in @code{case} labels must reduce to integer constants.
  6571. They can use arithmetic, and @code{enum} constants, but they cannot
  6572. refer to data in memory, because they have to be computed at compile
  6573. time. It is an error if two @code{case} labels specify the same
  6574. value, or ranges that overlap, or if one is a range and the other is a
  6575. value in that range.
  6576. You can also define a default case to handle ``any other value,'' like
  6577. this:
  6578. @example
  6579. default:
  6580. @var{statements}
  6581. break;
  6582. @end example
  6583. If the @code{switch} statement has no @code{default:} label, then it
  6584. does nothing when the value matches none of the cases.
  6585. The brace-group inside the @code{switch} statement is a block, and you
  6586. can declare variables with that scope just as in any other block
  6587. (@pxref{Blocks}). However, initializers in these declarations won't
  6588. necessarily be executed every time the @code{switch} statement runs,
  6589. so it is best to avoid giving them initializers.
  6590. @code{break;} inside a @code{switch} statement exits immediately from
  6591. the @code{switch} statement. @xref{break Statement}.
  6592. If there is no @code{break;} at the end of the code for a case,
  6593. execution continues into the code for the following case. This
  6594. happens more often by mistake than intentionally, but since this
  6595. feature is used in real code, we cannot eliminate it.
  6596. @strong{Warning:} When one case is intended to fall through to the
  6597. next, write a comment like @samp{falls through} to say it's
  6598. intentional. That way, other programmers won't assume it was an error
  6599. and ``fix'' it erroneously.
  6600. Consecutive @code{case} statements could, pedantically, be considered
  6601. an instance of falling through, but we don't consider or treat them that
  6602. way because they won't confuse anyone.
  6603. @node switch Example
  6604. @section Example of @code{switch}
  6605. Here's an example of using the @code{switch} statement
  6606. to distinguish among characters:
  6607. @cindex counting vowels and punctuation
  6608. @example
  6609. struct vp @{ int vowels, punct; @};
  6610. struct vp
  6611. count_vowels_and_punct (char *string)
  6612. @{
  6613. int c;
  6614. int vowels = 0;
  6615. int punct = 0;
  6616. /* @r{Don't change the parameter itself.} */
  6617. /* @r{That helps in debugging.} */
  6618. char *p = string;
  6619. struct vp value;
  6620. while (c = *p++)
  6621. switch (c)
  6622. @{
  6623. case 'y':
  6624. case 'Y':
  6625. /* @r{We assume @code{y_is_consonant} will check surrounding
  6626. letters to determine whether this y is a vowel.} */
  6627. if (y_is_consonant (p - 1))
  6628. break;
  6629. /* @r{Falls through} */
  6630. case 'a':
  6631. case 'e':
  6632. case 'i':
  6633. case 'o':
  6634. case 'u':
  6635. case 'A':
  6636. case 'E':
  6637. case 'I':
  6638. case 'O':
  6639. case 'U':
  6640. vowels++;
  6641. break;
  6642. case '.':
  6643. case ',':
  6644. case ':':
  6645. case ';':
  6646. case '?':
  6647. case '!':
  6648. case '\"':
  6649. case '\'':
  6650. punct++;
  6651. break;
  6652. @}
  6653. value.vowels = vowels;
  6654. value.punct = punct;
  6655. return value;
  6656. @}
  6657. @end example
  6658. @node Duffs Device
  6659. @section Duff's Device
  6660. @cindex Duff's device
  6661. The cases in a @code{switch} statement can be inside other control
  6662. constructs. For instance, we can use a technique known as @dfn{Duff's
  6663. device} to optimize this simple function,
  6664. @example
  6665. void
  6666. copy (char *to, char *from, int count)
  6667. @{
  6668. while (count > 0)
  6669. *to++ = *from++, count--;
  6670. @}
  6671. @end example
  6672. @noindent
  6673. which copies memory starting at @var{from} to memory starting at
  6674. @var{to}.
  6675. Duff's device involves unrolling the loop so that it copies
  6676. several characters each time around, and using a @code{switch} statement
  6677. to enter the loop body at the proper point:
  6678. @example
  6679. void
  6680. copy (char *to, char *from, int count)
  6681. @{
  6682. if (count <= 0)
  6683. return;
  6684. int n = (count + 7) / 8;
  6685. switch (count % 8)
  6686. @{
  6687. do @{
  6688. case 0: *to++ = *from++;
  6689. case 7: *to++ = *from++;
  6690. case 6: *to++ = *from++;
  6691. case 5: *to++ = *from++;
  6692. case 4: *to++ = *from++;
  6693. case 3: *to++ = *from++;
  6694. case 2: *to++ = *from++;
  6695. case 1: *to++ = *from++;
  6696. @} while (--n > 0);
  6697. @}
  6698. @}
  6699. @end example
  6700. @node Case Ranges
  6701. @section Case Ranges
  6702. @cindex case ranges
  6703. @cindex ranges in case statements
  6704. You can specify a range of consecutive values in a single @code{case} label,
  6705. like this:
  6706. @example
  6707. case @var{low} ... @var{high}:
  6708. @end example
  6709. @noindent
  6710. This has the same effect as the proper number of individual @code{case}
  6711. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6712. This feature is especially useful for ranges of ASCII character codes:
  6713. @example
  6714. case 'A' ... 'Z':
  6715. @end example
  6716. @strong{Be careful:} with integers, write spaces around the @code{...}
  6717. to prevent it from being parsed wrong. For example, write this:
  6718. @example
  6719. case 1 ... 5:
  6720. @end example
  6721. @noindent
  6722. rather than this:
  6723. @example
  6724. case 1...5:
  6725. @end example
  6726. @node Null Statement
  6727. @section Null Statement
  6728. @cindex null statement
  6729. @cindex statement, null
  6730. A @dfn{null statement} is just a semicolon. It does nothing.
  6731. A null statement is a placeholder for use where a statement is
  6732. grammatically required, but there is nothing to be done. For
  6733. instance, sometimes all the work of a @code{for}-loop is done in the
  6734. @code{for}-header itself, leaving no work for the body. Here is an
  6735. example that searches for the first newline in @code{array}:
  6736. @example
  6737. for (p = array; *p != '\n'; p++)
  6738. ;
  6739. @end example
  6740. @node goto Statement
  6741. @section @code{goto} Statement and Labels
  6742. @cindex @code{goto} statement
  6743. @cindex statement, @code{goto}
  6744. @cindex label
  6745. @findex goto
  6746. The @code{goto} statement looks like this:
  6747. @example
  6748. goto @var{label};
  6749. @end example
  6750. @noindent
  6751. Its effect is to transfer control immediately to another part of the
  6752. current function---where the label named @var{label} is defined.
  6753. An ordinary label definition looks like this:
  6754. @example
  6755. @var{label}:
  6756. @end example
  6757. @noindent
  6758. and it can appear before any statement. You can't use @code{default}
  6759. as a label, since that has a special meaning for @code{switch}
  6760. statements.
  6761. An ordinary label doesn't need a separate declaration; defining it is
  6762. enough.
  6763. Here's an example of using @code{goto} to implement a loop
  6764. equivalent to @code{do}--@code{while}:
  6765. @example
  6766. @{
  6767. loop_restart:
  6768. @var{body}
  6769. if (@var{condition})
  6770. goto loop_restart;
  6771. @}
  6772. @end example
  6773. The name space of labels is separate from that of variables and functions.
  6774. Thus, there is no error in using a single name in both ways:
  6775. @example
  6776. @{
  6777. int foo; // @r{Variable @code{foo}.}
  6778. foo: // @r{Label @code{foo}.}
  6779. @var{body}
  6780. if (foo > 0) // @r{Variable @code{foo}.}
  6781. goto foo; // @r{Label @code{foo}.}
  6782. @}
  6783. @end example
  6784. Blocks have no effect on ordinary labels; each label name is defined
  6785. throughout the whole of the function it appears in. It looks strange to
  6786. jump into a block with @code{goto}, but it works. For example,
  6787. @example
  6788. if (x < 0)
  6789. goto negative;
  6790. if (y < 0)
  6791. @{
  6792. negative:
  6793. printf ("Negative\n");
  6794. return;
  6795. @}
  6796. @end example
  6797. If the goto jumps into the scope of a variable, it does not
  6798. initialize the variable. For example, if @code{x} is negative,
  6799. @example
  6800. if (x < 0)
  6801. goto negative;
  6802. if (y < 0)
  6803. @{
  6804. int i = 5;
  6805. negative:
  6806. printf ("Negative, and i is %d\n", i);
  6807. return;
  6808. @}
  6809. @end example
  6810. @noindent
  6811. prints junk because @code{i} was not initialized.
  6812. If the block declares a variable-length automatic array, jumping into
  6813. it gives a compilation error. However, jumping out of the scope of a
  6814. variable-length array works fine, and deallocates its storage.
  6815. A label can't come directly before a declaration, so the code can't
  6816. jump directly to one. For example, this is not allowed:
  6817. @example
  6818. @{
  6819. goto foo;
  6820. foo:
  6821. int x = 5;
  6822. bar(&x);
  6823. @}
  6824. @end example
  6825. @noindent
  6826. The workaround is to add a statement, even an empty statement,
  6827. directly after the label. For example:
  6828. @example
  6829. @{
  6830. goto foo;
  6831. foo:
  6832. ;
  6833. int x = 5;
  6834. bar(&x);
  6835. @}
  6836. @end example
  6837. Likewise, a label can't be the last thing in a block. The workaround
  6838. solution is the same: add a semicolon after the label.
  6839. These unnecessary restrictions on labels make no sense, and ought in
  6840. principle to be removed; but they do only a little harm since labels
  6841. and @code{goto} are rarely the best way to write a program.
  6842. These examples are all artificial; it would be more natural to
  6843. write them in other ways, without @code{goto}. For instance,
  6844. the clean way to write the example that prints @samp{Negative} is this:
  6845. @example
  6846. if (x < 0 || y < 0)
  6847. @{
  6848. printf ("Negative\n");
  6849. return;
  6850. @}
  6851. @end example
  6852. @noindent
  6853. It is hard to construct simple examples where @code{goto} is actually
  6854. the best way to write a program. Its rare good uses tend to be in
  6855. complex code, thus not apt for the purpose of explaining the meaning
  6856. of @code{goto}.
  6857. The only good time to use @code{goto} is when it makes the code
  6858. simpler than any alternative. Jumping backward is rarely desirable,
  6859. because usually the other looping and control constructs give simpler
  6860. code. Using @code{goto} to jump forward is more often desirable, for
  6861. instance when a function needs to do some processing in an error case
  6862. and errors can occur at various different places within the function.
  6863. @node Local Labels
  6864. @section Locally Declared Labels
  6865. @cindex local labels
  6866. @cindex macros, local labels
  6867. @findex __label__
  6868. In GNU C you can declare @dfn{local labels} in any nested block
  6869. scope. A local label is used in a @code{goto} statement just like an
  6870. ordinary label, but you can only reference it within the block in
  6871. which it was declared.
  6872. A local label declaration looks like this:
  6873. @example
  6874. __label__ @var{label};
  6875. @end example
  6876. @noindent
  6877. or
  6878. @example
  6879. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6880. @end example
  6881. Local label declarations must come at the beginning of the block,
  6882. before any ordinary declarations or statements.
  6883. The label declaration declares the label @emph{name}, but does not define
  6884. the label itself. That's done in the usual way, with
  6885. @code{@var{label}:}, before one of the statements in the block.
  6886. The local label feature is useful for complex macros. If a macro
  6887. contains nested loops, a @code{goto} can be useful for breaking out of
  6888. them. However, an ordinary label whose scope is the whole function
  6889. cannot be used: if the macro can be expanded several times in one
  6890. function, the label will be multiply defined in that function. A
  6891. local label avoids this problem. For example:
  6892. @example
  6893. #define SEARCH(value, array, target) \
  6894. do @{ \
  6895. __label__ found; \
  6896. __auto_type _SEARCH_target = (target); \
  6897. __auto_type _SEARCH_array = (array); \
  6898. int i, j; \
  6899. int value; \
  6900. for (i = 0; i < max; i++) \
  6901. for (j = 0; j < max; j++) \
  6902. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6903. @{ (value) = i; goto found; @} \
  6904. (value) = -1; \
  6905. found:; \
  6906. @} while (0)
  6907. @end example
  6908. This could also be written using a statement expression
  6909. (@pxref{Statement Exprs}):
  6910. @example
  6911. #define SEARCH(array, target) \
  6912. (@{ \
  6913. __label__ found; \
  6914. __auto_type _SEARCH_target = (target); \
  6915. __auto_type _SEARCH_array = (array); \
  6916. int i, j; \
  6917. int value; \
  6918. for (i = 0; i < max; i++) \
  6919. for (j = 0; j < max; j++) \
  6920. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6921. @{ value = i; goto found; @} \
  6922. value = -1; \
  6923. found: \
  6924. value; \
  6925. @})
  6926. @end example
  6927. Ordinary labels are visible throughout the function where they are
  6928. defined, and only in that function. However, explicitly declared
  6929. local labels of a block are visible in nested functions declared
  6930. within that block. @xref{Nested Functions}, for details.
  6931. @xref{goto Statement}.
  6932. @node Labels as Values
  6933. @section Labels as Values
  6934. @cindex labels as values
  6935. @cindex computed gotos
  6936. @cindex goto with computed label
  6937. @cindex address of a label
  6938. In GNU C, you can get the address of a label defined in the current
  6939. function (or a local label defined in the containing function) with
  6940. the unary operator @samp{&&}. The value has type @code{void *}. This
  6941. value is a constant and can be used wherever a constant of that type
  6942. is valid. For example:
  6943. @example
  6944. void *ptr;
  6945. @r{@dots{}}
  6946. ptr = &&foo;
  6947. @end example
  6948. To use these values requires a way to jump to one. This is done
  6949. with the computed goto statement@footnote{The analogous feature in
  6950. Fortran is called an assigned goto, but that name seems inappropriate in
  6951. C, since you can do more with label addresses than store them in special label
  6952. variables.}, @code{goto *@var{exp};}. For example,
  6953. @example
  6954. goto *ptr;
  6955. @end example
  6956. @noindent
  6957. Any expression of type @code{void *} is allowed.
  6958. @xref{goto Statement}.
  6959. @menu
  6960. * Label Value Uses:: Examples of using label values.
  6961. * Label Value Caveats:: Limitations of label values.
  6962. @end menu
  6963. @node Label Value Uses
  6964. @subsection Label Value Uses
  6965. One use for label-valued constants is to initialize a static array to
  6966. serve as a jump table:
  6967. @example
  6968. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6969. @end example
  6970. Then you can select a label with indexing, like this:
  6971. @example
  6972. goto *array[i];
  6973. @end example
  6974. @noindent
  6975. Note that this does not check whether the subscript is in bounds---array
  6976. indexing in C never checks that.
  6977. You can make the table entries offsets instead of addresses
  6978. by subtracting one label from the others. Here is an example:
  6979. @example
  6980. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6981. &&hack - &&foo @};
  6982. goto *(&&foo + array[i]);
  6983. @end example
  6984. @noindent
  6985. Using offsets is preferable in shared libraries, as it avoids the need
  6986. for dynamic relocation of the array elements; therefore, the array can
  6987. be read-only.
  6988. An array of label values or offsets serves a purpose much like that of
  6989. the @code{switch} statement. The @code{switch} statement is cleaner,
  6990. so use @code{switch} by preference when feasible.
  6991. Another use of label values is in an interpreter for threaded code.
  6992. The labels within the interpreter function can be stored in the
  6993. threaded code for super-fast dispatching.
  6994. @node Label Value Caveats
  6995. @subsection Label Value Caveats
  6996. Jumping to a label defined in another function does not work.
  6997. It can cause unpredictable results.
  6998. The best way to avoid this is to store label values only in
  6999. automatic variables, or static variables whose names are declared
  7000. within the function. Never pass them as arguments.
  7001. @cindex cloning
  7002. An optimization known as @dfn{cloning} generates multiple simplified
  7003. variants of a function's code, for use with specific fixed arguments.
  7004. Using label values in certain ways, such as saving the address in one
  7005. call to the function and using it again in another call, would make cloning
  7006. give incorrect results. These functions must disable cloning.
  7007. Inlining calls to the function would also result in multiple copies of
  7008. the code, each with its own value of the same label. Using the label
  7009. in a computed goto is no problem, because the computed goto inhibits
  7010. inlining. However, using the label value in some other way, such as
  7011. an indication of where an error occurred, would be optimized wrong.
  7012. These functions must disable inlining.
  7013. To prevent inlining or cloning of a function, specify
  7014. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7015. @xref{Attributes}.
  7016. When a function uses a label value in a static variable initializer,
  7017. that automatically prevents inlining or cloning the function.
  7018. @node Statement Exprs
  7019. @section Statements and Declarations in Expressions
  7020. @cindex statements inside expressions
  7021. @cindex declarations inside expressions
  7022. @cindex expressions containing statements
  7023. @c the above section title wrapped and causes an underfull hbox.. i
  7024. @c changed it from "within" to "in". --mew 4feb93
  7025. A block enclosed in parentheses can be used as an expression in GNU
  7026. C@. This provides a way to use local variables, loops and switches within
  7027. an expression. We call it a @dfn{statement expression}.
  7028. Recall that a block is a sequence of statements
  7029. surrounded by braces. In this construct, parentheses go around the
  7030. braces. For example:
  7031. @example
  7032. (@{ int y = foo (); int z;
  7033. if (y > 0) z = y;
  7034. else z = - y;
  7035. z; @})
  7036. @end example
  7037. @noindent
  7038. is a valid (though slightly more complex than necessary) expression
  7039. for the absolute value of @code{foo ()}.
  7040. The last statement in the block should be an expression statement; an
  7041. expression followed by a semicolon, that is. The value of this
  7042. expression serves as the value of statement expression. If the last
  7043. statement is anything else, the statement expression's value is
  7044. @code{void}.
  7045. This feature is mainly useful in making macro definitions compute each
  7046. operand exactly once. @xref{Macros and Auto Type}.
  7047. Statement expressions are not allowed in expressions that must be
  7048. constant, such as the value for an enumerator, the width of a
  7049. bit-field, or the initial value of a static variable.
  7050. Jumping into a statement expression---with @code{goto}, or using a
  7051. @code{switch} statement outside the statement expression---is an
  7052. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7053. compiler can't detect the error, but it still won't work.
  7054. Jumping out of a statement expression is permitted, but since
  7055. subexpressions in C are not computed in a strict order, it is
  7056. unpredictable which other subexpressions will have been computed by
  7057. then. For example,
  7058. @example
  7059. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7060. @end example
  7061. @noindent
  7062. calls @code{foo} and @code{bar1} before it jumps, and never
  7063. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7064. does get called, that occurs after @code{foo} and before @code{bar1}.
  7065. @node Variables
  7066. @chapter Variables
  7067. @cindex variables
  7068. Every variable used in a C program needs to be made known by a
  7069. @dfn{declaration}. It can be used only after it has been declared.
  7070. It is an error to declare a variable name more than once in the same
  7071. scope; an exception is that @code{extern} declarations and tentative
  7072. definitions can coexist with another declaration of the same
  7073. variable.
  7074. Variables can be declared anywhere within a block or file. (Older
  7075. versions of C required that all variable declarations within a block
  7076. occur before any statements.)
  7077. Variables declared within a function or block are @dfn{local} to
  7078. it. This means that the variable name is visible only until the end
  7079. of that function or block, and the memory space is allocated only
  7080. while control is within it.
  7081. Variables declared at the top level in a file are called @dfn{file-scope}.
  7082. They are assigned fixed, distinct memory locations, so they retain
  7083. their values for the whole execution of the program.
  7084. @menu
  7085. * Variable Declarations:: Name a variable and and reserve space for it.
  7086. * Initializers:: Assigning inital values to variables.
  7087. * Designated Inits:: Assigning initial values to array elements
  7088. at particular array indices.
  7089. * Auto Type:: Obtaining the type of a variable.
  7090. * Local Variables:: Variables declared in function definitions.
  7091. * File-Scope Variables:: Variables declared outside of
  7092. function definitions.
  7093. * Static Local Variables:: Variables declared within functions,
  7094. but with permanent storage allocation.
  7095. * Extern Declarations:: Declaring a variable
  7096. which is allocated somewhere else.
  7097. * Allocating File-Scope:: When is space allocated
  7098. for file-scope variables?
  7099. * auto and register:: Historically used storage directions.
  7100. * Omitting Types:: The bad practice of declaring variables
  7101. with implicit type.
  7102. @end menu
  7103. @node Variable Declarations
  7104. @section Variable Declarations
  7105. @cindex variable declarations
  7106. @cindex declaration of variables
  7107. Here's what a variable declaration looks like:
  7108. @example
  7109. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7110. @end example
  7111. The @var{keywords} specify how to handle the scope of the variable
  7112. name and the allocation of its storage. Most declarations have
  7113. no keywords because the defaults are right for them.
  7114. C allows these keywords to come before or after @var{basetype}, or
  7115. even in the middle of it as in @code{unsigned static int}, but don't
  7116. do that---it would surprise other programmers. Always write the
  7117. keywords first.
  7118. The @var{basetype} can be any of the predefined types of C, or a type
  7119. keyword defined with @code{typedef}. It can also be @code{struct
  7120. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7121. addition, it can include type qualifiers such as @code{const} and
  7122. @code{volatile} (@pxref{Type Qualifiers}).
  7123. In the simplest case, @var{decorated-variable} is just the variable
  7124. name. That declares the variable with the type specified by
  7125. @var{basetype}. For instance,
  7126. @example
  7127. int foo;
  7128. @end example
  7129. @noindent
  7130. uses @code{int} as the @var{basetype} and @code{foo} as the
  7131. @var{decorated-variable}. It declares @code{foo} with type
  7132. @code{int}.
  7133. @example
  7134. struct tree_node foo;
  7135. @end example
  7136. @noindent
  7137. declares @code{foo} with type @code{struct tree_node}.
  7138. @menu
  7139. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7140. array and pointer types.
  7141. * Combining Variable Declarations:: More than one variable declaration
  7142. in a single statement.
  7143. @end menu
  7144. @node Declaring Arrays and Pointers
  7145. @subsection Declaring Arrays and Pointers
  7146. @cindex declaring arrays and pointers
  7147. @cindex array, declaring
  7148. @cindex pointers, declaring
  7149. To declare a variable that is an array, write
  7150. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7151. @example
  7152. int foo[5];
  7153. @end example
  7154. To declare a variable that has a pointer type, write
  7155. @code{*@var{variable}} for @var{decorated-variable}:
  7156. @example
  7157. struct list_elt *foo;
  7158. @end example
  7159. These constructs nest. For instance,
  7160. @example
  7161. int foo[3][5];
  7162. @end example
  7163. @noindent
  7164. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7165. @example
  7166. struct list_elt *foo[5];
  7167. @end example
  7168. @noindent
  7169. declares @code{foo} as an array of 5 pointers to structures, and
  7170. @example
  7171. struct list_elt **foo;
  7172. @end example
  7173. @noindent
  7174. declares @code{foo} as a pointer to a pointer to a structure.
  7175. @example
  7176. int **(*foo[30])(int, double);
  7177. @end example
  7178. @noindent
  7179. declares @code{foo} as an array of 30 pointers to functions
  7180. (@pxref{Function Pointers}), each of which must accept two arguments
  7181. (one @code{int} and one @code{double}) and return type @code{int **}.
  7182. @example
  7183. void
  7184. bar (int size)
  7185. @{
  7186. int foo[size];
  7187. @r{@dots{}}
  7188. @}
  7189. @end example
  7190. @noindent
  7191. declares @code{foo} as an array of integers with a size specified at
  7192. run time when the function @code{bar} is called.
  7193. @node Combining Variable Declarations
  7194. @subsection Combining Variable Declarations
  7195. @cindex combining variable declarations
  7196. @cindex variable declarations, combining
  7197. @cindex declarations, combining
  7198. When multiple declarations have the same @var{keywords} and
  7199. @var{basetype}, you can combine them using commas. Thus,
  7200. @example
  7201. @var{keywords} @var{basetype}
  7202. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7203. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7204. @end example
  7205. @noindent
  7206. is equivalent to
  7207. @example
  7208. @var{keywords} @var{basetype}
  7209. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7210. @var{keywords} @var{basetype}
  7211. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7212. @end example
  7213. Here are some simple examples:
  7214. @example
  7215. int a, b;
  7216. int a = 1, b = 2;
  7217. int a, *p, array[5];
  7218. int a = 0, *p = &a, array[5] = @{1, 2@};
  7219. @end example
  7220. @noindent
  7221. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7222. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7223. Since the initializer for @code{array} specifies only two elements,
  7224. the other three elements are initialized to zero.
  7225. @node Initializers
  7226. @section Initializers
  7227. @cindex initializers
  7228. A variable's declaration, unless it is @code{extern}, should also
  7229. specify its initial value. For numeric and pointer-type variables,
  7230. the initializer is an expression for the value. If necessary, it is
  7231. converted to the variable's type, just as in an assignment.
  7232. You can also initialize a local structure-type (@pxref{Structures}) or
  7233. local union-type (@pxref{Unions}) variable this way, from an
  7234. expression whose value has the same type. But you can't initialize an
  7235. array this way (@pxref{Arrays}), since arrays are not first-class
  7236. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7237. assignment.
  7238. You can initialize arrays and structures componentwise,
  7239. with a list of the elements or components. You can initialize
  7240. a union with any one of its alternatives.
  7241. @itemize @bullet
  7242. @item
  7243. A component-wise initializer for an array consists of element values
  7244. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7245. don't cover all the elements in the array, the remaining elements are
  7246. initialized to zero.
  7247. You can omit the size of the array when you declare it, and let
  7248. the initializer specify the size:
  7249. @example
  7250. int array[] = @{ 3, 9, 12 @};
  7251. @end example
  7252. @item
  7253. A component-wise initializer for a structure consists of field values
  7254. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7255. order as the fields are declared in the structure. If the values in
  7256. the initializer don't cover all the fields in the structure, the
  7257. remaining fields are initialized to zero.
  7258. @item
  7259. The initializer for a union-type variable has the form @code{@{
  7260. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7261. in the union definition.
  7262. @end itemize
  7263. For an array of arrays, a structure containing arrays, an array of
  7264. structures, etc., you can nest these constructs. For example,
  7265. @example
  7266. struct point @{ double x, y; @};
  7267. struct point series[]
  7268. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7269. @end example
  7270. You can omit a pair of inner braces if they contain the right
  7271. number of elements for the sub-value they initialize, so that
  7272. no elements or fields need to be filled in with zeros.
  7273. But don't do that very much, as it gets confusing.
  7274. An array of @code{char} can be initialized using a string constant.
  7275. Recall that the string constant includes an implicit null character at
  7276. the end (@pxref{String Constants}). Using a string constant as
  7277. initializer means to use its contents as the initial values of the
  7278. array elements. Here are examples:
  7279. @example
  7280. char text[6] = "text!"; /* @r{Includes the null.} */
  7281. char text[5] = "text!"; /* @r{Excludes the null.} */
  7282. char text[] = "text!"; /* @r{Gets length 6.} */
  7283. char text[]
  7284. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7285. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7286. @end example
  7287. @noindent
  7288. and this kind of initializer can be nested inside braces to initialize
  7289. structures or arrays that contain a @code{char}-array.
  7290. In like manner, you can use a wide string constant to initialize
  7291. an array of @code{wchar_t}.
  7292. @node Designated Inits
  7293. @section Designated Initializers
  7294. @cindex initializers with labeled elements
  7295. @cindex labeled elements in initializers
  7296. @cindex case labels in initializers
  7297. @cindex designated initializers
  7298. In a complex structure or long array, it's useful to indicate
  7299. which field or element we are initializing.
  7300. To designate specific array elements during initialization, include
  7301. the array index in brackets, and an assignment operator, for each
  7302. element:
  7303. @example
  7304. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7305. @end example
  7306. @noindent
  7307. This does the same thing as:
  7308. @example
  7309. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7310. @end example
  7311. The array initialization can include non-designated element values
  7312. alongside designated indices; these follow the expected ordering
  7313. of the array initialization, so that
  7314. @example
  7315. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7316. @end example
  7317. @noindent
  7318. does the same thing as:
  7319. @example
  7320. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7321. @end example
  7322. Note that you can only use constant expressions as array index values,
  7323. not variables.
  7324. If you need to initialize a subsequence of sequential array elements to
  7325. the same value, you can specify a range:
  7326. @example
  7327. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7328. @end example
  7329. @noindent
  7330. Using a range this way is a GNU C extension.
  7331. When subsequence ranges overlap, each element is initialized by the
  7332. last specification that applies to it. Thus, this initialization is
  7333. equivalent to the previous one.
  7334. @example
  7335. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7336. @end example
  7337. @noindent
  7338. as the second overrides the first for elements 0 through 19.
  7339. The value used to initialize a range of elements is evaluated only
  7340. once, for the first element in the range. So for example, this code
  7341. @example
  7342. int random_values[100]
  7343. = @{ [0 ... 99] = get_random_number() @};
  7344. @end example
  7345. @noindent
  7346. would initialize all 100 elements of the array @code{random_values} to
  7347. the same value---probably not what is intended.
  7348. Similarly, you can initialize specific fields of a structure variable
  7349. by specifying the field name prefixed with a dot:
  7350. @example
  7351. struct point @{ int x; int y; @};
  7352. struct point foo = @{ .y = 42; @};
  7353. @end example
  7354. @noindent
  7355. The same syntax works for union variables as well:
  7356. @example
  7357. union int_double @{ int i; double d; @};
  7358. union int_double foo = @{ .d = 34 @};
  7359. @end example
  7360. @noindent
  7361. This casts the integer value 34 to a double and stores it
  7362. in the union variable @code{foo}.
  7363. You can designate both array elements and structure elements in
  7364. the same initialization; for example, here's an array of point
  7365. structures:
  7366. @example
  7367. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7368. @end example
  7369. Along with the capability to specify particular array and structure
  7370. elements to initialize comes the possibility of initializing the same
  7371. element more than once:
  7372. @example
  7373. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7374. @end example
  7375. @noindent
  7376. In such a case, the last initialization value is retained.
  7377. @node Auto Type
  7378. @section Referring to a Type with @code{__auto_type}
  7379. @findex __auto_type
  7380. @findex typeof
  7381. @cindex macros, types of arguments
  7382. You can declare a variable copying the type from
  7383. the initializer by using @code{__auto_type} instead of a particular type.
  7384. Here's an example:
  7385. @example
  7386. #define max(a,b) \
  7387. (@{ __auto_type _a = (a); \
  7388. __auto_type _b = (b); \
  7389. _a > _b ? _a : _b @})
  7390. @end example
  7391. This defines @code{_a} to be of the same type as @code{a}, and
  7392. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7393. to do in a macro that ought to be able to handle any type of data
  7394. (@pxref{Macros and Auto Type}).
  7395. The original GNU C method for obtaining the type of a value is to use
  7396. @code{typeof}, which takes as an argument either a value or the name of
  7397. a type. The previous example could also be written as:
  7398. @example
  7399. #define max(a,b) \
  7400. (@{ typeof(a) _a = (a); \
  7401. typeof(b) _b = (b); \
  7402. _a > _b ? _a : _b @})
  7403. @end example
  7404. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7405. principal use case for @code{typeof} is in variable declarations with
  7406. initialization, which is exactly what @code{__auto_type} handles.
  7407. @node Local Variables
  7408. @section Local Variables
  7409. @cindex local variables
  7410. @cindex variables, local
  7411. Declaring a variable inside a function definition (@pxref{Function
  7412. Definitions}) makes the variable name @dfn{local} to the containing
  7413. block---that is, the containing pair of braces. More precisely, the
  7414. variable's name is visible starting just after where it appears in the
  7415. declaration, and its visibility continues until the end of the block.
  7416. Local variables in C are generally @dfn{automatic} variables: each
  7417. variable's storage exists only from the declaration to the end of the
  7418. block. Execution of the declaration allocates the storage, computes
  7419. the initial value, and stores it in the variable. The end of the
  7420. block deallocates the storage.@footnote{Due to compiler optimizations,
  7421. allocation and deallocation don't necessarily really happen at
  7422. those times.}
  7423. @strong{Warning:} Two declarations for the same local variable
  7424. in the same scope are an error.
  7425. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7426. The total space for the program's stack may be limited; therefore,
  7427. in using very large arrays, it may be necessary to allocate
  7428. them in some other way to stop the program from crashing.
  7429. @strong{Warning:} If the declaration of an automatic variable does not
  7430. specify an initial value, the variable starts out containing garbage.
  7431. In this example, the value printed could be anything at all:
  7432. @example
  7433. @{
  7434. int i;
  7435. printf ("Print junk %d\n", i);
  7436. @}
  7437. @end example
  7438. In a simple test program, that statement is likely to print 0, simply
  7439. because every process starts with memory zeroed. But don't rely on it
  7440. to be zero---that is erroneous.
  7441. @strong{Note:} Make sure to store a value into each local variable (by
  7442. assignment, or by initialization) before referring to its value.
  7443. @node File-Scope Variables
  7444. @section File-Scope Variables
  7445. @cindex file-scope variables
  7446. @cindex global variables
  7447. @cindex variables, file-scope
  7448. @cindex variables, global
  7449. A variable declaration at the top level in a file (not inside a
  7450. function definition) declares a @dfn{file-scope variable}. Loading a
  7451. program allocates the storage for all the file-scope variables in it,
  7452. and initializes them too.
  7453. Each file-scope variable is either @dfn{static} (limited to one
  7454. compilation module) or @dfn{global} (shared with all compilation
  7455. modules in the program). To make the variable static, write the
  7456. keyword @code{static} at the start of the declaration. Omitting
  7457. @code{static} makes the variable global.
  7458. The initial value for a file-scope variable can't depend on the
  7459. contents of storage, and can't call any functions.
  7460. @example
  7461. int foo = 5; /* @r{Valid.} */
  7462. int bar = foo; /* @r{Invalid!} */
  7463. int bar = sin (1.0); /* @r{Invalid!} */
  7464. @end example
  7465. But it can use the address of another file-scope variable:
  7466. @example
  7467. int foo;
  7468. int *bar = &foo; /* @r{Valid.} */
  7469. int arr[5];
  7470. int *bar3 = &arr[3]; /* @r{Valid.} */
  7471. int *bar4 = arr + 4; /* @r{Valid.} */
  7472. @end example
  7473. It is valid for a module to have multiple declarations for a
  7474. file-scope variable, as long as they are all global or all static, but
  7475. at most one declaration can specify an initial value for it.
  7476. @node Static Local Variables
  7477. @section Static Local Variables
  7478. @cindex static local variables
  7479. @cindex variables, static local
  7480. @findex static
  7481. The keyword @code{static} in a local variable declaration says to
  7482. allocate the storage for the variable permanently, just like a
  7483. file-scope variable, even if the declaration is within a function.
  7484. Here's an example:
  7485. @example
  7486. int
  7487. increment_counter ()
  7488. @{
  7489. static int counter = 0;
  7490. return ++counter;
  7491. @}
  7492. @end example
  7493. The scope of the name @code{counter} runs from the declaration to the
  7494. end of the containing block, just like an automatic local variable,
  7495. but its storage is permanent, so the value persists from one call to
  7496. the next. As a result, each call to @code{increment_counter}
  7497. returns a different, unique value.
  7498. The initial value of a static local variable has the same limitations
  7499. as for file-scope variables: it can't depend on the contents of
  7500. storage or call any functions. It can use the address of a file-scope
  7501. variable or a static local variable, because those addresses are
  7502. determined before the program runs.
  7503. @node Extern Declarations
  7504. @section @code{extern} Declarations
  7505. @cindex @code{extern} declarations
  7506. @cindex declarations, @code{extern}
  7507. @findex extern
  7508. An @code{extern} declaration is used to refer to a global variable
  7509. whose principal declaration comes elsewhere---in the same module, or in
  7510. another compilation module. It looks like this:
  7511. @example
  7512. extern @var{basetype} @var{decorated-variable};
  7513. @end example
  7514. Its meaning is that, in the current scope, the variable name refers to
  7515. the file-scope variable of that name---which needs to be declared in a
  7516. non-@code{extern}, non-@code{static} way somewhere else.
  7517. For instance, if one compilation module has this global variable
  7518. declaration
  7519. @example
  7520. int error_count = 0;
  7521. @end example
  7522. @noindent
  7523. then other compilation modules can specify this
  7524. @example
  7525. extern int error_count;
  7526. @end example
  7527. @noindent
  7528. to allow reference to the same variable.
  7529. The usual place to write an @code{extern} declaration is at top level
  7530. in a source file, but you can write an @code{extern} declaration
  7531. inside a block to make a global or static file-scope variable
  7532. accessible in that block.
  7533. Since an @code{extern} declaration does not allocate space for the
  7534. variable, it can omit the size of an array:
  7535. @example
  7536. extern int array[];
  7537. @end example
  7538. You can use @code{array} normally in all contexts where it is
  7539. converted automatically to a pointer. However, to use it as the
  7540. operand of @code{sizeof} is an error, since the size is unknown.
  7541. It is valid to have multiple @code{extern} declarations for the same
  7542. variable, even in the same scope, if they give the same type. They do
  7543. not conflict---they agree. For an array, it is legitimate for some
  7544. @code{extern} declarations can specify the size while others omit it.
  7545. However, if two declarations give different sizes, that is an error.
  7546. Likewise, you can use @code{extern} declarations at file scope
  7547. (@pxref{File-Scope Variables}) followed by an ordinary global
  7548. (non-static) declaration of the same variable. They do not conflict,
  7549. because they say compatible things about the same meaning of the variable.
  7550. @node Allocating File-Scope
  7551. @section Allocating File-Scope Variables
  7552. @cindex allocation file-scope variables
  7553. @cindex file-scope variables, allocating
  7554. Some file-scope declarations allocate space for the variable, and some
  7555. don't.
  7556. A file-scope declaration with an initial value @emph{must} allocate
  7557. space for the variable; if there are two of such declarations for the
  7558. same variable, even in different compilation modules, they conflict.
  7559. An @code{extern} declaration @emph{never} allocates space for the variable.
  7560. If all the top-level declarations of a certain variable are
  7561. @code{extern}, the variable never gets memory space. If that variable
  7562. is used anywhere in the program, the use will be reported as an error,
  7563. saying that the variable is not defined.
  7564. @cindex tentative definition
  7565. A file-scope declaration without an initial value is called a
  7566. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7567. allocate space for the variable, but does not insist. So it causes no
  7568. conflict, no error, if the variable has another declaration that
  7569. allocates space for it, perhaps in another compilation module. But if
  7570. nothing else allocates space for the variable, the tentative
  7571. definition will do it. Any number of compilation modules can declare
  7572. the same variable in this way, and that is sufficient for all of them
  7573. to use the variable.
  7574. @c @opindex -fno-common
  7575. @c @opindex --warn_common
  7576. In programs that are very large or have many contributors, it may be
  7577. wise to adopt the convention of never using tentative definitions.
  7578. You can use the compilation option @option{-fno-common} to make them
  7579. an error, or @option{--warn-common} to warn about them.
  7580. If a file-scope variable gets its space through a tentative
  7581. definition, it starts out containing all zeros.
  7582. @node auto and register
  7583. @section @code{auto} and @code{register}
  7584. @cindex @code{auto} declarations
  7585. @cindex @code{register} declarations
  7586. @findex auto
  7587. @findex register
  7588. For historical reasons, you can write @code{auto} or @code{register}
  7589. before a local variable declaration. @code{auto} merely emphasizes
  7590. that the variable isn't static; it changes nothing.
  7591. @code{register} suggests to the compiler storing this variable in a
  7592. register. However, GNU C ignores this suggestion, since it can
  7593. choose the best variables to store in registers without any hints.
  7594. It is an error to take the address of a variable declared
  7595. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7596. If the variable is an array, you can't use it at all (other than as
  7597. the operand of @code{sizeof}), which makes it rather useless.
  7598. @node Omitting Types
  7599. @section Omitting Types in Declarations
  7600. @cindex omitting types in declarations
  7601. The syntax of C traditionally allows omitting the data type in a
  7602. declaration if it specifies a storage class, a type qualifier (see the
  7603. next chapter), or @code{auto} or @code{register}. Then the type
  7604. defaults to @code{int}. For example:
  7605. @example
  7606. auto foo = 42;
  7607. @end example
  7608. This is bad practice; if you see it, fix it.
  7609. @node Type Qualifiers
  7610. @chapter Type Qualifiers
  7611. A declaration can include type qualifiers to advise the compiler
  7612. about how the variable will be used. There are three different
  7613. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7614. pertain to different issues, so you can use more than one together.
  7615. For instance, @code{const volatile} describes a value that the
  7616. program is not allowed to change, but might have a different value
  7617. each time the program examines it. (This might perhaps be a special
  7618. hardware register, or part of shared memory.)
  7619. If you are just learning C, you can skip this chapter.
  7620. @menu
  7621. * const:: Variables whose values don't change.
  7622. * volatile:: Variables whose values may be accessed
  7623. or changed outside of the control of
  7624. this program.
  7625. * restrict Pointers:: Restricted pointers for code optimization.
  7626. * restrict Pointer Example:: Example of how that works.
  7627. @end menu
  7628. @node const
  7629. @section @code{const} Variables and Fields
  7630. @cindex @code{const} variables and fields
  7631. @cindex variables, @code{const}
  7632. @findex const
  7633. You can mark a variable as ``constant'' by writing @code{const} in
  7634. front of the declaration. This says to treat any assignment to that
  7635. variable as an error. It may also permit some compiler
  7636. optimizations---for instance, to fetch the value only once to satisfy
  7637. multiple references to it. The construct looks like this:
  7638. @example
  7639. const double pi = 3.14159;
  7640. @end example
  7641. After this definition, the code can use the variable @code{pi}
  7642. but cannot assign a different value to it.
  7643. @example
  7644. pi = 3.0; /* @r{Error!} */
  7645. @end example
  7646. Simple variables that are constant can be used for the same purposes
  7647. as enumeration constants, and they are not limited to integers. The
  7648. constantness of the variable propagates into pointers, too.
  7649. A pointer type can specify that the @emph{target} is constant. For
  7650. example, the pointer type @code{const double *} stands for a pointer
  7651. to a constant @code{double}. That's the typethat results from taking
  7652. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7653. left side of an assignment.
  7654. @example
  7655. *(&pi) = 3.0; /* @r{Error!} */
  7656. @end example
  7657. Nonconstant pointers can be converted automatically to constant
  7658. pointers, but not vice versa. For instance,
  7659. @example
  7660. const double *cptr;
  7661. double *ptr;
  7662. cptr = &pi; /* @r{Valid.} */
  7663. cptr = ptr; /* @r{Valid.} */
  7664. ptr = cptr; /* @r{Error!} */
  7665. ptr = &pi; /* @r{Error!} */
  7666. @end example
  7667. This is not an ironclad protection against modifying the value. You
  7668. can always cast the constant pointer to a nonconstant pointer type:
  7669. @example
  7670. ptr = (double *)cptr; /* @r{Valid.} */
  7671. ptr = (double *)&pi; /* @r{Valid.} */
  7672. @end example
  7673. However, @code{const} provides a way to show that a certain function
  7674. won't modify the data structure whose address is passed to it. Here's
  7675. an example:
  7676. @example
  7677. int
  7678. string_length (const char *string)
  7679. @{
  7680. int count = 0;
  7681. while (*string++)
  7682. count++;
  7683. return count;
  7684. @}
  7685. @end example
  7686. @noindent
  7687. Using @code{const char *} for the parameter is a way of saying this
  7688. function never modifies the memory of the string itself.
  7689. In calling @code{string_length}, you can specify an ordinary
  7690. @code{char *} since that can be converted automatically to @code{const
  7691. char *}.
  7692. @node volatile
  7693. @section @code{volatile} Variables and Fields
  7694. @cindex @code{volatile} variables and fields
  7695. @cindex variables, @code{volatile}
  7696. @findex volatile
  7697. The GNU C compiler often performs optimizations that eliminate the
  7698. need to write or read a variable. For instance,
  7699. @example
  7700. int foo;
  7701. foo = 1;
  7702. foo++;
  7703. @end example
  7704. @noindent
  7705. might simply store the value 2 into @code{foo}, without ever storing 1.
  7706. These optimizations can also apply to structure fields in some cases.
  7707. If the memory containing @code{foo} is shared with another program,
  7708. or if it is examined asynchronously by hardware, such optimizations
  7709. could confuse the communication. Using @code{volatile} is one way
  7710. to prevent them.
  7711. Writing @code{volatile} with the type in a variable or field declaration
  7712. says that the value may be examined or changed for reasons outside the
  7713. control of the program at any moment. Therefore, the program must
  7714. execute in a careful way to assure correct interaction with those
  7715. accesses, whenever they may occur.
  7716. The simplest use looks like this:
  7717. @example
  7718. volatile int lock;
  7719. @end example
  7720. This directs the compiler not to do certain common optimizations on
  7721. use of the variable @code{lock}. All the reads and writes for a volatile
  7722. variable or field are really done, and done in the order specified
  7723. by the source code. Thus, this code:
  7724. @example
  7725. lock = 1;
  7726. list = list->next;
  7727. if (lock)
  7728. lock_broken (&lock);
  7729. lock = 0;
  7730. @end example
  7731. @noindent
  7732. really stores the value 1 in @code{lock}, even though there is no
  7733. sign it is really used, and the @code{if} statement reads and
  7734. checks the value of @code{lock}, rather than assuming it is still 1.
  7735. A limited amount of optimization can be done, in principle, on
  7736. @code{volatile} variables and fields: multiple references between two
  7737. sequence points (@pxref{Sequence Points}) can be simplified together.
  7738. Use of @code{volatile} does not eliminate the flexibility in ordering
  7739. the computation of the operands of most operators. For instance, in
  7740. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7741. @code{foo} is not specified, so they may be done in either order; the
  7742. fact that @code{lock} is @code{volatile} has no effect on that.
  7743. @node restrict Pointers
  7744. @section @code{restrict}-Qualified Pointers
  7745. @cindex @code{restrict} pointers
  7746. @cindex pointers, @code{restrict}-qualified
  7747. @findex restrict
  7748. You can declare a pointer as ``restricted'' using the @code{restrict}
  7749. type qualifier, like this:
  7750. @example
  7751. int *restrict p = x;
  7752. @end example
  7753. @noindent
  7754. This enables better optimization of code that uses the pointer.
  7755. If @code{p} is declared with @code{restrict}, and then the code
  7756. references the object that @code{p} points to (using @code{*p} or
  7757. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7758. code will not access that object in any other way---only through
  7759. @code{p}.
  7760. For instance, it means the code must not use another pointer
  7761. to access the same space, as shown here:
  7762. @example
  7763. int *restrict p = @var{whatever};
  7764. int *q = p;
  7765. foo (*p, *q);
  7766. @end example
  7767. @noindent
  7768. That contradicts the @code{restrict} promise by accessing the object
  7769. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7770. Likewise, it must not do this:
  7771. @example
  7772. int *restrict p = @var{whatever};
  7773. struct @{ int *a, *b; @} s;
  7774. s.a = p;
  7775. foo (*p, *s.a);
  7776. @end example
  7777. @noindent
  7778. This example uses a structure field instead of the variable @code{q}
  7779. to hold the other pointer, and that contradicts the promise just the
  7780. same.
  7781. The keyword @code{restrict} also promises that @code{p} won't point to
  7782. the allocated space of any automatic or static variable. So the code
  7783. must not do this:
  7784. @example
  7785. int a;
  7786. int *restrict p = &a;
  7787. foo (*p, a);
  7788. @end example
  7789. @noindent
  7790. because that does direct access to the object (@code{a}) that @code{p}
  7791. points to, which bypasses @code{p}.
  7792. If the code makes such promises with @code{restrict} then breaks them,
  7793. execution is unpredictable.
  7794. @node restrict Pointer Example
  7795. @section @code{restrict} Pointer Example
  7796. Here are examples where @code{restrict} enables real optimization.
  7797. In this example, @code{restrict} assures GCC that the array @code{out}
  7798. points to does not overlap with the array @code{in} points to.
  7799. @example
  7800. void
  7801. process_data (const char *in,
  7802. char * restrict out,
  7803. size_t size)
  7804. @{
  7805. for (i = 0; i < size; i++)
  7806. out[i] = in[i] + in[i + 1];
  7807. @}
  7808. @end example
  7809. Here's a simple tree structure, where each tree node holds data of
  7810. type @code{PAYLOAD} plus two subtrees.
  7811. @example
  7812. struct foo
  7813. @{
  7814. PAYLOAD payload;
  7815. struct foo *left;
  7816. struct foo *right;
  7817. @};
  7818. @end example
  7819. Now here's a function to null out both pointers in the @code{left}
  7820. subtree.
  7821. @example
  7822. void
  7823. null_left (struct foo *a)
  7824. @{
  7825. a->left->left = NULL;
  7826. a->left->right = NULL;
  7827. @}
  7828. @end example
  7829. Since @code{*a} and @code{*a->left} have the same data type,
  7830. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7831. the compiled code for @code{null_left} must read @code{a->left}
  7832. again from memory when executing the second assignment statement.
  7833. We can enable optimization, so that it does not need to read
  7834. @code{a->left} again, by writing @code{null_left} this in a less
  7835. obvious way.
  7836. @example
  7837. void
  7838. null_left (struct foo *a)
  7839. @{
  7840. struct foo *b = a->left;
  7841. b->left = NULL;
  7842. b->right = NULL;
  7843. @}
  7844. @end example
  7845. A more elegant way to fix this is with @code{restrict}.
  7846. @example
  7847. void
  7848. null_left (struct foo *restrict a)
  7849. @{
  7850. a->left->left = NULL;
  7851. a->left->right = NULL;
  7852. @}
  7853. @end example
  7854. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7855. as @code{a->left} will not point to the same memory space as @code{a}.
  7856. Therefore, the memory location @code{a->left->left} cannot be the same
  7857. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7858. reloading @code{a->left} for the second statement.
  7859. @node Functions
  7860. @chapter Functions
  7861. @cindex functions
  7862. We have already presented many examples of functions, so if you've
  7863. read this far, you basically understand the concept of a function. It
  7864. is vital, nonetheless, to have a chapter in the manual that collects
  7865. all the information about functions.
  7866. @menu
  7867. * Function Definitions:: Writing the body of a function.
  7868. * Function Declarations:: Declaring the interface of a function.
  7869. * Function Calls:: Using functions.
  7870. * Function Call Semantics:: Call-by-value argument passing.
  7871. * Function Pointers:: Using references to functions.
  7872. * The main Function:: Where execution of a GNU C program begins.
  7873. * Advanced Definitions:: Advanced features of function definitions.
  7874. * Obsolete Definitions:: Obsolete features still used
  7875. in function definitions in old code.
  7876. @end menu
  7877. @node Function Definitions
  7878. @section Function Definitions
  7879. @cindex function definitions
  7880. @cindex defining functions
  7881. We have already presented many examples of function definitions. To
  7882. summarize the rules, a function definition looks like this:
  7883. @example
  7884. @var{returntype}
  7885. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7886. @{
  7887. @var{body}
  7888. @}
  7889. @end example
  7890. The part before the open-brace is called the @dfn{function header}.
  7891. Write @code{void} as the @var{returntype} if the function does
  7892. not return a value.
  7893. @menu
  7894. * Function Parameter Variables:: Syntax and semantics
  7895. of function parameters.
  7896. * Forward Function Declarations:: Functions can only be called after
  7897. they have been defined or declared.
  7898. * Static Functions:: Limiting visibility of a function.
  7899. * Arrays as Parameters:: Functions that accept array arguments.
  7900. * Structs as Parameters:: Functions that accept structure arguments.
  7901. @end menu
  7902. @node Function Parameter Variables
  7903. @subsection Function Parameter Variables
  7904. @cindex function parameter variables
  7905. @cindex parameter variables in functions
  7906. @cindex parameter list
  7907. A function parameter variable is a local variable (@pxref{Local
  7908. Variables}) used within the function to store the value passed as an
  7909. argument in a call to the function. Usually we say ``function
  7910. parameter'' or ``parameter'' for short, not mentioning the fact that
  7911. it's a variable.
  7912. We declare these variables in the beginning of the function
  7913. definition, in the @dfn{parameter list}. For example,
  7914. @example
  7915. fib (int n)
  7916. @end example
  7917. @noindent
  7918. has a parameter list with one function parameter @code{n}, which has
  7919. type @code{int}.
  7920. Function parameter declarations differ from ordinary variable
  7921. declarations in several ways:
  7922. @itemize @bullet
  7923. @item
  7924. Inside the function definition header, commas separate parameter
  7925. declarations, and each parameter needs a complete declaration
  7926. including the type. For instance, if a function @code{foo} has two
  7927. @code{int} parameters, write this:
  7928. @example
  7929. foo (int a, int b)
  7930. @end example
  7931. You can't share the common @code{int} between the two declarations:
  7932. @example
  7933. foo (int a, b) /* @r{Invalid!} */
  7934. @end example
  7935. @item
  7936. A function parameter variable is initialized to whatever value is
  7937. passed in the function call, so its declaration cannot specify an
  7938. initial value.
  7939. @item
  7940. Writing an array type in a function parameter declaration has the
  7941. effect of declaring it as a pointer. The size specified for the array
  7942. has no effect at all, and we normally omit the size. Thus,
  7943. @example
  7944. foo (int a[5])
  7945. foo (int a[])
  7946. foo (int *a)
  7947. @end example
  7948. @noindent
  7949. are equivalent.
  7950. @item
  7951. The scope of the parameter variables is the entire function body,
  7952. notwithstanding the fact that they are written in the function header,
  7953. which is just outside the function body.
  7954. @end itemize
  7955. If a function has no parameters, it would be most natural for the
  7956. list of parameters in its definition to be empty. But that, in C, has
  7957. a special meaning for historical reasons: ``Do not check that calls to
  7958. this function have the right number of arguments.'' Thus,
  7959. @example
  7960. int
  7961. foo ()
  7962. @{
  7963. return 5;
  7964. @}
  7965. int
  7966. bar (int x)
  7967. @{
  7968. return foo (x);
  7969. @}
  7970. @end example
  7971. @noindent
  7972. would not report a compilation error in passing @code{x} as an
  7973. argument to @code{foo}. By contrast,
  7974. @example
  7975. int
  7976. foo (void)
  7977. @{
  7978. return 5;
  7979. @}
  7980. int
  7981. bar (int x)
  7982. @{
  7983. return foo (x);
  7984. @}
  7985. @end example
  7986. @noindent
  7987. would report an error because @code{foo} is supposed to receive
  7988. no arguments.
  7989. @node Forward Function Declarations
  7990. @subsection Forward Function Declarations
  7991. @cindex forward function declarations
  7992. @cindex function declarations, forward
  7993. The order of the function definitions in the source code makes no
  7994. difference, except that each function needs to be defined or declared
  7995. before code uses it.
  7996. The definition of a function also declares its name for the rest of
  7997. the containing scope. But what if you want to call the function
  7998. before its definition? To permit that, write a compatible declaration
  7999. of the same function, before the first call. A declaration that
  8000. prefigures a subsequent definition in this way is called a
  8001. @dfn{forward declaration}. The function declaration can be at top
  8002. @c ??? file scope
  8003. level or within a block, and it applies until the end of the containing
  8004. scope.
  8005. @xref{Function Declarations}, for more information about these
  8006. declarations.
  8007. @node Static Functions
  8008. @subsection Static Functions
  8009. @cindex static functions
  8010. @cindex functions, static
  8011. @findex static
  8012. The keyword @code{static} in a function definition limits the
  8013. visibility of the name to the current compilation module. (That's the
  8014. same thing @code{static} does in variable declarations;
  8015. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8016. contains this code:
  8017. @example
  8018. static int
  8019. foo (void)
  8020. @{
  8021. @r{@dots{}}
  8022. @}
  8023. @end example
  8024. @noindent
  8025. then the code of that compilation module can call @code{foo} anywhere
  8026. after the definition, but other compilation modules cannot refer to it
  8027. at all.
  8028. @cindex forward declaration
  8029. @cindex static function, declaration
  8030. To call @code{foo} before its definition, it needs a forward
  8031. declaration, which should use @code{static} since the function
  8032. definition does. For this function, it looks like this:
  8033. @example
  8034. static int foo (void);
  8035. @end example
  8036. It is generally wise to use @code{static} on the definitions of
  8037. functions that won't be called from outside the same compilation
  8038. module. This makes sure that calls are not added in other modules.
  8039. If programmers decide to change the function's calling convention, or
  8040. understand all the consequences of its use, they will only have to
  8041. check for calls in the same compilation module.
  8042. @node Arrays as Parameters
  8043. @subsection Arrays as Parameters
  8044. @cindex array as parameters
  8045. @cindex functions with array parameters
  8046. Arrays in C are not first-class objects: it is impossible to copy
  8047. them. So they cannot be passed as arguments like other values.
  8048. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8049. a special way.
  8050. @menu
  8051. * Array Parm Pointer::
  8052. * Passing Array Args::
  8053. * Array Parm Qualifiers::
  8054. @end menu
  8055. @node Array Parm Pointer
  8056. @subsubsection Array parameters are pointers
  8057. Declaring a function parameter variable as an array really gives it a
  8058. pointer type. C does this because an expression with array type, if
  8059. used as an argument in a function call, is converted automatically to
  8060. a pointer (to the zeroth element of the array). If you declare the
  8061. corresponding parameter as an ``array'', it will work correctly with
  8062. the pointer value that really gets passed.
  8063. This relates to the fact that C does not check array bounds in access
  8064. to elements of the array (@pxref{Accessing Array Elements}).
  8065. For example, in this function,
  8066. @example
  8067. void
  8068. clobber4 (int array[20])
  8069. @{
  8070. array[4] = 0;
  8071. @}
  8072. @end example
  8073. @noindent
  8074. the parameter @code{array}'s real type is @code{int *}; the specified
  8075. length, 20, has no effect on the program. You can leave out the length
  8076. and write this:
  8077. @example
  8078. void
  8079. clobber4 (int array[])
  8080. @{
  8081. array[4] = 0;
  8082. @}
  8083. @end example
  8084. @noindent
  8085. or write the parameter declaration explicitly as a pointer:
  8086. @example
  8087. void
  8088. clobber4 (int *array)
  8089. @{
  8090. array[4] = 0;
  8091. @}
  8092. @end example
  8093. They are all equivalent.
  8094. @node Passing Array Args
  8095. @subsubsection Passing array arguments
  8096. The function call passes this pointer by
  8097. value, like all argument values in C@. However, the result is
  8098. paradoxical in that the array itself is passed by reference: its
  8099. contents are treated as shared memory---shared between the caller and
  8100. the called function, that is. When @code{clobber4} assigns to element
  8101. 4 of @code{array}, the effect is to alter element 4 of the array
  8102. specified in the call.
  8103. @example
  8104. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8105. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8106. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8107. int
  8108. main (void)
  8109. @{
  8110. int data[] = @{1, 2, 3, 4, 5, 6@};
  8111. int i;
  8112. /* @r{Show the initial value of element 4.} */
  8113. for (i = 0; i < 6; i++)
  8114. printf ("data[%d] = %d\n", i, data[i]);
  8115. printf ("\n");
  8116. clobber4 (data);
  8117. /* @r{Show that element 4 has been changed.} */
  8118. for (i = 0; i < 6; i++)
  8119. printf ("data[%d] = %d\n", i, data[i]);
  8120. printf ("\n");
  8121. return EXIT_SUCCESS;
  8122. @}
  8123. @end example
  8124. @noindent
  8125. shows that @code{data[4]} has become zero after the call to
  8126. @code{clobber4}.
  8127. The array @code{data} has 6 elements, but passing it to a function
  8128. whose argument type is written as @code{int [20]} is not an error,
  8129. because that really stands for @code{int *}. The pointer that is the
  8130. real argument carries no indication of the length of the array it
  8131. points into. It is not required to point to the beginning of the
  8132. array, either. For instance,
  8133. @example
  8134. clobber4 (data+1);
  8135. @end example
  8136. @noindent
  8137. passes an ``array'' that starts at element 1 of @code{data}, and the
  8138. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8139. If all calls to the function will provide an array of a particular
  8140. size, you can specify the size of the array to be @code{static}:
  8141. @example
  8142. void
  8143. clobber4 (int array[static 20])
  8144. @r{@dots{}}
  8145. @end example
  8146. @noindent
  8147. This is a promise to the compiler that the function will always be
  8148. called with an array of 20 elements, so that the compiler can optimize
  8149. code accordingly. If the code breaks this promise and calls the
  8150. function with, for example, a shorter array, unpredictable things may
  8151. happen.
  8152. @node Array Parm Qualifiers
  8153. @subsubsection Type qualifiers on array parameters
  8154. You can use the type qualifiers @code{const}, @code{restrict}, and
  8155. @code{volatile} with array parameters; for example:
  8156. @example
  8157. void
  8158. clobber4 (volatile int array[20])
  8159. @r{@dots{}}
  8160. @end example
  8161. @noindent
  8162. denotes that @code{array} is equivalent to a pointer to a volatile
  8163. @code{int}. Alternatively:
  8164. @example
  8165. void
  8166. clobber4 (int array[const 20])
  8167. @r{@dots{}}
  8168. @end example
  8169. @noindent
  8170. makes the array parameter equivalent to a constant pointer to an
  8171. @code{int}. If we want the @code{clobber4} function to succeed, it
  8172. would not make sense to write
  8173. @example
  8174. void
  8175. clobber4 (const int array[20])
  8176. @r{@dots{}}
  8177. @end example
  8178. @noindent
  8179. as this would tell the compiler that the parameter should point to an
  8180. array of constant @code{int} values, and then we would not be able to
  8181. store zeros in them.
  8182. In a function with multiple array parameters, you can use @code{restrict}
  8183. to tell the compiler that each array parameter passed in will be distinct:
  8184. @example
  8185. void
  8186. foo (int array1[restrict 10], int array2[restrict 10])
  8187. @r{@dots{}}
  8188. @end example
  8189. @noindent
  8190. Using @code{restrict} promises the compiler that callers will
  8191. not pass in the same array for more than one @code{restrict} array
  8192. parameter. Knowing this enables the compiler to perform better code
  8193. optimization. This is the same effect as using @code{restrict}
  8194. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8195. the code that an array of a specific size is expected.
  8196. @node Structs as Parameters
  8197. @subsection Functions That Accept Structure Arguments
  8198. Structures in GNU C are first-class objects, so using them as function
  8199. parameters and arguments works in the natural way. This function
  8200. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8201. and returns a structure of the same type but with the fields
  8202. exchanged.
  8203. @example
  8204. struct foo @{ int a, b; @};
  8205. struct foo x;
  8206. struct foo
  8207. swapfoo (struct foo inval)
  8208. @{
  8209. struct foo outval;
  8210. outval.a = inval.b;
  8211. outval.b = inval.a;
  8212. return outval;
  8213. @}
  8214. @end example
  8215. This simpler definition of @code{swapfoo} avoids using a local
  8216. variable to hold the result about to be return, by using a structure
  8217. constructor (@pxref{Structure Constructors}), like this:
  8218. @example
  8219. struct foo
  8220. swapfoo (struct foo inval)
  8221. @{
  8222. return (struct foo) @{ inval.b, inval.a @};
  8223. @}
  8224. @end example
  8225. It is valid to define a structure type in a function's parameter list,
  8226. as in
  8227. @example
  8228. int
  8229. frob_bar (struct bar @{ int a, b; @} inval)
  8230. @{
  8231. @var{body}
  8232. @}
  8233. @end example
  8234. @noindent
  8235. and @var{body} can access the fields of @var{inval} since the
  8236. structure type @code{struct bar} is defined for the whole function
  8237. body. However, there is no way to create a @code{struct bar} argument
  8238. to pass to @code{frob_bar}, except with kludges. As a result,
  8239. defining a structure type in a parameter list is useless in practice.
  8240. @node Function Declarations
  8241. @section Function Declarations
  8242. @cindex function declarations
  8243. @cindex declararing functions
  8244. To call a function, or use its name as a pointer, a @dfn{function
  8245. declaration} for the function name must be in effect at that point in
  8246. the code. The function's definition serves as a declaration of that
  8247. function for the rest of the containing scope, but to use the function
  8248. in code before the definition, or from another compilation module, a
  8249. separate function declaration must precede the use.
  8250. A function declaration looks like the start of a function definition.
  8251. It begins with the return value type (@code{void} if none) and the
  8252. function name, followed by argument declarations in parentheses
  8253. (though these can sometimes be omitted). But that's as far as the
  8254. similarity goes: instead of the function body, the declaration uses a
  8255. semicolon.
  8256. @cindex function prototype
  8257. @cindex prototype of a function
  8258. A declaration that specifies argument types is called a @dfn{function
  8259. prototype}. You can include the argument names or omit them. The
  8260. names, if included in the declaration, have no effect, but they may
  8261. serve as documentation.
  8262. This form of prototype specifies fixed argument types:
  8263. @example
  8264. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8265. @end example
  8266. @noindent
  8267. This form says the function takes no arguments:
  8268. @example
  8269. @var{rettype} @var{function} (void);
  8270. @end example
  8271. @noindent
  8272. This form declares types for some arguments, and allows additional
  8273. arguments whose types are not specified:
  8274. @example
  8275. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8276. @end example
  8277. For a parameter that's an array of variable length, you can write
  8278. its declaration with @samp{*} where the ``length'' of the array would
  8279. normally go; for example, these are all equivalent.
  8280. @example
  8281. double maximum (int n, int m, double a[n][m]);
  8282. double maximum (int n, int m, double a[*][*]);
  8283. double maximum (int n, int m, double a[ ][*]);
  8284. double maximum (int n, int m, double a[ ][m]);
  8285. @end example
  8286. @noindent
  8287. The old-fashioned form of declaration, which is not a prototype, says
  8288. nothing about the types of arguments or how many they should be:
  8289. @example
  8290. @var{rettype} @var{function} ();
  8291. @end example
  8292. @strong{Warning:} Arguments passed to a function declared without a
  8293. prototype are converted with the default argument promotions
  8294. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8295. types are unspecified.
  8296. Function declarations are usually written at the top level in a source file,
  8297. but you can also put them inside code blocks. Then the function name
  8298. is visible for the rest of the containing scope. For example:
  8299. @example
  8300. void
  8301. foo (char *file_name)
  8302. @{
  8303. void save_file (char *);
  8304. save_file (file_name);
  8305. @}
  8306. @end example
  8307. If another part of the code tries to call the function
  8308. @code{save_file}, this declaration won't be in effect there. So the
  8309. function will get an implicit declaration of the form @code{extern int
  8310. save_file ();}. That conflicts with the explicit declaration
  8311. here, and the discrepancy generates a warning.
  8312. The syntax of C traditionally allows omitting the data type in a
  8313. function declaration if it specifies a storage class or a qualifier.
  8314. Then the type defaults to @code{int}. For example:
  8315. @example
  8316. static foo (double x);
  8317. @end example
  8318. @noindent
  8319. defaults the return type to @code{int}.
  8320. This is bad practice; if you see it, fix it.
  8321. Calling a function that is undeclared has the effect of an creating
  8322. @dfn{implicit} declaration in the innermost containing scope,
  8323. equivalent to this:
  8324. @example
  8325. extern int @dfn{function} ();
  8326. @end example
  8327. @noindent
  8328. This declaration says that the function returns @code{int} but leaves
  8329. its argument types unspecified. If that does not accurately fit the
  8330. function, then the program @strong{needs} an explicit declaration of
  8331. the function with argument types in order to call it correctly.
  8332. Implicit declarations are deprecated, and a function call that creates one
  8333. causes a warning.
  8334. @node Function Calls
  8335. @section Function Calls
  8336. @cindex function calls
  8337. @cindex calling functions
  8338. Starting a program automatically calls the function named @code{main}
  8339. (@pxref{The main Function}). Aside from that, a function does nothing
  8340. except when it is @dfn{called}. That occurs during the execution of a
  8341. function-call expression specifying that function.
  8342. A function-call expression looks like this:
  8343. @example
  8344. @var{function} (@var{arguments}@r{@dots{}})
  8345. @end example
  8346. Most of the time, @var{function} is a function name. However, it can
  8347. also be an expression with a function pointer value; that way, the
  8348. program can determine at run time which function to call.
  8349. The @var{arguments} are a series of expressions separated by commas.
  8350. Each expression specifies one argument to pass to the function.
  8351. The list of arguments in a function call looks just like use of the
  8352. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8353. the parentheses of a function call gives it a different meaning.
  8354. Here's an example of a function call, taken from an example near the
  8355. beginning (@pxref{Complete Program}).
  8356. @example
  8357. printf ("Fibonacci series item %d is %d\n",
  8358. 19, fib (19));
  8359. @end example
  8360. The three arguments given to @code{printf} are a constant string, the
  8361. integer 19, and the integer returned by @code{fib (19)}.
  8362. @node Function Call Semantics
  8363. @section Function Call Semantics
  8364. @cindex function call semantics
  8365. @cindex semantics of function calls
  8366. @cindex call-by-value
  8367. The meaning of a function call is to compute the specified argument
  8368. expressions, convert their values according to the function's
  8369. declaration, then run the function giving it copies of the converted
  8370. values. (This method of argument passing is known as
  8371. @dfn{call-by-value}.) When the function finishes, the value it
  8372. returns becomes the value of the function-call expression.
  8373. Call-by-value implies that an assignment to the function argument
  8374. variable has no direct effect on the caller. For instance,
  8375. @example
  8376. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8377. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8378. void
  8379. subroutine (int x)
  8380. @{
  8381. x = 5;
  8382. @}
  8383. void
  8384. main (void)
  8385. @{
  8386. int y = 20;
  8387. subroutine (y);
  8388. printf ("y is %d\n", y);
  8389. return EXIT_SUCCESS;
  8390. @}
  8391. @end example
  8392. @noindent
  8393. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8394. from the value of @code{y}, but this does not establish any other
  8395. relationship between the two variables. Thus, the assignment to
  8396. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8397. If an argument's type is specified by the function's declaration, the
  8398. function call converts the argument expression to that type if
  8399. possible. If the conversion is impossible, that is an error.
  8400. If the function's declaration doesn't specify the type of that
  8401. argument, then the @emph{default argument promotions} apply.
  8402. @xref{Argument Promotions}.
  8403. @node Function Pointers
  8404. @section Function Pointers
  8405. @cindex function pointers
  8406. @cindex pointers to functions
  8407. A function name refers to a fixed function. Sometimes it is useful to
  8408. call a function to be determined at run time; to do this, you can use
  8409. a @dfn{function pointer value} that points to the chosen function
  8410. (@pxref{Pointers}).
  8411. Pointer-to-function types can be used to declare variables and other
  8412. data, including array elements, structure fields, and union
  8413. alternatives. They can also be used for function arguments and return
  8414. values. These types have the peculiarity that they are never
  8415. converted automatically to @code{void *} or vice versa. However, you
  8416. can do that conversion with a cast.
  8417. @menu
  8418. * Declaring Function Pointers:: How to declare a pointer to a function.
  8419. * Assigning Function Pointers:: How to assign values to function pointers.
  8420. * Calling Function Pointers:: How to call functions through pointers.
  8421. @end menu
  8422. @node Declaring Function Pointers
  8423. @subsection Declaring Function Pointers
  8424. @cindex declaring function pointers
  8425. @cindex function pointers, declaring
  8426. The declaration of a function pointer variable (or structure field)
  8427. looks almost like a function declaration, except it has an additional
  8428. @samp{*} just before the variable name. Proper nesting requires a
  8429. pair of parentheses around the two of them. For instance, @code{int
  8430. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8431. an @code{int}-returning function.''
  8432. Contrast these three declarations:
  8433. @example
  8434. /* @r{Declare a function returning @code{char *}.} */
  8435. char *a (char *);
  8436. /* @r{Declare a pointer to a function returning @code{char}.} */
  8437. char (*a) (char *);
  8438. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8439. char *(*a) (char *);
  8440. @end example
  8441. The possible argument types of the function pointed to are the same
  8442. as in a function declaration. You can write a prototype
  8443. that specifies all the argument types:
  8444. @example
  8445. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8446. @end example
  8447. @noindent
  8448. or one that specifies some and leaves the rest unspecified:
  8449. @example
  8450. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8451. @end example
  8452. @noindent
  8453. or one that says there are no arguments:
  8454. @example
  8455. @var{rettype} (*@var{function}) (void);
  8456. @end example
  8457. You can also write a non-prototype declaration that says
  8458. nothing about the argument types:
  8459. @example
  8460. @var{rettype} (*@var{function}) ();
  8461. @end example
  8462. For example, here's a declaration for a variable that should
  8463. point to some arithmetic function that operates on two @code{double}s:
  8464. @example
  8465. double (*binary_op) (double, double);
  8466. @end example
  8467. Structure fields, union alternatives, and array elements can be
  8468. function pointers; so can parameter variables. The function pointer
  8469. declaration construct can also be combined with other operators
  8470. allowed in declarations. For instance,
  8471. @example
  8472. int **(*foo)();
  8473. @end example
  8474. @noindent
  8475. declares @code{foo} as a pointer to a function that returns
  8476. type @code{int **}, and
  8477. @example
  8478. int **(*foo[30])();
  8479. @end example
  8480. @noindent
  8481. declares @code{foo} as an array of 30 pointers to functions that
  8482. return type @code{int **}.
  8483. @example
  8484. int **(**foo)();
  8485. @end example
  8486. @noindent
  8487. declares @code{foo} as a pointer to a pointer to a function that
  8488. returns type @code{int **}.
  8489. @node Assigning Function Pointers
  8490. @subsection Assigning Function Pointers
  8491. @cindex assigning function pointers
  8492. @cindex function pointers, assigning
  8493. Assuming we have declared the variable @code{binary_op} as in the
  8494. previous section, giving it a value requires a suitable function to
  8495. use. So let's define a function suitable for the variable to point
  8496. to. Here's one:
  8497. @example
  8498. double
  8499. double_add (double a, double b)
  8500. @{
  8501. return a+b;
  8502. @}
  8503. @end example
  8504. Now we can give it a value:
  8505. @example
  8506. binary_op = double_add;
  8507. @end example
  8508. The target type of the function pointer must be upward compatible with
  8509. the type of the function (@pxref{Compatible Types}).
  8510. There is no need for @samp{&} in front of @code{double_add}.
  8511. Using a function name such as @code{double_add} as an expression
  8512. automatically converts it to the function's address, with the
  8513. appropriate function pointer type. However, it is ok to use
  8514. @samp{&} if you feel that is clearer:
  8515. @example
  8516. binary_op = &double_add;
  8517. @end example
  8518. @node Calling Function Pointers
  8519. @subsection Calling Function Pointers
  8520. @cindex calling function pointers
  8521. @cindex function pointers, calling
  8522. To call the function specified by a function pointer, just write the
  8523. function pointer value in a function call. For instance, here's a
  8524. call to the function @code{binary_op} points to:
  8525. @example
  8526. binary_op (x, 5)
  8527. @end example
  8528. Since the data type of @code{binary_op} explicitly specifies type
  8529. @code{double} for the arguments, the call converts @code{x} and 5 to
  8530. @code{double}.
  8531. The call conceptually dereferences the pointer @code{binary_op} to
  8532. ``get'' the function it points to, and calls that function. If you
  8533. wish, you can explicitly represent the derefence by writing the
  8534. @code{*} operator:
  8535. @example
  8536. (*binary_op) (x, 5)
  8537. @end example
  8538. The @samp{*} reminds people reading the code that @code{binary_op} is
  8539. a function pointer rather than the name of a specific function.
  8540. @node The main Function
  8541. @section The @code{main} Function
  8542. @cindex @code{main} function
  8543. @findex main
  8544. Every complete executable program requires at least one function,
  8545. called @code{main}, which is where execution begins. You do not have
  8546. to explicitly declare @code{main}, though GNU C permits you to do so.
  8547. Conventionally, @code{main} should be defined to follow one of these
  8548. calling conventions:
  8549. @example
  8550. int main (void) @{@r{@dots{}}@}
  8551. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8552. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8553. @end example
  8554. @noindent
  8555. Using @code{void} as the parameter list means that @code{main} does
  8556. not use the arguments. You can write @code{char **argv} instead of
  8557. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8558. constructs are equivalent.
  8559. @ignore @c Not so at present
  8560. Defining @code{main} in any other way generates a warning. Your
  8561. program will still compile, but you may get unexpected results when
  8562. executing it.
  8563. @end ignore
  8564. You can call @code{main} from C code, as you can call any other
  8565. function, though that is an unusual thing to do. When you do that,
  8566. you must write the call to pass arguments that match the parameters in
  8567. the definition of @code{main}.
  8568. The @code{main} function is not actually the first code that runs when
  8569. a program starts. In fact, the first code that runs is system code
  8570. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8571. code, but in GNU we replaced it with C code. Its job is to find
  8572. the arguments for @code{main} and call that.
  8573. @menu
  8574. * Values from main:: Returning values from the main function.
  8575. * Command-line Parameters:: Accessing command-line parameters
  8576. provided to the program.
  8577. * Environment Variables:: Accessing system environment variables.
  8578. @end menu
  8579. @node Values from main
  8580. @subsection Returning Values from @code{main}
  8581. @cindex returning values from @code{main}
  8582. @cindex success
  8583. @cindex failure
  8584. @cindex exit status
  8585. When @code{main} returns, the process terminates. Whatever value
  8586. @code{main} returns becomes the exit status which is reported to the
  8587. parent process. While nominally the return value is of type
  8588. @code{int}, in fact the exit status gets truncated to eight bits; if
  8589. @code{main} returns the value 256, the exit status is 0.
  8590. Normally, programs return only one of two values: 0 for success,
  8591. and 1 for failure. For maximum portability, use the macro
  8592. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8593. @code{stdlib.h}. Here's an example:
  8594. @cindex @code{EXIT_FAILURE}
  8595. @cindex @code{EXIT_SUCCESS}
  8596. @example
  8597. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8598. /* @r{and @code{EXIT_FAILURE}.} */
  8599. int
  8600. main (void)
  8601. @{
  8602. @r{@dots{}}
  8603. if (foo)
  8604. return EXIT_SUCCESS;
  8605. else
  8606. return EXIT_FAILURE;
  8607. @}
  8608. @end example
  8609. Some types of programs maintain special conventions for various return
  8610. values; for example, comparison programs including @code{cmp} and
  8611. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8612. the comparison couldn't be performed.
  8613. @node Command-line Parameters
  8614. @subsection Accessing Command-line Parameters
  8615. @cindex command-line parameters
  8616. @cindex parameters, command-line
  8617. If the program was invoked with any command-line arguments, it can
  8618. access them through the arguments of @code{main}, @code{argc} and
  8619. @code{argv}. (You can give these arguments any names, but the names
  8620. @code{argc} and @code{argv} are customary.)
  8621. The value of @code{argv} is an array containing all of the
  8622. command-line arguments as strings, with the name of the command
  8623. invoked as the first string. @code{argc} is an integer that says how
  8624. many strings @code{argv} contains. Here is an example of accessing
  8625. the command-line parameters, retrieving the program's name and
  8626. checking for the standard @option{--version} and @option{--help} options:
  8627. @example
  8628. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8629. int
  8630. main (int argc, char *argv[])
  8631. @{
  8632. char *program_name = argv[0];
  8633. for (int i = 1; i < argc; i++)
  8634. @{
  8635. if (!strcmp (argv[i], "--version"))
  8636. @{
  8637. /* @r{Print version information and exit.} */
  8638. @r{@dots{}}
  8639. @}
  8640. else if (!strcmp (argv[i], "--help"))
  8641. @{
  8642. /* @r{Print help information and exit.} */
  8643. @r{@dots{}}
  8644. @}
  8645. @}
  8646. @r{@dots{}}
  8647. @}
  8648. @end example
  8649. @node Environment Variables
  8650. @subsection Accessing Environment Variables
  8651. @cindex environment variables
  8652. You can optionally include a third parameter to @code{main}, another
  8653. array of strings, to capture the environment variables available to
  8654. the program. Unlike what happens with @code{argv}, there is no
  8655. additional parameter for the count of environment variables; rather,
  8656. the array of environment variables concludes with a null pointer.
  8657. @example
  8658. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8659. int
  8660. main (int argc, char *argv[], char *envp[])
  8661. @{
  8662. /* @r{Print out all environment variables.} */
  8663. int i = 0;
  8664. while (envp[i])
  8665. @{
  8666. printf ("%s\n", envp[i]);
  8667. i++;
  8668. @}
  8669. @}
  8670. @end example
  8671. Another method of retrieving environment variables is to use the
  8672. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8673. Using @code{getenv} does not require defining @code{main} to accept the
  8674. @code{envp} pointer. For example, here is a program that fetches and prints
  8675. the user's home directory (if defined):
  8676. @example
  8677. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8678. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8679. int
  8680. main (void)
  8681. @{
  8682. char *home_directory = getenv ("HOME");
  8683. if (home_directory)
  8684. printf ("My home directory is: %s\n", home_directory);
  8685. else
  8686. printf ("My home directory is not defined!\n");
  8687. @}
  8688. @end example
  8689. @node Advanced Definitions
  8690. @section Advanced Function Features
  8691. This section describes some advanced or obscure features for GNU C
  8692. function definitions. If you are just learning C, you can skip the
  8693. rest of this chapter.
  8694. @menu
  8695. * Variable-Length Array Parameters:: Functions that accept arrays
  8696. of variable length.
  8697. * Variable Number of Arguments:: Variadic functions.
  8698. * Nested Functions:: Defining functions within functions.
  8699. * Inline Function Definitions:: A function call optimization technique.
  8700. @end menu
  8701. @node Variable-Length Array Parameters
  8702. @subsection Variable-Length Array Parameters
  8703. @cindex variable-length array parameters
  8704. @cindex array parameters, variable-length
  8705. @cindex functions that accept variable-length arrays
  8706. An array parameter can have variable length: simply declare the array
  8707. type with a size that isn't constant. In a nested function, the
  8708. length can refer to a variable defined in a containing scope. In any
  8709. function, it can refer to a previous parameter, like this:
  8710. @example
  8711. struct entry
  8712. tester (int len, char data[len][len])
  8713. @{
  8714. @r{@dots{}}
  8715. @}
  8716. @end example
  8717. Alternatively, in function declarations (but not in function
  8718. definitions), you can use @code{[*]} to denote that the array
  8719. parameter is of a variable length, such that these two declarations
  8720. mean the same thing:
  8721. @example
  8722. struct entry
  8723. tester (int len, char data[len][len]);
  8724. @end example
  8725. @example
  8726. struct entry
  8727. tester (int len, char data[*][*]);
  8728. @end example
  8729. @noindent
  8730. The two forms of input are equivalent in GNU C, but emphasizing that
  8731. the array parameter is variable-length may be helpful to those
  8732. studying the code.
  8733. You can also omit the length parameter, and instead use some other
  8734. in-scope variable for the length in the function definition:
  8735. @example
  8736. struct entry
  8737. tester (char data[*][*]);
  8738. @r{@dots{}}
  8739. int dataLength = 20;
  8740. @r{@dots{}}
  8741. struct entry
  8742. tester (char data[dataLength][dataLength])
  8743. @{
  8744. @r{@dots{}}
  8745. @}
  8746. @end example
  8747. @c ??? check text above
  8748. @cindex parameter forward declaration
  8749. In GNU C, to pass the array first and the length afterward, you can
  8750. use a @dfn{parameter forward declaration}, like this:
  8751. @example
  8752. struct entry
  8753. tester (int len; char data[len][len], int len)
  8754. @{
  8755. @r{@dots{}}
  8756. @}
  8757. @end example
  8758. The @samp{int len} before the semicolon is the parameter forward
  8759. declaration; it serves the purpose of making the name @code{len} known
  8760. when the declaration of @code{data} is parsed.
  8761. You can write any number of such parameter forward declarations in the
  8762. parameter list. They can be separated by commas or semicolons, but
  8763. the last one must end with a semicolon, which is followed by the
  8764. ``real'' parameter declarations. Each forward declaration must match
  8765. a subsequent ``real'' declaration in parameter name and data type.
  8766. Standard C does not support parameter forward declarations.
  8767. @node Variable Number of Arguments
  8768. @subsection Variable-Length Parameter Lists
  8769. @cindex variable-length parameter lists
  8770. @cindex parameters lists, variable length
  8771. @cindex function parameter lists, variable length
  8772. @cindex variadic function
  8773. A function that takes a variable number of arguments is called a
  8774. @dfn{variadic function}. In C, a variadic function must specify at
  8775. least one fixed argument with an explicitly declared data type.
  8776. Additional arguments can follow, and can vary in both quantity and
  8777. data type.
  8778. In the function header, declare the fixed parameters in the normal
  8779. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8780. example of a variadic function header:
  8781. @example
  8782. int add_multiple_values (int number, ...)
  8783. @end example
  8784. @cindex @code{va_list}
  8785. @cindex @code{va_start}
  8786. @cindex @code{va_end}
  8787. The function body can refer to fixed arguments by their parameter
  8788. names, but the additional arguments have no names. Accessing them in
  8789. the function body uses certain standard macros. They are defined in
  8790. the library header file @file{stdarg.h}, so the code must
  8791. @code{#include} that file.
  8792. In the body, write
  8793. @example
  8794. va_list ap;
  8795. va_start (ap, @var{last_fixed_parameter});
  8796. @end example
  8797. @noindent
  8798. This declares the variable @code{ap} (you can use any name for it)
  8799. and then sets it up to point before the first additional argument.
  8800. Then, to fetch the next consecutive additional argument, write this:
  8801. @example
  8802. va_arg (ap, @var{type})
  8803. @end example
  8804. After fetching all the additional arguments (or as many as need to be
  8805. used), write this:
  8806. @example
  8807. va_end (ap);
  8808. @end example
  8809. Here's an example of a variadic function definition that adds any
  8810. number of @code{int} arguments. The first (fixed) argument says how
  8811. many more arguments follow.
  8812. @example
  8813. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8814. @r{@dots{}}
  8815. int
  8816. add_multiple_values (int argcount, ...)
  8817. @{
  8818. int counter, total = 0;
  8819. /* @r{Declare a variable of type @code{va_list}.} */
  8820. va_list argptr;
  8821. /* @r{Initialize that variable..} */
  8822. va_start (argptr, argcount);
  8823. for (counter = 0; counter < argcount; counter++)
  8824. @{
  8825. /* @r{Get the next additional argument.} */
  8826. total += va_arg (argptr, int);
  8827. @}
  8828. /* @r{End use of the @code{argptr} variable.} */
  8829. va_end (argptr);
  8830. return total;
  8831. @}
  8832. @end example
  8833. With GNU C, @code{va_end} is superfluous, but some other compilers
  8834. might make @code{va_start} allocate memory so that calling
  8835. @code{va_end} is necessary to avoid a memory leak. Before doing
  8836. @code{va_start} again with the same variable, do @code{va_end}
  8837. first.
  8838. @cindex @code{va_copy}
  8839. Because of this possible memory allocation, it is risky (in principle)
  8840. to copy one @code{va_list} variable to another with assignment.
  8841. Instead, use @code{va_copy}, which copies the substance but allocates
  8842. separate memory in the variable you copy to. The call looks like
  8843. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8844. @var{from} should be variables of type @code{va_list}. In principle,
  8845. do @code{va_end} on each of these variables before its scope ends.
  8846. Since the additional arguments' types are not specified in the
  8847. function's definition, the default argument promotions
  8848. (@pxref{Argument Promotions}) apply to them in function calls. The
  8849. function definition must take account of this; thus, if an argument
  8850. was passed as @code{short}, the function should get it as @code{int}.
  8851. If an argument was passed as @code{float}, the function should get it
  8852. as @code{double}.
  8853. C has no mechanism to tell the variadic function how many arguments
  8854. were passed to it, so its calling convention must give it a way to
  8855. determine this. That's why @code{add_multiple_values} takes a fixed
  8856. argument that says how many more arguments follow. Thus, you can
  8857. call the function like this:
  8858. @example
  8859. sum = add_multiple_values (3, 12, 34, 190);
  8860. /* @r{Value is 12+34+190.} */
  8861. @end example
  8862. In GNU C, there is no actual need to use the @code{va_end} function.
  8863. In fact, it does nothing. It's used for compatibility with other
  8864. compilers, when that matters.
  8865. It is a mistake to access variables declared as @code{va_list} except
  8866. in the specific ways described here. Just what that type consists of
  8867. is an implementation detail, which could vary from one platform to
  8868. another.
  8869. @node Nested Functions
  8870. @subsection Nested Functions
  8871. @cindex nested functions
  8872. @cindex functions, nested
  8873. @cindex downward funargs
  8874. @cindex thunks
  8875. A @dfn{nested function} is a function defined inside another function.
  8876. The nested function's name is local to the block where it is defined.
  8877. For example, here we define a nested function named @code{square}, and
  8878. call it twice:
  8879. @example
  8880. @group
  8881. foo (double a, double b)
  8882. @{
  8883. double square (double z) @{ return z * z; @}
  8884. return square (a) + square (b);
  8885. @}
  8886. @end group
  8887. @end example
  8888. The nested function can access all the variables of the containing
  8889. function that are visible at the point of its definition. This is
  8890. called @dfn{lexical scoping}. For example, here we show a nested
  8891. function that uses an inherited variable named @code{offset}:
  8892. @example
  8893. @group
  8894. bar (int *array, int offset, int size)
  8895. @{
  8896. int access (int *array, int index)
  8897. @{ return array[index + offset]; @}
  8898. int i;
  8899. @r{@dots{}}
  8900. for (i = 0; i < size; i++)
  8901. @r{@dots{}} access (array, i) @r{@dots{}}
  8902. @}
  8903. @end group
  8904. @end example
  8905. Nested function definitions can appear wherever automatic variable
  8906. declarations are allowed; that is, in any block, interspersed with the
  8907. other declarations and statements in the block.
  8908. The nested function's name is visible only within the parent block;
  8909. the name's scope starts from its definition and continues to the end
  8910. of the containing block. If the nested function's name
  8911. is the same as the parent function's name, there wil be
  8912. no way to refer to the parent function inside the scope of the
  8913. name of the nested function.
  8914. Using @code{extern} or @code{static} on a nested function definition
  8915. is an error.
  8916. It is possible to call the nested function from outside the scope of its
  8917. name by storing its address or passing the address to another function.
  8918. You can do this safely, but you must be careful:
  8919. @example
  8920. @group
  8921. hack (int *array, int size, int addition)
  8922. @{
  8923. void store (int index, int value)
  8924. @{ array[index] = value + addition; @}
  8925. intermediate (store, size);
  8926. @}
  8927. @end group
  8928. @end example
  8929. Here, the function @code{intermediate} receives the address of
  8930. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8931. the arguments given to @code{store} are used to store into @code{array}.
  8932. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8933. It is safe for @code{intermediate} to call @code{store} because
  8934. @code{hack}'s stack frame, with its arguments and local variables,
  8935. continues to exist during the call to @code{intermediate}.
  8936. Calling the nested function through its address after the containing
  8937. function has exited is asking for trouble. If it is called after a
  8938. containing scope level has exited, and if it refers to some of the
  8939. variables that are no longer in scope, it will refer to memory
  8940. containing junk or other data. It's not wise to take the risk.
  8941. The GNU C Compiler implements taking the address of a nested function
  8942. using a technique called @dfn{trampolines}. This technique was
  8943. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8944. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8945. A nested function can jump to a label inherited from a containing
  8946. function, provided the label was explicitly declared in the containing
  8947. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8948. containing function, exiting the nested function that did the
  8949. @code{goto} and any intermediate function invocations as well. Here
  8950. is an example:
  8951. @example
  8952. @group
  8953. bar (int *array, int offset, int size)
  8954. @{
  8955. /* @r{Explicitly declare the label @code{failure}.} */
  8956. __label__ failure;
  8957. int access (int *array, int index)
  8958. @{
  8959. if (index > size)
  8960. /* @r{Exit this function,}
  8961. @r{and return to @code{bar}.} */
  8962. goto failure;
  8963. return array[index + offset];
  8964. @}
  8965. @end group
  8966. @group
  8967. int i;
  8968. @r{@dots{}}
  8969. for (i = 0; i < size; i++)
  8970. @r{@dots{}} access (array, i) @r{@dots{}}
  8971. @r{@dots{}}
  8972. return 0;
  8973. /* @r{Control comes here from @code{access}
  8974. if it does the @code{goto}.} */
  8975. failure:
  8976. return -1;
  8977. @}
  8978. @end group
  8979. @end example
  8980. To declare the nested function before its definition, use
  8981. @code{auto} (which is otherwise meaningless for function declarations;
  8982. @pxref{auto and register}). For example,
  8983. @example
  8984. bar (int *array, int offset, int size)
  8985. @{
  8986. auto int access (int *, int);
  8987. @r{@dots{}}
  8988. @r{@dots{}} access (array, i) @r{@dots{}}
  8989. @r{@dots{}}
  8990. int access (int *array, int index)
  8991. @{
  8992. @r{@dots{}}
  8993. @}
  8994. @r{@dots{}}
  8995. @}
  8996. @end example
  8997. @node Inline Function Definitions
  8998. @subsection Inline Function Definitions
  8999. @cindex inline function definitions
  9000. @cindex function definitions, inline
  9001. @findex inline
  9002. To declare a function inline, use the @code{inline} keyword in its
  9003. definition. Here's a simple function that takes a pointer-to-@code{int}
  9004. and increments the integer stored there---declared inline.
  9005. @example
  9006. struct list
  9007. @{
  9008. struct list *first, *second;
  9009. @};
  9010. inline struct list *
  9011. list_first (struct list *p)
  9012. @{
  9013. return p->first;
  9014. @}
  9015. inline struct list *
  9016. list_second (struct list *p)
  9017. @{
  9018. return p->second;
  9019. @}
  9020. @end example
  9021. optimized compilation can substitute the inline function's body for
  9022. any call to it. This is called @emph{inlining} the function. It
  9023. makes the code that contains the call run faster, significantly so if
  9024. the inline function is small.
  9025. Here's a function that uses @code{pair_second}:
  9026. @example
  9027. int
  9028. pairlist_length (struct list *l)
  9029. @{
  9030. int length = 0;
  9031. while (l)
  9032. @{
  9033. length++;
  9034. l = pair_second (l);
  9035. @}
  9036. return length;
  9037. @}
  9038. @end example
  9039. Substituting the code of @code{pair_second} into the definition of
  9040. @code{pairlist_length} results in this code, in effect:
  9041. @example
  9042. int
  9043. pairlist_length (struct list *l)
  9044. @{
  9045. int length = 0;
  9046. while (l)
  9047. @{
  9048. length++;
  9049. l = l->second;
  9050. @}
  9051. return length;
  9052. @}
  9053. @end example
  9054. Since the definition of @code{pair_second} does not say @code{extern}
  9055. or @code{static}, that definition is used only for inlining. It
  9056. doesn't generate code that can be called at run time. If not all the
  9057. calls to the function are inlined, there must be a definition of the
  9058. same function name in another module for them to call.
  9059. @cindex inline functions, omission of
  9060. @c @opindex fkeep-inline-functions
  9061. Adding @code{static} to an inline function definition means the
  9062. function definition is limited to this compilation module. Also, it
  9063. generates run-time code if necessary for the sake of any calls that
  9064. were not inlined. If all calls are inlined then the function
  9065. definition does not generate run-time code, but you can force
  9066. generation of run-time code with the option
  9067. @option{-fkeep-inline-functions}.
  9068. @cindex extern inline function
  9069. Specifying @code{extern} along with @code{inline} means the function is
  9070. external and generates run-time code to be called from other
  9071. separately compiled modules, as well as inlined. You can define the
  9072. function as @code{inline} without @code{extern} in other modules so as
  9073. to inline calls to the same function in those modules.
  9074. Why are some calls not inlined? First of all, inlining is an
  9075. optimization, so non-optimized compilation does not inline.
  9076. Some calls cannot be inlined for technical reasons. Also, certain
  9077. usages in a function definition can make it unsuitable for inline
  9078. substitution. Among these usages are: variadic functions, use of
  9079. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9080. use of nonlocal goto. The option @option{-Winline} requests a warning
  9081. when a function marked @code{inline} is unsuitable to be inlined. The
  9082. warning explains what obstacle makes it unsuitable.
  9083. Just because a call @emph{can} be inlined does not mean it
  9084. @emph{should} be inlined. The GNU C compiler weighs costs and
  9085. benefits to decide whether inlining a particular call is advantageous.
  9086. You can force inlining of all calls to a given function that can be
  9087. inlined, even in a non-optimized compilation. by specifying the
  9088. @samp{always_inline} attribute for the function, like this:
  9089. @example
  9090. /* @r{Prototype.} */
  9091. inline void foo (const char) __attribute__((always_inline));
  9092. @end example
  9093. @noindent
  9094. This is a GNU C extension. @xref{Attributes}.
  9095. A function call may be inlined even if not declared @code{inline} in
  9096. special cases where the compiler can determine this is correct and
  9097. desirable. For instance, when a static function is called only once,
  9098. it will very likely be inlined. With @option{-flto}, link-time
  9099. optimization, any function might be inlined. To absolutely prevent
  9100. inlining of a specific function, specify
  9101. @code{__attribute__((__noinline__))} in the function's definition.
  9102. @node Obsolete Definitions
  9103. @section Obsolete Function Features
  9104. These features of function definitions are still used in old
  9105. programs, but you shouldn't write code this way today.
  9106. If you are just learning C, you can skip this section.
  9107. @menu
  9108. * Old GNU Inlining:: An older inlining technique.
  9109. * Old-Style Function Definitions:: Original K&R style functions.
  9110. @end menu
  9111. @node Old GNU Inlining
  9112. @subsection Older GNU C Inlining
  9113. The GNU C spec for inline functions, before GCC version 5, defined
  9114. @code{extern inline} on a function definition to mean to inline calls
  9115. to it but @emph{not} generate code for the function that could be
  9116. called at run time. By contrast, @code{inline} without @code{extern}
  9117. specified to generate run-time code for the function. In effect, ISO
  9118. incompatibly flipped the meanings of these two cases. We changed GCC
  9119. in version 5 to adopt the ISO specification.
  9120. Many programs still use these cases with the previous GNU C meanings.
  9121. You can specify use of those meanings with the option
  9122. @option{-fgnu89-inline}. You can also specify this for a single
  9123. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9124. @example
  9125. inline __attribute__ ((gnu_inline))
  9126. int
  9127. inc (int *a)
  9128. @{
  9129. (*a)++;
  9130. @}
  9131. @end example
  9132. @node Old-Style Function Definitions
  9133. @subsection Old-Style Function Definitions
  9134. @cindex old-style function definitions
  9135. @cindex function definitions, old-style
  9136. @cindex K&R-style function definitions
  9137. The syntax of C traditionally allows omitting the data type in a
  9138. function declaration if it specifies a storage class or a qualifier.
  9139. Then the type defaults to @code{int}. For example:
  9140. @example
  9141. static foo (double x);
  9142. @end example
  9143. @noindent
  9144. defaults the return type to @code{int}. This is bad practice; if you
  9145. see it, fix it.
  9146. An @dfn{old-style} (or ``K&R'') function definition is the way
  9147. function definitions were written in the 1980s. It looks like this:
  9148. @example
  9149. @var{rettype}
  9150. @var{function} (@var{parmnames})
  9151. @var{parm_declarations}
  9152. @{
  9153. @var{body}
  9154. @}
  9155. @end example
  9156. In @var{parmnames}, only the parameter names are listed, separated by
  9157. commas. Then @var{parm_declarations} declares their data types; these
  9158. declarations look just like variable declarations. If a parameter is
  9159. listed in @var{parmnames} but has no declaration, it is implicitly
  9160. declared @code{int}.
  9161. There is no reason to write a definition this way nowadays, but they
  9162. can still be seen in older GNU programs.
  9163. An old-style variadic function definition looks like this:
  9164. @example
  9165. #include <varargs.h>
  9166. int
  9167. add_multiple_values (va_alist)
  9168. va_dcl
  9169. @{
  9170. int argcount;
  9171. int counter, total = 0;
  9172. /* @r{Declare a variable of type @code{va_list}.} */
  9173. va_list argptr;
  9174. /* @r{Initialize that variable.} */
  9175. va_start (argptr);
  9176. /* @r{Get the first argument (fixed).} */
  9177. argcount = va_arg (int);
  9178. for (counter = 0; counter < argcount; counter++)
  9179. @{
  9180. /* @r{Get the next additional argument.} */
  9181. total += va_arg (argptr, int);
  9182. @}
  9183. /* @r{End use of the @code{argptr} variable.} */
  9184. va_end (argptr);
  9185. return total;
  9186. @}
  9187. @end example
  9188. Note that the old-style variadic function definition has no fixed
  9189. parameter variables; all arguments must be obtained with
  9190. @code{va_arg}.
  9191. @node Compatible Types
  9192. @chapter Compatible Types
  9193. @cindex compatible types
  9194. @cindex types, compatible
  9195. Declaring a function or variable twice is valid in C only if the two
  9196. declarations specify @dfn{compatible} types. In addition, some
  9197. operations on pointers require operands to have compatible target
  9198. types.
  9199. In C, two different primitive types are never compatible. Likewise for
  9200. the defined types @code{struct}, @code{union} and @code{enum}: two
  9201. separately defined types are incompatible unless they are defined
  9202. exactly the same way.
  9203. However, there are a few cases where different types can be
  9204. compatible:
  9205. @itemize @bullet
  9206. @item
  9207. Every enumeration type is compatible with some integer type. In GNU
  9208. C, the choice of integer type depends on the largest enumeration
  9209. value.
  9210. @c ??? Which one, in GCC?
  9211. @c ??? ... it varies, depending on the enum values. Testing on
  9212. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9213. @c ??? then moves on to an 8-byte signed integer. These details
  9214. @c ??? might be platform-dependent, as the C standard says that even
  9215. @c ??? char could be used as an enum type, but it's at least true
  9216. @c ??? that GCC chooses a type that is at least large enough to
  9217. @c ??? hold the largest enum value.
  9218. @item
  9219. Array types are compatible if the element types are compatible
  9220. and the sizes (when specified) match.
  9221. @item
  9222. Pointer types are compatible if the pointer target types are
  9223. compatible.
  9224. @item
  9225. Function types that specify argument types are compatible if the
  9226. return types are compatible and the argument types are compatible,
  9227. argument by argument. In addition, they must all agree in whether
  9228. they use @code{...} to allow additional arguments.
  9229. @item
  9230. Function types that don't specify argument types are compatible if the
  9231. return types are.
  9232. @item
  9233. Function types that specify the argument types are compatible with
  9234. function types that omit them, if the return types are compatible and
  9235. the specified argument types are unaltered by the argument promotions
  9236. (@pxref{Argument Promotions}).
  9237. @end itemize
  9238. In order for types to be compatible, they must agree in their type
  9239. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9240. It follows that @code{const int *} and @code{int *} are incompatible
  9241. too (they are pointers to types that are not compatible).
  9242. If two types are compatible ignoring the qualifiers, we call them
  9243. @dfn{nearly compatible}. (If they are array types, we ignore
  9244. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9245. Comparison of pointers is valid if the pointers' target types are
  9246. nearly compatible. Likewise, the two branches of a conditional
  9247. expression may be pointers to nearly compatible target types.
  9248. If two types are compatible ignoring the qualifiers, and the first
  9249. type has all the qualifiers of the second type, we say the first is
  9250. @dfn{upward compatible} with the second. Assignment of pointers
  9251. requires the assigned pointer's target type to be upward compatible
  9252. with the right operand (the new value)'s target type.
  9253. @node Type Conversions
  9254. @chapter Type Conversions
  9255. @cindex type conversions
  9256. @cindex conversions, type
  9257. C converts between data types automatically when that seems clearly
  9258. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9259. @menu
  9260. * Explicit Type Conversion:: Casting a value from one type to another.
  9261. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9262. * Argument Promotions:: Automatic conversion of function parameters.
  9263. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9264. * Common Type:: When operand types differ, which one is used?
  9265. @end menu
  9266. @node Explicit Type Conversion
  9267. @section Explicit Type Conversion
  9268. @cindex cast
  9269. @cindex explicit type conversion
  9270. You can do explicit conversions using the unary @dfn{cast} operator,
  9271. which is written as a type designator (@pxref{Type Designators}) in
  9272. parentheses. For example, @code{(int)} is the operator to cast to
  9273. type @code{int}. Here's an example of using it:
  9274. @example
  9275. @{
  9276. double d = 5.5;
  9277. printf ("Floating point value: %f\n", d);
  9278. printf ("Rounded to integer: %d\n", (int) d);
  9279. @}
  9280. @end example
  9281. Using @code{(int) d} passes an @code{int} value as argument to
  9282. @code{printf}, so you can print it with @samp{%d}. Using just
  9283. @code{d} without the cast would pass the value as @code{double}.
  9284. That won't work at all with @samp{%d}; the results would be gibberish.
  9285. To divide one integer by another without rounding,
  9286. cast either of the integers to @code{double} first:
  9287. @example
  9288. (double) @var{dividend} / @var{divisor}
  9289. @var{dividend} / (double) @var{divisor}
  9290. @end example
  9291. It is enough to cast one of them, because that forces the common type
  9292. to @code{double} so the other will be converted automatically.
  9293. The valid cast conversions are:
  9294. @itemize @bullet
  9295. @item
  9296. One numerical type to another.
  9297. @item
  9298. One pointer type to another.
  9299. (Converting between pointers that point to functions
  9300. and pointers that point to data is not standard C.)
  9301. @item
  9302. A pointer type to an integer type.
  9303. @item
  9304. An integer type to a pointer type.
  9305. @item
  9306. To a union type, from the type of any alternative in the union
  9307. (@pxref{Unions}). (This is a GNU extension.)
  9308. @item
  9309. Anything, to @code{void}.
  9310. @end itemize
  9311. @node Assignment Type Conversions
  9312. @section Assignment Type Conversions
  9313. @cindex assignment type conversions
  9314. Certain type conversions occur automatically in assignments
  9315. and certain other contexts. These are the conversions
  9316. assignments can do:
  9317. @itemize @bullet
  9318. @item
  9319. Converting any numeric type to any other numeric type.
  9320. @item
  9321. Converting @code{void *} to any other pointer type
  9322. (except pointer-to-function types).
  9323. @item
  9324. Converting any other pointer type to @code{void *}.
  9325. (except pointer-to-function types).
  9326. @item
  9327. Converting 0 (a null pointer constant) to any pointer type.
  9328. @item
  9329. Converting any pointer type to @code{bool}. (The result is
  9330. 1 if the pointer is not null.)
  9331. @item
  9332. Converting between pointer types when the left-hand target type is
  9333. upward compatible with the right-hand target type. @xref{Compatible
  9334. Types}.
  9335. @end itemize
  9336. These type conversions occur automatically in certain contexts,
  9337. which are:
  9338. @itemize @bullet
  9339. @item
  9340. An assignment converts the type of the right-hand expression
  9341. to the type wanted by the left-hand expression. For example,
  9342. @example
  9343. double i;
  9344. i = 5;
  9345. @end example
  9346. @noindent
  9347. converts 5 to @code{double}.
  9348. @item
  9349. A function call, when the function specifies the type for that
  9350. argument, converts the argument value to that type. For example,
  9351. @example
  9352. void foo (double);
  9353. foo (5);
  9354. @end example
  9355. @noindent
  9356. converts 5 to @code{double}.
  9357. @item
  9358. A @code{return} statement converts the specified value to the type
  9359. that the function is declared to return. For example,
  9360. @example
  9361. double
  9362. foo ()
  9363. @{
  9364. return 5;
  9365. @}
  9366. @end example
  9367. @noindent
  9368. also converts 5 to @code{double}.
  9369. @end itemize
  9370. In all three contexts, if the conversion is impossible, that
  9371. constitutes an error.
  9372. @node Argument Promotions
  9373. @section Argument Promotions
  9374. @cindex argument promotions
  9375. @cindex promotion of arguments
  9376. When a function's definition or declaration does not specify the type
  9377. of an argument, that argument is passed without conversion in whatever
  9378. type it has, with these exceptions:
  9379. @itemize @bullet
  9380. @item
  9381. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9382. expression is a narrow integer, such as @code{char} or @code{short},
  9383. the call converts it automatically to @code{int} (@pxref{Integer
  9384. Types}).@footnote{On an embedded controller where @code{char}
  9385. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9386. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9387. never occurs in GNU C on real computers.}
  9388. In this example, the expression @code{c} is passed as an @code{int}:
  9389. @example
  9390. char c = '$';
  9391. printf ("Character c is '%c'\n", c);
  9392. @end example
  9393. @item
  9394. If the expression
  9395. has type @code{float}, the call converts it automatically to
  9396. @code{double}.
  9397. @item
  9398. An array as argument is converted to a pointer to its zeroth element.
  9399. @item
  9400. A function name as argument is converted to a pointer to that function.
  9401. @end itemize
  9402. @node Operand Promotions
  9403. @section Operand Promotions
  9404. @cindex operand promotions
  9405. The operands in arithmetic operations undergo type conversion automatically.
  9406. These @dfn{operand promotions} are the same as the argument promotions
  9407. except without converting @code{float} to @code{double}. In other words,
  9408. the operand promotions convert
  9409. @itemize @bullet
  9410. @item
  9411. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9412. @item
  9413. an array to a pointer to its zeroth element, and
  9414. @item
  9415. a function name to a pointer to that function.
  9416. @end itemize
  9417. @node Common Type
  9418. @section Common Type
  9419. @cindex common type
  9420. Arithmetic binary operators (except the shift operators) convert their
  9421. operands to the @dfn{common type} before operating on them.
  9422. Conditional expressions also convert the two possible results to their
  9423. common type. Here are the rules for determining the common type.
  9424. If one of the numbers has a floating-point type and the other is an
  9425. integer, the common type is that floating-point type. For instance,
  9426. @example
  9427. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9428. @end example
  9429. If both are floating point, the type with the larger range is the
  9430. common type.
  9431. If both are integers but of different widths, the common type
  9432. is the wider of the two.
  9433. If they are integer types of the same width, the common type is
  9434. unsigned if either operand is unsigned, and it's @code{long} if either
  9435. operand is @code{long}. It's @code{long long} if either operand is
  9436. @code{long long}.
  9437. These rules apply to addition, subtraction, multiplication, division,
  9438. remainder, comparisons, and bitwise operations. They also apply to
  9439. the two branches of a conditional expression, and to the arithmetic
  9440. done in a modifying assignment operation.
  9441. @node Scope
  9442. @chapter Scope
  9443. @cindex scope
  9444. @cindex block scope
  9445. @cindex function scope
  9446. @cindex function prototype scope
  9447. Each definition or declaration of an identifier is visible
  9448. in certain parts of the program, which is typically less than the whole
  9449. of the program. The parts where it is visible are called its @dfn{scope}.
  9450. Normally, declarations made at the top-level in the source -- that is,
  9451. not within any blocks and function definitions -- are visible for the
  9452. entire contents of the source file after that point. This is called
  9453. @dfn{file scope} (@pxref{File-Scope Variables}).
  9454. Declarations made within blocks of code, including within function
  9455. definitions, are visible only within those blocks. This is called
  9456. @dfn{block scope}. Here is an example:
  9457. @example
  9458. @group
  9459. void
  9460. foo (void)
  9461. @{
  9462. int x = 42;
  9463. @}
  9464. @end group
  9465. @end example
  9466. @noindent
  9467. In this example, the variable @code{x} has block scope; it is visible
  9468. only within the @code{foo} function definition block. Thus, other
  9469. blocks could have their own variables, also named @code{x}, without
  9470. any conflict between those variables.
  9471. A variable declared inside a subblock has a scope limited to
  9472. that subblock,
  9473. @example
  9474. @group
  9475. void
  9476. foo (void)
  9477. @{
  9478. @{
  9479. int x = 42;
  9480. @}
  9481. // @r{@code{x} is out of scope here.}
  9482. @}
  9483. @end group
  9484. @end example
  9485. If a variable declared within a block has the same name as a variable
  9486. declared outside of that block, the definition within the block
  9487. takes precedence during its scope:
  9488. @example
  9489. @group
  9490. int x = 42;
  9491. void
  9492. foo (void)
  9493. @{
  9494. int x = 17;
  9495. printf ("%d\n", x);
  9496. @}
  9497. @end group
  9498. @end example
  9499. @noindent
  9500. This prints 17, the value of the variable @code{x} declared in the
  9501. function body block, rather than the value of the variable @code{x} at
  9502. file scope. We say that the inner declaration of @code{x}
  9503. @dfn{shadows} the outer declaration, for the extent of the inner
  9504. declaration's scope.
  9505. A declaration with block scope can be shadowed by another declaration
  9506. with the same name in a subblock.
  9507. @example
  9508. @group
  9509. void
  9510. foo (void)
  9511. @{
  9512. char *x = "foo";
  9513. @{
  9514. int x = 42;
  9515. @r{@dots{}}
  9516. exit (x / 6);
  9517. @}
  9518. @}
  9519. @end group
  9520. @end example
  9521. A function parameter's scope is the entire function body, but it can
  9522. be shadowed. For example:
  9523. @example
  9524. @group
  9525. int x = 42;
  9526. void
  9527. foo (int x)
  9528. @{
  9529. printf ("%d\n", x);
  9530. @}
  9531. @end group
  9532. @end example
  9533. @noindent
  9534. This prints the value of @code{x} the function parameter, rather than
  9535. the value of the file-scope variable @code{x}. However,
  9536. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9537. is visible for the whole of the containing function body, both before
  9538. and after the label declaration:
  9539. @example
  9540. @group
  9541. void
  9542. foo (void)
  9543. @{
  9544. @r{@dots{}}
  9545. goto bar;
  9546. @r{@dots{}}
  9547. @{ // @r{Subblock does not affect labels.}
  9548. bar:
  9549. @r{@dots{}}
  9550. @}
  9551. goto bar;
  9552. @}
  9553. @end group
  9554. @end example
  9555. Except for labels, a declared identifier is not
  9556. visible to code before its declaration. For example:
  9557. @example
  9558. @group
  9559. int x = 5;
  9560. int y = x + 10;
  9561. @end group
  9562. @end example
  9563. @noindent
  9564. will work, but:
  9565. @example
  9566. @group
  9567. int x = y + 10;
  9568. int y = 5;
  9569. @end group
  9570. @end example
  9571. @noindent
  9572. cannot refer to the variable @code{y} before its declaration.
  9573. @include cpp.texi
  9574. @node Integers in Depth
  9575. @chapter Integers in Depth
  9576. This chapter explains the machine-level details of integer types: how
  9577. they are represented as bits in memory, and the range of possible
  9578. values for each integer type.
  9579. @menu
  9580. * Integer Representations:: How integer values appear in memory.
  9581. * Maximum and Minimum Values:: Value ranges of integer types.
  9582. @end menu
  9583. @node Integer Representations
  9584. @section Integer Representations
  9585. @cindex integer representations
  9586. @cindex representation of integers
  9587. Modern computers store integer values as binary (base-2) numbers that
  9588. occupy a single unit of storage, typically either as an 8-bit
  9589. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9590. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9591. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9592. any of these types could have some other size, bit it's not worth even
  9593. a minute to cater to that possibility. It never happens on
  9594. GNU/Linux.}
  9595. @cindex @code{CHAR_BIT}
  9596. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9597. of bits in type @code{char}. On any real operating system, the value
  9598. is 8.
  9599. The fixed sizes of numeric types necessarily limits their @dfn{range
  9600. of values}, and the particular encoding of integers decides what that
  9601. range is.
  9602. @cindex two's-complement representation
  9603. For unsigned integers, the entire space is used to represent a
  9604. nonnegative value. Signed integers are stored using
  9605. @dfn{two's-complement representation}: a signed integer with @var{n}
  9606. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9607. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9608. high-order, bit is called the @dfn{sign bit}.
  9609. @c ??? Needs correcting
  9610. There is only one value that means zero, and the most negative number
  9611. lacks a positive counterpart. As a result, negating that number
  9612. causes overflow; in practice, its result is that number back again.
  9613. For example, a two's-complement signed 8-bit integer can represent all
  9614. decimal numbers from @minus{}128 to +127. We will revisit that
  9615. peculiarity shortly.
  9616. Decades ago, there were computers that didn't use two's-complement
  9617. representation for integers (@pxref{Integers in Depth}), but they are
  9618. long gone and not worth any effort to support.
  9619. @c ??? Is this duplicate?
  9620. When an arithmetic operation produces a value that is too big to
  9621. represent, the operation is said to @dfn{overflow}. In C, integer
  9622. overflow does not interrupt the control flow or signal an error.
  9623. What it does depends on signedness.
  9624. For unsigned arithmetic, the result of an operation that overflows is
  9625. the @var{n} low-order bits of the correct value. If the correct value
  9626. is representable in @var{n} bits, that is always the result;
  9627. thus we often say that ``integer arithmetic is exact,'' omitting the
  9628. crucial qualifying phrase ``as long as the exact result is
  9629. representable.''
  9630. In principle, a C program should be written so that overflow never
  9631. occurs for signed integers, but in GNU C you can specify various ways
  9632. of handling such overflow (@pxref{Integer Overflow}).
  9633. Integer representations are best understood by looking at a table for
  9634. a tiny integer size; here are the possible values for an integer with
  9635. three bits:
  9636. @multitable @columnfractions .25 .25 .25 .25
  9637. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9638. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9639. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9640. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9641. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9642. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9643. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9644. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9645. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9646. @end multitable
  9647. The parenthesized decimal numbers in the last column represent the
  9648. signed meanings of the two's-complement of the line's value. Recall
  9649. that, in two's-complement encoding, the high-order bit is 0 when
  9650. the number is nonnegative.
  9651. We can now understand the peculiar behavior of negation of the
  9652. most negative two's-complement integer: start with 0b100,
  9653. invert the bits to get 0b011, and add 1: we get
  9654. 0b100, the value we started with.
  9655. We can also see overflow behavior in two's-complement:
  9656. @example
  9657. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9658. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9659. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9660. @end example
  9661. @noindent
  9662. A sum of two nonnegative signed values that overflows has a 1 in the
  9663. sign bit, so the exact positive result is truncated to a negative
  9664. value.
  9665. @c =====================================================================
  9666. @node Maximum and Minimum Values
  9667. @section Maximum and Minimum Values
  9668. @cindex maximum integer values
  9669. @cindex minimum integer values
  9670. @cindex integer ranges
  9671. @cindex ranges of integer types
  9672. @findex INT_MAX
  9673. @findex UINT_MAX
  9674. @findex SHRT_MAX
  9675. @findex LONG_MAX
  9676. @findex LLONG_MAX
  9677. @findex USHRT_MAX
  9678. @findex ULONG_MAX
  9679. @findex ULLONG_MAX
  9680. @findex CHAR_MAX
  9681. @findex SCHAR_MAX
  9682. @findex UCHAR_MAX
  9683. For each primitive integer type, there is a standard macro defined in
  9684. @file{limits.h} that gives the largest value that type can hold. For
  9685. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9686. On a 32-bit computer, that is equal to 2,147,483,647. The
  9687. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9688. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9689. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9690. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9691. @code{ULLONG_MAX}.
  9692. Since there are three ways to specify a @code{char} type, there are
  9693. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9694. @code{UCHAR_MAX}.
  9695. For each type that is or might be signed, there is another symbol that
  9696. gives the minimum value it can hold. (Just replace @code{MAX} with
  9697. @code{MIN} in the names listed above.) There is no minimum limit
  9698. symbol for types specified with @code{unsigned} because the
  9699. minimum for them is universally zero.
  9700. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9701. two's-complement representation, the most negative number is 1 less
  9702. than the negative of the most positive number. Thus, @code{INT_MIN}
  9703. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9704. actually write the value that way in C, since it would overflow.
  9705. That's a good reason to use @code{INT_MIN} to specify
  9706. that value. Its definition is written to avoid overflow.
  9707. @include fp.texi
  9708. @node Compilation
  9709. @chapter Compilation
  9710. @cindex object file
  9711. @cindex compilation module
  9712. @cindex make rules
  9713. Early in the manual we explained how to compile a simple C program
  9714. that consists of a single source file (@pxref{Compile Example}).
  9715. However, we handle only short programs that way. A typical C program
  9716. consists of many source files, each of which is a separate
  9717. @dfn{compilation module}---meaning that it has to be compiled
  9718. separately.
  9719. The full details of how to compile with GCC are documented in xxxx.
  9720. @c ??? ref
  9721. Here we give only a simple introduction.
  9722. These are the commands to compile two compilation modules,
  9723. @file{foo.c} and @file{bar.c}, with a command for each module:
  9724. @example
  9725. gcc -c -O -g foo.c
  9726. gcc -c -O -g bar.c
  9727. @end example
  9728. @noindent
  9729. In these commands, @option{-g} says to generate debugging information,
  9730. @option{-O} says to do some optimization, and @option{-c} says to put
  9731. the compiled code for that module into a corresponding @dfn{object
  9732. file} and go no further. The object file for @file{foo.c} is called
  9733. @file{foo.o}, and so on.
  9734. If you wish, you can specify the additional options @option{-Wformat
  9735. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9736. One reason to divide a large program into multiple compilation modules
  9737. is to control how each module can access the internals of the others.
  9738. When a module declares a function or variable @code{extern}, other
  9739. modules can access it. The other functions and variables in
  9740. a module can't be accessed from outside that module.
  9741. The other reason for using multiple modules is so that changing
  9742. one source file does not require recompiling all of them in order
  9743. to try the modified program. Dividing a large program into many
  9744. substantial modules in this way typically makes recompilation much faster.
  9745. @cindex linking object files
  9746. After you compile all the program's modules, in order to run the
  9747. program you must @dfn{link} the object files into a combined
  9748. executable, like this:
  9749. @example
  9750. gcc -o foo foo.o bar.o
  9751. @end example
  9752. @noindent
  9753. In this command, @option{-o foo} species the file name for the
  9754. executable file, and the other arguments are the object files to link.
  9755. Always specify the executable file name in a command that generates
  9756. one.
  9757. Normally we don't run any of these commands directly. Instead we
  9758. write a set of @dfn{make rules} for the program, then use the
  9759. @command{make} program to recompile only the source files that need to
  9760. be recompiled.
  9761. @c ??? ref to make manual
  9762. @node Directing Compilation
  9763. @chapter Directing Compilation
  9764. This chapter describes C constructs that don't alter the program's
  9765. meaning @emph{as such}, but rather direct the compiler how to treat
  9766. some aspects of the program.
  9767. @menu
  9768. * Pragmas:: Controling compilation of some constructs.
  9769. * Static Assertions:: Compile-time tests for conditions.
  9770. @end menu
  9771. @node Pragmas
  9772. @section Pragmas
  9773. A @dfn{pragma} is an annotation in a program that gives direction to
  9774. the compiler.
  9775. @menu
  9776. * Pragma Basics:: Pragma syntax and usage.
  9777. * Severity Pragmas:: Settings for compile-time pragma output.
  9778. * Optimization Pragmas:: Controlling optimizations.
  9779. @end menu
  9780. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9781. @node Pragma Basics
  9782. @subsection Pragma Basics
  9783. C defines two syntactical forms for pragmas, the line form and the
  9784. token form. You can write any pragma in either form, with the same
  9785. meaning.
  9786. The line form is a line in the source code, like this:
  9787. @example
  9788. #pragma @var{line}
  9789. @end example
  9790. @noindent
  9791. The line pragma has no effect on the parsing of the lines around it.
  9792. This form has the drawback that it can't be generated by a macro expansion.
  9793. The token form is a series of tokens; it can appear anywhere in the
  9794. program between the other tokens.
  9795. @example
  9796. _Pragma (@var{stringconstant})
  9797. @end example
  9798. @noindent
  9799. The pragma has no effect on the syntax of the tokens that surround it;
  9800. thus, here's a pragma in the middle of an @code{if} statement:
  9801. @example
  9802. if _Pragma ("hello") (x > 1)
  9803. @end example
  9804. @noindent
  9805. However, that's an unclear thing to do; for the sake of
  9806. understandability, it is better to put a pragma on a line by itself
  9807. and not embedded in the middle of another construct.
  9808. Both forms of pragma have a textual argument. In a line pragma, the
  9809. text is the rest of the line. The textual argument to @code{_Pragma}
  9810. uses the same syntax as a C string constant: surround the text with
  9811. two @samp{"} characters, and add a backslash before each @samp{"} or
  9812. @samp{\} character in it.
  9813. With either syntax, the textual argument specifies what to do.
  9814. It begins with one or several words that specify the operation.
  9815. If the compiler does not recognize them, it ignores the pragma.
  9816. Here are the pragma operations supported in GNU C@.
  9817. @c ??? Verify font for []
  9818. @table @code
  9819. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9820. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9821. Declares that the current source file depends on @var{file}, so GNU C
  9822. compares the file times and gives a warning if @var{file} is newer
  9823. than the current source file.
  9824. This directive searches for @var{file} the way @code{#include}
  9825. searches for a non-system header file.
  9826. If @var{message} is given, the warning message includes that text.
  9827. Examples:
  9828. @example
  9829. #pragma GCC dependency "parse.y"
  9830. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9831. rerun fixincludes")
  9832. @end example
  9833. @item #pragma GCC poison @var{identifiers}
  9834. @itemx _Pragma ("GCC poison @var{identifiers}")
  9835. Poisons the identifiers listed in @var{identifiers}.
  9836. This is useful to make sure all mention of @var{identifiers} has been
  9837. deleted from the program and that no reference to them creeps back in.
  9838. If any of those identifiers appears anywhere in the source after the
  9839. directive, it causes a compilation error. For example,
  9840. @example
  9841. #pragma GCC poison printf sprintf fprintf
  9842. sprintf(some_string, "hello");
  9843. @end example
  9844. @noindent
  9845. generates an error.
  9846. If a poisoned identifier appears as part of the expansion of a macro
  9847. that was defined before the identifier was poisoned, it will @emph{not}
  9848. cause an error. Thus, system headers that define macros that use
  9849. the identifier will not cause errors.
  9850. For example,
  9851. @example
  9852. #define strrchr rindex
  9853. _Pragma ("GCC poison rindex")
  9854. strrchr(some_string, 'h');
  9855. @end example
  9856. @noindent
  9857. does not cause a compilation error.
  9858. @item #pragma GCC system_header
  9859. @itemx _Pragma ("GCC system_header")
  9860. Specify treating the rest of the current source file as if it came
  9861. from a system header file. @xref{System Headers, System Headers,
  9862. System Headers, gcc, Using the GNU Compiler Collection}.
  9863. @item #pragma GCC warning @var{message}
  9864. @itemx _Pragma ("GCC warning @var{message}")
  9865. Equivalent to @code{#warning}. Its advantage is that the
  9866. @code{_Pragma} form can be included in a macro definition.
  9867. @item #pragma GCC error @var{message}
  9868. @itemx _Pragma ("GCC error @var{message}")
  9869. Equivalent to @code{#error}. Its advantage is that the
  9870. @code{_Pragma} form can be included in a macro definition.
  9871. @item #pragma GCC message @var{message}
  9872. @itemx _Pragma ("GCC message @var{message}")
  9873. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9874. informational message, and could be used to include additional warning
  9875. or error text without triggering more warnings or errors. (Note that
  9876. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9877. @samp{GCC} as part of the pragma.)
  9878. @end table
  9879. @node Severity Pragmas
  9880. @subsection Severity Pragmas
  9881. These pragmas control the severity of classes of diagnostics.
  9882. You can specify the class of diagnostic with the GCC option that causes
  9883. those diagnostics to be generated.
  9884. @table @code
  9885. @item #pragma GCC diagnostic error @var{option}
  9886. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9887. For code following this pragma, treat diagnostics of the variety
  9888. specified by @var{option} as errors. For example:
  9889. @example
  9890. _Pragma ("GCC diagnostic error -Wformat")
  9891. @end example
  9892. @noindent
  9893. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9894. as errors rather than warnings.
  9895. @item #pragma GCC diagnostic warning @var{option}
  9896. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9897. For code following this pragma, treat diagnostics of the variety
  9898. specified by @var{option} as warnings. This overrides the
  9899. @var{-Werror} option which says to treat warnings as errors.
  9900. @item #pragma GCC diagnostic ignore @var{option}
  9901. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9902. For code following this pragma, refrain from reporting any diagnostics
  9903. of the variety specified by @var{option}.
  9904. @item #pragma GCC diagnostic push
  9905. @itemx _Pragma ("GCC diagnostic push")
  9906. @itemx #pragma GCC diagnostic pop
  9907. @itemx _Pragma ("GCC diagnostic pop")
  9908. These pragmas maintain a stack of states for severity settings.
  9909. @samp{GCC diagnostic push} saves the current settings on the stack,
  9910. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9911. the current settings from that.
  9912. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9913. restores the settings to what they were at the start of compilation.
  9914. Here is an example:
  9915. @example
  9916. _Pragma ("GCC diagnostic error -Wformat")
  9917. /* @r{@option{-Wformat} messages treated as errors. } */
  9918. _Pragma ("GCC diagnostic push")
  9919. _Pragma ("GCC diagnostic warning -Wformat")
  9920. /* @r{@option{-Wformat} messages treated as warnings. } */
  9921. _Pragma ("GCC diagnostic push")
  9922. _Pragma ("GCC diagnostic ignored -Wformat")
  9923. /* @r{@option{-Wformat} messages suppressed. } */
  9924. _Pragma ("GCC diagnostic pop")
  9925. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9926. _Pragma ("GCC diagnostic pop")
  9927. /* @r{@option{-Wformat} messages treated as errors again. } */
  9928. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9929. _Pragma ("GCC diagnostic pop")
  9930. /* @r{@option{-Wformat} messages treated once again}
  9931. @r{as specified by the GCC command-line options.} */
  9932. @end example
  9933. @end table
  9934. @node Optimization Pragmas
  9935. @subsection Optimization Pragmas
  9936. These pragmas enable a particular optimization for specific function
  9937. definitions. The settings take effect at the end of a function
  9938. definition, so the clean place to use these pragmas is between
  9939. function definitions.
  9940. @table @code
  9941. @item #pragma GCC optimize @var{optimization}
  9942. @itemx _Pragma ("GCC optimize @var{optimization}")
  9943. These pragmas enable the optimization @var{optimization} for the
  9944. following functions. For example,
  9945. @example
  9946. _Pragma ("GCC optimize -fforward-propagate")
  9947. @end example
  9948. @noindent
  9949. says to apply the @samp{forward-propagate} optimization to all
  9950. following function definitions. Specifying optimizations for
  9951. individual functions, rather than for the entire program, is rare but
  9952. can be useful for getting around a bug in the compiler.
  9953. If @var{optimization} does not correspond to a defined optimization
  9954. option, the pragma is erroneous. To turn off an optimization, use the
  9955. corresponding @samp{-fno-} option, such as
  9956. @samp{-fno-forward-propagate}.
  9957. @item #pragma GCC target @var{optimizations}
  9958. @itemx _Pragma ("GCC target @var{optimizations}")
  9959. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9960. used for platform-specific optimizations. Thus,
  9961. @example
  9962. _Pragma ("GCC target popcnt")
  9963. @end example
  9964. @noindent
  9965. activates the optimization @samp{popcnt} for all
  9966. following function definitions. This optimization is supported
  9967. on a few common targets but not on others.
  9968. @item #pragma GCC push_options
  9969. @itemx _Pragma ("GCC push_options")
  9970. The @samp{push_options} pragma saves on a stack the current settings
  9971. specified with the @samp{target} and @samp{optimize} pragmas.
  9972. @item #pragma GCC pop_options
  9973. @itemx _Pragma ("GCC pop_options")
  9974. The @samp{pop_options} pragma pops saved settings from that stack.
  9975. Here's an example of using this stack.
  9976. @example
  9977. _Pragma ("GCC push_options")
  9978. _Pragma ("GCC optimize forward-propagate")
  9979. /* @r{Functions to compile}
  9980. @r{with the @code{forward-propagate} optimization.} */
  9981. _Pragma ("GCC pop_options")
  9982. /* @r{Ends enablement of @code{forward-propagate}.} */
  9983. @end example
  9984. @item #pragma GCC reset_options
  9985. @itemx _Pragma ("GCC reset_options")
  9986. Clears all pragma-defined @samp{target} and @samp{optimize}
  9987. optimization settings.
  9988. @end table
  9989. @node Static Assertions
  9990. @section Static Assertions
  9991. @cindex static assertions
  9992. @findex _Static_assert
  9993. You can add compiler-time tests for necessary conditions into your
  9994. code using @code{_Static_assert}. This can be useful, for example, to
  9995. check that the compilation target platform supports the type sizes
  9996. that the code expects. For example,
  9997. @example
  9998. _Static_assert ((sizeof (long int) >= 8),
  9999. "long int needs to be at least 8 bytes");
  10000. @end example
  10001. @noindent
  10002. reports a compile-time error if compiled on a system with long
  10003. integers smaller than 8 bytes, with @samp{long int needs to be at
  10004. least 8 bytes} as the error message.
  10005. Since calls @code{_Static_assert} are processed at compile time, the
  10006. expression must be computable at compile time and the error message
  10007. must be a literal string. The expression can refer to the sizes of
  10008. variables, but can't refer to their values. For example, the
  10009. following static assertion is invalid for two reasons:
  10010. @example
  10011. char *error_message
  10012. = "long int needs to be at least 8 bytes";
  10013. int size_of_long_int = sizeof (long int);
  10014. _Static_assert (size_of_long_int == 8, error_message);
  10015. @end example
  10016. @noindent
  10017. The expression @code{size_of_long_int == 8} isn't computable at
  10018. compile time, and the error message isn't a literal string.
  10019. You can, though, use preprocessor definition values with
  10020. @code{_Static_assert}:
  10021. @example
  10022. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10023. at least 8 bytes"
  10024. _Static_assert ((sizeof (long int) == 8),
  10025. LONG_INT_ERROR_MESSAGE);
  10026. @end example
  10027. Static assertions are permitted wherever a statement or declaration is
  10028. permitted, including at top level in the file, and also inside the
  10029. definition of a type.
  10030. @example
  10031. union y
  10032. @{
  10033. int i;
  10034. int *ptr;
  10035. _Static_assert (sizeof (int *) == sizeof (int),
  10036. "Pointer and int not same size");
  10037. @};
  10038. @end example
  10039. @node Type Alignment
  10040. @appendix Type Alignment
  10041. @cindex type alignment
  10042. @cindex alignment of type
  10043. @findex _Alignof
  10044. @findex __alignof__
  10045. Code for device drivers and other communication with low-level
  10046. hardware sometimes needs to be concerned with the alignment of
  10047. data objects in memory.
  10048. Each data type has a required @dfn{alignment}, always a power of 2,
  10049. that says at which memory addresses an object of that type can validly
  10050. start. A valid address for the type must be a multiple of its
  10051. alignment. If a type's alignment is 1, that means it can validly
  10052. start at any address. If a type's alignment is 2, that means it can
  10053. only start at an even address. If a type's alignment is 4, that means
  10054. it can only start at an address that is a multiple of 4.
  10055. The alignment of a type (except @code{char}) can vary depending on the
  10056. kind of computer in use. To refer to the alignment of a type in a C
  10057. program, use @code{_Alignof}, whose syntax parallels that of
  10058. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10059. operation, and it doesn't compute the value of the expression used
  10060. as its argument.
  10061. Nominally, each integer and floating-point type has an alignment equal to
  10062. the largest power of 2 that divides its size. Thus, @code{int} with
  10063. size 4 has a nominal alignment of 4, and @code{long long int} with
  10064. size 8 has a nominal alignment of 8.
  10065. However, each kind of computer generally has a maximum alignment, and
  10066. no type needs more alignment than that. If the computer's maximum
  10067. alignment is 4 (which is common), then no type's alignment is more
  10068. than 4.
  10069. The size of any type is always a multiple of its alignment; that way,
  10070. in an array whose elements have that type, all the elements are
  10071. properly aligned if the first one is.
  10072. These rules apply to all real computers today, but some embedded
  10073. controllers have odd exceptions. We don't have references to cite for
  10074. them.
  10075. @c We can't cite a nonfree manual as documentation.
  10076. Ordinary C code guarantees that every object of a given type is in
  10077. fact aligned as that type requires.
  10078. If the operand of @code{_Alignof} is a structure field, the value
  10079. is the alignment it requires. It may have a greater alignment by
  10080. coincidence, due to the other fields, but @code{_Alignof} is not
  10081. concerned about that. @xref{Structures}.
  10082. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10083. but now that the feature has been standardized, it is better
  10084. to use the standard keyword @code{_Alignof}.
  10085. @findex _Alignas
  10086. @findex __aligned__
  10087. You can explicitly specify an alignment requirement for a particular
  10088. variable or structure field by adding @code{_Alignas
  10089. (@var{alignment})} to the declaration, where @var{alignment} is a
  10090. power of 2 or a type name. For instance:
  10091. @example
  10092. char _Alignas (8) x;
  10093. @end example
  10094. @noindent
  10095. or
  10096. @example
  10097. char _Alignas (double) x;
  10098. @end example
  10099. @noindent
  10100. specifies that @code{x} must start on an address that is a multiple of
  10101. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10102. machine, that maximum is how much alignment @code{x} will get.
  10103. The older GNU C syntax for this feature looked like
  10104. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10105. declaration, and was added after the variable. For instance:
  10106. @example
  10107. char x __attribute__ ((__aligned__ 8));
  10108. @end example
  10109. @xref{Attributes}.
  10110. @node Aliasing
  10111. @appendix Aliasing
  10112. @cindex aliasing (of storage)
  10113. @cindex pointer type conversion
  10114. @cindex type conversion, pointer
  10115. We have already presented examples of casting a @code{void *} pointer
  10116. to another pointer type, and casting another pointer type to
  10117. @code{void *}.
  10118. One common kind of pointer cast is guaranteed safe: casting the value
  10119. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10120. Allocation}). It is safe because these functions do not save the
  10121. pointer anywhere else; the only way the program will access the newly
  10122. allocated memory is via the pointer just returned.
  10123. In fact, C allows casting any pointer type to any other pointer type.
  10124. Using this to access the same place in memory using two
  10125. different data types is called @dfn{aliasing}.
  10126. Aliasing is necessary in some programs that do sophisticated memory
  10127. management, such as GNU Emacs, but most C programs don't need to do
  10128. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10129. aliasing correctly requires following the rules stated below.
  10130. Otherwise, the aliasing may result in malfunctions when the program
  10131. runs.
  10132. The rest of this appendix explains the pitfalls and rules of aliasing.
  10133. @menu
  10134. * Aliasing Alignment:: Memory alignment considerations for
  10135. casting between pointer types.
  10136. * Aliasing Length:: Type size considerations for
  10137. casting between pointer types.
  10138. * Aliasing Type Rules:: Even when type alignment and size matches,
  10139. aliasing can still have surprising results.
  10140. @end menu
  10141. @node Aliasing Alignment
  10142. @appendixsection Aliasing and Alignment
  10143. In order for a type-converted pointer to be valid, it must have the
  10144. alignment that the new pointer type requires. For instance, on most
  10145. computers, @code{int} has alignment 4; the address of an @code{int}
  10146. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10147. address of a @code{char} is usually not a multiple of 4. Taking the
  10148. address of such a @code{char} and casting it to @code{int *} probably
  10149. results in an invalid pointer. Trying to dereference it may cause a
  10150. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10151. @example
  10152. foo ()
  10153. @{
  10154. char i[4];
  10155. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10156. return *p; /* @r{Crash!} */
  10157. @}
  10158. @end example
  10159. This requirement is never a problem when casting the return value
  10160. of @code{malloc} because that function always returns a pointer
  10161. with as much alignment as any type can require.
  10162. @node Aliasing Length
  10163. @appendixsection Aliasing and Length
  10164. When converting a pointer to a different pointer type, make sure the
  10165. object it really points to is at least as long as the target of the
  10166. converted pointer. For instance, suppose @code{p} has type @code{int
  10167. *} and it's cast as follows:
  10168. @example
  10169. int *p;
  10170. struct
  10171. @{
  10172. double d, e, f;
  10173. @} foo;
  10174. struct foo *q = (struct foo *)p;
  10175. q->f = 5.14159;
  10176. @end example
  10177. @noindent
  10178. the value @code{q->f} will run past the end of the @code{int} that
  10179. @code{p} points to. If @code{p} was initialized to the start of an
  10180. array of type @code{int[6]}, the object is long enough for three
  10181. @code{double}s. But if @code{p} points to something shorter,
  10182. @code{q->f} will run on beyond the end of that, overlaying some other
  10183. data. Storing that will garble that other data. Or it could extend
  10184. past the end of memory space and cause a @code{SIGSEGV} signal
  10185. (@pxref{Signals}).
  10186. @node Aliasing Type Rules
  10187. @appendixsection Type Rules for Aliasing
  10188. C code that converts a pointer to a different pointer type can use the
  10189. pointers to access the same memory locations with two different data
  10190. types. If the same address is accessed with different types in a
  10191. single control thread, optimization can make the code do surprising
  10192. things (in effect, make it malfunction).
  10193. Here's a concrete example where aliasing that can change the code's
  10194. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10195. long, like @code{int}, and so is every pointer. Thus, the structures
  10196. @code{struct a} and @code{struct b} are both 8 bytes.
  10197. @example
  10198. #include <stdio.h>
  10199. struct a @{ int size; char *data; @};
  10200. struct b @{ float size; char *data; @};
  10201. void sub (struct a *p, struct b *q)
  10202. @{
  10203.   int x;
  10204.   p->size = 0;
  10205.   q->size = 1;
  10206.   x = p->size;
  10207.   printf("x       =%d\n", x);
  10208.   printf("p->size =%d\n", (int)p->size);
  10209.   printf("q->size =%d\n", (int)q->size);
  10210. @}
  10211. int main(void)
  10212. @{
  10213.   struct a foo;
  10214.   struct a *p = &foo;
  10215.   struct b *q = (struct b *) &foo;
  10216.   sub (p, q);
  10217. @}
  10218. @end example
  10219. This code works as intended when compiled without optimization. All
  10220. the operations are carried out sequentially as written. The code
  10221. sets @code{x} to @code{p->size}, but what it actually gets is the
  10222. bits of the floating point number 1, as type @code{int}.
  10223. However, when optimizing, the compiler is allowed to assume
  10224. (mistakenly, here) that @code{q} does not point to the same storage as
  10225. @code{p}, because their data types are not allowed to alias.
  10226. From this assumption, the compiler can deduce (falsely, here) that the
  10227. assignment into @code{q->size} has no effect on the value of
  10228. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10229. be set to 0.
  10230. GNU C, following the C standard, @emph{defines} this optimization as
  10231. legitimate. Code that misbehaves when optimized following these rules
  10232. is, by definition, incorrect C code.
  10233. The rules for storage aliasing in C are based on the two data types:
  10234. the type of the object, and the type it is accessed through. The
  10235. rules permit accessing part of a storage object of type @var{t} using
  10236. only these types:
  10237. @itemize @bullet
  10238. @item
  10239. @var{t}.
  10240. @item
  10241. A type compatible with @var{t}. @xref{Compatible Types}.
  10242. @item
  10243. A signed or unsigned version of one of the above.
  10244. @item
  10245. A qualifed version of one of the above.
  10246. @xref{Type Qualifiers}.
  10247. @item
  10248. An array, structure (@pxref{Structures}), or union type
  10249. (@code{Unions}) that contains one of the above, either directly as a
  10250. field or through multiple levels of fields. If @var{t} is
  10251. @code{double}, this would include @code{struct s @{ union @{ double
  10252. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10253. inside it somewhere.
  10254. @item
  10255. A character type.
  10256. @end itemize
  10257. What do these rules say about the example in this subsection?
  10258. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10259. @code{int}. The type @code{float} is not allowed as an aliasing type
  10260. by those rules, so @code{b->size} is not supposed to alias with
  10261. elements of @code{j}. Based on that assumption, GNU C makes a
  10262. permitted optimization that was not, in this case, consistent with
  10263. what the programmer intended the program to do.
  10264. Whether GCC actually performs type-based aliasing analysis depends on
  10265. the details of the code. GCC has other ways to determine (in some cases)
  10266. whether objects alias, and if it gets a reliable answer that way, it won't
  10267. fall back on type-based heuristics.
  10268. @c @opindex -fno-strict-aliasing
  10269. The importance of knowing the type-based aliasing rules is not so as
  10270. to ensure that the optimization is done where it would be safe, but so
  10271. as to ensure it is @emph{not} done in a way that would break the
  10272. program. You can turn off type-based aliasing analysis by giving GCC
  10273. the option @option{-fno-strict-aliasing}.
  10274. @node Digraphs
  10275. @appendix Digraphs
  10276. @cindex digraphs
  10277. C accepts aliases for certain characters. Apparently in the 1990s
  10278. some computer systems had trouble inputting these characters, or
  10279. trouble displaying them. These digraphs almost never appear in C
  10280. programs nowadays, but we mention them for completeness.
  10281. @table @samp
  10282. @item <:
  10283. An alias for @samp{[}.
  10284. @item :>
  10285. An alias for @samp{]}.
  10286. @item <%
  10287. An alias for @samp{@{}.
  10288. @item %>
  10289. An alias for @samp{@}}.
  10290. @item %:
  10291. An alias for @samp{#},
  10292. used for preprocessing directives (@pxref{Directives}) and
  10293. macros (@pxref{Macros}).
  10294. @end table
  10295. @node Attributes
  10296. @appendix Attributes in Declarations
  10297. @cindex attributes
  10298. @findex __attribute__
  10299. You can specify certain additional requirements in a declaration, to
  10300. get fine-grained control over code generation, and helpful
  10301. informational messages during compilation. We use a few attributes in
  10302. code examples throughout this manual, including
  10303. @table @code
  10304. @item aligned
  10305. The @code{aligned} attribute specifies a minimum alignment for a
  10306. variable or structure field, measured in bytes:
  10307. @example
  10308. int foo __attribute__ ((aligned (8))) = 0;
  10309. @end example
  10310. @noindent
  10311. This directs GNU C to allocate @code{foo} at an address that is a
  10312. multiple of 8 bytes. However, you can't force an alignment bigger
  10313. than the computer's maximum meaningful alignment.
  10314. @item packed
  10315. The @code{packed} attribute specifies to compact the fields of a
  10316. structure by not leaving gaps between fields. For example,
  10317. @example
  10318. struct __attribute__ ((packed)) bar
  10319. @{
  10320. char a;
  10321. int b;
  10322. @};
  10323. @end example
  10324. @noindent
  10325. allocates the integer field @code{b} at byte 1 in the structure,
  10326. immediately after the character field @code{a}. The packed structure
  10327. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10328. alignment is 1, that of @code{char}.
  10329. @item deprecated
  10330. Applicable to both variables and functions, the @code{deprecated}
  10331. attribute tells the compiler to issue a warning if the variable or
  10332. function is ever used in the source file.
  10333. @example
  10334. int old_foo __attribute__ ((deprecated));
  10335. int old_quux () __attribute__ ((deprecated));
  10336. @end example
  10337. @item __noinline__
  10338. The @code{__noinline__} attribute, in a function's declaration or
  10339. definition, specifies never to inline calls to that function. All
  10340. calls to that function, in a compilation unit where it has this
  10341. attribute, will be compiled to invoke the separately compiled
  10342. function. @xref{Inline Function Definitions}.
  10343. @item __noclone__
  10344. The @code{__noclone__} attribute, in a function's declaration or
  10345. definition, specifies never to clone that function. Thus, there will
  10346. be only one compiled version of the function. @xref{Label Value
  10347. Caveats}, for more information about cloning.
  10348. @item always_inline
  10349. The @code{always_inline} attribute, in a function's declaration or
  10350. definition, specifies to inline all calls to that function (unless
  10351. something about the function makes inlining impossible). This applies
  10352. to all calls to that function in a compilation unit where it has this
  10353. attribute. @xref{Inline Function Definitions}.
  10354. @item gnu_inline
  10355. The @code{gnu_inline} attribute, in a function's declaration or
  10356. definition, specifies to handle the @code{inline} keywprd the way GNU
  10357. C originally implemented it, many years before ISO C said anything
  10358. about inlining. @xref{Inline Function Definitions}.
  10359. @end table
  10360. For full documentation of attributes, see the GCC manual.
  10361. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10362. the GNU Compiler Collection}.
  10363. @node Signals
  10364. @appendix Signals
  10365. @cindex signal
  10366. @cindex handler (for signal)
  10367. @cindex @code{SIGSEGV}
  10368. @cindex @code{SIGFPE}
  10369. @cindex @code{SIGBUS}
  10370. Some program operations bring about an error condition called a
  10371. @dfn{signal}. These signals terminate the program, by default.
  10372. There are various different kinds of signals, each with a name. We
  10373. have seen several such error conditions through this manual:
  10374. @table @code
  10375. @item SIGSEGV
  10376. This signal is generated when a program tries to read or write outside
  10377. the memory that is allocated for it, or to write memory that can only
  10378. be read. The name is an abbreviation for ``segmentation violation''.
  10379. @item SIGFPE
  10380. This signal indicates a fatal arithmetic error. The name is an
  10381. abbreviation for ``floating-point exception'', but covers all types of
  10382. arithmetic errors, including division by zero and overflow.
  10383. @item SIGBUS
  10384. This signal is generated when an invalid pointer is dereferenced,
  10385. typically the result of dereferencing an uninintalized pointer. It is
  10386. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10387. invalid access to valid memory, while @code{SIGBUS} indicates an
  10388. attempt to access an invalid address.
  10389. @end table
  10390. These kinds of signal allow the program to specify a function as a
  10391. @dfn{signal handler}. When a signal has a handler, it doesn't
  10392. terminate the program; instead it calls the handler.
  10393. There are many other kinds of signal; here we list only those that
  10394. come from run-time errors in C operations. The rest have to do with
  10395. the functioning of the operating system. The GNU C Library Reference
  10396. Manual gives more explanation about signals (@pxref{Program Signal
  10397. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10398. Manual}).
  10399. @node GNU Free Documentation License
  10400. @appendix GNU Free Documentation License
  10401. @include fdl.texi
  10402. @node Symbol Index
  10403. @unnumbered Index of Symbols and Keywords
  10404. @printindex fn
  10405. @node Concept Index
  10406. @unnumbered Concept Index
  10407. @printindex cp
  10408. @bye