c.texi 423 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089
  1. \input texinfo
  2. @c Copyright (C) 2022 Richard Stallman and Free Software Foundation, Inc.
  3. @c (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. @c licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @c Merge variable index into the function index.
  10. @synindex vr fn
  11. @copying
  12. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  13. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  14. licensed to the FSF.)
  15. @quotation
  16. Permission is granted to copy, distribute and/or modify this document
  17. under the terms of the GNU Free Documentation License, Version 1.3 or
  18. any later version published by the Free Software Foundation; with the
  19. Invariant Sections being ``GNU General Public License,'' with the
  20. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  21. Texts as in (a) below. A copy of the license is included in the
  22. section entitled ``GNU Free Documentation License.''
  23. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  24. modify this GNU manual.''
  25. @end quotation
  26. @end copying
  27. @dircategory Programming
  28. @direntry
  29. * C: (c). GNU C Language Intro and Reference Manual
  30. @end direntry
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Introduction}
  34. @center @titlefont{and Reference Manual}
  35. @sp 4
  36. @c @center @value{EDITION} Edition
  37. @sp 5
  38. @center Richard Stallman
  39. @center and
  40. @center Trevis Rothwell
  41. @center plus Nelson Beebe
  42. @center on floating point
  43. @page
  44. @vskip 0pt plus 1filll
  45. @insertcopying
  46. @sp 2
  47. @ignore
  48. WILL BE Published by the Free Software Foundation @*
  49. 51 Franklin Street, Fifth Floor @*
  50. Boston, MA 02110-1301 USA @*
  51. ISBN ?-??????-??-?
  52. @end ignore
  53. @ignore
  54. @sp 1
  55. Cover art by J. Random Artist
  56. @end ignore
  57. @end titlepage
  58. @summarycontents
  59. @contents
  60. @node Top
  61. @ifnottex
  62. @top GNU C Manual
  63. @end ifnottex
  64. @iftex
  65. @top Preface
  66. @end iftex
  67. This manual explains the C language for use with the GNU Compiler
  68. Collection (GCC) on the GNU/Linux system and other systems. We refer
  69. to this dialect as GNU C. If you already know C, you can use this as
  70. a reference manual.
  71. If you understand basic concepts of programming but know nothing about
  72. C, you can read this manual sequentially from the beginning to learn
  73. the C language.
  74. If you are a beginner in programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are provided by
  112. functions defined in the standard library, which is automatically
  113. available in every C program. @xref{Top, The GNU C Library, , libc,
  114. The GNU C Library Reference Manual}.
  115. GNU/Linux systems use the GNU C Library to do this job. It is itself
  116. a C program, so once you know C you can read its source code and see
  117. how its library functions do their jobs. Some fraction of the
  118. functions are implemented as @dfn{system calls}, which means they
  119. contain a special instruction that asks the system kernel (Linux) to
  120. do a specific task. To understand how those are implemented, you'd
  121. need to read Linux source code instead. Whether a library function is
  122. a system call is an internal implementation detail that makes no
  123. difference for how to call the function.
  124. This manual incorporates the former GNU C Preprocessor Manual, which
  125. was among the earliest GNU manuals. It also uses some text from the
  126. earlier GNU C Manual that was written by Trevis Rothwell and James
  127. Youngman.
  128. GNU C has many obscure features, each one either for historical
  129. compatibility or meant for very special situations. We have left them
  130. to a companion manual, the GNU C Obscurities Manual, which will be
  131. published digitally later.
  132. Please report errors and suggestions to c-manual@@gnu.org.
  133. @menu
  134. * The First Example:: Getting started with basic C code.
  135. * Complete Program:: A whole example program
  136. that can be compiled and run.
  137. * Storage:: Basic layout of storage; bytes.
  138. * Beyond Integers:: Exploring different numeric types.
  139. * Lexical Syntax:: The various lexical components of C programs.
  140. * Arithmetic:: Numeric computations.
  141. * Assignment Expressions:: Storing values in variables.
  142. * Execution Control Expressions:: Expressions combining values in various ways.
  143. * Binary Operator Grammar:: An overview of operator precedence.
  144. * Order of Execution:: The order of program execution.
  145. * Primitive Types:: More details about primitive data types.
  146. * Constants:: Explicit constant values:
  147. details and examples.
  148. * Type Size:: The memory space occupied by a type.
  149. * Pointers:: Creating and manipulating memory pointers.
  150. * Structures:: Compound data types built
  151. by grouping other types.
  152. * Arrays:: Creating and manipulating arrays.
  153. * Enumeration Types:: Sets of integers with named values.
  154. * Defining Typedef Names:: Using @code{typedef} to define type names.
  155. * Statements:: Controlling program flow.
  156. * Variables:: Details about declaring, initializing,
  157. and using variables.
  158. * Type Qualifiers:: Mark variables for certain intended uses.
  159. * Functions:: Declaring, defining, and calling functions.
  160. * Compatible Types:: How to tell if two types are compatible
  161. with each other.
  162. * Type Conversions:: Converting between types.
  163. * Scope:: Different categories of identifier scope.
  164. * Preprocessing:: Using the GNU C preprocessor.
  165. * Integers in Depth:: How integer numbers are represented.
  166. * Floating Point in Depth:: How floating-point numbers are represented.
  167. * Compilation:: How to compile multi-file programs.
  168. * Directing Compilation:: Operations that affect compilation
  169. but don't change the program.
  170. Appendices
  171. * Type Alignment:: Where in memory a type can validly start.
  172. * Aliasing:: Accessing the same data in two types.
  173. * Digraphs:: Two-character aliases for some characters.
  174. * Attributes:: Specifying additional information
  175. in a declaration.
  176. * Signals:: Fatal errors triggered in various scenarios.
  177. * GNU Free Documentation License:: The license for this manual.
  178. * Symbol Index:: Keyword and symbol index.
  179. * Concept Index:: Detailed topical index.
  180. @detailmenu
  181. --- The Detailed Node Listing ---
  182. * Recursive Fibonacci:: Writing a simple function recursively.
  183. * Stack:: Each function call uses space in the stack.
  184. * Iterative Fibonacci:: Writing the same function iteratively.
  185. * Complete Example:: Turn the simple function into a full program.
  186. * Complete Explanation:: Explanation of each part of the example.
  187. * Complete Line-by-Line:: Explaining each line of the example.
  188. * Compile Example:: Using GCC to compile the example.
  189. * Float Example:: A function that uses floating-point numbers.
  190. * Array Example:: A function that works with arrays.
  191. * Array Example Call:: How to call that function.
  192. * Array Example Variations:: Different ways to write the call example.
  193. Lexical Syntax
  194. * English:: Write programs in English!
  195. * Characters:: The characters allowed in C programs.
  196. * Whitespace:: The particulars of whitespace characters.
  197. * Comments:: How to include comments in C code.
  198. * Identifiers:: How to form identifiers (names).
  199. * Operators/Punctuation:: Characters used as operators or punctuation.
  200. * Line Continuation:: Splitting one line into multiple lines.
  201. * Digraphs:: Two-character substitutes for some characters.
  202. Arithmetic
  203. * Basic Arithmetic:: Addition, subtraction, multiplication,
  204. and division.
  205. * Integer Arithmetic:: How C performs arithmetic with integer values.
  206. * Integer Overflow:: When an integer value exceeds the range
  207. of its type.
  208. * Mixed Mode:: Calculating with both integer values
  209. and floating-point values.
  210. * Division and Remainder:: How integer division works.
  211. * Numeric Comparisons:: Comparing numeric values for
  212. equality or order.
  213. * Shift Operations:: Shift integer bits left or right.
  214. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  215. Assignment Expressions
  216. * Simple Assignment:: The basics of storing a value.
  217. * Lvalues:: Expressions into which a value can be stored.
  218. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  219. * Increment/Decrement:: Shorthand for incrementing and decrementing
  220. an lvalue's contents.
  221. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  222. * Assignment in Subexpressions:: How to avoid ambiguity.
  223. * Write Assignments Separately:: Write assignments as separate statements.
  224. Execution Control Expressions
  225. * Logical Operators:: Logical conjunction, disjunction, negation.
  226. * Logicals and Comparison:: Logical operators with comparison operators.
  227. * Logicals and Assignments:: Assignments with logical operators.
  228. * Conditional Expression:: An if/else construct inside expressions.
  229. * Comma Operator:: Build a sequence of subexpressions.
  230. Order of Execution
  231. * Reordering of Operands:: Operations in C are not necessarily computed
  232. in the order they are written.
  233. * Associativity and Ordering:: Some associative operations are performed
  234. in a particular order; others are not.
  235. * Sequence Points:: Some guarantees about the order of operations.
  236. * Postincrement and Ordering:: Ambiguous execution order with postincrement.
  237. * Ordering of Operands:: Evaluation order of operands
  238. and function arguments.
  239. * Optimization and Ordering:: Compiler optimizations can reorder operations
  240. only if it has no impact on program results.
  241. Primitive Data Types
  242. * Integer Types:: Description of integer types.
  243. * Floating-Point Data Types:: Description of floating-point types.
  244. * Complex Data Types:: Description of complex number types.
  245. * The Void Type:: A type indicating no value at all.
  246. * Other Data Types:: A brief summary of other types.
  247. Constants
  248. * Integer Constants:: Literal integer values.
  249. * Integer Const Type:: Types of literal integer values.
  250. * Floating Constants:: Literal floating-point values.
  251. * Imaginary Constants:: Literal imaginary number values.
  252. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  253. * Character Constants:: Literal character values.
  254. * Unicode Character Codes:: Unicode characters represented
  255. in either UTF-16 or UTF-32.
  256. * Wide Character Constants:: Literal characters values larger than 8 bits.
  257. * String Constants:: Literal string values.
  258. * UTF-8 String Constants:: Literal UTF-8 string values.
  259. * Wide String Constants:: Literal string values made up of
  260. 16- or 32-bit characters.
  261. Pointers
  262. * Address of Data:: Using the ``address-of'' operator.
  263. * Pointer Types:: For each type, there is a pointer type.
  264. * Pointer Declarations:: Declaring variables with pointer types.
  265. * Pointer Type Designators:: Designators for pointer types.
  266. * Pointer Dereference:: Accessing what a pointer points at.
  267. * Null Pointers:: Pointers which do not point to any object.
  268. * Invalid Dereference:: Dereferencing null or invalid pointers.
  269. * Void Pointers:: Totally generic pointers, can cast to any.
  270. * Pointer Comparison:: Comparing memory address values.
  271. * Pointer Arithmetic:: Computing memory address values.
  272. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  273. * Low-Level Pointer Arithmetic:: More about computing memory address values.
  274. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  275. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  276. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  277. * Printing Pointers:: Using @code{printf} for a pointer's value.
  278. Structures
  279. * Referencing Fields:: Accessing field values in a structure object.
  280. * Dynamic Memory Allocation:: Allocating space for objects
  281. while the program is running.
  282. * Field Offset:: Memory layout of fields within a structure.
  283. * Structure Layout:: Planning the memory layout of fields.
  284. * Packed Structures:: Packing structure fields as close as possible.
  285. * Bit Fields:: Dividing integer fields
  286. into fields with fewer bits.
  287. * Bit Field Packing:: How bit fields pack together in integers.
  288. * const Fields:: Making structure fields immutable.
  289. * Zero Length:: Zero-length array as a variable-length object.
  290. * Flexible Array Fields:: Another approach to variable-length objects.
  291. * Overlaying Structures:: Casting one structure type
  292. over an object of another structure type.
  293. * Structure Assignment:: Assigning values to structure objects.
  294. * Unions:: Viewing the same object in different types.
  295. * Packing With Unions:: Using a union type to pack various types into
  296. the same memory space.
  297. * Cast to Union:: Casting a value one of the union's alternative
  298. types to the type of the union itself.
  299. * Structure Constructors:: Building new structure objects.
  300. * Unnamed Types as Fields:: Fields' types do not always need names.
  301. * Incomplete Types:: Types which have not been fully defined.
  302. * Intertwined Incomplete Types:: Defining mutually-recursive structure types.
  303. * Type Tags:: Scope of structure and union type tags.
  304. Arrays
  305. * Accessing Array Elements:: How to access individual elements of an array.
  306. * Declaring an Array:: How to name and reserve space for a new array.
  307. * Strings:: A string in C is a special case of array.
  308. * Incomplete Array Types:: Naming, but not allocating, a new array.
  309. * Limitations of C Arrays:: Arrays are not first-class objects.
  310. * Multidimensional Arrays:: Arrays of arrays.
  311. * Constructing Array Values:: Assigning values to an entire array at once.
  312. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  313. Statements
  314. * Expression Statement:: Evaluate an expression, as a statement,
  315. usually done for a side effect.
  316. * if Statement:: Basic conditional execution.
  317. * if-else Statement:: Multiple branches for conditional execution.
  318. * Blocks:: Grouping multiple statements together.
  319. * return Statement:: Return a value from a function.
  320. * Loop Statements:: Repeatedly executing a statement or block.
  321. * switch Statement:: Multi-way conditional choices.
  322. * switch Example:: A plausible example of using @code{switch}.
  323. * Duffs Device:: A special way to use @code{switch}.
  324. * Case Ranges:: Ranges of values for @code{switch} cases.
  325. * Null Statement:: A statement that does nothing.
  326. * goto Statement:: Jump to another point in the source code,
  327. identified by a label.
  328. * Local Labels:: Labels with limited scope.
  329. * Labels as Values:: Getting the address of a label.
  330. * Statement Exprs:: A series of statements used as an expression.
  331. Variables
  332. * Variable Declarations:: Name a variable and and reserve space for it.
  333. * Initializers:: Assigning initial values to variables.
  334. * Designated Inits:: Assigning initial values to array elements
  335. at particular array indices.
  336. * Auto Type:: Obtaining the type of a variable.
  337. * Local Variables:: Variables declared in function definitions.
  338. * File-Scope Variables:: Variables declared outside of
  339. function definitions.
  340. * Static Local Variables:: Variables declared within functions,
  341. but with permanent storage allocation.
  342. * Extern Declarations:: Declaring a variable
  343. which is allocated somewhere else.
  344. * Allocating File-Scope:: When is space allocated
  345. for file-scope variables?
  346. * auto and register:: Historically used storage directions.
  347. * Omitting Types:: The bad practice of declaring variables
  348. with implicit type.
  349. Type Qualifiers
  350. * const:: Variables whose values don't change.
  351. * volatile:: Variables whose values may be accessed
  352. or changed outside of the control of
  353. this program.
  354. * restrict Pointers:: Restricted pointers for code optimization.
  355. * restrict Pointer Example:: Example of how that works.
  356. Functions
  357. * Function Definitions:: Writing the body of a function.
  358. * Function Declarations:: Declaring the interface of a function.
  359. * Function Calls:: Using functions.
  360. * Function Call Semantics:: Call-by-value argument passing.
  361. * Function Pointers:: Using references to functions.
  362. * The main Function:: Where execution of a GNU C program begins.
  363. Type Conversions
  364. * Explicit Type Conversion:: Casting a value from one type to another.
  365. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  366. * Argument Promotions:: Automatic conversion of function parameters.
  367. * Operand Promotions:: Automatic conversion of arithmetic operands.
  368. * Common Type:: When operand types differ, which one is used?
  369. Scope
  370. * Scope:: Different categories of identifier scope.
  371. Preprocessing
  372. * Preproc Overview:: Introduction to the C preprocessor.
  373. * Directives:: The form of preprocessor directives.
  374. * Preprocessing Tokens:: The lexical elements of preprocessing.
  375. * Header Files:: Including one source file in another.
  376. * Macros:: Macro expansion by the preprocessor.
  377. * Conditionals:: Controlling whether to compile some lines
  378. or ignore them.
  379. * Diagnostics:: Reporting warnings and errors.
  380. * Line Control:: Reporting source line numbers.
  381. * Null Directive:: A preprocessing no-op.
  382. Integers in Depth
  383. * Integer Representations:: How integer values appear in memory.
  384. * Maximum and Minimum Values:: Value ranges of integer types.
  385. Floating Point in Depth
  386. * Floating Representations:: How floating-point values appear in memory.
  387. * Floating Type Specs:: Precise details of memory representations.
  388. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  389. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  390. * Exception Flags:: Handling certain conditions in floating point.
  391. * Exact Floating-Point:: Not all floating calculations lose precision.
  392. * Rounding:: When a floating result can't be represented
  393. exactly in the floating-point type in use.
  394. * Rounding Issues:: Avoid magnifying rounding errors.
  395. * Significance Loss:: Subtracting numbers that are almost equal.
  396. * Fused Multiply-Add:: Taking advantage of a special floating-point
  397. instruction for faster execution.
  398. * Error Recovery:: Determining rounding errors.
  399. * Exact Floating Constants:: Precisely specified floating-point numbers.
  400. * Handling Infinity:: When floating calculation is out of range.
  401. * Handling NaN:: What floating calculation is undefined.
  402. * Signed Zeros:: Positive zero vs. negative zero.
  403. * Scaling by the Base:: A useful exact floating-point operation.
  404. * Rounding Control:: Specifying some rounding behaviors.
  405. * Machine Epsilon:: The smallest number you can add to 1.0
  406. and get a sum which is larger than 1.0.
  407. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  408. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  409. * Further Reading:: References for floating-point numbers.
  410. Directing Compilation
  411. * Pragmas:: Controlling compilation of some constructs.
  412. * Static Assertions:: Compile-time tests for conditions.
  413. @end detailmenu
  414. @end menu
  415. @node The First Example
  416. @chapter The First Example
  417. This chapter presents the source code for a very simple C program and
  418. uses it to explain a few features of the language. If you already
  419. know the basic points of C presented in this chapter, you can skim it
  420. or skip it.
  421. We present examples of C source code (other than comments) using a
  422. fixed-width typeface, since that's the way they look when you edit
  423. them in an editor such as GNU Emacs.
  424. @menu
  425. * Recursive Fibonacci:: Writing a simple function recursively.
  426. * Stack:: Each function call uses space in the stack.
  427. * Iterative Fibonacci:: Writing the same function iteratively.
  428. @end menu
  429. @node Recursive Fibonacci
  430. @section Example: Recursive Fibonacci
  431. @cindex recursive Fibonacci function
  432. @cindex Fibonacci function, recursive
  433. To introduce the most basic features of C, let's look at code for a
  434. simple mathematical function that does calculations on integers. This
  435. function calculates the @var{n}th number in the Fibonacci series, in
  436. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  437. 13, 21, 34, 55, @dots{}.
  438. @example
  439. int
  440. fib (int n)
  441. @{
  442. if (n <= 2) /* @r{This avoids infinite recursion.} */
  443. return 1;
  444. else
  445. return fib (n - 1) + fib (n - 2);
  446. @}
  447. @end example
  448. This very simple program illustrates several features of C:
  449. @itemize @bullet
  450. @item
  451. A function definition, whose first two lines constitute the function
  452. header. @xref{Function Definitions}.
  453. @item
  454. A function parameter @code{n}, referred to as the variable @code{n}
  455. inside the function body. @xref{Function Parameter Variables}.
  456. A function definition uses parameters to refer to the argument
  457. values provided in a call to that function.
  458. @item
  459. Arithmetic. C programs add with @samp{+} and subtract with
  460. @samp{-}. @xref{Arithmetic}.
  461. @item
  462. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  463. equal.'' @xref{Numeric Comparisons}.
  464. @item
  465. Integer constants written in base 10.
  466. @xref{Integer Constants}.
  467. @item
  468. A function call. The function call @code{fib (n - 1)} calls the
  469. function @code{fib}, passing as its argument the value @code{n - 1}.
  470. @xref{Function Calls}.
  471. @item
  472. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  473. comment has no effect on the execution of the program. Its purpose is
  474. to provide explanations to people reading the source code. Including
  475. comments in the code is tremendously important---they provide
  476. background information so others can understand the code more quickly.
  477. @xref{Comments}.
  478. In this manual, we present comment text in the variable-width typeface
  479. used for the text of the chapters, not in the fixed-width typeface
  480. used for the rest of the code. That is to make comments easier to
  481. read. This distinction of typeface does not exist in a real file of C
  482. source code.
  483. @item
  484. Two kinds of statements, the @code{return} statement and the
  485. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  486. @item
  487. Recursion. The function @code{fib} calls itself; that is called a
  488. @dfn{recursive call}. These are valid in C, and quite common.
  489. The @code{fib} function would not be useful if it didn't return.
  490. Thus, recursive definitions, to be of any use, must avoid
  491. @dfn{infinite recursion}.
  492. This function definition prevents infinite recursion by specially
  493. handling the case where @code{n} is two or less. Thus the maximum
  494. depth of recursive calls is less than @code{n}.
  495. @end itemize
  496. @menu
  497. * Function Header:: The function's name and how it is called.
  498. * Function Body:: Declarations and statements that implement the function.
  499. @end menu
  500. @node Function Header
  501. @subsection Function Header
  502. @cindex function header
  503. In our example, the first two lines of the function definition are the
  504. @dfn{header}. Its purpose is to state the function's name and say how
  505. it is called:
  506. @example
  507. int
  508. fib (int n)
  509. @end example
  510. @noindent
  511. says that the function returns an integer (type @code{int}), its name is
  512. @code{fib}, and it takes one argument named @code{n} which is also an
  513. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  514. @node Function Body
  515. @subsection Function Body
  516. @cindex function body
  517. @cindex recursion
  518. The rest of the function definition is called the @dfn{function body}.
  519. Like every function body, this one starts with @samp{@{}, ends with
  520. @samp{@}}, and contains zero or more @dfn{statements} and
  521. @dfn{declarations}. Statements specify actions to take, whereas
  522. declarations define names of variables, functions, and so on. Each
  523. statement and each declaration ends with a semicolon (@samp{;}).
  524. Statements and declarations often contain @dfn{expressions}; an
  525. expression is a construct whose execution produces a @dfn{value} of
  526. some data type, but may also take actions through ``side effects''
  527. that alter subsequent execution. A statement, by contrast, does not
  528. have a value; it affects further execution of the program only through
  529. the actions it takes.
  530. This function body contains no declarations, and just one statement,
  531. but that one is a complex statement in that it contains nested
  532. statements. This function uses two kinds of statements:
  533. @table @code
  534. @item return
  535. The @code{return} statement makes the function return immediately.
  536. It looks like this:
  537. @example
  538. return @var{value};
  539. @end example
  540. Its meaning is to compute the expression @var{value} and exit the
  541. function, making it return whatever value that expression produced.
  542. For instance,
  543. @example
  544. return 1;
  545. @end example
  546. @noindent
  547. returns the integer 1 from the function, and
  548. @example
  549. return fib (n - 1) + fib (n - 2);
  550. @end example
  551. @noindent
  552. returns a value computed by performing two function calls
  553. as specified and adding their results.
  554. @item @code{if}@dots{}@code{else}
  555. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  556. Each time it executes, it chooses one of its two substatements to execute
  557. and ignores the other. It looks like this:
  558. @example
  559. if (@var{condition})
  560. @var{if-true-statement}
  561. else
  562. @var{if-false-statement}
  563. @end example
  564. Its meaning is to compute the expression @var{condition} and, if it's
  565. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  566. @var{if-false-statement}. @xref{if-else Statement}.
  567. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  568. simply an expression. It's considered ``true'' if its value is
  569. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  570. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  571. Comparisons}.) Thus,
  572. @example
  573. if (n <= 2)
  574. return 1;
  575. else
  576. return fib (n - 1) + fib (n - 2);
  577. @end example
  578. @noindent
  579. first tests whether the value of @code{n} is less than or equal to 2.
  580. If so, the expression @code{n <= 2} has the value 1. So execution
  581. continues with the statement
  582. @example
  583. return 1;
  584. @end example
  585. @noindent
  586. Otherwise, execution continues with this statement:
  587. @example
  588. return fib (n - 1) + fib (n - 2);
  589. @end example
  590. Each of these statements ends the execution of the function and
  591. provides a value for it to return. @xref{return Statement}.
  592. @end table
  593. Calculating @code{fib} using ordinary integers in C works only for
  594. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  595. in type @code{int}. The addition operation that tries to add
  596. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  597. This occurrence is called @dfn{integer overflow}.
  598. Overflow can manifest itself in various ways, but one thing that can't
  599. possibly happen is to produce the correct value, since that can't fit
  600. in the space for the value. @xref{Integer Overflow}.
  601. @xref{Functions}, for a full explanation about functions.
  602. @node Stack
  603. @section The Stack, And Stack Overflow
  604. @cindex stack
  605. @cindex stack frame
  606. @cindex stack overflow
  607. @cindex recursion, drawbacks of
  608. @cindex stack frame
  609. Recursion has a drawback: there are limits to how many nested levels of
  610. function calls a program can make. In C, each function call allocates a block
  611. of memory which it uses until the call returns. C allocates these
  612. blocks consecutively within a large area of memory known as the
  613. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  614. The size of the stack is limited; if the program tries to use too
  615. much, that causes the program to fail because the stack is full. This
  616. is called @dfn{stack overflow}.
  617. @cindex crash
  618. @cindex segmentation fault
  619. Stack overflow on GNU/Linux typically manifests itself as the
  620. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  621. fault.'' By default, this signal terminates the program immediately,
  622. rather than letting the program try to recover, or reach an expected
  623. ending point. (We commonly say in this case that the program
  624. ``crashes''). @xref{Signals}.
  625. It is inconvenient to observe a crash by passing too large
  626. an argument to recursive Fibonacci, because the program would run a
  627. long time before it crashes. This algorithm is simple but
  628. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  629. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  630. the final result.
  631. However, you can observe stack overflow very quickly if you use
  632. this function instead:
  633. @example
  634. int
  635. fill_stack (int n)
  636. @{
  637. if (n <= 1) /* @r{This limits the depth of recursion.} */
  638. return 1;
  639. else
  640. return fill_stack (n - 1);
  641. @}
  642. @end example
  643. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  644. and using the default configuration, an experiment showed there is
  645. enough stack space to do 261906 nested calls to that function. One
  646. more, and the stack overflows and the program crashes. On another
  647. platform, with a different configuration, or with a different
  648. function, the limit might be bigger or smaller.
  649. @node Iterative Fibonacci
  650. @section Example: Iterative Fibonacci
  651. @cindex iterative Fibonacci function
  652. @cindex Fibonacci function, iterative
  653. Here's a much faster algorithm for computing the same Fibonacci
  654. series. It is faster for two reasons. First, it uses @dfn{iteration}
  655. (that is, repetition or looping) rather than recursion, so it doesn't
  656. take time for a large number of function calls. But mainly, it is
  657. faster because the number of repetitions is small---only @code{@var{n}}.
  658. @c If you change this, change the duplicate in node Example of for.
  659. @example
  660. int
  661. fib (int n)
  662. @{
  663. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  664. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  665. int i;
  666. for (i = 1; i < n; ++i)
  667. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  668. /* @r{since @code{i < n} is false the first time.} */
  669. @{
  670. /* @r{Now @code{last} is @code{fib (@code{i})}}
  671. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  672. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  673. int next = prev + last;
  674. /* @r{Shift the values down.} */
  675. prev = last;
  676. last = next;
  677. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  678. @r{and @code{prev} is @code{fib (@code{i})}.}
  679. @r{But that won't stay true for long,}
  680. @r{because we are about to increment @code{i}.} */
  681. @}
  682. return last;
  683. @}
  684. @end example
  685. This definition computes @code{fib (@var{n})} in a time proportional
  686. to @code{@var{n}}. The comments in the definition explain how it works: it
  687. advances through the series, always keeps the last two values in
  688. @code{last} and @code{prev}, and adds them to get the next value.
  689. Here are the additional C features that this definition uses:
  690. @table @asis
  691. @item Internal blocks
  692. Within a function, wherever a statement is called for, you can write a
  693. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  694. more statements and declarations. (You can also use additional
  695. blocks as statements in a block.)
  696. The function body also counts as a block, which is why it can contain
  697. statements and declarations.
  698. @xref{Blocks}.
  699. @item Declarations of local variables
  700. This function body contains declarations as well as statements. There
  701. are three declarations directly in the function body, as well as a
  702. fourth declaration in an internal block. Each starts with @code{int}
  703. because it declares a variable whose type is integer. One declaration
  704. can declare several variables, but each of these declarations is
  705. simple and declares just one variable.
  706. Variables declared inside a block (either a function body or an
  707. internal block) are @dfn{local variables}. These variables exist only
  708. within that block; their names are not defined outside the block, and
  709. exiting the block deallocates their storage. This example declares
  710. four local variables: @code{last}, @code{prev}, @code{i}, and
  711. @code{next}.
  712. The most basic local variable declaration looks like this:
  713. @example
  714. @var{type} @var{variablename};
  715. @end example
  716. For instance,
  717. @example
  718. int i;
  719. @end example
  720. @noindent
  721. declares the local variable @code{i} as an integer.
  722. @xref{Variable Declarations}.
  723. @item Initializers
  724. When you declare a variable, you can also specify its initial value,
  725. like this:
  726. @example
  727. @var{type} @var{variablename} = @var{value};
  728. @end example
  729. For instance,
  730. @example
  731. int last = 1;
  732. @end example
  733. @noindent
  734. declares the local variable @code{last} as an integer (type
  735. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  736. @item Assignment
  737. Assignment: a specific kind of expression, written with the @samp{=}
  738. operator, that stores a new value in a variable or other place. Thus,
  739. @example
  740. @var{variable} = @var{value}
  741. @end example
  742. @noindent
  743. is an expression that computes @code{@var{value}} and stores the value in
  744. @code{@var{variable}}. @xref{Assignment Expressions}.
  745. @item Expression statements
  746. An expression statement is an expression followed by a semicolon.
  747. That computes the value of the expression, then ignores the value.
  748. An expression statement is useful when the expression changes some
  749. data or has other side effects---for instance, with function calls, or
  750. with assignments as in this example. @xref{Expression Statement}.
  751. Using an expression with no side effects in an expression statement is
  752. pointless except in very special cases. For instance, the expression
  753. statement @code{x;} would examine the value of @code{x} and ignore it.
  754. That is not useful.
  755. @item Increment operator
  756. The increment operator is @samp{++}. @code{++i} is an
  757. expression that is short for @code{i = i + 1}.
  758. @xref{Increment/Decrement}.
  759. @item @code{for} statements
  760. A @code{for} statement is a clean way of executing a statement
  761. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  762. @example
  763. for (i = 1; i < n; ++i)
  764. @var{body}
  765. @end example
  766. @noindent
  767. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  768. for the loop. The loop itself consists of
  769. @itemize @bullet
  770. @item
  771. Testing @code{i < n} and exiting the loop if that's false.
  772. @item
  773. Executing @var{body}.
  774. @item
  775. Advancing the loop (executing @code{++i}, which increments @code{i}).
  776. @end itemize
  777. The net result is to execute @var{body} with 1 in @code{i},
  778. then with 2 in @code{i}, and so on, stopping just before the repetition
  779. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  780. the loop will execute the body zero times.
  781. The body of the @code{for} statement must be one and only one
  782. statement. You can't write two statements in a row there; if you try
  783. to, only the first of them will be treated as part of the loop.
  784. The way to put multiple statements in such a place is to group them
  785. with a block, and that's what we do in this example.
  786. @end table
  787. @node Complete Program
  788. @chapter A Complete Program
  789. @cindex complete example program
  790. @cindex example program, complete
  791. It's all very well to write a Fibonacci function, but you cannot run
  792. it by itself. It is a useful program, but it is not a complete
  793. program.
  794. In this chapter we present a complete program that contains the
  795. @code{fib} function. This example shows how to make the program
  796. start, how to make it finish, how to do computation, and how to print
  797. a result.
  798. @menu
  799. * Complete Example:: Turn the simple function into a full program.
  800. * Complete Explanation:: Explanation of each part of the example.
  801. * Complete Line-by-Line:: Explaining each line of the example.
  802. * Compile Example:: Using GCC to compile the example.
  803. @end menu
  804. @node Complete Example
  805. @section Complete Program Example
  806. Here is the complete program that uses the simple, recursive version
  807. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  808. @example
  809. #include <stdio.h>
  810. int
  811. fib (int n)
  812. @{
  813. if (n <= 2) /* @r{This avoids infinite recursion.} */
  814. return 1;
  815. else
  816. return fib (n - 1) + fib (n - 2);
  817. @}
  818. int
  819. main (void)
  820. @{
  821. printf ("Fibonacci series item %d is %d\n",
  822. 20, fib (20));
  823. return 0;
  824. @}
  825. @end example
  826. @noindent
  827. This program prints a message that shows the value of @code{fib (20)}.
  828. Now for an explanation of what that code means.
  829. @node Complete Explanation
  830. @section Complete Program Explanation
  831. @ifnottex
  832. Here's the explanation of the code of the example in the
  833. previous section.
  834. @end ifnottex
  835. This sample program prints a message that shows the value of @code{fib
  836. (20)}, and exits with code 0 (which stands for successful execution).
  837. Every C program is started by running the function named @code{main}.
  838. Therefore, the example program defines a function named @code{main} to
  839. provide a way to start it. Whatever that function does is what the
  840. program does. @xref{The main Function}.
  841. The @code{main} function is the first one called when the program
  842. runs, but it doesn't come first in the example code. The order of the
  843. function definitions in the source code makes no difference to the
  844. program's meaning.
  845. The initial call to @code{main} always passes certain arguments, but
  846. @code{main} does not have to pay attention to them. To ignore those
  847. arguments, define @code{main} with @code{void} as the parameter list.
  848. (@code{void} as a function's parameter list normally means ``call with
  849. no arguments,'' but @code{main} is a special case.)
  850. The function @code{main} returns 0 because that is
  851. the conventional way for @code{main} to indicate successful execution.
  852. It could instead return a positive integer to indicate failure, and
  853. some utility programs have specific conventions for the meaning of
  854. certain numeric @dfn{failure codes}. @xref{Values from main}.
  855. @cindex @code{printf}
  856. The simplest way to print text in C is by calling the @code{printf}
  857. function, so here we explain very briefly what that function does.
  858. For a full explanation of @code{printf} and the other standard I/O
  859. functions, see @ref{I/O on Streams, The GNU C Library, , libc, The GNU
  860. C Library Reference Manual}.
  861. @cindex standard output
  862. The first argument to @code{printf} is a @dfn{string constant}
  863. (@pxref{String Constants}) that is a template for output. The
  864. function @code{printf} copies most of that string directly as output,
  865. including the newline character at the end of the string, which is
  866. written as @samp{\n}. The output goes to the program's @dfn{standard
  867. output} destination, which in the usual case is the terminal.
  868. @samp{%} in the template introduces a code that substitutes other text
  869. into the output. Specifically, @samp{%d} means to take the next
  870. argument to @code{printf} and substitute it into the text as a decimal
  871. number. (The argument for @samp{%d} must be of type @code{int}; if it
  872. isn't, @code{printf} will malfunction.) So the output is a line that
  873. looks like this:
  874. @example
  875. Fibonacci series item 20 is 6765
  876. @end example
  877. This program does not contain a definition for @code{printf} because
  878. it is defined by the C library, which makes it available in all C
  879. programs. However, each program does need to @dfn{declare}
  880. @code{printf} so it will be called correctly. The @code{#include}
  881. line takes care of that; it includes a @dfn{header file} called
  882. @file{stdio.h} into the program's code. That file is provided by the
  883. operating system and it contains declarations for the many standard
  884. input/output functions in the C library, one of which is
  885. @code{printf}.
  886. Don't worry about header files for now; we'll explain them later in
  887. @ref{Header Files}.
  888. The first argument of @code{printf} does not have to be a string
  889. constant; it can be any string (@pxref{Strings}). However, using a
  890. constant is the most common case.
  891. @node Complete Line-by-Line
  892. @section Complete Program, Line by Line
  893. Here's the same example, explained line by line.
  894. @strong{Beginners, do you find this helpful or not?
  895. Would you prefer a different layout for the example?
  896. Please tell rms@@gnu.org.}
  897. @example
  898. #include <stdio.h> /* @r{Include declaration of usual} */
  899. /* @r{I/O functions such as @code{printf}.} */
  900. /* @r{Most programs need these.} */
  901. int /* @r{This function returns an @code{int}.} */
  902. fib (int n) /* @r{Its name is @code{fib};} */
  903. /* @r{its argument is called @code{n}.} */
  904. @{ /* @r{Start of function body.} */
  905. /* @r{This stops the recursion from being infinite.} */
  906. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  907. return 1; /* @r{make @code{fib} return 1.} */
  908. else /* @r{otherwise, add the two previous} */
  909. /* @r{Fibonacci numbers.} */
  910. return fib (n - 1) + fib (n - 2);
  911. @}
  912. int /* @r{This function returns an @code{int}.} */
  913. main (void) /* @r{Start here; ignore arguments.} */
  914. @{ /* @r{Print message with numbers in it.} */
  915. printf ("Fibonacci series item %d is %d\n",
  916. 20, fib (20));
  917. return 0; /* @r{Terminate program, report success.} */
  918. @}
  919. @end example
  920. @node Compile Example
  921. @section Compiling the Example Program
  922. @cindex compiling
  923. @cindex executable file
  924. To run a C program requires converting the source code into an
  925. @dfn{executable file}. This is called @dfn{compiling} the program,
  926. and the command to do that using GNU C is @command{gcc}.
  927. This example program consists of a single source file. If we
  928. call that file @file{fib1.c}, the complete command to compile it is
  929. this:
  930. @example
  931. gcc -g -O -o fib1 fib1.c
  932. @end example
  933. @noindent
  934. Here, @option{-g} says to generate debugging information, @option{-O}
  935. says to optimize at the basic level, and @option{-o fib1} says to put
  936. the executable program in the file @file{fib1}.
  937. To run the program, use its file name as a shell command.
  938. For instance,
  939. @example
  940. ./fib1
  941. @end example
  942. @noindent
  943. However, unless you are sure the program is correct, you should
  944. expect to need to debug it. So use this command,
  945. @example
  946. gdb fib1
  947. @end example
  948. @noindent
  949. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  950. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  951. debug the executable program @code{fib1}.
  952. Richard Stallman's advice, from personal experience, is to turn to the
  953. debugger as soon as you can reproduce the problem. Don't try to avoid
  954. it by using other methods instead---occasionally they are shortcuts,
  955. but usually they waste an unbounded amount of time. With the
  956. debugger, you will surely find the bug in a reasonable time; overall,
  957. you will get your work done faster. The sooner you get serious and
  958. start the debugger, the sooner you are likely to find the bug.
  959. @xref{Compilation}, for an introduction to compiling more complex
  960. programs which consist of more than one source file.
  961. @node Storage
  962. @chapter Storage and Data
  963. @cindex bytes
  964. @cindex storage organization
  965. @cindex memory organization
  966. Storage in C programs is made up of units called @dfn{bytes}. On
  967. nearly all computers, a byte consists of 8 bits, but there are a few
  968. peculiar computers (mostly ``embedded controllers'' for very small
  969. systems) where a byte is longer than that. This manual does not try
  970. to explain the peculiarity of those computers; we assume that a byte
  971. is 8 bits.
  972. Every C data type is made up of a certain number of bytes; that number
  973. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  974. types @code{signed char} and @code{unsigned char} are one byte long;
  975. use those types to operate on data byte by byte. @xref{Signed and
  976. Unsigned Types}. You can refer to a series of consecutive bytes as an
  977. array of @code{char} elements; that's what an ASCII string looks like
  978. in memory. @xref{String Constants}.
  979. @node Beyond Integers
  980. @chapter Beyond Integers
  981. So far we've presented programs that operate on integers. In this
  982. chapter we'll present examples of handling non-integral numbers and
  983. arrays of numbers.
  984. @menu
  985. * Float Example:: A function that uses floating-point numbers.
  986. * Array Example:: A function that works with arrays.
  987. * Array Example Call:: How to call that function.
  988. * Array Example Variations:: Different ways to write the call example.
  989. @end menu
  990. @node Float Example
  991. @section An Example with Non-Integer Numbers
  992. @cindex floating point example
  993. Here's a function that operates on and returns @dfn{floating point}
  994. numbers that don't have to be integers. Floating point represents a
  995. number as a fraction together with a power of 2. (For more detail,
  996. @pxref{Floating-Point Data Types}.) This example calculates the
  997. average of three floating point numbers that are passed to it as
  998. arguments:
  999. @example
  1000. double
  1001. average_of_three (double a, double b, double c)
  1002. @{
  1003. return (a + b + c) / 3;
  1004. @}
  1005. @end example
  1006. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  1007. integers, and even when they happen to be integers, most likely their
  1008. average is not an integer.
  1009. @code{double} is the usual data type in C for calculations on
  1010. floating-point numbers.
  1011. To print a @code{double} with @code{printf}, we must use @samp{%f}
  1012. instead of @samp{%d}:
  1013. @example
  1014. printf ("Average is %f\n",
  1015. average_of_three (1.1, 9.8, 3.62));
  1016. @end example
  1017. The code that calls @code{printf} must pass a @code{double} for
  1018. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  1019. If the argument has the wrong type, @code{printf} will produce garbage
  1020. output.
  1021. Here's a complete program that computes the average of three
  1022. specific numbers and prints the result:
  1023. @example
  1024. double
  1025. average_of_three (double a, double b, double c)
  1026. @{
  1027. return (a + b + c) / 3;
  1028. @}
  1029. int
  1030. main (void)
  1031. @{
  1032. printf ("Average is %f\n",
  1033. average_of_three (1.1, 9.8, 3.62));
  1034. return 0;
  1035. @}
  1036. @end example
  1037. From now on we will not present examples of calls to @code{main}.
  1038. Instead we encourage you to write them for yourself when you want
  1039. to test executing some code.
  1040. @node Array Example
  1041. @section An Example with Arrays
  1042. @cindex array example
  1043. A function to take the average of three numbers is very specific and
  1044. limited. A more general function would take the average of any number
  1045. of numbers. That requires passing the numbers in an array. An array
  1046. is an object in memory that contains a series of values of the same
  1047. data type. This chapter presents the basic concepts and use of arrays
  1048. through an example; for the full explanation, see @ref{Arrays}.
  1049. Here's a function definition to take the average of several
  1050. floating-point numbers, passed as type @code{double}. The first
  1051. parameter, @code{length}, specifies how many numbers are passed. The
  1052. second parameter, @code{input_data}, is an array that holds those
  1053. numbers.
  1054. @example
  1055. double
  1056. avg_of_double (int length, double input_data[])
  1057. @{
  1058. double sum = 0;
  1059. int i;
  1060. for (i = 0; i < length; i++)
  1061. sum = sum + input_data[i];
  1062. return sum / length;
  1063. @}
  1064. @end example
  1065. This introduces the expression to refer to an element of an array:
  1066. @code{input_data[i]} means the element at index @code{i} in
  1067. @code{input_data}. The index of the element can be any expression
  1068. with an integer value; in this case, the expression is @code{i}.
  1069. @xref{Accessing Array Elements}.
  1070. @cindex zero-origin indexing
  1071. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1072. valid index is one less than the number of elements. (This is known
  1073. as @dfn{zero-origin indexing}.)
  1074. This example also introduces the way to declare that a function
  1075. parameter is an array. Such declarations are modeled after the syntax
  1076. for an element of the array. Just as @code{double foo} declares that
  1077. @code{foo} is of type @code{double}, @code{double input_data[]}
  1078. declares that each element of @code{input_data} is of type
  1079. @code{double}. Therefore, @code{input_data} itself has type ``array
  1080. of @code{double}.''
  1081. When declaring an array parameter, it's not necessary to say how long
  1082. the array is. In this case, the parameter @code{input_data} has no
  1083. length information. That's why the function needs another parameter,
  1084. @code{length}, for the caller to provide that information to the
  1085. function @code{avg_of_double}.
  1086. @node Array Example Call
  1087. @section Calling the Array Example
  1088. To call the function @code{avg_of_double} requires making an
  1089. array and then passing it as an argument. Here is an example.
  1090. @example
  1091. @{
  1092. /* @r{The array of values to average.} */
  1093. double nums_to_average[5];
  1094. /* @r{The average, once we compute it.} */
  1095. double average;
  1096. /* @r{Fill in elements of @code{nums_to_average}.} */
  1097. nums_to_average[0] = 58.7;
  1098. nums_to_average[1] = 5.1;
  1099. nums_to_average[2] = 7.7;
  1100. nums_to_average[3] = 105.2;
  1101. nums_to_average[4] = -3.14159;
  1102. average = avg_of_double (5, nums_to_average);
  1103. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1104. @}
  1105. @end example
  1106. This shows an array subscripting expression again, this time
  1107. on the left side of an assignment, storing a value into an
  1108. element of an array.
  1109. It also shows how to declare a local variable that is an array:
  1110. @code{double nums_to_average[5];}. Since this declaration allocates the
  1111. space for the array, it needs to know the array's length. You can
  1112. specify the length with any expression whose value is an integer, but
  1113. in this declaration the length is a constant, the integer 5.
  1114. The name of the array, when used by itself as an expression, stands
  1115. for the address of the array's data, and that's what gets passed to
  1116. the function @code{avg_of_double} in @code{avg_of_double (5,
  1117. nums_to_average)}.
  1118. We can make the code easier to maintain by avoiding the need to write
  1119. 5, the array length, when calling @code{avg_of_double}. That way, if
  1120. we change the array to include more elements, we won't have to change
  1121. that call. One way to do this is with the @code{sizeof} operator:
  1122. @example
  1123. average = avg_of_double ((sizeof (nums_to_average)
  1124. / sizeof (nums_to_average[0])),
  1125. nums_to_average);
  1126. @end example
  1127. This computes the number of elements in @code{nums_to_average} by dividing
  1128. its total size by the size of one element. @xref{Type Size}, for more
  1129. details of using @code{sizeof}.
  1130. We don't show in this example what happens after storing the result of
  1131. @code{avg_of_double} in the variable @code{average}. Presumably
  1132. more code would follow that uses that result somehow. (Why compute
  1133. the average and not use it?) But that isn't part of this topic.
  1134. @node Array Example Variations
  1135. @section Variations for Array Example
  1136. The code to call @code{avg_of_double} has two declarations that
  1137. start with the same data type:
  1138. @example
  1139. /* @r{The array of values to average.} */
  1140. double nums_to_average[5];
  1141. /* @r{The average, once we compute it.} */
  1142. double average;
  1143. @end example
  1144. In C, you can combine the two, like this:
  1145. @example
  1146. double nums_to_average[5], average;
  1147. @end example
  1148. This declares @code{nums_to_average} so each of its elements is a
  1149. @code{double}, and @code{average} so that it simply is a
  1150. @code{double}.
  1151. However, while you @emph{can} combine them, that doesn't mean you
  1152. @emph{should}. If it is useful to write comments about the variables,
  1153. and usually it is, then it's clearer to keep the declarations separate
  1154. so you can put a comment on each one.
  1155. We set all of the elements of the array @code{nums_to_average} with
  1156. assignments, but it is more convenient to use an initializer in the
  1157. declaration:
  1158. @example
  1159. @{
  1160. /* @r{The array of values to average.} */
  1161. double nums_to_average[]
  1162. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1163. /* @r{The average, once we compute it.} */
  1164. average = avg_of_double ((sizeof (nums_to_average)
  1165. / sizeof (nums_to_average[0])),
  1166. nums_to_average);
  1167. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1168. @}
  1169. @end example
  1170. The array initializer is a comma-separated list of values, delimited
  1171. by braces. @xref{Initializers}.
  1172. Note that the declaration does not specify a size for
  1173. @code{nums_to_average}, so the size is determined from the
  1174. initializer. There are five values in the initializer, so
  1175. @code{nums_to_average} gets length 5. If we add another element to
  1176. the initializer, @code{nums_to_average} will have six elements.
  1177. Because the code computes the number of elements from the size of
  1178. the array, using @code{sizeof}, the program will operate on all the
  1179. elements in the initializer, regardless of how many those are.
  1180. @node Lexical Syntax
  1181. @chapter Lexical Syntax
  1182. @cindex lexical syntax
  1183. @cindex token
  1184. To start the full description of the C language, we explain the
  1185. lexical syntax and lexical units of C code. The lexical units of a
  1186. programming language are known as @dfn{tokens}. This chapter covers
  1187. all the tokens of C except for constants, which are covered in a later
  1188. chapter (@pxref{Constants}). One vital kind of token is the
  1189. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1190. kind.
  1191. @menu
  1192. * English:: Write programs in English!
  1193. * Characters:: The characters allowed in C programs.
  1194. * Whitespace:: The particulars of whitespace characters.
  1195. * Comments:: How to include comments in C code.
  1196. * Identifiers:: How to form identifiers (names).
  1197. * Operators/Punctuation:: Characters used as operators or punctuation.
  1198. * Line Continuation:: Splitting one line into multiple lines.
  1199. @end menu
  1200. @node English
  1201. @section Write Programs in English!
  1202. In principle, you can write the function and variable names in a
  1203. program, and the comments, in any human language. C allows any kinds
  1204. of characters in comments, and you can put non-ASCII characters into
  1205. identifiers with a special prefix. However, to enable programmers in
  1206. all countries to understand and develop the program, it is best given
  1207. today's circumstances to write identifiers and comments in
  1208. English.
  1209. English is the one language that programmers in all countries
  1210. generally study. If a program's names are in English, most
  1211. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1212. understand them. Most programmers in those countries can speak
  1213. English, or at least read it, but they do not read each other's
  1214. languages at all. In India, with so many languages, two programmers
  1215. may have no common language other than English.
  1216. If you don't feel confident in writing English, do the best you can,
  1217. and follow each English comment with a version in a language you
  1218. write better; add a note asking others to translate that to English.
  1219. Someone will eventually do that.
  1220. The program's user interface is a different matter. We don't need to
  1221. choose one language for that; it is easy to support multiple languages
  1222. and let each user choose the language to use. This requires writing
  1223. the program to support localization of its interface. (The
  1224. @code{gettext} package exists to support this; @pxref{Message
  1225. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1226. Manual}.) Then a community-based translation effort can provide
  1227. support for all the languages users want to use.
  1228. @node Characters
  1229. @section Characters
  1230. @cindex character set
  1231. @cindex Unicode
  1232. @c ??? How to express ¶?
  1233. GNU C source files are usually written in the
  1234. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1235. was defined in the 1960s for English. However, they can also include
  1236. Unicode characters represented in the
  1237. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1238. This makes it possible to represent accented letters such as @samp{á},
  1239. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1240. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1241. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1242. manual.}
  1243. In C source code, non-ASCII characters are valid in comments, in wide
  1244. character constants (@pxref{Wide Character Constants}), and in string
  1245. constants (@pxref{String Constants}).
  1246. @c ??? valid in identifiers?
  1247. Another way to specify non-ASCII characters in constants (character or
  1248. string) and identifiers is with an escape sequence starting with
  1249. backslash, specifying the intended Unicode character. (@xref{Unicode
  1250. Character Codes}.) This specifies non-ASCII characters without
  1251. putting a real non-ASCII character in the source file itself.
  1252. C accepts two-character aliases called @dfn{digraphs} for certain
  1253. characters. @xref{Digraphs}.
  1254. @node Whitespace
  1255. @section Whitespace
  1256. @cindex whitespace characters in source files
  1257. @cindex space character in source
  1258. @cindex tab character in source
  1259. @cindex formfeed in source
  1260. @cindex linefeed in source
  1261. @cindex newline in source
  1262. @cindex carriage return in source
  1263. @cindex vertical tab in source
  1264. Whitespace means characters that exist in a file but appear blank in a
  1265. printed listing of a file (or traditionally did appear blank, several
  1266. decades ago). The C language requires whitespace in order to separate
  1267. two consecutive identifiers, or to separate an identifier from a
  1268. numeric constant. Other than that, and a few special situations
  1269. described later, whitespace is optional; you can put it in when you
  1270. wish, to make the code easier to read.
  1271. Space and tab in C code are treated as whitespace characters. So are
  1272. line breaks. You can represent a line break with the newline
  1273. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1274. the CRLF sequence (two characters: carriage return followed by a
  1275. newline character).
  1276. The @dfn{formfeed} character, Control-L, was traditionally used to
  1277. divide a file into pages. It is still used this way in source code,
  1278. and the tools that generate nice printouts of source code still start
  1279. a new page after each ``formfeed'' character. Dividing code into
  1280. pages separated by formfeed characters is a good way to break it up
  1281. into comprehensible pieces and show other programmers where they start
  1282. and end.
  1283. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1284. make printing advance down to the next section of a page. We know of
  1285. no particular reason to use it in source code, but it is still
  1286. accepted as whitespace in C.
  1287. Comments are also syntactically equivalent to whitespace.
  1288. @ifinfo
  1289. @xref{Comments}.
  1290. @end ifinfo
  1291. @node Comments
  1292. @section Comments
  1293. @cindex comments
  1294. A comment encapsulates text that has no effect on the program's
  1295. execution or meaning.
  1296. The purpose of comments is to explain the code to people that read it.
  1297. Writing good comments for your code is tremendously important---they
  1298. should provide background information that helps programmers
  1299. understand the reasons why the code is written the way it is. You,
  1300. returning to the code six months from now, will need the help of these
  1301. comments to remember why you wrote it this way.
  1302. Outdated comments that become incorrect are counterproductive, so part
  1303. of the software developer's responsibility is to update comments as
  1304. needed to correspond with changes to the program code.
  1305. C allows two kinds of comment syntax, the traditional style and the
  1306. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1307. with @samp{*/}. For instance,
  1308. @example
  1309. /* @r{This is a comment in traditional C syntax.} */
  1310. @end example
  1311. A traditional comment can contain @samp{/*}, but these delimiters do
  1312. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1313. whether it contains @samp{/*} sequences.
  1314. @example
  1315. /* @r{This} /* @r{is a comment} */ But this is not! */
  1316. @end example
  1317. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1318. For instance,
  1319. @example
  1320. // @r{This is a comment in C@t{++} style.}
  1321. @end example
  1322. Line comments do nest, in effect, because @samp{//} inside a line
  1323. comment is part of that comment:
  1324. @example
  1325. // @r{this whole line is} // @r{one comment}
  1326. This is code, not comment.
  1327. @end example
  1328. It is safe to put line comments inside block comments, or vice versa.
  1329. @example
  1330. @group
  1331. /* @r{traditional comment}
  1332. // @r{contains line comment}
  1333. @r{more traditional comment}
  1334. */ text here is not a comment
  1335. // @r{line comment} /* @r{contains traditional comment} */
  1336. @end group
  1337. @end example
  1338. But beware of commenting out one end of a traditional comment with a line
  1339. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1340. inside an already-started comment.
  1341. @example
  1342. @group
  1343. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1344. Oops! The line comment has ended;
  1345. this isn't a comment any more. */
  1346. @end group
  1347. @end example
  1348. Comments are not recognized within string constants. @t{@w{"/* blah
  1349. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1350. string.
  1351. In this manual we show the text in comments in a variable-width font,
  1352. for readability, but this font distinction does not exist in source
  1353. files.
  1354. A comment is syntactically equivalent to whitespace, so it always
  1355. separates tokens. Thus,
  1356. @example
  1357. @group
  1358. int/* @r{comment} */foo;
  1359. @r{is equivalent to}
  1360. int foo;
  1361. @end group
  1362. @end example
  1363. @noindent
  1364. but clean code always uses real whitespace to separate the comment
  1365. visually from surrounding code.
  1366. @node Identifiers
  1367. @section Identifiers
  1368. @cindex identifiers
  1369. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1370. as well as @samp{_}, that does not start with a digit. Most compilers
  1371. also allow @samp{$}. An identifier can be as long as you like; for
  1372. example,
  1373. @example
  1374. int anti_dis_establishment_arian_ism;
  1375. @end example
  1376. @cindex case of letters in identifiers
  1377. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1378. and @code{A} are two different identifiers.
  1379. @cindex keyword
  1380. @cindex reserved words
  1381. Identifiers in C are used as variable names, function names, typedef
  1382. names, enumeration constants, type tags, field names, and labels.
  1383. Certain identifiers in C are @dfn{keywords}, which means they have
  1384. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1385. meaning you cannot use them in any other way. For instance, you can't
  1386. define a variable or function named @code{return} or @code{if}.
  1387. You can also include other characters, even non-ASCII characters, in
  1388. identifiers by writing their Unicode character names, which start with
  1389. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1390. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1391. characters in identifiers, and when they are written in English, they
  1392. never need non-ASCII characters. @xref{English}.
  1393. Whitespace is required to separate two consecutive identifiers, or to
  1394. separate an identifier from a preceding or following numeric
  1395. constant.
  1396. @node Operators/Punctuation
  1397. @section Operators and Punctuation
  1398. @cindex operators
  1399. @cindex punctuation
  1400. Here we describe the lexical syntax of operators and punctuation in C.
  1401. The specific operators of C and their meanings are presented in
  1402. subsequent chapters.
  1403. Most operators in C consist of one or two characters that can't be
  1404. used in identifiers. The characters used for operators in C are
  1405. @samp{!~^&|*/%+-=<>,.?:}.
  1406. Some operators are a single character. For instance, @samp{-} is the
  1407. operator for negation (with one operand) and the operator for
  1408. subtraction (with two operands).
  1409. Some operators are two characters. For example, @samp{++} is the
  1410. increment operator. Recognition of multicharacter operators works by
  1411. grouping together as many consecutive characters as can constitute one
  1412. operator.
  1413. For instance, the character sequence @samp{++} is always interpreted
  1414. as the increment operator; therefore, if we want to write two
  1415. consecutive instances of the operator @samp{+}, we must separate them
  1416. with a space so that they do not combine as one token. Applying the
  1417. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1418. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1419. of a valid C program and the former could not (since @code{a++}
  1420. is not an lvalue and thus can't be the operand of @code{++}).
  1421. A few C operators are keywords rather than special characters. They
  1422. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1423. (@pxref{Type Alignment}).
  1424. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1425. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1426. @samp{@}}) begin and end a block at the statement level
  1427. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1428. for a variable with multiple elements or components (such as arrays or
  1429. structures).
  1430. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1431. @code{array[5]}.
  1432. Parentheses are used in expressions for explicit nesting of
  1433. expressions (@pxref{Basic Arithmetic}), around the parameter
  1434. declarations in a function declaration or definition, and around the
  1435. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1436. (@pxref{Function Calls}). Several kinds of statements also use
  1437. parentheses as part of their syntax---for instance, @code{if}
  1438. statements, @code{for} statements, @code{while} statements, and
  1439. @code{switch} statements. @xref{if Statement}, and following
  1440. sections.
  1441. Parentheses are also required around the operand of the operator
  1442. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1443. type rather than a value. @xref{Type Size}.
  1444. @node Line Continuation
  1445. @section Line Continuation
  1446. @cindex line continuation
  1447. @cindex continuation of lines
  1448. The sequence of a backslash and a newline is ignored absolutely
  1449. anywhere in a C program. This makes it possible to split a single
  1450. source line into multiple lines in the source file. GNU C tolerates
  1451. and ignores other whitespace between the backslash and the newline.
  1452. In particular, it always ignores a CR (carriage return) character
  1453. there, in case some text editor decided to end the line with the CRLF
  1454. sequence.
  1455. The main use of line continuation in C is for macro definitions that
  1456. would be inconveniently long for a single line (@pxref{Macros}).
  1457. It is possible to continue a line comment onto another line with
  1458. backslash-newline. You can put backslash-newline in the middle of an
  1459. identifier, even a keyword, or an operator. You can even split
  1460. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1461. backslash-newline. Here's an ugly example:
  1462. @example
  1463. @group
  1464. /\
  1465. *
  1466. */ fo\
  1467. o +\
  1468. = 1\
  1469. 0;
  1470. @end group
  1471. @end example
  1472. @noindent
  1473. That's equivalent to @samp{/* */ foo += 10;}.
  1474. Don't do those things in real programs, since they make code hard to
  1475. read.
  1476. @strong{Note:} For the sake of using certain tools on the source code, it is
  1477. wise to end every source file with a newline character which is not
  1478. preceded by a backslash, so that it really ends the last line.
  1479. @node Arithmetic
  1480. @chapter Arithmetic
  1481. @cindex arithmetic operators
  1482. @cindex operators, arithmetic
  1483. @c ??? Duplication with other sections -- get rid of that?
  1484. Arithmetic operators in C attempt to be as similar as possible to the
  1485. abstract arithmetic operations, but it is impossible to do this
  1486. perfectly. Numbers in a computer have a finite range of possible
  1487. values, and non-integer values have a limit on their possible
  1488. accuracy. Nonetheless, except when results are out of range, you will
  1489. encounter no surprises in using @samp{+} for addition, @samp{-} for
  1490. subtraction, and @samp{*} for multiplication.
  1491. Each C operator has a @dfn{precedence}, which is its rank in the
  1492. grammatical order of the various operators. The operators with the
  1493. highest precedence grab adjoining operands first; these expressions
  1494. then become operands for operators of lower precedence. We give some
  1495. information about precedence of operators in this chapter where we
  1496. describe the operators; for the full explanation, see @ref{Binary
  1497. Operator Grammar}.
  1498. The arithmetic operators always @dfn{promote} their operands before
  1499. operating on them. This means converting narrow integer data types to
  1500. a wider data type (@pxref{Operand Promotions}). If you are just
  1501. learning C, don't worry about this yet.
  1502. Given two operands that have different types, most arithmetic
  1503. operations convert them both to their @dfn{common type}. For
  1504. instance, if one is @code{int} and the other is @code{double}, the
  1505. common type is @code{double}. (That's because @code{double} can
  1506. represent all the values that an @code{int} can hold, but not vice
  1507. versa.) For the full details, see @ref{Common Type}.
  1508. @menu
  1509. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1510. and division.
  1511. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1512. * Integer Overflow:: When an integer value exceeds the range
  1513. of its type.
  1514. * Mixed Mode:: Calculating with both integer values
  1515. and floating-point values.
  1516. * Division and Remainder:: How integer division works.
  1517. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1518. * Shift Operations:: Shift integer bits left or right.
  1519. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1520. @end menu
  1521. @node Basic Arithmetic
  1522. @section Basic Arithmetic
  1523. @cindex addition operator
  1524. @cindex subtraction operator
  1525. @cindex multiplication operator
  1526. @cindex division operator
  1527. @cindex negation operator
  1528. @cindex operator, addition
  1529. @cindex operator, subtraction
  1530. @cindex operator, multiplication
  1531. @cindex operator, division
  1532. @cindex operator, negation
  1533. Basic arithmetic in C is done with the usual binary operators of
  1534. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1535. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1536. used to change the sign of a number. The unary @code{+} operator also
  1537. exists; it yields its operand unaltered.
  1538. @samp{/} is the division operator, but dividing integers may not give
  1539. the result you expect. Its value is an integer, which is not equal to
  1540. the mathematical quotient when that is a fraction. Use @samp{%} to
  1541. get the corresponding integer remainder when necessary.
  1542. @xref{Division and Remainder}. Floating point division yields value
  1543. as close as possible to the mathematical quotient.
  1544. These operators use algebraic syntax with the usual algebraic
  1545. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1546. and division are done before addition and subtraction, but you can use
  1547. parentheses to explicitly specify how the operators nest. They are
  1548. left-associative (@pxref{Associativity and Ordering}). Thus,
  1549. @example
  1550. -a + b - c + d * e / f
  1551. @end example
  1552. @noindent
  1553. is equivalent to
  1554. @example
  1555. (((-a) + b) - c) + ((d * e) / f)
  1556. @end example
  1557. @node Integer Arithmetic
  1558. @section Integer Arithmetic
  1559. @cindex integer arithmetic
  1560. Each of the basic arithmetic operations in C has two variants for
  1561. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1562. by the data types of their operands.
  1563. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1564. A signed type can hold a range of positive and negative numbers, with
  1565. zero near the middle of the range. An unsigned type can hold only
  1566. nonnegative numbers; its range starts with zero and runs upward.
  1567. The most basic integer types are @code{int}, which normally can hold
  1568. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1569. int}, which normally can hold numbers from 0 to 4,294,967,295. (This
  1570. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1571. computers but not always on embedded controllers.) @xref{Integer
  1572. Types}, for full information about integer types.
  1573. When a basic arithmetic operation is given two signed operands, it
  1574. does signed arithmetic. Given two unsigned operands, it does
  1575. unsigned arithmetic.
  1576. If one operand is @code{unsigned int} and the other is @code{int}, the
  1577. operator treats them both as unsigned. More generally, the common
  1578. type of the operands determines whether the operation is signed or
  1579. not. @xref{Common Type}.
  1580. Printing the results of unsigned arithmetic with @code{printf} using
  1581. @samp{%d} can produce surprising results for values far away from
  1582. zero. Even though the rules above say that the computation was done
  1583. with unsigned arithmetic, the printed result may appear to be signed!
  1584. The explanation is that the bit pattern resulting from addition,
  1585. subtraction or multiplication is actually the same for signed and
  1586. unsigned operations. The difference is only in the data type of the
  1587. result, which affects the @emph{interpretation} of the result bit pattern,
  1588. and whether the arithmetic operation can overflow (see the next section).
  1589. But @samp{%d} doesn't know its argument's data type. It sees only the
  1590. value's bit pattern, and it is defined to interpret that as
  1591. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1592. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1593. libc, The GNU C Library Reference Manual}.
  1594. Arithmetic in C never operates directly on narrow integer types (those
  1595. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1596. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1597. @node Integer Overflow
  1598. @section Integer Overflow
  1599. @cindex integer overflow
  1600. @cindex overflow, integer
  1601. When the mathematical value of an arithmetic operation doesn't fit in
  1602. the range of the data type in use, that's called @dfn{overflow}.
  1603. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1604. Integer overflow happens only in arithmetic operations. Type conversion
  1605. operations, by definition, do not cause overflow, not even when the
  1606. result can't fit in its new type. @xref{Integer Conversion}.
  1607. Signed numbers use two's-complement representation, in which the most
  1608. negative number lacks a positive counterpart (@pxref{Integers in
  1609. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1610. overflow.
  1611. @menu
  1612. * Unsigned Overflow:: Overflow in unsigned integer arithmetic.
  1613. * Signed Overflow:: Overflow in signed integer arithmetic.
  1614. @end menu
  1615. @node Unsigned Overflow
  1616. @subsection Overflow with Unsigned Integers
  1617. Unsigned arithmetic in C ignores overflow; it produces the true result
  1618. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1619. in the data type. We say it ``truncates'' the true result to the
  1620. lowest @var{n} bits.
  1621. A true result that is negative, when taken modulo the @var{n}th power
  1622. of 2, yields a positive number. For instance,
  1623. @example
  1624. unsigned int x = 1;
  1625. unsigned int y;
  1626. y = -x;
  1627. @end example
  1628. @noindent
  1629. causes overflow because the negative number @minus{}1 can't be stored
  1630. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1631. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1632. is the largest value that the unsigned data type can store. For a
  1633. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1634. and Minimum Values}.
  1635. Adding that number to itself, as here,
  1636. @example
  1637. unsigned int z;
  1638. z = y + y;
  1639. @end example
  1640. @noindent
  1641. ought to yield 8,489,934,590; however, that is again too large to fit,
  1642. so overflow truncates the value to 4,294,967,294. If that were a
  1643. signed integer, it would mean @minus{}2, which (not by coincidence)
  1644. equals @minus{}1 + @minus{}1.
  1645. @node Signed Overflow
  1646. @subsection Overflow with Signed Integers
  1647. @cindex compiler options for integer overflow
  1648. @cindex integer overflow, compiler options
  1649. @cindex overflow, compiler options
  1650. For signed integers, the result of overflow in C is @emph{in
  1651. principle} undefined, meaning that anything whatsoever could happen.
  1652. Therefore, C compilers can do optimizations that treat the overflow
  1653. case with total unconcern. (Since the result of overflow is undefined
  1654. in principle, one cannot claim that these optimizations are
  1655. erroneous.)
  1656. @strong{Watch out:} These optimizations can do surprising things. For
  1657. instance,
  1658. @example
  1659. int i;
  1660. @r{@dots{}}
  1661. if (i < i + 1)
  1662. x = 5;
  1663. @end example
  1664. @noindent
  1665. could be optimized to do the assignment unconditionally, because the
  1666. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1667. GCC offers compiler options to control handling signed integer
  1668. overflow. These options operate per module; that is, each module
  1669. behaves according to the options it was compiled with.
  1670. These two options specify particular ways to handle signed integer
  1671. overflow, other than the default way:
  1672. @table @option
  1673. @item -fwrapv
  1674. Make signed integer operations well-defined, like unsigned integer
  1675. operations: they produce the @var{n} low-order bits of the true
  1676. result. The highest of those @var{n} bits is the sign bit of the
  1677. result. With @option{-fwrapv}, these out-of-range operations are not
  1678. considered overflow, so (strictly speaking) integer overflow never
  1679. happens.
  1680. The option @option{-fwrapv} enables some optimizations based on the
  1681. defined values of out-of-range results. In GCC 8, it disables
  1682. optimizations that are based on assuming signed integer operations
  1683. will not overflow.
  1684. @item -ftrapv
  1685. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1686. This terminates the program unless the program handles the signal.
  1687. @xref{Signals}.
  1688. @end table
  1689. One other option is useful for finding where overflow occurs:
  1690. @ignore
  1691. @item -fno-strict-overflow
  1692. Disable optimizations that are based on assuming signed integer
  1693. operations will not overflow.
  1694. @end ignore
  1695. @table @option
  1696. @item -fsanitize=signed-integer-overflow
  1697. Output a warning message at run time when signed integer overflow
  1698. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1699. This takes priority over @option{-ftrapv}.
  1700. @end table
  1701. @node Mixed Mode
  1702. @section Mixed-Mode Arithmetic
  1703. Mixing integers and floating-point numbers in a basic arithmetic
  1704. operation converts the integers automatically to floating point.
  1705. In most cases, this gives exactly the desired results.
  1706. But sometimes it matters precisely where the conversion occurs.
  1707. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1708. as an integer, then converts the sum to floating point for the
  1709. multiplication. If the addition causes an overflow, that is not
  1710. equivalent to converting each integer to floating point and then
  1711. adding the two floating point numbers. You can get the latter result
  1712. by explicitly converting the integers, as in @code{((double) i +
  1713. (double) j) * 2.0}. @xref{Explicit Type Conversion}.
  1714. @c Eggert's report
  1715. Adding or multiplying several values, including some integers and some
  1716. floating point, performs the operations left to right. Thus, @code{3.0 +
  1717. i + j} converts @code{i} to floating point, then adds 3.0, then
  1718. converts @code{j} to floating point and adds that. You can specify a
  1719. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1720. and @code{j} first and then adds that sum (converted to floating
  1721. point) to 3.0. In this respect, C differs from other languages, such
  1722. as Fortran.
  1723. @node Division and Remainder
  1724. @section Division and Remainder
  1725. @cindex remainder operator
  1726. @cindex modulus
  1727. @cindex operator, remainder
  1728. Division of integers in C rounds the result to an integer. The result
  1729. is always rounded towards zero.
  1730. @example
  1731. 16 / 3 @result{} 5
  1732. -16 / 3 @result{} -5
  1733. 16 / -3 @result{} -5
  1734. -16 / -3 @result{} 5
  1735. @end example
  1736. @noindent
  1737. To get the corresponding remainder, use the @samp{%} operator:
  1738. @example
  1739. 16 % 3 @result{} 1
  1740. -16 % 3 @result{} -1
  1741. 16 % -3 @result{} 1
  1742. -16 % -3 @result{} -1
  1743. @end example
  1744. @noindent
  1745. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1746. From the rounded quotient and the remainder, you can reconstruct
  1747. the dividend, like this:
  1748. @example
  1749. int
  1750. original_dividend (int divisor, int quotient, int remainder)
  1751. @{
  1752. return divisor * quotient + remainder;
  1753. @}
  1754. @end example
  1755. To do unrounded division, use floating point. If only one operand is
  1756. floating point, @samp{/} converts the other operand to floating
  1757. point.
  1758. @example
  1759. 16.0 / 3 @result{} 5.333333333333333
  1760. 16 / 3.0 @result{} 5.333333333333333
  1761. 16.0 / 3.0 @result{} 5.333333333333333
  1762. 16 / 3 @result{} 5
  1763. @end example
  1764. The remainder operator @samp{%} is not allowed for floating-point
  1765. operands, because it is not needed. The concept of remainder makes
  1766. sense for integers because the result of division of integers has to
  1767. be an integer. For floating point, the result of division is a
  1768. floating-point number, in other words a fraction, which will differ
  1769. from the exact result only by a very small amount.
  1770. There are functions in the standard C library to calculate remainders
  1771. from integral-values division of floating-point numbers.
  1772. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1773. Reference Manual}.
  1774. Integer division overflows in one specific case: dividing the smallest
  1775. negative value for the data type (@pxref{Maximum and Minimum Values})
  1776. by @minus{}1. That's because the correct result, which is the
  1777. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1778. in the same number of bits. On some computers now in use, this always
  1779. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1780. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1781. Division by zero leads to unpredictable results---depending on the
  1782. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1783. produce a numeric result.
  1784. @cindex division by zero
  1785. @cindex zero, division by
  1786. @strong{Watch out:} Make sure the program does not divide by zero. If
  1787. you can't prove that the divisor is not zero, test whether it is zero,
  1788. and skip the division if so.
  1789. @node Numeric Comparisons
  1790. @section Numeric Comparisons
  1791. @cindex numeric comparisons
  1792. @cindex comparisons
  1793. @cindex operators, comparison
  1794. @cindex equal operator
  1795. @cindex not-equal operator
  1796. @cindex less-than operator
  1797. @cindex greater-than operator
  1798. @cindex less-or-equal operator
  1799. @cindex greater-or-equal operator
  1800. @cindex operator, equal
  1801. @cindex operator, not-equal
  1802. @cindex operator, less-than
  1803. @cindex operator, greater-than
  1804. @cindex operator, less-or-equal
  1805. @cindex operator, greater-or-equal
  1806. @cindex truth value
  1807. There are two kinds of comparison operators: @dfn{equality} and
  1808. @dfn{ordering}. Equality comparisons test whether two expressions
  1809. have the same value. The result is a @dfn{truth value}: a number that
  1810. is 1 for ``true'' and 0 for ``false.''
  1811. @example
  1812. a == b /* @r{Test for equal.} */
  1813. a != b /* @r{Test for not equal.} */
  1814. @end example
  1815. The equality comparison is written @code{==} because plain @code{=}
  1816. is the assignment operator.
  1817. Ordering comparisons test which operand is greater or less. Their
  1818. results are truth values. These are the ordering comparisons of C:
  1819. @example
  1820. a < b /* @r{Test for less-than.} */
  1821. a > b /* @r{Test for greater-than.} */
  1822. a <= b /* @r{Test for less-than-or-equal.} */
  1823. a >= b /* @r{Test for greater-than-or-equal.} */
  1824. @end example
  1825. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1826. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1827. mathematics. However, if @code{a} and @code{b} are special floating
  1828. point values (not ordinary numbers), all three can be false.
  1829. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1830. @node Shift Operations
  1831. @section Shift Operations
  1832. @cindex shift operators
  1833. @cindex operators, shift
  1834. @cindex operators, shift
  1835. @cindex shift count
  1836. @dfn{Shifting} an integer means moving the bit values to the left or
  1837. right within the bits of the data type. Shifting is defined only for
  1838. integers. Here's the way to write it:
  1839. @example
  1840. /* @r{Left shift.} */
  1841. 5 << 2 @result{} 20
  1842. /* @r{Right shift.} */
  1843. 5 >> 2 @result{} 1
  1844. @end example
  1845. @noindent
  1846. The left operand is the value to be shifted, and the right operand
  1847. says how many bits to shift it (the @dfn{shift count}). The left
  1848. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1849. operates on a narrow integer type; it's always either @code{int} or
  1850. wider. The result of the shift operation has the same type as the
  1851. promoted left operand.
  1852. @menu
  1853. * Bits Shifted In:: How shifting makes new bits to shift in.
  1854. * Shift Caveats:: Caveats of shift operations.
  1855. * Shift Hacks:: Clever tricks with shift operations.
  1856. @end menu
  1857. @node Bits Shifted In
  1858. @subsection Shifting Makes New Bits
  1859. A shift operation shifts towards one end of the number and has to
  1860. generate new bits at the other end.
  1861. Shifting left one bit must generate a new least significant bit. It
  1862. always brings in zero there. It is equivalent to multiplying by the
  1863. appropriate power of 2. For example,
  1864. @example
  1865. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1866. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1867. @end example
  1868. The meaning of shifting right depends on whether the data type is
  1869. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1870. data type, it performs ``arithmetic shift,'' which keeps the number's
  1871. sign unchanged by duplicating the sign bit. For an unsigned data
  1872. type, it performs ``logical shift,'' which always shifts in zeros at
  1873. the most significant bit.
  1874. In both cases, shifting right one bit is division by two, rounding
  1875. towards negative infinity. For example,
  1876. @example
  1877. (unsigned) 19 >> 2 @result{} 4
  1878. (unsigned) 20 >> 2 @result{} 5
  1879. (unsigned) 21 >> 2 @result{} 5
  1880. @end example
  1881. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1882. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1883. zero.
  1884. The shift count must be zero or greater. Shifting by a negative
  1885. number of bits gives machine-dependent results.
  1886. @node Shift Caveats
  1887. @subsection Caveats for Shift Operations
  1888. @strong{Warning:} If the shift count is greater than or equal to the
  1889. width in bits of the promoted first operand, the results are
  1890. machine-dependent. Logically speaking, the ``correct'' value would be
  1891. either @minus{}1 (for right shift of a negative number) or 0 (in all other
  1892. cases), but the actual result is whatever the machine's shift
  1893. instruction does in that case. So unless you can prove that the
  1894. second operand is not too large, write code to check it at run time.
  1895. @strong{Warning:} Never rely on how the shift operators relate in
  1896. precedence to other arithmetic binary operators. Programmers don't
  1897. remember these precedences, and won't understand the code. Always use
  1898. parentheses to explicitly specify the nesting, like this:
  1899. @example
  1900. a + (b << 5) /* @r{Shift first, then add.} */
  1901. (a + b) << 5 /* @r{Add first, then shift.} */
  1902. @end example
  1903. Note: according to the C standard, shifting of signed values isn't
  1904. guaranteed to work properly when the value shifted is negative, or
  1905. becomes negative during the operation of shifting left. However, only
  1906. pedants have a reason to be concerned about this; only computers with
  1907. strange shift instructions could plausibly do this wrong. In GNU C,
  1908. the operation always works as expected,
  1909. @node Shift Hacks
  1910. @subsection Shift Hacks
  1911. You can use the shift operators for various useful hacks. For
  1912. example, given a date specified by day of the month @code{d}, month
  1913. @code{m}, and year @code{y}, you can store the entire date in a single
  1914. integer @code{date}:
  1915. @example
  1916. unsigned int d = 12;
  1917. unsigned int m = 6;
  1918. unsigned int y = 1983;
  1919. unsigned int date = ((y << 4) + m) << 5) + d;
  1920. @end example
  1921. @noindent
  1922. To extract the original day, month, and year out of
  1923. @code{date}, use a combination of shift and remainder.
  1924. @example
  1925. d = date % 32;
  1926. m = (date >> 5) % 16;
  1927. y = date >> 9;
  1928. @end example
  1929. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1930. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1931. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1932. multiplication, since negating a value is equivalent to multiplying it
  1933. by @minus{}1.
  1934. @node Bitwise Operations
  1935. @section Bitwise Operations
  1936. @cindex bitwise operators
  1937. @cindex operators, bitwise
  1938. @cindex negation, bitwise
  1939. @cindex conjunction, bitwise
  1940. @cindex disjunction, bitwise
  1941. Bitwise operators operate on integers, treating each bit independently.
  1942. They are not allowed for floating-point types.
  1943. The examples in this section use binary constants, starting with
  1944. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1945. of type @code{int}.
  1946. @table @code
  1947. @item ~@code{a}
  1948. Unary operator for bitwise negation; this changes each bit of
  1949. @code{a} from 1 to 0 or from 0 to 1.
  1950. @example
  1951. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1952. ~0 @result{} 0b11111111111111111111111111111111
  1953. ~0b11111111111111111111111111111111 @result{} 0
  1954. ~ (-1) @result{} 0
  1955. @end example
  1956. It is useful to remember that @code{~@var{x} + 1} equals
  1957. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1958. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1959. as @var{x}.
  1960. @item @code{a} & @code{b}
  1961. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1962. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1963. @example
  1964. 0b10101010 & 0b11001100 @result{} 0b10001000
  1965. @end example
  1966. @item @code{a} | @code{b}
  1967. Binary operator for bitwise ``or'' (``inclusive or'' or
  1968. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1969. either @code{a} or @code{b}.
  1970. @example
  1971. 0b10101010 | 0b11001100 @result{} 0b11101110
  1972. @end example
  1973. @item @code{a} ^ @code{b}
  1974. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1975. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1976. @example
  1977. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1978. @end example
  1979. @end table
  1980. To understand the effect of these operators on signed integers, keep
  1981. in mind that all modern computers use two's-complement representation
  1982. (@pxref{Integer Representations}) for negative integers. This means
  1983. that the highest bit of the number indicates the sign; it is 1 for a
  1984. negative number and 0 for a positive number. In a negative number,
  1985. the value in the other bits @emph{increases} as the number gets closer
  1986. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1987. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1988. @strong{Warning:} C defines a precedence ordering for the bitwise
  1989. binary operators, but you should never rely on it. You should
  1990. never rely on how bitwise binary operators relate in precedence to the
  1991. arithmetic and shift binary operators. Other programmers don't
  1992. remember this precedence ordering, so always use parentheses to
  1993. explicitly specify the nesting.
  1994. For example, suppose @code{offset} is an integer that specifies
  1995. the offset within shared memory of a table, except that its bottom few
  1996. bits (@code{LOWBITS} says how many) are special flags. Here's
  1997. how to get just that offset and add it to the base address.
  1998. @example
  1999. shared_mem_base + (offset & (-1 << LOWBITS))
  2000. @end example
  2001. Thanks to the outer set of parentheses, we don't need to know whether
  2002. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  2003. set, we don't need to know whether @samp{&} has higher precedence than
  2004. @samp{<<}. But we can rely on all unary operators to have higher
  2005. precedence than any binary operator, so we don't need parentheses
  2006. around the left operand of @samp{<<}.
  2007. @node Assignment Expressions
  2008. @chapter Assignment Expressions
  2009. @cindex assignment expressions
  2010. @cindex operators, assignment
  2011. As a general concept in programming, an @dfn{assignment} is a
  2012. construct that stores a new value into a place where values can be
  2013. stored---for instance, in a variable. Such places are called
  2014. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  2015. An assignment in C is an expression because it has a value; we call
  2016. it an @dfn{assignment expression}. A simple assignment looks like
  2017. @example
  2018. @var{lvalue} = @var{value-to-store}
  2019. @end example
  2020. @noindent
  2021. We say it assigns the value of the expression @var{value-to-store} to
  2022. the location @var{lvalue}, or that it stores @var{value-to-store}
  2023. there. You can think of the ``l'' in ``lvalue'' as standing for
  2024. ``left,'' since that's what you put on the left side of the assignment
  2025. operator.
  2026. However, that's not the only way to use an lvalue, and not all lvalues
  2027. can be assigned to. To use the lvalue in the left side of an
  2028. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2029. not declared with the type qualifier @code{const} (@pxref{const}).
  2030. The value of the assignment expression is that of @var{lvalue} after
  2031. the new value is stored in it. This means you can use an assignment
  2032. inside other expressions. Assignment operators are right-associative
  2033. so that
  2034. @example
  2035. x = y = z = 0;
  2036. @end example
  2037. @noindent
  2038. is equivalent to
  2039. @example
  2040. x = (y = (z = 0));
  2041. @end example
  2042. This is the only useful way for them to associate;
  2043. the other way,
  2044. @example
  2045. ((x = y) = z) = 0;
  2046. @end example
  2047. @noindent
  2048. would be invalid since an assignment expression such as @code{x = y}
  2049. is not valid as an lvalue.
  2050. @strong{Warning:} Write parentheses around an assignment if you nest
  2051. it inside another expression, unless that is a conditional expression,
  2052. or comma-separated series, or another assignment.
  2053. @menu
  2054. * Simple Assignment:: The basics of storing a value.
  2055. * Lvalues:: Expressions into which a value can be stored.
  2056. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2057. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2058. an lvalue's contents.
  2059. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2060. * Assignment in Subexpressions:: How to avoid ambiguity.
  2061. * Write Assignments Separately:: Write assignments as separate statements.
  2062. @end menu
  2063. @node Simple Assignment
  2064. @section Simple Assignment
  2065. @cindex simple assignment
  2066. @cindex assignment, simple
  2067. A @dfn{simple assignment expression} computes the value of the right
  2068. operand and stores it into the lvalue on the left. Here is a simple
  2069. assignment expression that stores 5 in @code{i}:
  2070. @example
  2071. i = 5
  2072. @end example
  2073. @noindent
  2074. We say that this is an @dfn{assignment to} the variable @code{i} and
  2075. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2076. because it is an expression (so it has a value). Adding a semicolon
  2077. at the end would make it a statement (@pxref{Expression Statement}).
  2078. Here is another example of a simple assignment expression. Its
  2079. operands are not simple, but the kind of assignment done here is
  2080. simple assignment.
  2081. @example
  2082. x[foo ()] = y + 6
  2083. @end example
  2084. A simple assignment with two different numeric data types converts the
  2085. right operand value to the lvalue's type, if possible. It can convert
  2086. any numeric type to any other numeric type.
  2087. Simple assignment is also allowed on some non-numeric types: pointers
  2088. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2089. unions (@pxref{Unions}).
  2090. @strong{Warning:} Assignment is not allowed on arrays because
  2091. there are no array values in C; C variables can be arrays, but these
  2092. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2093. Arrays}.
  2094. @xref{Assignment Type Conversions}, for the complete rules about data
  2095. types used in assignments.
  2096. @node Lvalues
  2097. @section Lvalues
  2098. @cindex lvalues
  2099. An expression that identifies a memory space that holds a value is
  2100. called an @dfn{lvalue}, because it is a location that can hold a value.
  2101. The standard kinds of lvalues are:
  2102. @itemize @bullet
  2103. @item
  2104. A variable.
  2105. @item
  2106. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2107. unary @samp{*}.
  2108. @item
  2109. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2110. the structure value is an lvalue.
  2111. @item
  2112. A structure field reference using @samp{->}. This is always an lvalue
  2113. since @samp{->} implies pointer dereference.
  2114. @item
  2115. A union alternative reference (@pxref{Unions}), on the same conditions
  2116. as for structure fields.
  2117. @item
  2118. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2119. is an lvalue.
  2120. @end itemize
  2121. If an expression's outermost operation is any other operator, that
  2122. expression is not an lvalue. Thus, the variable @code{x} is an
  2123. lvalue, but @code{x + 0} is not, even though these two expressions
  2124. compute the same value (assuming @code{x} is a number).
  2125. An array can be an lvalue (the rules above determine whether it is
  2126. one), but using the array in an expression converts it automatically
  2127. to a pointer to the first element. The result of this conversion is
  2128. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2129. use @code{a} by itself as the left operand of an assignment. But you
  2130. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2131. lvalue since @code{a} is an lvalue.
  2132. @node Modifying Assignment
  2133. @section Modifying Assignment
  2134. @cindex modifying assignment
  2135. @cindex assignment, modifying
  2136. You can abbreviate the common construct
  2137. @example
  2138. @var{lvalue} = @var{lvalue} + @var{expression}
  2139. @end example
  2140. @noindent
  2141. as
  2142. @example
  2143. @var{lvalue} += @var{expression}
  2144. @end example
  2145. This is known as a @dfn{modifying assignment}. For instance,
  2146. @example
  2147. i = i + 5;
  2148. i += 5;
  2149. @end example
  2150. @noindent
  2151. shows two statements that are equivalent. The first uses
  2152. simple assignment; the second uses modifying assignment.
  2153. Modifying assignment works with any binary arithmetic operator. For
  2154. instance, you can subtract something from an lvalue like this,
  2155. @example
  2156. @var{lvalue} -= @var{expression}
  2157. @end example
  2158. @noindent
  2159. or multiply it by a certain amount like this,
  2160. @example
  2161. @var{lvalue} *= @var{expression}
  2162. @end example
  2163. @noindent
  2164. or shift it by a certain amount like this.
  2165. @example
  2166. @var{lvalue} <<= @var{expression}
  2167. @var{lvalue} >>= @var{expression}
  2168. @end example
  2169. In most cases, this feature adds no power to the language, but it
  2170. provides substantial convenience. Also, when @var{lvalue} contains
  2171. code that has side effects, the simple assignment performs those side
  2172. effects twice, while the modifying assignment performs them once. For
  2173. instance,
  2174. @example
  2175. x[foo ()] = x[foo ()] + 5;
  2176. @end example
  2177. @noindent
  2178. calls @code{foo} twice, and it could return different values each
  2179. time. If @code{foo ()} returns 1 the first time and 3 the second
  2180. time, then the effect could be to add @code{x[3]} and 5 and store the
  2181. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2182. result in @code{x[3]}. We don't know which of the two it will do,
  2183. because C does not specify which call to @code{foo} is computed first.
  2184. Such a statement is not well defined, and shouldn't be used.
  2185. By contrast,
  2186. @example
  2187. x[foo ()] += 5;
  2188. @end example
  2189. @noindent
  2190. is well defined: it calls @code{foo} only once to determine which
  2191. element of @code{x} to adjust, and it adjusts that element by adding 5
  2192. to it.
  2193. @node Increment/Decrement
  2194. @section Increment and Decrement Operators
  2195. @cindex increment operator
  2196. @cindex decrement operator
  2197. @cindex operator, increment
  2198. @cindex operator, decrement
  2199. @cindex preincrement expression
  2200. @cindex predecrement expression
  2201. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2202. @dfn{decrement} operators. When used on a numeric value, they add or
  2203. subtract 1. We don't consider them assignments, but they are
  2204. equivalent to assignments.
  2205. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2206. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2207. and the result becomes the expression's value. For instance,
  2208. @example
  2209. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2210. int
  2211. main (void)
  2212. @{
  2213. int i = 5;
  2214. printf ("%d\n", i);
  2215. printf ("%d\n", ++i);
  2216. printf ("%d\n", i);
  2217. return 0;
  2218. @}
  2219. @end example
  2220. @noindent
  2221. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2222. increments @code{i} from 5 to 6, and has the value 6, so the output
  2223. from @code{printf} on that line says @samp{6}.
  2224. Using @samp{--} instead, for predecrement,
  2225. @example
  2226. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2227. int
  2228. main (void)
  2229. @{
  2230. int i = 5;
  2231. printf ("%d\n", i);
  2232. printf ("%d\n", --i);
  2233. printf ("%d\n", i);
  2234. return 0;
  2235. @}
  2236. @end example
  2237. @noindent
  2238. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2239. again @samp{4}.
  2240. @node Postincrement/Postdecrement
  2241. @section Postincrement and Postdecrement
  2242. @cindex postincrement expression
  2243. @cindex postdecrement expression
  2244. @cindex operator, postincrement
  2245. @cindex operator, postdecrement
  2246. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2247. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2248. increments or decrements it. Thus, the value of @code{i++} is the same
  2249. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2250. little later.'' This is called @dfn{postincrement} or
  2251. @dfn{postdecrement}.
  2252. For example,
  2253. @example
  2254. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2255. int
  2256. main (void)
  2257. @{
  2258. int i = 5;
  2259. printf ("%d\n", i);
  2260. printf ("%d\n", i++);
  2261. printf ("%d\n", i);
  2262. return 0;
  2263. @}
  2264. @end example
  2265. @noindent
  2266. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2267. has the value 5, which is the value of @code{i} at the time,
  2268. but it increments @code{i} from 5 to 6 just a little later.
  2269. How much later is ``just a little later''? That is flexible. The
  2270. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2271. that means by the end of the statement. @xref{Sequence Points}.
  2272. If a unary operator precedes a postincrement or postincrement expression,
  2273. the increment nests inside:
  2274. @example
  2275. -a++ @r{is equivalent to} -(a++)
  2276. @end example
  2277. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2278. it can't be incremented.
  2279. @node Assignment in Subexpressions
  2280. @section Pitfall: Assignment in Subexpressions
  2281. @cindex assignment in subexpressions
  2282. @cindex subexpressions, assignment in
  2283. In C, the order of computing parts of an expression is not fixed.
  2284. Aside from a few special cases, the operations can be computed in any
  2285. order. If one part of the expression has an assignment to @code{x}
  2286. and another part of the expression uses @code{x}, the result is
  2287. unpredictable because that use might be computed before or after the
  2288. assignment.
  2289. Here's an example of ambiguous code:
  2290. @example
  2291. x = 20;
  2292. printf ("%d %d\n", x, x = 4);
  2293. @end example
  2294. @noindent
  2295. If the second argument, @code{x}, is computed before the third argument,
  2296. @code{x = 4}, the second argument's value will be 20. If they are
  2297. computed in the other order, the second argument's value will be 4.
  2298. Here's one way to make that code unambiguous:
  2299. @example
  2300. y = 20;
  2301. printf ("%d %d\n", y, x = 4);
  2302. @end example
  2303. Here's another way, with the other meaning:
  2304. @example
  2305. x = 4;
  2306. printf ("%d %d\n", x, x);
  2307. @end example
  2308. This issue applies to all kinds of assignments, and to the increment
  2309. and decrement operators, which are equivalent to assignments.
  2310. @xref{Order of Execution}, for more information about this.
  2311. However, it can be useful to write assignments inside an
  2312. @code{if}-condition or @code{while}-test along with logical operators.
  2313. @xref{Logicals and Assignments}.
  2314. @node Write Assignments Separately
  2315. @section Write Assignments in Separate Statements
  2316. It is often convenient to write an assignment inside an
  2317. @code{if}-condition, but that can reduce the readability of the
  2318. program. Here's an example of what to avoid:
  2319. @example
  2320. if (x = advance (x))
  2321. @r{@dots{}}
  2322. @end example
  2323. The idea here is to advance @code{x} and test if the value is nonzero.
  2324. However, readers might miss the fact that it uses @samp{=} and not
  2325. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2326. inside a condition is a common error, so GNU C can give warnings when
  2327. @samp{=} appears in a way that suggests it's an error.
  2328. It is much clearer to write the assignment as a separate statement, like this:
  2329. @example
  2330. x = advance (x);
  2331. if (x != 0)
  2332. @r{@dots{}}
  2333. @end example
  2334. @noindent
  2335. This makes it unmistakably clear that @code{x} is assigned a new value.
  2336. Another method is to use the comma operator (@pxref{Comma Operator}),
  2337. like this:
  2338. @example
  2339. if (x = advance (x), x != 0)
  2340. @r{@dots{}}
  2341. @end example
  2342. @noindent
  2343. However, putting the assignment in a separate statement is usually clearer
  2344. unless the assignment is very short, because it reduces nesting.
  2345. @node Execution Control Expressions
  2346. @chapter Execution Control Expressions
  2347. @cindex execution control expressions
  2348. @cindex expressions, execution control
  2349. This chapter describes the C operators that combine expressions to
  2350. control which of those expressions execute, or in which order.
  2351. @menu
  2352. * Logical Operators:: Logical conjunction, disjunction, negation.
  2353. * Logicals and Comparison:: Logical operators with comparison operators.
  2354. * Logicals and Assignments:: Assignments with logical operators.
  2355. * Conditional Expression:: An if/else construct inside expressions.
  2356. * Comma Operator:: Build a sequence of subexpressions.
  2357. @end menu
  2358. @node Logical Operators
  2359. @section Logical Operators
  2360. @cindex logical operators
  2361. @cindex operators, logical
  2362. @cindex conjunction operator
  2363. @cindex disjunction operator
  2364. @cindex negation operator, logical
  2365. The @dfn{logical operators} combine truth values, which are normally
  2366. represented in C as numbers. Any expression with a numeric value is a
  2367. valid truth value: zero means false, and any other value means true.
  2368. A pointer type is also meaningful as a truth value; a null pointer
  2369. (which is zero) means false, and a non-null pointer means true
  2370. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2371. or 0 and has type @code{int} (@pxref{Integer Types}).
  2372. The logical operators are used mainly in the condition of an @code{if}
  2373. statement, or in the end test in a @code{for} statement or
  2374. @code{while} statement (@pxref{Statements}). However, they are valid
  2375. in any context where an integer-valued expression is allowed.
  2376. @table @samp
  2377. @item ! @var{exp}
  2378. Unary operator for logical ``not.'' The value is 1 (true) if
  2379. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2380. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2381. function call, you should write parentheses around it.
  2382. @item @var{left} && @var{right}
  2383. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2384. @var{right}. If both of the operands are true, the @samp{&&} expression
  2385. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2386. gives the value 0 (false). If @var{left} yields a false value,
  2387. that determines the overall result, so @var{right} is not computed.
  2388. @item @var{left} || @var{right}
  2389. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2390. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2391. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2392. gives the value 0 (false). If @var{left} yields a true value,
  2393. that determines the overall result, so @var{right} is not computed.
  2394. @end table
  2395. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2396. and @samp{||}. When you use them together, always use parentheses to
  2397. specify explicitly how they nest, as shown here:
  2398. @example
  2399. if ((r != 0 && x % r == 0)
  2400. ||
  2401. (s != 0 && x % s == 0))
  2402. @end example
  2403. @node Logicals and Comparison
  2404. @section Logical Operators and Comparisons
  2405. The most common thing to use inside the logical operators is a
  2406. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2407. precedence than comparison operators and arithmetic operators, so we
  2408. can write expressions like this without parentheses and get the
  2409. nesting that is natural: two comparison operations that must both be
  2410. true.
  2411. @example
  2412. if (r != 0 && x % r == 0)
  2413. @end example
  2414. @noindent
  2415. This example also shows how it is useful that @samp{&&} guarantees to
  2416. skip the right operand if the left one turns out false. Because of
  2417. that, this code never tries to divide by zero.
  2418. This is equivalent:
  2419. @example
  2420. if (r && x % r == 0)
  2421. @end example
  2422. @noindent
  2423. A truth value is simply a number, so using @code{r} as a truth value
  2424. tests whether it is nonzero. But @code{r}'s meaning as en expression
  2425. is not a truth value---it is a number to divide by. So it is better
  2426. style to write the explicit @code{!= 0}.
  2427. Here's another equivalent way to write it:
  2428. @example
  2429. if (!(r == 0) && x % r == 0)
  2430. @end example
  2431. @noindent
  2432. This illustrates the unary @samp{!} operator, and the need to
  2433. write parentheses around its operand.
  2434. @node Logicals and Assignments
  2435. @section Logical Operators and Assignments
  2436. There are cases where assignments nested inside the condition can
  2437. actually make a program @emph{easier} to read. Here is an example
  2438. using a hypothetical type @code{list} which represents a list; it
  2439. tests whether the list has at least two links, using hypothetical
  2440. functions, @code{nonempty} which is true if the argument is a nonempty
  2441. list, and @code{list_next} which advances from one list link to the
  2442. next. We assume that a list is never a null pointer, so that the
  2443. assignment expressions are always ``true.''
  2444. @example
  2445. if (nonempty (list)
  2446. && (temp1 = list_next (list))
  2447. && nonempty (temp1)
  2448. && (temp2 = list_next (temp1)))
  2449. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2450. @end example
  2451. @noindent
  2452. Here we take advantage of the @samp{&&} operator to avoid executing
  2453. the rest of the code if a call to @code{nonempty} returns ``false.'' The
  2454. only natural place to put the assignments is among those calls.
  2455. It would be possible to rewrite this as several statements, but that
  2456. could make it much more cumbersome. On the other hand, when the test
  2457. is even more complex than this one, splitting it into multiple
  2458. statements might be necessary for clarity.
  2459. If an empty list is a null pointer, we can dispense with calling
  2460. @code{nonempty}:
  2461. @example
  2462. if ((temp1 = list_next (list))
  2463. && (temp2 = list_next (temp1)))
  2464. @r{@dots{}}
  2465. @end example
  2466. @node Conditional Expression
  2467. @section Conditional Expression
  2468. @cindex conditional expression
  2469. @cindex expression, conditional
  2470. C has a conditional expression that selects one of two expressions
  2471. to compute and get the value from. It looks like this:
  2472. @example
  2473. @var{condition} ? @var{iftrue} : @var{iffalse}
  2474. @end example
  2475. @menu
  2476. * Conditional Rules:: Rules for the conditional operator.
  2477. * Conditional Branches:: About the two branches in a conditional.
  2478. @end menu
  2479. @node Conditional Rules
  2480. @subsection Rules for the Conditional Operator
  2481. The first operand, @var{condition}, should be a value that can be
  2482. compared with zero---a number or a pointer. If it is true (nonzero),
  2483. then the conditional expression computes @var{iftrue} and its value
  2484. becomes the value of the conditional expression. Otherwise the
  2485. conditional expression computes @var{iffalse} and its value becomes
  2486. the value of the conditional expression. The conditional expression
  2487. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2488. of them.
  2489. Here's an example: the absolute value of a number @code{x}
  2490. can be written as @code{(x >= 0 ? x : -x)}.
  2491. @strong{Warning:} The conditional expression operators have rather low
  2492. syntactic precedence. Except when the conditional expression is used
  2493. as an argument in a function call, write parentheses around it. For
  2494. clarity, always write parentheses around it if it extends across more
  2495. than one line.
  2496. Assignment operators and the comma operator (@pxref{Comma Operator})
  2497. have lower precedence than conditional expression operators, so write
  2498. parentheses around those when they appear inside a conditional
  2499. expression. @xref{Order of Execution}.
  2500. @node Conditional Branches
  2501. @subsection Conditional Operator Branches
  2502. @cindex branches of conditional expression
  2503. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2504. conditional.
  2505. The two branches should normally have the same type, but a few
  2506. exceptions are allowed. If they are both numeric types, the
  2507. conditional converts both to their common type (@pxref{Common Type}).
  2508. With pointers (@pxref{Pointers}), the two values can be pointers to
  2509. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2510. result type is a similar pointer whose target type combines all the
  2511. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2512. If one branch has type @code{void *} and the other is a pointer to an
  2513. object (not to a function), the conditional converts the @code{void *}
  2514. branch to the type of the other.
  2515. If one branch is an integer constant with value zero and the other is
  2516. a pointer, the conditional converts zero to the pointer's type.
  2517. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2518. that case, if @var{condition} is nonzero, its value becomes the value of
  2519. the conditional expression, after conversion to the common type.
  2520. Thus,
  2521. @example
  2522. x ? : y
  2523. @end example
  2524. @noindent
  2525. has the value of @code{x} if that is nonzero; otherwise, the value of
  2526. @code{y}.
  2527. @cindex side effect in ?:
  2528. @cindex ?: side effect
  2529. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2530. In that case, writing that expression twice would carry out the side
  2531. effects twice, but writing it once does them just once. For example,
  2532. if we suppose that the function @code{next_element} advances a pointer
  2533. variable to point to the next element in a list and returns the new
  2534. pointer,
  2535. @example
  2536. next_element () ? : default_pointer
  2537. @end example
  2538. @noindent
  2539. is a way to advance the pointer and use its new value if it isn't
  2540. null, but use @code{default_pointer} if that is null. We cannot do
  2541. it this way,
  2542. @example
  2543. next_element () ? next_element () : default_pointer
  2544. @end example
  2545. @noindent
  2546. because that would advance the pointer a second time.
  2547. @node Comma Operator
  2548. @section Comma Operator
  2549. @cindex comma operator
  2550. @cindex operator, comma
  2551. The comma operator stands for sequential execution of expressions.
  2552. The value of the comma expression comes from the last expression in
  2553. the sequence; the previous expressions are computed only for their
  2554. side effects. It looks like this:
  2555. @example
  2556. @var{exp1}, @var{exp2} @r{@dots{}}
  2557. @end example
  2558. @noindent
  2559. You can bundle any number of expressions together this way, by putting
  2560. commas between them.
  2561. @menu
  2562. * Uses of Comma:: When to use the comma operator.
  2563. * Clean Comma:: Clean use of the comma operator.
  2564. * Avoid Comma:: When to not use the comma operator.
  2565. @end menu
  2566. @node Uses of Comma
  2567. @subsection The Uses of the Comma Operator
  2568. With commas, you can put several expressions into a place that
  2569. requires just one expression---for example, in the header of a
  2570. @code{for} statement. This statement
  2571. @example
  2572. for (i = 0, j = 10, k = 20; i < n; i++)
  2573. @end example
  2574. @noindent
  2575. contains three assignment expressions, to initialize @code{i}, @code{j}
  2576. and @code{k}. The syntax of @code{for} requires just one expression
  2577. for initialization; to include three assignments, we use commas to
  2578. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2579. 20}. This technique is also useful in the loop-advance expression,
  2580. the last of the three inside the @code{for} parentheses.
  2581. In the @code{for} statement and the @code{while} statement
  2582. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2583. effect before the loop-exit test. For example,
  2584. @example
  2585. while (printf ("At the test, x = %d\n", x), x != 0)
  2586. @end example
  2587. @node Clean Comma
  2588. @subsection Clean Use of the Comma Operator
  2589. Always write parentheses around a series of comma operators, except
  2590. when it is at top level in an expression statement, or within the
  2591. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2592. statement (@pxref{Statements}). For instance, in
  2593. @example
  2594. for (i = 0, j = 10, k = 20; i < n; i++)
  2595. @end example
  2596. @noindent
  2597. the commas between the assignments are clear because they are between
  2598. a parenthesis and a semicolon.
  2599. The arguments in a function call are also separated by commas, but that is
  2600. not an instance of the comma operator. Note the difference between
  2601. @example
  2602. foo (4, 5, 6)
  2603. @end example
  2604. @noindent
  2605. which passes three arguments to @code{foo} and
  2606. @example
  2607. foo ((4, 5, 6))
  2608. @end example
  2609. @noindent
  2610. which uses the comma operator and passes just one argument
  2611. (with value 6).
  2612. @strong{Warning:} don't use the comma operator around an argument
  2613. of a function unless it makes the code more readable. When you do so,
  2614. don't put part of another argument on the same line. Instead, add a
  2615. line break to make the parentheses around the comma operator easier to
  2616. see, like this.
  2617. @example
  2618. foo ((mumble (x, y), frob (z)),
  2619. *p)
  2620. @end example
  2621. @node Avoid Comma
  2622. @subsection When Not to Use the Comma Operator
  2623. You can use a comma in any subexpression, but in most cases it only
  2624. makes the code confusing, and it is clearer to raise all but the last
  2625. of the comma-separated expressions to a higher level. Thus, instead
  2626. of this:
  2627. @example
  2628. x = (y += 4, 8);
  2629. @end example
  2630. @noindent
  2631. it is much clearer to write this:
  2632. @example
  2633. y += 4, x = 8;
  2634. @end example
  2635. @noindent
  2636. or this:
  2637. @example
  2638. y += 4;
  2639. x = 8;
  2640. @end example
  2641. Use commas only in the cases where there is no clearer alternative
  2642. involving multiple statements.
  2643. By contrast, don't hesitate to use commas in the expansion in a macro
  2644. definition. The trade-offs of code clarity are different in that
  2645. case, because the @emph{use} of the macro may improve overall clarity
  2646. so much that the ugliness of the macro's @emph{definition} is a small
  2647. price to pay. @xref{Macros}.
  2648. @node Binary Operator Grammar
  2649. @chapter Binary Operator Grammar
  2650. @cindex binary operator grammar
  2651. @cindex grammar, binary operator
  2652. @cindex operator precedence
  2653. @cindex precedence, operator
  2654. @cindex left-associative
  2655. @dfn{Binary operators} are those that take two operands, one
  2656. on the left and one on the right.
  2657. All the binary operators in C are syntactically left-associative.
  2658. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2659. @var{op} b) @var{op} c}}. However, the only operators you should
  2660. repeat in this way without parentheses are @samp{+}, @samp{-},
  2661. @samp{*} and @samp{/}, because those cases are clear from algebra. So
  2662. it is OK to write @code{a + b + c} or @code{a - b - c}, but never
  2663. @code{a == b == c} or @code{a % b % c}. For those operators, use
  2664. explicit parentheses to show how the operations nest.
  2665. Each C operator has a @dfn{precedence}, which is its rank in the
  2666. grammatical order of the various operators. The operators with the
  2667. highest precedence grab adjoining operands first; these expressions
  2668. then become operands for operators of lower precedence.
  2669. The precedence order of operators in C is fully specified, so any
  2670. combination of operations leads to a well-defined nesting. We state
  2671. only part of the full precedence ordering here because it is bad
  2672. practice for C code to depend on the other cases. For cases not
  2673. specified in this chapter, always use parentheses to make the nesting
  2674. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2675. remembering anything about the C precedence order beyond what's stated
  2676. here. I studied the full precedence table to write the parser, and
  2677. promptly forgot it again. If you need to look up the full precedence order
  2678. to understand some C code, fix the code with parentheses so nobody else
  2679. needs to do that.}
  2680. You can depend on this subsequence of the precedence ordering
  2681. (stated from highest precedence to lowest):
  2682. @enumerate
  2683. @item
  2684. Component access (@samp{.} and @samp{->}).
  2685. @item
  2686. Unary prefix operators.
  2687. @item
  2688. Unary postfix operators.
  2689. @item
  2690. Multiplication, division, and remainder (they have the same precedence).
  2691. @item
  2692. Addition and subtraction (they have the same precedence).
  2693. @item
  2694. Comparisons---but watch out!
  2695. @item
  2696. Logical operators @samp{&&} and @samp{||}---but watch out!
  2697. @item
  2698. Conditional expression with @samp{?} and @samp{:}.
  2699. @item
  2700. Assignments.
  2701. @item
  2702. Sequential execution (the comma operator, @samp{,}).
  2703. @end enumerate
  2704. Two of the lines in the above list say ``but watch out!'' That means
  2705. that the line covers operators with subtly different precedence.
  2706. Never depend on the grammar of C to decide how two comparisons nest;
  2707. instead, always use parentheses to specify their nesting.
  2708. You can let several @samp{&&} operators associate, or several
  2709. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2710. and @samp{||} nest with each other. @xref{Logical Operators}.
  2711. There is one other precedence ordering that code can depend on:
  2712. @enumerate
  2713. @item
  2714. Unary postfix operators.
  2715. @item
  2716. Bitwise and shift operators---but watch out!
  2717. @item
  2718. Conditional expression with @samp{?} and @samp{:}.
  2719. @end enumerate
  2720. The caveat for bitwise and shift operators is like that for logical
  2721. operators: you can let multiple uses of one bitwise operator
  2722. associate, but always use parentheses to control nesting of dissimilar
  2723. operators.
  2724. These lists do not specify any precedence ordering between the bitwise
  2725. and shift operators of the second list and the binary operators above
  2726. conditional expressions in the first list. When they come together,
  2727. parenthesize them. @xref{Bitwise Operations}.
  2728. @node Order of Execution
  2729. @chapter Order of Execution
  2730. @cindex order of execution
  2731. The order of execution of a C program is not always obvious, and not
  2732. necessarily predictable. This chapter describes what you can count on.
  2733. @menu
  2734. * Reordering of Operands:: Operations in C are not necessarily computed
  2735. in the order they are written.
  2736. * Associativity and Ordering:: Some associative operations are performed
  2737. in a particular order; others are not.
  2738. * Sequence Points:: Some guarantees about the order of operations.
  2739. * Postincrement and Ordering:: Ambiguous execution order with postincrement.
  2740. * Ordering of Operands:: Evaluation order of operands
  2741. and function arguments.
  2742. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2743. only if it has no impact on program results.
  2744. @end menu
  2745. @node Reordering of Operands
  2746. @section Reordering of Operands
  2747. @cindex ordering of operands
  2748. @cindex reordering of operands
  2749. @cindex operand execution ordering
  2750. The C language does not necessarily carry out operations within an
  2751. expression in the order they appear in the code. For instance, in
  2752. this expression,
  2753. @example
  2754. foo () + bar ()
  2755. @end example
  2756. @noindent
  2757. @code{foo} might be called first or @code{bar} might be called first.
  2758. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2759. results can be unpredictable.
  2760. The unpredictable order of computation of subexpressions also makes a
  2761. difference when one of them contains an assignment. We already saw
  2762. this example of bad code,
  2763. @example
  2764. x = 20;
  2765. printf ("%d %d\n", x, x = 4);
  2766. @end example
  2767. @noindent
  2768. in which the second argument, @code{x}, has a different value
  2769. depending on whether it is computed before or after the assignment in
  2770. the third argument.
  2771. @node Associativity and Ordering
  2772. @section Associativity and Ordering
  2773. @cindex associativity and ordering
  2774. An associative binary operator, such as @code{+}, when used repeatedly
  2775. can combine any number of operands. The operands' values may be
  2776. computed in any order.
  2777. If the values are integers and overflow can be ignored, they may be
  2778. combined in any order. Thus, given four functions that return
  2779. @code{unsigned int}, calling them and adding their results as here
  2780. @example
  2781. (foo () + bar ()) + (baz () + quux ())
  2782. @end example
  2783. @noindent
  2784. may add up the results in any order.
  2785. By contrast, arithmetic on signed integers, in which overflow is significant,
  2786. is not always associative (@pxref{Integer Overflow}). Thus, the
  2787. additions must be done in the order specified, obeying parentheses and
  2788. left-association. That means computing @code{(foo () + bar ())} and
  2789. @code{(baz () + quux ())} first (in either order), then adding the
  2790. two.
  2791. The same applies to arithmetic on floating-point values, since that
  2792. too is not really associative. However, the GCC option
  2793. @option{-funsafe-math-optimizations} allows the compiler to change the
  2794. order of calculation when an associative operation (associative in
  2795. exact mathematics) combines several operands. The option takes effect
  2796. when compiling a module (@pxref{Compilation}). Changing the order
  2797. of association can enable the program to pipeline the floating point
  2798. operations.
  2799. In all these cases, the four function calls can be done in any order.
  2800. There is no right or wrong about that.
  2801. @node Sequence Points
  2802. @section Sequence Points
  2803. @cindex sequence points
  2804. @cindex full expression
  2805. There are some points in the code where C makes limited guarantees
  2806. about the order of operations. These are called @dfn{sequence
  2807. points}. Here is where they occur:
  2808. @itemize @bullet
  2809. @item
  2810. At the end of a @dfn{full expression}; that is to say, an expression
  2811. that is not part of a larger expression. All side effects specified
  2812. by that expression are carried out before execution moves
  2813. on to subsequent code.
  2814. @item
  2815. At the end of the first operand of certain operators: @samp{,},
  2816. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2817. that expression are carried out before any execution of the
  2818. next operand.
  2819. The commas that separate arguments in a function call are @emph{not}
  2820. comma operators, and they do not create sequence points. The rule
  2821. for function arguments and the rule for operands are different
  2822. (@pxref{Ordering of Operands}).
  2823. @item
  2824. Just before calling a function. All side effects specified by the
  2825. argument expressions are carried out before calling the function.
  2826. If the function to be called is not constant---that is, if it is
  2827. computed by an expression---all side effects in that expression are
  2828. carried out before calling the function.
  2829. @end itemize
  2830. The ordering imposed by a sequence point applies locally to a limited
  2831. range of code, as stated above in each case. For instance, the
  2832. ordering imposed by the comma operator does not apply to code outside
  2833. the operands of that comma operator. Thus, in this code,
  2834. @example
  2835. (x = 5, foo (x)) + x * x
  2836. @end example
  2837. @noindent
  2838. the sequence point of the comma operator orders @code{x = 5} before
  2839. @code{foo (x)}, but @code{x * x} could be computed before or after
  2840. them.
  2841. @node Postincrement and Ordering
  2842. @section Postincrement and Ordering
  2843. @cindex postincrement and ordering
  2844. @cindex ordering and postincrement
  2845. The ordering requirements for the postincrement and postdecrement
  2846. operations (@pxref{Postincrement/Postdecrement}) are loose: those side
  2847. effects must happen ``a little later,'' before the next sequence
  2848. point. That still leaves room for various orders that give different
  2849. results. In this expression,
  2850. @example
  2851. z = x++ - foo ()
  2852. @end example
  2853. @noindent
  2854. it's unpredictable whether @code{x} gets incremented before or after
  2855. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2856. it might see the old value or it might see the incremented value.
  2857. In this perverse expression,
  2858. @example
  2859. x = x++
  2860. @end example
  2861. @noindent
  2862. @code{x} will certainly be incremented but the incremented value may
  2863. be replaced with the old value. That's because the incrementation and
  2864. the assignment may occur in either oder. If the incrementation of
  2865. @code{x} occurs after the assignment to @code{x}, the incremented
  2866. value will remain in place. But if the incrementation happens first,
  2867. the assignment will put the not-yet-incremented value back into
  2868. @code{x}, so the expression as a whole will leave @code{x} unchanged.
  2869. The conclusion: @strong{avoid such expressions}. Take care, when you
  2870. use postincrement and postdecrement, that the specific expression you
  2871. use is not ambiguous as to order of execution.
  2872. @node Ordering of Operands
  2873. @section Ordering of Operands
  2874. @cindex ordering of operands
  2875. @cindex operand ordering
  2876. Operands and arguments can be computed in any order, but there are limits to
  2877. this intermixing in GNU C:
  2878. @itemize @bullet
  2879. @item
  2880. The operands of a binary arithmetic operator can be computed in either
  2881. order, but they can't be intermixed: one of them has to come first,
  2882. followed by the other. Any side effects in the operand that's computed
  2883. first are executed before the other operand is computed.
  2884. @item
  2885. That applies to assignment operators too, except that, in simple assignment,
  2886. the previous value of the left operand is unused.
  2887. @item
  2888. The arguments in a function call can be computed in any order, but
  2889. they can't be intermixed. Thus, one argument is fully computed, then
  2890. another, and so on until they have all been done. Any side effects in
  2891. one argument are executed before computation of another argument
  2892. begins.
  2893. @end itemize
  2894. These rules don't cover side effects caused by postincrement and
  2895. postdecrement operators---those can be deferred up to the next
  2896. sequence point.
  2897. If you want to get pedantic, the fact is that GCC can reorder the
  2898. computations in many other ways provided that it doesn't alter the result
  2899. of running the program. However, because it doesn't alter the result
  2900. of running the program, it is negligible, unless you are concerned
  2901. with the values in certain variables at various times as seen by other
  2902. processes. In those cases, you should use @code{volatile} to prevent
  2903. optimizations that would make them behave strangely. @xref{volatile}.
  2904. @node Optimization and Ordering
  2905. @section Optimization and Ordering
  2906. @cindex optimization and ordering
  2907. @cindex ordering and optimization
  2908. Sequence points limit the compiler's freedom to reorder operations
  2909. arbitrarily, but optimizations can still reorder them if the compiler
  2910. concludes that this won't alter the results. Thus, in this code,
  2911. @example
  2912. x++;
  2913. y = z;
  2914. x++;
  2915. @end example
  2916. @noindent
  2917. there is a sequence point after each statement, so the code is
  2918. supposed to increment @code{x} once before the assignment to @code{y}
  2919. and once after. However, incrementing @code{x} has no effect on
  2920. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2921. the code could be optimized into this:
  2922. @example
  2923. y = z;
  2924. x += 2;
  2925. @end example
  2926. Normally that has no effect except to make the program faster. But
  2927. there are special situations where it can cause trouble due to things
  2928. that the compiler cannot know about, such as shared memory. To limit
  2929. optimization in those places, use the @code{volatile} type qualifier
  2930. (@pxref{volatile}).
  2931. @node Primitive Types
  2932. @chapter Primitive Data Types
  2933. @cindex primitive types
  2934. @cindex types, primitive
  2935. This chapter describes all the primitive data types of C---that is,
  2936. all the data types that aren't built up from other types. They
  2937. include the types @code{int} and @code{double} that we've already covered.
  2938. @menu
  2939. * Integer Types:: Description of integer types.
  2940. * Floating-Point Data Types:: Description of floating-point types.
  2941. * Complex Data Types:: Description of complex number types.
  2942. * The Void Type:: A type indicating no value at all.
  2943. * Other Data Types:: A brief summary of other types.
  2944. * Type Designators:: Referring to a data type abstractly.
  2945. @end menu
  2946. These types are all made up of bytes (@pxref{Storage}).
  2947. @node Integer Types
  2948. @section Integer Data Types
  2949. @cindex integer types
  2950. @cindex types, integer
  2951. Here we describe all the integer types and their basic
  2952. characteristics. @xref{Integers in Depth}, for more information about
  2953. the bit-level integer data representations and arithmetic.
  2954. @menu
  2955. * Basic Integers:: Overview of the various kinds of integers.
  2956. * Signed and Unsigned Types:: Integers can either hold both negative and
  2957. non-negative values, or only non-negative.
  2958. * Narrow Integers:: When to use smaller integer types.
  2959. * Integer Conversion:: Casting a value from one integer type
  2960. to another.
  2961. * Boolean Type:: An integer type for boolean values.
  2962. * Integer Variations:: Sizes of integer types can vary
  2963. across platforms.
  2964. @end menu
  2965. @node Basic Integers
  2966. @subsection Basic Integers
  2967. @findex char
  2968. @findex int
  2969. @findex short int
  2970. @findex long int
  2971. @findex long long int
  2972. Integer data types in C can be signed or unsigned. An unsigned type
  2973. can represent only positive numbers and zero. A signed type can
  2974. represent both positive and negative numbers, in a range spread almost
  2975. equally on both sides of zero.
  2976. Aside from signedness, the integer data types vary in size: how many
  2977. bytes long they are. The size determines the range of integer values
  2978. the type can hold.
  2979. Here's a list of the signed integer data types, with the sizes they
  2980. have on most computers. Each has a corresponding unsigned type; see
  2981. @ref{Signed and Unsigned Types}.
  2982. @table @code
  2983. @item signed char
  2984. One byte (8 bits). This integer type is used mainly for integers that
  2985. represent characters, usually as elements of arrays or fields of other
  2986. data structures.
  2987. @item short
  2988. @itemx short int
  2989. Two bytes (16 bits).
  2990. @item int
  2991. Four bytes (32 bits).
  2992. @item long
  2993. @itemx long int
  2994. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2995. platform. Typically it is 32 bits on 32-bit computers
  2996. and 64 bits on 64-bit computers, but there are exceptions.
  2997. @item long long
  2998. @itemx long long int
  2999. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  3000. incorporated into standard C as of ISO C99.
  3001. @end table
  3002. You can omit @code{int} when you use @code{long} or @code{short}.
  3003. This is harmless and customary.
  3004. @node Signed and Unsigned Types
  3005. @subsection Signed and Unsigned Types
  3006. @cindex signed types
  3007. @cindex unsigned types
  3008. @cindex types, signed
  3009. @cindex types, unsigned
  3010. @findex signed
  3011. @findex unsigned
  3012. An unsigned integer type can represent only positive numbers and zero.
  3013. A signed type can represent both positive and negative number, in a
  3014. range spread almost equally on both sides of zero. For instance,
  3015. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  3016. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  3017. these types holds 256 different possible values, since they are both 8
  3018. bits wide.
  3019. Write @code{signed} or @code{unsigned} before the type keyword to
  3020. specify a signed or an unsigned type. However, the integer types
  3021. other than @code{char} are signed by default; with them, @code{signed}
  3022. is a no-op.
  3023. Plain @code{char} may be signed or unsigned; this depends on the
  3024. compiler, the machine in use, and its operating system.
  3025. In many programs, it makes no difference whether @code{char} is
  3026. signed. When it does matter, don't leave it to chance; write
  3027. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  3028. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  3029. Arctic Char. When my meal arrived, I noted that the chef had not
  3030. signed it. So I complained, ``This char is unsigned---I wanted a
  3031. signed char!'' Or rather, I would have said this if I had thought of
  3032. it fast enough.}
  3033. @node Narrow Integers
  3034. @subsection Narrow Integers
  3035. The types that are narrower than @code{int} are rarely used for
  3036. ordinary variables---we declare them @code{int} instead. This is
  3037. because C converts those narrower types to @code{int} for any
  3038. arithmetic. There is literally no reason to declare a local variable
  3039. @code{char}, for instance.
  3040. In particular, if the value is really a character, you should declare
  3041. the variable @code{int}. Not @code{char}! Using that narrow type can
  3042. force the compiler to truncate values for conversion, which is a
  3043. waste. Furthermore, some functions return either a character value,
  3044. or @minus{}1 for ``no character.'' Using @code{int} makes it possible
  3045. to distinguish @minus{}1 from a character by sign.
  3046. The narrow integer types are useful as parts of other objects, such as
  3047. arrays and structures. Compare these array declarations, whose sizes
  3048. on 32-bit processors are shown:
  3049. @example
  3050. signed char ac[1000]; /* @r{1000 bytes} */
  3051. short as[1000]; /* @r{2000 bytes} */
  3052. int ai[1000]; /* @r{4000 bytes} */
  3053. long long all[1000]; /* @r{8000 bytes} */
  3054. @end example
  3055. In addition, character strings must be made up of @code{char}s,
  3056. because that's what all the standard library string functions expect.
  3057. Thus, array @code{ac} could be used as a character string, but the
  3058. others could not be.
  3059. @node Integer Conversion
  3060. @subsection Conversion among Integer Types
  3061. C converts between integer types implicitly in many situations. It
  3062. converts the narrow integer types, @code{char} and @code{short}, to
  3063. @code{int} whenever they are used in arithmetic. Assigning a new
  3064. value to an integer variable (or other lvalue) converts the value to
  3065. the variable's type.
  3066. You can also convert one integer type to another explicitly with a
  3067. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3068. The process of conversion to a wider type is straightforward: the
  3069. value is unchanged. The only exception is when converting a negative
  3070. value (in a signed type, obviously) to a wider unsigned type. In that
  3071. case, the result is a positive value with the same bits
  3072. (@pxref{Integers in Depth}).
  3073. @cindex truncation
  3074. Converting to a narrower type, also called @dfn{truncation}, involves
  3075. discarding some of the value's bits. This is not considered overflow
  3076. (@pxref{Integer Overflow}) because loss of significant bits is a
  3077. normal consequence of truncation. Likewise for conversion between
  3078. signed and unsigned types of the same width.
  3079. More information about conversion for assignment is in
  3080. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3081. see @ref{Argument Promotions}.
  3082. @node Boolean Type
  3083. @subsection Boolean Type
  3084. @cindex boolean type
  3085. @cindex type, boolean
  3086. @findex bool
  3087. The unsigned integer type @code{bool} holds truth values: its possible
  3088. values are 0 and 1. Converting any nonzero value to @code{bool}
  3089. results in 1. For example:
  3090. @example
  3091. bool a = 0;
  3092. bool b = 1;
  3093. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3094. @end example
  3095. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3096. the header file @file{stdbool.h}.
  3097. @node Integer Variations
  3098. @subsection Integer Variations
  3099. The integer types of C have standard @emph{names}, but what they
  3100. @emph{mean} varies depending on the kind of platform in use:
  3101. which kind of computer, which operating system, and which compiler.
  3102. It may even depend on the compiler options used.
  3103. Plain @code{char} may be signed or unsigned; this depends on the
  3104. platform, too. Even for GNU C, there is no general rule.
  3105. In theory, all of the integer types' sizes can vary. @code{char} is
  3106. always considered one ``byte'' for C, but it is not necessarily an
  3107. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3108. specifies only that none of these types is narrower than the ones
  3109. above it in the list in @ref{Basic Integers}, and that @code{short}
  3110. has at least 16 bits.
  3111. It is possible that in the future GNU C will support platforms where
  3112. @code{int} is 64 bits long. In practice, however, on today's real
  3113. computers, there is little variation; you can rely on the table
  3114. given previously (@pxref{Basic Integers}).
  3115. To be completely sure of the size of an integer type,
  3116. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3117. Their corresponding unsigned types add @samp{u} at the front:
  3118. @code{uint16_t}, @code{uint32_t} and @code{uint64_t}.
  3119. To define all these types, include the header file @file{stdint.h}.
  3120. The GNU C Compiler can compile for some embedded controllers that use two
  3121. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3122. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3123. 32 bits. These processors can't support an ordinary operating system
  3124. (they may have their own specialized operating systems), and most C
  3125. programs do not try to support them.
  3126. @node Floating-Point Data Types
  3127. @section Floating-Point Data Types
  3128. @cindex floating-point types
  3129. @cindex types, floating-point
  3130. @findex double
  3131. @findex float
  3132. @findex long double
  3133. @dfn{Floating point} is the binary analogue of scientific notation:
  3134. internally it represents a number as a fraction and a binary exponent;
  3135. the value is that fraction multiplied by the specified power of 2.
  3136. (The C standard nominally permits other bases, but in GNU C the base
  3137. is always 2.)
  3138. @c ???
  3139. For instance, to represent 6, the fraction would be 0.75 and the
  3140. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3141. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3142. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3143. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3144. @minus{}1 as the exponent.
  3145. These binary exponents are used by machine instructions. You can
  3146. write a floating-point constant this way if you wish, using
  3147. hexadecimal; but normally we write floating-point numbers in decimal (base 10).
  3148. @xref{Floating Constants}.
  3149. C has three floating-point data types:
  3150. @table @code
  3151. @item double
  3152. ``Double-precision'' floating point, which uses 64 bits. This is the
  3153. normal floating-point type, and modern computers normally do
  3154. their floating-point computations in this type, or some wider type.
  3155. Except when there is a special reason to do otherwise, this is the
  3156. type to use for floating-point values.
  3157. @item float
  3158. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3159. for floating-point values stored in structures and arrays, to save
  3160. space when the full precision of @code{double} is not needed. In
  3161. addition, single-precision arithmetic is faster on some computers, and
  3162. occasionally that is useful. But not often---most programs don't use
  3163. the type @code{float}.
  3164. C would be cleaner if @code{float} were the name of the type we
  3165. use for most floating-point values; however, for historical reasons,
  3166. that's not so.
  3167. @item long double
  3168. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3169. precision, depending on the machine in use. On some machines, which
  3170. have no floating-point format wider than @code{double}, this is
  3171. equivalent to @code{double}.
  3172. @end table
  3173. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3174. Point in Depth}, for more information.
  3175. @node Complex Data Types
  3176. @section Complex Data Types
  3177. @cindex complex numbers
  3178. @cindex types, complex
  3179. @cindex @code{_Complex} keyword
  3180. @cindex @code{__complex__} keyword
  3181. @findex _Complex
  3182. @findex __complex__
  3183. Complex numbers can include both a real part and an imaginary part.
  3184. The numeric constants covered above have real-numbered values. An
  3185. imaginary-valued constant is an ordinary real-valued constant followed
  3186. by @samp{i}.
  3187. To declare numeric variables as complex, use the @code{_Complex}
  3188. keyword.@footnote{For compatibility with older versions of GNU C, the
  3189. keyword @code{__complex__} is also allowed. Going forward, however,
  3190. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3191. standard C complex data types are floating point,
  3192. @example
  3193. _Complex float foo;
  3194. _Complex double bar;
  3195. _Complex long double quux;
  3196. @end example
  3197. @noindent
  3198. but GNU C supports integer complex types as well.
  3199. Since @code{_Complex} is a keyword just like @code{float} and
  3200. @code{double} and @code{long}, the keywords can appear in any order,
  3201. but the order shown above seems most logical.
  3202. GNU C supports constants for complex values; for instance, @code{4.0 +
  3203. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3204. @xref{Imaginary Constants}.
  3205. To pull the real and imaginary parts of the number back out, GNU C
  3206. provides the keywords @code{__real__} and @code{__imag__}:
  3207. @example
  3208. _Complex double foo = 4.0 + 3.0i;
  3209. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3210. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3211. @end example
  3212. @noindent
  3213. Standard C does not include these keywords, and instead relies on
  3214. functions defined in @code{complex.h} for accessing the real and
  3215. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3216. @code{creall} extract the real part of a float, double, or long double
  3217. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3218. @code{cimagl} extract the imaginary part.
  3219. @cindex complex conjugation
  3220. GNU C also defines @samp{~} as an operator for complex conjugation,
  3221. which means negating the imaginary part of a complex number:
  3222. @example
  3223. _Complex double foo = 4.0 + 3.0i;
  3224. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3225. @end example
  3226. @noindent
  3227. For standard C compatibility, you can use the appropriate library
  3228. function: @code{conjf}, @code{conj}, or @code{confl}.
  3229. @node The Void Type
  3230. @section The Void Type
  3231. @cindex void type
  3232. @cindex type, void
  3233. @findex void
  3234. The data type @code{void} is a dummy---it allows no operations. It
  3235. really means ``no value at all.'' When a function is meant to return
  3236. no value, we write @code{void} for its return type. Then
  3237. @code{return} statements in that function should not specify a value
  3238. (@pxref{return Statement}). Here's an example:
  3239. @example
  3240. void
  3241. print_if_positive (double x, double y)
  3242. @{
  3243. if (x <= 0)
  3244. return;
  3245. if (y <= 0)
  3246. return;
  3247. printf ("Next point is (%f,%f)\n", x, y);
  3248. @}
  3249. @end example
  3250. A @code{void}-returning function is comparable to what some other
  3251. languages (for instance, Fortran and Pascal) call a ``procedure''
  3252. instead of a ``function.''
  3253. @c ??? Already presented
  3254. @c @samp{%f} in an output template specifies to format a @code{double} value
  3255. @c as a decimal number, using a decimal point if needed.
  3256. @node Other Data Types
  3257. @section Other Data Types
  3258. Beyond the primitive types, C provides several ways to construct new
  3259. data types. For instance, you can define @dfn{pointers}, values that
  3260. represent the addresses of other data (@pxref{Pointers}). You can
  3261. define @dfn{structures}, as in many other languages
  3262. (@pxref{Structures}), and @dfn{unions}, which define multiple ways to
  3263. interpret the contents of the same memory space (@pxref{Unions}).
  3264. @dfn{Enumerations} are collections of named integer codes
  3265. (@pxref{Enumeration Types}).
  3266. @dfn{Array types} in C are used for allocating space for objects,
  3267. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3268. @node Type Designators
  3269. @section Type Designators
  3270. @cindex type designator
  3271. Some C constructs require a way to designate a specific data type
  3272. independent of any particular variable or expression which has that
  3273. type. The way to do this is with a @dfn{type designator}. The
  3274. constructs that need one include casts (@pxref{Explicit Type
  3275. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3276. We also use type designators to talk about the type of a value in C,
  3277. so you will see many type designators in this manual. When we say,
  3278. ``The value has type @code{int},'' @code{int} is a type designator.
  3279. To make the designator for any type, imagine a variable declaration
  3280. for a variable of that type and delete the variable name and the final
  3281. semicolon.
  3282. For example, to designate the type of full-word integers, we start
  3283. with the declaration for a variable @code{foo} with that type,
  3284. which is this:
  3285. @example
  3286. int foo;
  3287. @end example
  3288. @noindent
  3289. Then we delete the variable name @code{foo} and the semicolon, leaving
  3290. @code{int}---exactly the keyword used in such a declaration.
  3291. Therefore, the type designator for this type is @code{int}.
  3292. What about long unsigned integers? From the declaration
  3293. @example
  3294. unsigned long int foo;
  3295. @end example
  3296. @noindent
  3297. we determine that the designator is @code{unsigned long int}.
  3298. Following this procedure, the designator for any primitive type is
  3299. simply the set of keywords which specifies that type in a declaration.
  3300. The same is true for compound types such as structures, unions, and
  3301. enumerations.
  3302. Designators for pointer types do follow the rule of deleting the
  3303. variable name and semicolon, but the result is not so simple.
  3304. @xref{Pointer Type Designators}, as part of the chapter about
  3305. pointers. @xref{Array Type Designators}), for designators for array
  3306. types.
  3307. To understand what type a designator stands for, imagine a variable
  3308. name inserted into the right place in the designator to make a valid
  3309. declaration. What type would that variable be declared as? That is the
  3310. type the designator designates.
  3311. @node Constants
  3312. @chapter Constants
  3313. @cindex constants
  3314. A @dfn{constant} is an expression that stands for a specific value by
  3315. explicitly representing the desired value. C allows constants for
  3316. numbers, characters, and strings. We have already seen numeric and
  3317. string constants in the examples.
  3318. @menu
  3319. * Integer Constants:: Literal integer values.
  3320. * Integer Const Type:: Types of literal integer values.
  3321. * Floating Constants:: Literal floating-point values.
  3322. * Imaginary Constants:: Literal imaginary number values.
  3323. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3324. * Character Constants:: Literal character values.
  3325. * String Constants:: Literal string values.
  3326. * UTF-8 String Constants:: Literal UTF-8 string values.
  3327. * Unicode Character Codes:: Unicode characters represented
  3328. in either UTF-16 or UTF-32.
  3329. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3330. * Wide String Constants:: Literal string values made up of
  3331. 16- or 32-bit characters.
  3332. @end menu
  3333. @node Integer Constants
  3334. @section Integer Constants
  3335. @cindex integer constants
  3336. @cindex constants, integer
  3337. An integer constant consists of a number to specify the value,
  3338. followed optionally by suffix letters to specify the data type.
  3339. The simplest integer constants are numbers written in base 10
  3340. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3341. constant cannot start with the character @samp{0} (zero) because
  3342. that makes the constant octal.
  3343. You can get the effect of a negative integer constant by putting a
  3344. minus sign at the beginning. In grammatical terms, that is an
  3345. arithmetic expression rather than a constant, but it behaves just like
  3346. a true constant.
  3347. Integer constants can also be written in octal (base 8), hexadecimal
  3348. (base 16), or binary (base 2). An octal constant starts with the
  3349. character @samp{0} (zero), followed by any number of octal digits
  3350. (@samp{0} to @samp{7}):
  3351. @example
  3352. 0 // @r{zero}
  3353. 077 // @r{63}
  3354. 0403 // @r{259}
  3355. @end example
  3356. @noindent
  3357. Pedantically speaking, the constant @code{0} is an octal constant, but
  3358. we can think of it as decimal; it has the same value either way.
  3359. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3360. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3361. through @samp{f} in upper or lower case):
  3362. @example
  3363. 0xff // @r{255}
  3364. 0XA0 // @r{160}
  3365. 0xffFF // @r{65535}
  3366. @end example
  3367. @cindex binary integer constants
  3368. A binary constant starts with @samp{0b} (upper or lower case) followed
  3369. by bits (each represented by the characters @samp{0} or @samp{1}):
  3370. @example
  3371. 0b101 // @r{5}
  3372. @end example
  3373. @noindent
  3374. Binary constants are a GNU C extension, not part of the C standard.
  3375. Sometimes a space is needed after an integer constant to avoid
  3376. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3377. @node Integer Const Type
  3378. @section Integer Constant Data Types
  3379. @cindex integer constant data types
  3380. @cindex constant data types, integer
  3381. @cindex types of integer constants
  3382. The type of an integer constant is normally @code{int}, if the value
  3383. fits in that type, but here are the complete rules. The type
  3384. of an integer constant is the first one in this sequence that can
  3385. properly represent the value,
  3386. @enumerate
  3387. @item
  3388. @code{int}
  3389. @item
  3390. @code{unsigned int}
  3391. @item
  3392. @code{long int}
  3393. @item
  3394. @code{unsigned long int}
  3395. @item
  3396. @code{long long int}
  3397. @item
  3398. @code{unsigned long long int}
  3399. @end enumerate
  3400. @noindent
  3401. and that isn't excluded by the following rules.
  3402. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3403. first two types (non-@code{long}).
  3404. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3405. first four types (non-@code{long long}).
  3406. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3407. the signed types.
  3408. Otherwise, if the constant is decimal (not binary, octal, or
  3409. hexadecimal), that excludes the unsigned types.
  3410. @c ### This said @code{unsigned int} is excluded.
  3411. @c ### See 17 April 2016
  3412. Here are some examples of the suffixes.
  3413. @example
  3414. 3000000000u // @r{three billion as @code{unsigned int}.}
  3415. 0LL // @r{zero as a @code{long long int}.}
  3416. 0403l // @r{259 as a @code{long int}.}
  3417. @end example
  3418. Suffixes in integer constants are rarely used. When the precise type
  3419. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3420. Type Conversion}).
  3421. @xref{Integer Types}.
  3422. @node Floating Constants
  3423. @section Floating-Point Constants
  3424. @cindex floating-point constants
  3425. @cindex constants, floating-point
  3426. A floating-point constant must have either a decimal point, an
  3427. exponent-of-ten, or both; they distinguish it from an integer
  3428. constant.
  3429. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3430. value follows. It is always written as a decimal number; it can
  3431. optionally start with a sign. The exponent @var{n} means to multiply
  3432. the constant's value by ten to the @var{n}th power.
  3433. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3434. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3435. writing a floating-point number whose value is 1500. They are all
  3436. equivalent.
  3437. Here are more examples with decimal points:
  3438. @example
  3439. 1.0
  3440. 1000.
  3441. 3.14159
  3442. .05
  3443. .0005
  3444. @end example
  3445. For each of them, here are some equivalent constants written with
  3446. exponents:
  3447. @example
  3448. 1e0, 1.0000e0
  3449. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3450. 3.14159e0
  3451. 5e-2, .0005e+2, 5E-2, .0005E2
  3452. .05e-2
  3453. @end example
  3454. A floating-point constant normally has type @code{double}. You can
  3455. force it to type @code{float} by adding @samp{f} or @samp{F}
  3456. at the end. For example,
  3457. @example
  3458. 3.14159f
  3459. 3.14159e0f
  3460. 1000.f
  3461. 100E1F
  3462. .0005f
  3463. .05e-2f
  3464. @end example
  3465. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3466. to type @code{long double}.
  3467. You can use exponents in hexadecimal floating constants, but since
  3468. @samp{e} would be interpreted as a hexadecimal digit, the character
  3469. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3470. The exponent in a hexadecimal floating constant is an optionally signed
  3471. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3472. multiply into the number.
  3473. Here are some examples:
  3474. @example
  3475. @group
  3476. 0xAp2 // @r{40 in decimal}
  3477. 0xAp-1 // @r{5 in decimal}
  3478. 0x2.0Bp4 // @r{16.75 decimal}
  3479. 0xE.2p3 // @r{121 decimal}
  3480. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3481. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3482. 0x100p-8 // @r{1}
  3483. 0x10p-4 // @r{1}
  3484. 0x1p+4 // @r{16}
  3485. 0x1p+8 // @r{256}
  3486. @end group
  3487. @end example
  3488. @xref{Floating-Point Data Types}.
  3489. @node Imaginary Constants
  3490. @section Imaginary Constants
  3491. @cindex imaginary constants
  3492. @cindex complex constants
  3493. @cindex constants, imaginary
  3494. A complex number consists of a real part plus an imaginary part. (You
  3495. may omit one part if it is zero.) This section explains how to write
  3496. numeric constants with imaginary values. By adding these to ordinary
  3497. real-valued numeric constants, we can make constants with complex
  3498. values.
  3499. The simple way to write an imaginary-number constant is to attach the
  3500. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3501. floating-point constant. For example, @code{2.5fi} has type
  3502. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3503. The four alternative suffix letters are all equivalent.
  3504. @cindex _Complex_I
  3505. The other way to write an imaginary constant is to multiply a real
  3506. constant by @code{_Complex_I}, which represents the imaginary number
  3507. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3508. this clunky method is needed.
  3509. To write a complex constant with a nonzero real part and a nonzero
  3510. imaginary part, write the two separately and add them, like this:
  3511. @example
  3512. 4.0 + 3.0i
  3513. @end example
  3514. @noindent
  3515. That gives the value 4 + 3i, with type @code{_Complex double}.
  3516. Such a sum can include multiple real constants, or none. Likewise, it
  3517. can include multiple imaginary constants, or none. For example:
  3518. @example
  3519. _Complex double foo, bar, quux;
  3520. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3521. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3522. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3523. @end example
  3524. @xref{Complex Data Types}.
  3525. @node Invalid Numbers
  3526. @section Invalid Numbers
  3527. Some number-like constructs which are not really valid as numeric
  3528. constants are treated as numbers in preprocessing directives. If
  3529. these constructs appear outside of preprocessing, they are erroneous.
  3530. @xref{Preprocessing Tokens}.
  3531. Sometimes we need to insert spaces to separate tokens so that they
  3532. won't be combined into a single number-like construct. For example,
  3533. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3534. constant, so it is a syntax error. If what we want is the three
  3535. tokens @code{@w{0xE + 12}}, we have to insert two spaces as separators.
  3536. @node Character Constants
  3537. @section Character Constants
  3538. @cindex character constants
  3539. @cindex constants, character
  3540. @cindex escape sequence
  3541. A @dfn{character constant} is written with single quotes, as in
  3542. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3543. character that the constant should represent. The constant has type
  3544. @code{int}, and its value is the character code of that character.
  3545. For instance, @code{'a'} represents the character code for the letter
  3546. @samp{a}: 97, that is.
  3547. To put the @samp{'} character (single quote) in the character
  3548. constant, @dfn{escape} it with a backslash (@samp{\}). This character
  3549. constant looks like @code{'\''}. The backslash character here
  3550. functions as an @dfn{escape character}, and such a sequence,
  3551. starting with @samp{\}, is called an @dfn{escape sequence}.
  3552. To put the @samp{\} character (backslash) in the character constant,
  3553. escape it with @samp{\} (another backslash). This character
  3554. constant looks like @code{'\\'}.
  3555. @cindex bell character
  3556. @cindex @samp{\a}
  3557. @cindex backspace
  3558. @cindex @samp{\b}
  3559. @cindex tab (ASCII character)
  3560. @cindex @samp{\t}
  3561. @cindex vertical tab
  3562. @cindex @samp{\v}
  3563. @cindex formfeed
  3564. @cindex @samp{\f}
  3565. @cindex newline
  3566. @cindex @samp{\n}
  3567. @cindex return (ASCII character)
  3568. @cindex @samp{\r}
  3569. @cindex escape (ASCII character)
  3570. @cindex @samp{\e}
  3571. Here are all the escape sequences that represent specific
  3572. characters in a character constant. The numeric values shown are
  3573. the corresponding ASCII character codes, as decimal numbers.
  3574. @example
  3575. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3576. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3577. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3578. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3579. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3580. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3581. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3582. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3583. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3584. '\'' @result{} 39 /* @r{single quote character, @kbd{'}} */
  3585. '\"' @result{} 34 /* @r{double quote character, @kbd{"}} */
  3586. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3587. @end example
  3588. @samp{\e} is a GNU C extension; to stick to standard C, write
  3589. @samp{\33}. (The number after @samp{backslash} is octal.) To specify
  3590. a character constant using decimal, use a cast; for instance,
  3591. @code{(unsigned char) 27}.
  3592. You can also write octal and hex character codes as
  3593. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3594. option here, so octal codes do not need to start with @samp{0}.
  3595. The character constant's value has type @code{int}. However, the
  3596. character code is treated initially as a @code{char} value, which is
  3597. then converted to @code{int}. If the character code is greater than
  3598. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3599. on a platform where the type @code{char} is 8 bits long and signed.
  3600. @node String Constants
  3601. @section String Constants
  3602. @cindex string constants
  3603. @cindex constants, string
  3604. A @dfn{string constant} represents a series of characters. It starts
  3605. with @samp{"} and ends with @samp{"}; in between are the contents of
  3606. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3607. newline in the contents works in string constants as in character
  3608. constants. In a string constant, @samp{'} does not need to be quoted.
  3609. A string constant defines an array of characters which contains the
  3610. specified characters followed by the null character (code 0). Using
  3611. the string constant is equivalent to using the name of an array with
  3612. those contents. In simple cases, where there are no backslash escape
  3613. sequences, the length in bytes of the string constant is one greater
  3614. than the number of characters written in it.
  3615. As with any array in C, using the string constant in an expression
  3616. converts the array to a pointer (@pxref{Pointers}) to the array's
  3617. first element (@pxref{Accessing Array Elements}). This pointer will
  3618. have type @code{char *} because it points to an element of type
  3619. @code{char}. @code{char *} is an example of a type designator for a
  3620. pointer type (@pxref{Pointer Type Designators}). That type is used
  3621. for strings generally, not just the strings expressed as constants
  3622. in a program.
  3623. Thus, the string constant @code{"Foo!"} is almost
  3624. equivalent to declaring an array like this
  3625. @example
  3626. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3627. @end example
  3628. @noindent
  3629. and then using @code{string_array_1} in the program. There
  3630. are two differences, however:
  3631. @itemize @bullet
  3632. @item
  3633. The string constant doesn't define a name for the array.
  3634. @item
  3635. The string constant is probably stored in a read-only area of memory.
  3636. @end itemize
  3637. Newlines are not allowed in the text of a string constant. The motive
  3638. for this prohibition is to catch the error of omitting the closing
  3639. @samp{"}. To put a newline in a constant string, write it as
  3640. @samp{\n} in the string constant.
  3641. A real null character in the source code inside a string constant
  3642. causes a warning. To put a null character in the middle of a string
  3643. constant, write @samp{\0} or @samp{\000}.
  3644. Consecutive string constants are effectively concatenated. Thus,
  3645. @example
  3646. "Fo" "o!" @r{is equivalent to} "Foo!"
  3647. @end example
  3648. This is useful for writing a string containing multiple lines,
  3649. like this:
  3650. @example
  3651. "This message is so long that it needs more than\n"
  3652. "a single line of text. C does not allow a newline\n"
  3653. "to represent itself in a string constant, so we have to\n"
  3654. "write \\n to put it in the string. For readability of\n"
  3655. "the source code, it is advisable to put line breaks in\n"
  3656. "the source where they occur in the contents of the\n"
  3657. "constant.\n"
  3658. @end example
  3659. The sequence of a backslash and a newline is ignored anywhere
  3660. in a C program, and that includes inside a string constant.
  3661. Thus, you can write multi-line string constants this way:
  3662. @example
  3663. "This is another way to put newlines in a string constant\n\
  3664. and break the line after them in the source code."
  3665. @end example
  3666. @noindent
  3667. However, concatenation is the recommended way to do this.
  3668. You can also write perverse string constants like this,
  3669. @example
  3670. "Fo\
  3671. o!"
  3672. @end example
  3673. @noindent
  3674. but don't do that---write it like this instead:
  3675. @example
  3676. "Foo!"
  3677. @end example
  3678. Be careful to avoid passing a string constant to a function that
  3679. modifies the string it receives. The memory where the string constant
  3680. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3681. signal that normally terminates the function (@pxref{Signals}. Even
  3682. worse, the memory may not be read-only. Then the function might
  3683. modify the string constant, thus spoiling the contents of other string
  3684. constants that are supposed to contain the same value and are unified
  3685. by the compiler.
  3686. @node UTF-8 String Constants
  3687. @section UTF-8 String Constants
  3688. @cindex UTF-8 String Constants
  3689. Writing @samp{u8} immediately before a string constant, with no
  3690. intervening space, means to represent that string in UTF-8 encoding as
  3691. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3692. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3693. as multibyte sequences. Here is an example of a UTF-8 constant:
  3694. @example
  3695. u8"A cónstàñt"
  3696. @end example
  3697. This constant occupies 13 bytes plus the terminating null,
  3698. because each of the accented letters is a two-byte sequence.
  3699. Concatenating an ordinary string with a UTF-8 string conceptually
  3700. produces another UTF-8 string. However, if the ordinary string
  3701. contains character codes 128 and up, the results cannot be relied on.
  3702. @node Unicode Character Codes
  3703. @section Unicode Character Codes
  3704. @cindex Unicode character codes
  3705. @cindex universal character names
  3706. You can specify Unicode characters, for individual character constants
  3707. or as part of string constants (@pxref{String Constants}), using
  3708. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3709. hexadecimal Unicode character code. If the code value is too big for
  3710. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3711. Unicode character code. (These codes are called @dfn{universal
  3712. character names}.) For example,
  3713. @example
  3714. \u6C34 /* @r{16-bit code (UTF-16)} */
  3715. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3716. @end example
  3717. @noindent
  3718. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3719. Constants}). For instance,
  3720. @example
  3721. u8"fóó \u6C34 \U0010ABCD"
  3722. @end example
  3723. You can also use them in wide character constants (@pxref{Wide
  3724. Character Constants}), like this:
  3725. @example
  3726. u'\u6C34' /* @r{16-bit code} */
  3727. U'\U0010ABCD' /* @r{32-bit code} */
  3728. @end example
  3729. @noindent
  3730. and in wide string constants (@pxref{Wide String Constants}), like
  3731. this:
  3732. @example
  3733. u"\u6C34\u6C33" /* @r{16-bit code} */
  3734. U"\U0010ABCD" /* @r{32-bit code} */
  3735. @end example
  3736. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3737. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3738. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3739. actually ASCII control characters, and you can specify them with other
  3740. escape sequences (@pxref{Character Constants}).
  3741. @node Wide Character Constants
  3742. @section Wide Character Constants
  3743. @cindex wide character constants
  3744. @cindex constants, wide character
  3745. A @dfn{wide character constant} represents characters with more than 8
  3746. bits of character code. This is an obscure feature that we need to
  3747. document but that you probably won't ever use. If you're just
  3748. learning C, you may as well skip this section.
  3749. The original C wide character constant looks like @samp{L} (upper
  3750. case!) followed immediately by an ordinary character constant (with no
  3751. intervening space). Its data type is @code{wchar_t}, which is an
  3752. alias defined in @file{stddef.h} for one of the standard integer
  3753. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3754. it is 16 bits, these character constants use the UTF-16 form of
  3755. Unicode; if 32 bits, UTF-32.
  3756. There are also Unicode wide character constants which explicitly
  3757. specify the width. These constants start with @samp{u} or @samp{U}
  3758. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3759. character constant, and @samp{U} a 32-bit Unicode wide character
  3760. constant. Their types are, respectively, @code{char16_t} and
  3761. @w{@code{char32_t}}; they are declared in the header file
  3762. @file{uchar.h}. These character constants are valid even if
  3763. @file{uchar.h} is not included, but some uses of them may be
  3764. inconvenient without including it to declare those type names.
  3765. The character represented in a wide character constant can be an
  3766. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3767. are all valid, and they are all equal to @code{'a'}.
  3768. In all three kinds of wide character constants, you can write a
  3769. non-ASCII Unicode character in the constant itself; the constant's
  3770. value is the character's Unicode character code. Or you can specify
  3771. the Unicode character with an escape sequence (@pxref{Unicode
  3772. Character Codes}).
  3773. @node Wide String Constants
  3774. @section Wide String Constants
  3775. @cindex wide string constants
  3776. @cindex constants, wide string
  3777. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3778. characters. They are rarely used; if you're just
  3779. learning C, you may as well skip this section.
  3780. There are three kinds of wide string constants, which differ in the
  3781. data type used for each character in the string. Each wide string
  3782. constant is equivalent to an array of integers, but the data type of
  3783. those integers depends on the kind of wide string. Using the constant
  3784. in an expression will convert the array to a pointer to its first
  3785. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3786. For each kind of wide string constant, we state here what type that
  3787. pointer will be.
  3788. @table @code
  3789. @item char16_t
  3790. This is a 16-bit Unicode wide string constant: each element is a
  3791. 16-bit Unicode character code with type @code{char16_t}, so the string
  3792. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3793. @pxref{Pointer Type Designators}.) The constant is written as
  3794. @samp{u} (which must be lower case) followed (with no intervening
  3795. space) by a string constant with the usual syntax.
  3796. @item char32_t
  3797. This is a 32-bit Unicode wide string constant: each element is a
  3798. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3799. It's written as @samp{U} (which must be upper case) followed (with no
  3800. intervening space) by a string constant with the usual syntax.
  3801. @item wchar_t
  3802. This is the original kind of wide string constant. It's written as
  3803. @samp{L} (which must be upper case) followed (with no intervening
  3804. space) by a string constant with the usual syntax, and the string has
  3805. type @code{wchar_t@ *}.
  3806. The width of the data type @code{wchar_t} depends on the target
  3807. platform, which makes this kind of wide string somewhat less useful
  3808. than the newer kinds.
  3809. @end table
  3810. @code{char16_t} and @code{char32_t} are declared in the header file
  3811. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3812. Consecutive wide string constants of the same kind concatenate, just
  3813. like ordinary string constants. A wide string constant concatenated
  3814. with an ordinary string constant results in a wide string constant.
  3815. You can't concatenate two wide string constants of different kinds.
  3816. In addition, you can't concatenate a wide string constant (of any
  3817. kind) with a UTF-8 string constant.
  3818. @node Type Size
  3819. @chapter Type Size
  3820. @cindex type size
  3821. @cindex size of type
  3822. @findex sizeof
  3823. Each data type has a @dfn{size}, which is the number of bytes
  3824. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3825. a C program, use @code{sizeof}. There are two ways to use it:
  3826. @table @code
  3827. @item sizeof @var{expression}
  3828. This gives the size of @var{expression}, based on its data type. It
  3829. does not calculate the value of @var{expression}, only its size, so if
  3830. @var{expression} includes side effects or function calls, they do not
  3831. happen. Therefore, @code{sizeof} is always a compile-time operation
  3832. that has zero run-time cost.
  3833. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3834. operand of @code{sizeof}.
  3835. For example,
  3836. @example
  3837. double a;
  3838. i = sizeof a + 10;
  3839. @end example
  3840. @noindent
  3841. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3842. Here's how to determine the number of elements in an array
  3843. @code{array}:
  3844. @example
  3845. (sizeof array / sizeof array[0])
  3846. @end example
  3847. @noindent
  3848. The expression @code{sizeof array} gives the size of the array, not
  3849. the size of a pointer to an element. However, if @var{expression} is
  3850. a function parameter that was declared as an array, that
  3851. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3852. the result is the size of that pointer.
  3853. @item sizeof (@var{type})
  3854. This gives the size of @var{type}.
  3855. For example,
  3856. @example
  3857. i = sizeof (double) + 10;
  3858. @end example
  3859. @noindent
  3860. is equivalent to the previous example.
  3861. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3862. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3863. C, which makes adding an integer to a function pointer work as desired
  3864. (@pxref{Pointer Arithmetic}).
  3865. @end table
  3866. @strong{Warning}: When you use @code{sizeof} with a type
  3867. instead of an expression, you must write parentheses around the type.
  3868. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3869. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3870. the cast expression to avoid an ambiguity in the grammar of C@.
  3871. Specifically,
  3872. @example
  3873. sizeof (int) -x
  3874. @end example
  3875. @noindent
  3876. parses as
  3877. @example
  3878. (sizeof (int)) - x
  3879. @end example
  3880. @noindent
  3881. If what you want is
  3882. @example
  3883. sizeof ((int) -x)
  3884. @end example
  3885. @noindent
  3886. you must write it that way, with parentheses.
  3887. The data type of the value of the @code{sizeof} operator is always one
  3888. of the unsigned integer types; which one of those types depends on the
  3889. machine. The header file @code{stddef.h} defines the typedef name
  3890. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3891. Names}.
  3892. @node Pointers
  3893. @chapter Pointers
  3894. @cindex pointers
  3895. Among high-level languages, C is rather low-level, close to the
  3896. machine. This is mainly because it has explicit @dfn{pointers}. A
  3897. pointer value is the numeric address of data in memory. The type of
  3898. data to be found at that address is specified by the data type of the
  3899. pointer itself. Nothing in C can determine the ``correct'' data type
  3900. of data in memory; it can only blindly follow the data type of the
  3901. pointer you use to access the data.
  3902. The unary operator @samp{*} gets the data that a pointer points
  3903. to---this is called @dfn{dereferencing the pointer}. Its value
  3904. always has the type that the pointer points to.
  3905. C also allows pointers to functions, but since there are some
  3906. differences in how they work, we treat them later. @xref{Function
  3907. Pointers}.
  3908. @menu
  3909. * Address of Data:: Using the ``address-of'' operator.
  3910. * Pointer Types:: For each type, there is a pointer type.
  3911. * Pointer Declarations:: Declaring variables with pointer types.
  3912. * Pointer Type Designators:: Designators for pointer types.
  3913. * Pointer Dereference:: Accessing what a pointer points at.
  3914. * Null Pointers:: Pointers which do not point to any object.
  3915. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3916. * Void Pointers:: Totally generic pointers, can cast to any.
  3917. * Pointer Comparison:: Comparing memory address values.
  3918. * Pointer Arithmetic:: Computing memory address values.
  3919. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3920. * Low-Level Pointer Arithmetic:: More about computing memory address values.
  3921. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3922. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3923. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3924. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3925. @end menu
  3926. @node Address of Data
  3927. @section Address of Data
  3928. @cindex address-of operator
  3929. The most basic way to make a pointer is with the ``address-of''
  3930. operator, @samp{&}. Let's suppose we have these variables available:
  3931. @example
  3932. int i;
  3933. double a[5];
  3934. @end example
  3935. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3936. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3937. address of the element 3 of @code{a}. (It is actually the fourth
  3938. element in the array, since the first element has index 0.)
  3939. The address-of operator is unusual because it operates on a place to
  3940. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3941. stored there. (The left argument of a simple assignment is unusual in
  3942. the same way.) You can use it on any lvalue except a bit field
  3943. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3944. Constructors}).
  3945. @node Pointer Types
  3946. @section Pointer Types
  3947. For each data type @var{t}, there is a type for pointers to type
  3948. @var{t}. For these variables,
  3949. @example
  3950. int i;
  3951. double a[5];
  3952. @end example
  3953. @itemize @bullet
  3954. @item
  3955. @code{i} has type @code{int}; we say
  3956. @code{&i} is a ``pointer to @code{int}.''
  3957. @item
  3958. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3959. arrays of five @code{double}s.''
  3960. @item
  3961. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3962. to @code{double}.''
  3963. @end itemize
  3964. @node Pointer Declarations
  3965. @section Pointer-Variable Declarations
  3966. The way to declare that a variable @code{foo} points to type @var{t} is
  3967. @example
  3968. @var{t} *foo;
  3969. @end example
  3970. To remember this syntax, think ``if you dereference @code{foo}, using
  3971. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3972. points to type @var{t}.''
  3973. Thus, we can declare variables that hold pointers to these three
  3974. types, like this:
  3975. @example
  3976. int *ptri; /* @r{Pointer to @code{int}.} */
  3977. double *ptrd; /* @r{Pointer to @code{double}.} */
  3978. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3979. @end example
  3980. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3981. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3982. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3983. @code{double}.'' The parentheses express the point that you would
  3984. dereference it first, then subscript it.
  3985. Contrast the last one with this:
  3986. @example
  3987. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3988. @end example
  3989. @noindent
  3990. Because @samp{*} has lower syntactic precedence than subscripting,
  3991. @samp{double *aptrd[5]} means, ``if you subscript @code{aptrd} by an
  3992. integer less than 5, then dereference it, you get a @code{double}.''
  3993. Therefore, @code{*aptrd[5]} declares an array of pointers, not a
  3994. pointer to an array.
  3995. @node Pointer Type Designators
  3996. @section Pointer-Type Designators
  3997. Every type in C has a designator; you make it by deleting the variable
  3998. name and the semicolon from a declaration (@pxref{Type
  3999. Designators}). Here are the designators for the pointer
  4000. types of the example declarations in the previous section:
  4001. @example
  4002. int * /* @r{Pointer to @code{int}.} */
  4003. double * /* @r{Pointer to @code{double}.} */
  4004. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  4005. @end example
  4006. Remember, to understand what type a designator stands for, imagine the
  4007. corresponding variable declaration with a variable name in it, and
  4008. figure out what type that variable would have. Thus, the type
  4009. designator @code{double (*)[5]} corresponds to the variable declaration
  4010. @code{double (*@var{variable})[5]}. That deciares a pointer variable
  4011. which, when dereferenced, gives an array of 5 @code{double}s.
  4012. So the type designator means, ``pointer to an array of 5 @code{double}s.''
  4013. @node Pointer Dereference
  4014. @section Dereferencing Pointers
  4015. @cindex dereferencing pointers
  4016. @cindex pointer dereferencing
  4017. The main use of a pointer value is to @dfn{dereference it} (access the
  4018. data it points at) with the unary @samp{*} operator. For instance,
  4019. @code{*&i} is the value at @code{i}'s address---which is just
  4020. @code{i}. The two expressions are equivalent, provided @code{&i} is
  4021. valid.
  4022. A pointer-dereference expression whose type is data (not a function)
  4023. is an lvalue.
  4024. Pointers become really useful when we store them somewhere and use
  4025. them later. Here's a simple example to illustrate the practice:
  4026. @example
  4027. @{
  4028. int i;
  4029. int *ptr;
  4030. ptr = &i;
  4031. i = 5;
  4032. @r{@dots{}}
  4033. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  4034. @}
  4035. @end example
  4036. This shows how to declare the variable @code{ptr} as type
  4037. @code{int *} (pointer to @code{int}), store a pointer value into it
  4038. (pointing at @code{i}), and use it later to get the value of the
  4039. object it points at (the value in @code{i}).
  4040. If anyone can provide a useful example which is this basic,
  4041. I would be grateful.
  4042. @node Null Pointers
  4043. @section Null Pointers
  4044. @cindex null pointers
  4045. @cindex pointers, null
  4046. @c ???stdio loads sttddef
  4047. A pointer value can be @dfn{null}, which means it does not point to
  4048. any object. The cleanest way to get a null pointer is by writing
  4049. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4050. also do it by casting 0 to the desired pointer type, as in
  4051. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4052. @xref{Explicit Type Conversion}.)
  4053. You can store a null pointer in any lvalue whose data type
  4054. is a pointer type:
  4055. @example
  4056. char *foo;
  4057. foo = NULL;
  4058. @end example
  4059. These two, if consecutive, can be combined into a declaration with
  4060. initializer,
  4061. @example
  4062. char *foo = NULL;
  4063. @end example
  4064. You can also explicitly cast @code{NULL} to the specific pointer type
  4065. you want---it makes no difference.
  4066. @example
  4067. char *foo;
  4068. foo = (char *) NULL;
  4069. @end example
  4070. To test whether a pointer is null, compare it with zero or
  4071. @code{NULL}, as shown here:
  4072. @example
  4073. if (p != NULL)
  4074. /* @r{@code{p} is not null.} */
  4075. operate (p);
  4076. @end example
  4077. Since testing a pointer for not being null is basic and frequent, all
  4078. but beginners in C will understand the conditional without need for
  4079. @code{!= NULL}:
  4080. @example
  4081. if (p)
  4082. /* @r{@code{p} is not null.} */
  4083. operate (p);
  4084. @end example
  4085. @node Invalid Dereference
  4086. @section Dereferencing Null or Invalid Pointers
  4087. Trying to dereference a null pointer is an error. On most platforms,
  4088. it generally causes a signal, usually @code{SIGSEGV}
  4089. (@pxref{Signals}).
  4090. @example
  4091. char *foo = NULL;
  4092. c = *foo; /* @r{This causes a signal and terminates.} */
  4093. @end example
  4094. @noindent
  4095. Likewise a pointer that has the wrong alignment for the target data type
  4096. (on most types of computer), or points to a part of memory that has
  4097. not been allocated in the process's address space.
  4098. The signal terminates the program, unless the program has arranged to
  4099. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4100. The GNU C Library Reference Manual}).
  4101. However, the signal might not happen if the dereference is optimized
  4102. away. In the example above, if you don't subsequently use the value
  4103. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4104. can prevent such optimization using the @code{volatile} qualifier, as
  4105. shown here:
  4106. @example
  4107. volatile char *p;
  4108. volatile char c;
  4109. c = *p;
  4110. @end example
  4111. You can use this to test whether @code{p} points to unallocated
  4112. memory. Set up a signal handler first, so the signal won't terminate
  4113. the program.
  4114. @node Void Pointers
  4115. @section Void Pointers
  4116. @cindex void pointers
  4117. @cindex pointers, void
  4118. The peculiar type @code{void *}, a pointer whose target type is
  4119. @code{void}, is used often in C@. It represents a pointer to
  4120. we-don't-say-what. Thus,
  4121. @example
  4122. void *numbered_slot_pointer (int);
  4123. @end example
  4124. @noindent
  4125. declares a function @code{numbered_slot_pointer} that takes an
  4126. integer parameter and returns a pointer, but we don't say what type of
  4127. data it points to.
  4128. With type @code{void *}, you can pass the pointer around and test
  4129. whether it is null. However, dereferencing it gives a @code{void}
  4130. value that can't be used (@pxref{The Void Type}). To dereference the
  4131. pointer, first convert it to some other pointer type.
  4132. Assignments convert @code{void *} automatically to any other pointer
  4133. type, if the left operand has a pointer type; for instance,
  4134. @example
  4135. @{
  4136. int *p;
  4137. /* @r{Converts return value to @code{int *}.} */
  4138. p = numbered_slot_pointer (5);
  4139. @r{@dots{}}
  4140. @}
  4141. @end example
  4142. Passing an argument of type @code{void *} for a parameter that has a
  4143. pointer type also converts. For example, supposing the function
  4144. @code{hack} is declared to require type @code{float *} for its
  4145. argument, this will convert the null pointer to that type.
  4146. @example
  4147. /* @r{Declare @code{hack} that way.}
  4148. @r{We assume it is defined somewhere else.} */
  4149. void hack (float *);
  4150. @dots{}
  4151. /* @r{Now call @code{hack}.} */
  4152. @{
  4153. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4154. @r{to @code{float *} to pass it to @code{hack}.} */
  4155. hack (numbered_slot_pointer (5));
  4156. @r{@dots{}}
  4157. @}
  4158. @end example
  4159. You can also convert to another pointer type with an explicit cast
  4160. (@pxref{Explicit Type Conversion}), like this:
  4161. @example
  4162. (int *) numbered_slot_pointer (5)
  4163. @end example
  4164. Here is an example which decides at run time which pointer
  4165. type to convert to:
  4166. @example
  4167. void
  4168. extract_int_or_double (void *ptr, bool its_an_int)
  4169. @{
  4170. if (its_an_int)
  4171. handle_an_int (*(int *)ptr);
  4172. else
  4173. handle_a_double (*(double *)ptr);
  4174. @}
  4175. @end example
  4176. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4177. to type @code{int *}, then dereference it.
  4178. @node Pointer Comparison
  4179. @section Pointer Comparison
  4180. @cindex pointer comparison
  4181. @cindex comparison, pointer
  4182. Two pointer values are equal if they point to the same location, or if
  4183. they are both null. You can test for this with @code{==} and
  4184. @code{!=}. Here's a trivial example:
  4185. @example
  4186. @{
  4187. int i;
  4188. int *p, *q;
  4189. p = &i;
  4190. q = &i;
  4191. if (p == q)
  4192. printf ("This will be printed.\n");
  4193. if (p != q)
  4194. printf ("This won't be printed.\n");
  4195. @}
  4196. @end example
  4197. Ordering comparisons such as @code{>} and @code{>=} operate on
  4198. pointers by converting them to unsigned integers. The C standard says
  4199. the two pointers must point within the same object in memory, but on
  4200. GNU/Linux systems these operations simply compare the numeric values
  4201. of the pointers.
  4202. The pointer values to be compared should in principle have the same type, but
  4203. they are allowed to differ in limited cases. First of all, if the two
  4204. pointers' target types are nearly compatible (@pxref{Compatible
  4205. Types}), the comparison is allowed.
  4206. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4207. the other is another pointer type, the comparison operator converts
  4208. the @code{void *} pointer to the other type so as to compare them.
  4209. (In standard C, this is not allowed if the other type is a function
  4210. pointer type, but it works in GNU C@.)
  4211. Comparison operators also allow comparing the integer 0 with a pointer
  4212. value. This works by converting 0 to a null pointer of the same type
  4213. as the other operand.
  4214. @node Pointer Arithmetic
  4215. @section Pointer Arithmetic
  4216. @cindex pointer arithmetic
  4217. @cindex arithmetic, pointer
  4218. Adding an integer (positive or negative) to a pointer is valid in C@.
  4219. It assumes that the pointer points to an element in an array, and
  4220. advances or retracts the pointer across as many array elements as the
  4221. integer specifies. Here is an example, in which adding a positive
  4222. integer advances the pointer to a later element in the same array.
  4223. @example
  4224. void
  4225. incrementing_pointers ()
  4226. @{
  4227. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4228. int elt0, elt1, elt4;
  4229. int *p = &array[0];
  4230. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4231. elt0 = *p;
  4232. ++p;
  4233. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4234. elt1 = *p;
  4235. p += 3;
  4236. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4237. elt4 = *p;
  4238. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4239. elt0, elt1, elt4);
  4240. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4241. @}
  4242. @end example
  4243. Here's an example where adding a negative integer retracts the pointer
  4244. to an earlier element in the same array.
  4245. @example
  4246. void
  4247. decrementing_pointers ()
  4248. @{
  4249. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4250. int elt0, elt3, elt4;
  4251. int *p = &array[4];
  4252. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4253. elt4 = *p;
  4254. --p;
  4255. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4256. elt3 = *p;
  4257. p -= 3;
  4258. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4259. elt0 = *p;
  4260. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4261. elt0, elt3, elt4);
  4262. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4263. @}
  4264. @end example
  4265. If one pointer value was made by adding an integer to another
  4266. pointer value, it should be possible to subtract the pointer values
  4267. and recover that integer. That works too in C@.
  4268. @example
  4269. void
  4270. subtract_pointers ()
  4271. @{
  4272. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4273. int *p0, *p3, *p4;
  4274. int *p = &array[4];
  4275. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4276. p4 = p;
  4277. --p;
  4278. /* @r{Now @code{p} points at element 3. Save the value.} */
  4279. p3 = p;
  4280. p -= 3;
  4281. /* @r{Now @code{p} points at element 0. Save the value.} */
  4282. p0 = p;
  4283. printf ("%d, %d, %d, %d\n",
  4284. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4285. /* @r{Prints 4, 0, 3, -3.} */
  4286. @}
  4287. @end example
  4288. The addition operation does not know where arrays begin or end in
  4289. memory. All it does is add the integer (multiplied by target object
  4290. size) to the numeric value of the pointer. When the initial pointer
  4291. and the result point into the same array, the result is well-defined.
  4292. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4293. into different memory objects.
  4294. The difference between two pointers has type @code{int}, or
  4295. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4296. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4297. file @file{stddef.h}.
  4298. C defines pointer subtraction to be consistent with pointer-integer
  4299. addition, so that @code{(p3 - p1) + p1} equals @code{p3}, as in
  4300. ordinary algebra. Pointer subtraction works by subtracting
  4301. @code{p1}'s numeric value from @code{p3}'s, and dividing by target
  4302. object size. The two pointer arguments should point into the same
  4303. array.
  4304. In standard C, addition and subtraction are not allowed on @code{void
  4305. *}, since the target type's size is not defined in that case.
  4306. Likewise, they are not allowed on pointers to function types.
  4307. However, these operations work in GNU C, and the ``size of the target
  4308. type'' is taken as 1 byte.
  4309. @node Pointers and Arrays
  4310. @section Pointers and Arrays
  4311. @cindex pointers and arrays
  4312. @cindex arrays and pointers
  4313. The clean way to refer to an array element is
  4314. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4315. same job is to get the address of that element as a pointer, then
  4316. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4317. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4318. pointer to element zero, then increments it with @code{+} to point to
  4319. the desired element, then gets the value from there.
  4320. That pointer-arithmetic construct is the @emph{definition} of square
  4321. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4322. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4323. symmetrically, so one must be a pointer and the other an integer; it
  4324. does not matter which comes first.
  4325. Since indexing with square brackets is defined in terms of addition
  4326. and dereferencing, that too is symmetrical. Thus, you can write
  4327. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4328. would be foolish to write @code{3[array]}, since it has no advantage
  4329. and could confuse people who read the code.
  4330. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4331. @var{b})} requires a pointer, while @code{array[3]} uses an array value
  4332. instead. Why is this valid? The name of the array, when used by
  4333. itself as an expression (other than in @code{sizeof}), stands for a
  4334. pointer to the array's zeroth element. Thus, @code{array + 3}
  4335. converts @code{array} implicitly to @code{&array[0]}, and the result
  4336. is a pointer to element 3, equivalent to @code{&array[3]}.
  4337. Since square brackets are defined in terms of such an addition,
  4338. @code{array[3]} first converts @code{array} to a pointer. That's why
  4339. it works to use an array directly in that construct.
  4340. @node Low-Level Pointer Arithmetic
  4341. @section Pointer Arithmetic at Low-Level
  4342. @cindex pointer arithmetic, low-level
  4343. @cindex low level pointer arithmetic
  4344. The behavior of pointer arithmetic is theoretically defined only when
  4345. the pointer values all point within one object allocated in memory.
  4346. But the addition and subtraction operators can't tell whether the
  4347. pointer values are all within one object. They don't know where
  4348. objects start and end. So what do they really do?
  4349. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4350. address, which is in fact an integer---call it @var{pint}. It treats
  4351. @var{i} as a number of elements of the type that @var{p} points to.
  4352. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4353. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4354. (*@var{p})}. This value is reinterpreted as a pointer of the same
  4355. type as @var{p}.
  4356. If the starting pointer value @var{p} and the result do not point at
  4357. parts of the same object, the operation is not officially legitimate,
  4358. and C code is not ``supposed'' to do it. But you can do it anyway,
  4359. and it gives precisely the results described by the procedure above.
  4360. In some special situations it can do something useful, but non-wizards
  4361. should avoid it.
  4362. Here's a function to offset a pointer value @emph{as if} it pointed to
  4363. an object of any given size, by explicitly performing that calculation:
  4364. @example
  4365. #include <stdint.h>
  4366. void *
  4367. ptr_add (void *p, int i, int objsize)
  4368. @{
  4369. intptr_t p_address = (long) p;
  4370. intptr_t totalsize = i * objsize;
  4371. intptr_t new_address = p_address + totalsize;
  4372. return (void *) new_address;
  4373. @}
  4374. @end example
  4375. @noindent
  4376. @cindex @code{intptr_t}
  4377. This does the same job as @code{@var{p} + @var{i}} with the proper
  4378. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4379. defined in the header file @file{stdint.h}. (In practice, @code{long
  4380. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4381. @node Pointer Increment/Decrement
  4382. @section Pointer Increment and Decrement
  4383. @cindex pointer increment and decrement
  4384. @cindex incrementing pointers
  4385. @cindex decrementing pointers
  4386. The @samp{++} operator adds 1 to a variable. We have seen it for
  4387. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4388. For instance, suppose we have a series of positive integers,
  4389. terminated by a zero, and we want to add them up. Here is a simple
  4390. way to step forward through the array by advancing a pointer.
  4391. @example
  4392. int
  4393. sum_array_till_0 (int *p)
  4394. @{
  4395. int sum = 0;
  4396. for (;;)
  4397. @{
  4398. /* @r{Fetch the next integer.} */
  4399. int next = *p++;
  4400. /* @r{Exit the loop if it's 0.} */
  4401. if (next == 0)
  4402. break;
  4403. /* @r{Add it into running total.} */
  4404. sum += next;
  4405. @}
  4406. return sum;
  4407. @}
  4408. @end example
  4409. @noindent
  4410. The statement @samp{break;} will be explained further on (@pxref{break
  4411. Statement}). Used in this way, it immediately exits the surrounding
  4412. @code{for} statement.
  4413. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4414. takes precedence over a prefix operator. Therefore, it dereferences
  4415. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4416. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4417. pointer, adding 1 to it advances it by the width of the datum it
  4418. points to---in this case, @code{sizeof (int)}. Therefore, each iteration
  4419. of the loop picks up the next integer from the series and puts it into
  4420. @code{next}.
  4421. This @code{for}-loop has no initialization expression since @code{p}
  4422. and @code{sum} are already initialized, has no end-test since the
  4423. @samp{break;} statement will exit it, and needs no expression to
  4424. advance it since that's done within the loop by incrementing @code{p}
  4425. and @code{sum}. Thus, those three expressions after @code{for} are
  4426. left empty.
  4427. Another way to write this function is by keeping the parameter value unchanged
  4428. and using indexing to access the integers in the table.
  4429. @example
  4430. int
  4431. sum_array_till_0_indexing (int *p)
  4432. @{
  4433. int i;
  4434. int sum = 0;
  4435. for (i = 0; ; i++)
  4436. @{
  4437. /* @r{Fetch the next integer.} */
  4438. int next = p[i];
  4439. /* @r{Exit the loop if it's 0.} */
  4440. if (next == 0)
  4441. break;
  4442. /* @r{Add it into running total.} */
  4443. sum += next;
  4444. @}
  4445. return sum;
  4446. @}
  4447. @end example
  4448. In this program, instead of advancing @code{p}, we advance @code{i}
  4449. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4450. i)}.) Either way, it uses the same address to get the next integer.
  4451. It makes no difference in this program whether we write @code{i++} or
  4452. @code{++i}, because the value @emph{of that expression} is not used.
  4453. We use it for its effect, to increment @code{i}.
  4454. The @samp{--} operator also works on pointers; it can be used
  4455. to step backwards through an array, like this:
  4456. @example
  4457. int
  4458. after_last_nonzero (int *p, int len)
  4459. @{
  4460. /* @r{Set up @code{q} to point just after the last array element.} */
  4461. int *q = p + len;
  4462. while (q != p)
  4463. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4464. if (*--q != 0)
  4465. /* @r{Return the index of the element after that nonzero.} */
  4466. return q - p + 1;
  4467. return 0;
  4468. @}
  4469. @end example
  4470. That function returns the length of the nonzero part of the
  4471. array specified by its arguments; that is, the index of the
  4472. first zero of the run of zeros at the end.
  4473. @node Pointer Arithmetic Drawbacks
  4474. @section Drawbacks of Pointer Arithmetic
  4475. @cindex drawbacks of pointer arithmetic
  4476. @cindex pointer arithmetic, drawbacks
  4477. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4478. major security flaw in the C language. Theoretically, it is only
  4479. valid to adjust a pointer within one object allocated as a unit in
  4480. memory. However, if you unintentionally adjust a pointer across the
  4481. bounds of the object and into some other object, the system has no way
  4482. to detect this error.
  4483. A bug which does that can easily result in clobbering (overwriting)
  4484. part of another object. For example, with @code{array[-1]} you can
  4485. read or write the nonexistent element before the beginning of an
  4486. array---probably part of some other data.
  4487. Combining pointer arithmetic with casts between pointer types, you can
  4488. create a pointer that fails to be properly aligned for its type. For
  4489. example,
  4490. @example
  4491. int a[2];
  4492. char *pa = (char *)a;
  4493. int *p = (int *)(pa + 1);
  4494. @end example
  4495. @noindent
  4496. gives @code{p} a value pointing to an ``integer'' that includes part
  4497. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4498. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4499. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4500. ``works,'' it may be quite slow. It can also cause aliasing
  4501. confusions (@pxref{Aliasing}).
  4502. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4503. unless it is really necessary.
  4504. @node Pointer-Integer Conversion
  4505. @section Pointer-Integer Conversion
  4506. @cindex pointer-integer conversion
  4507. @cindex conversion between pointers and integers
  4508. @cindex @code{uintptr_t}
  4509. On modern computers, an address is simply a number. It occupies the
  4510. same space as some size of integer. In C, you can convert a pointer
  4511. to the appropriate integer types and vice versa, without losing
  4512. information. The appropriate integer types are @code{uintptr_t} (an
  4513. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4514. in @file{stdint.h}.
  4515. For instance,
  4516. @example
  4517. #include <stdint.h>
  4518. #include <stdio.h>
  4519. void
  4520. print_pointer (void *ptr)
  4521. @{
  4522. uintptr_t converted = (uintptr_t) ptr;
  4523. printf ("Pointer value is 0x%x\n",
  4524. (unsigned int) converted);
  4525. @}
  4526. @end example
  4527. @noindent
  4528. The specification @samp{%x} in the template (the first argument) for
  4529. @code{printf} means to represent this argument using hexadecimal
  4530. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4531. printing treats the number as unsigned, but it won't actually matter:
  4532. all @code{printf} gets to see is the series of bits in the number.
  4533. @strong{Warning:} Converting pointers to integers is risky---don't do
  4534. it unless it is really necessary.
  4535. @node Printing Pointers
  4536. @section Printing Pointers
  4537. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4538. For example:
  4539. @example
  4540. void
  4541. print_pointer (void *ptr)
  4542. @{
  4543. printf ("Pointer value is %p\n", ptr);
  4544. @}
  4545. @end example
  4546. The specification @samp{%p} works with any pointer type. It prints
  4547. @samp{0x} followed by the address in hexadecimal, printed as the
  4548. appropriate unsigned integer type.
  4549. @node Structures
  4550. @chapter Structures
  4551. @cindex structures
  4552. @findex struct
  4553. @cindex fields in structures
  4554. A @dfn{structure} is a user-defined data type that holds various
  4555. @dfn{fields} of data. Each field has a name and a data type specified
  4556. in the structure's definition.
  4557. Here we define a structure suitable for storing a linked list of
  4558. integers. Each list item will hold one integer, plus a pointer
  4559. to the next item.
  4560. @example
  4561. struct intlistlink
  4562. @{
  4563. int datum;
  4564. struct intlistlink *next;
  4565. @};
  4566. @end example
  4567. The structure definition has a @dfn{type tag} so that the code can
  4568. refer to this structure. The type tag here is @code{intlistlink}.
  4569. The definition refers recursively to the same structure through that
  4570. tag.
  4571. You can define a structure without a type tag, but then you can't
  4572. refer to it again. That is useful only in some special contexts, such
  4573. as inside a @code{typedef} or a @code{union}.
  4574. The contents of the structure are specified by the @dfn{field
  4575. declarations} inside the braces. Each field in the structure needs a
  4576. declaration there. The fields in one structure definition must have
  4577. distinct names, but these names do not conflict with any other names
  4578. in the program.
  4579. A field declaration looks just like a variable declaration. You can
  4580. combine field declarations with the same beginning, just as you can
  4581. combine variable declarations.
  4582. This structure has two fields. One, named @code{datum}, has type
  4583. @code{int} and will hold one integer in the list. The other, named
  4584. @code{next}, is a pointer to another @code{struct intlistlink}
  4585. which would be the rest of the list. In the last list item, it would
  4586. be @code{NULL}.
  4587. This structure definition is recursive, since the type of the
  4588. @code{next} field refers to the structure type. Such recursion is not
  4589. a problem; in fact, you can use the type @code{struct intlistlink *}
  4590. before the definition of the type @code{struct intlistlink} itself.
  4591. That works because pointers to all kinds of structures really look the
  4592. same at the machine level.
  4593. After defining the structure, you can declare a variable of type
  4594. @code{struct intlistlink} like this:
  4595. @example
  4596. struct intlistlink foo;
  4597. @end example
  4598. The structure definition itself can serve as the beginning of a
  4599. variable declaration, so you can declare variables immediately after,
  4600. like this:
  4601. @example
  4602. struct intlistlink
  4603. @{
  4604. int datum;
  4605. struct intlistlink *next;
  4606. @} foo;
  4607. @end example
  4608. @noindent
  4609. But that is ugly. It is almost always clearer to separate the
  4610. definition of the structure from its uses.
  4611. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4612. the scope of the structure type name to that block. That means the
  4613. structure type is recognized only within that block. Declaring it in
  4614. a function parameter list, as here,
  4615. @example
  4616. int f (struct foo @{int a, b@} parm);
  4617. @end example
  4618. @noindent
  4619. (assuming that @code{struct foo} is not already defined) limits the
  4620. scope of the structure type @code{struct foo} to that parameter list;
  4621. that is basically useless, so it triggers a warning.
  4622. Standard C requires at least one field in a structure.
  4623. GNU C does not require this.
  4624. @menu
  4625. * Referencing Fields:: Accessing field values in a structure object.
  4626. * Dynamic Memory Allocation:: Allocating space for objects
  4627. while the program is running.
  4628. * Field Offset:: Memory layout of fields within a structure.
  4629. * Structure Layout:: Planning the memory layout of fields.
  4630. * Packed Structures:: Packing structure fields as close as possible.
  4631. * Bit Fields:: Dividing integer fields
  4632. into fields with fewer bits.
  4633. * Bit Field Packing:: How bit fields pack together in integers.
  4634. * const Fields:: Making structure fields immutable.
  4635. * Zero Length:: Zero-length array as a variable-length object.
  4636. * Flexible Array Fields:: Another approach to variable-length objects.
  4637. * Overlaying Structures:: Casting one structure type
  4638. over an object of another structure type.
  4639. * Structure Assignment:: Assigning values to structure objects.
  4640. * Unions:: Viewing the same object in different types.
  4641. * Packing With Unions:: Using a union type to pack various types into
  4642. the same memory space.
  4643. * Cast to Union:: Casting a value one of the union's alternative
  4644. types to the type of the union itself.
  4645. * Structure Constructors:: Building new structure objects.
  4646. * Unnamed Types as Fields:: Fields' types do not always need names.
  4647. * Incomplete Types:: Types which have not been fully defined.
  4648. * Intertwined Incomplete Types:: Defining mutually-recursive structure types.
  4649. * Type Tags:: Scope of structure and union type tags.
  4650. @end menu
  4651. @node Referencing Fields
  4652. @section Referencing Structure Fields
  4653. @cindex referencing structure fields
  4654. @cindex structure fields, referencing
  4655. To make a structure useful, there has to be a way to examine and store
  4656. its fields. The @samp{.} (period) operator does that; its use looks
  4657. like @code{@var{object}.@var{field}}.
  4658. Given this structure and variable,
  4659. @example
  4660. struct intlistlink
  4661. @{
  4662. int datum;
  4663. struct intlistlink *next;
  4664. @};
  4665. struct intlistlink foo;
  4666. @end example
  4667. @noindent
  4668. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4669. fields in the value of @code{foo}. These fields are lvalues, so you
  4670. can store values into them, and read the values out again.
  4671. Most often, structures are dynamically allocated (see the next
  4672. section), and we refer to the objects via pointers.
  4673. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4674. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4675. contains this declaration:
  4676. @example
  4677. struct intlistlink *ptr;
  4678. @end example
  4679. @noindent
  4680. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4681. to the two fields in the object that @code{ptr} points to.
  4682. If a unary operator precedes an expression using @samp{->},
  4683. the @samp{->} nests inside:
  4684. @example
  4685. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4686. @end example
  4687. You can intermix @samp{->} and @samp{.} without parentheses,
  4688. as shown here:
  4689. @example
  4690. struct @{ double d; struct intlistlink l; @} foo;
  4691. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4692. @end example
  4693. @node Dynamic Memory Allocation
  4694. @section Dynamic Memory Allocation
  4695. @cindex dynamic memory allocation
  4696. @cindex memory allocation, dynamic
  4697. @cindex allocating memory dynamically
  4698. To allocate an object dynamically, call the library function
  4699. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4700. Reference Manual}). Here is how to allocate an object of type
  4701. @code{struct intlistlink}. To make this code work, include the file
  4702. @file{stdlib.h}, like this:
  4703. @example
  4704. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4705. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4706. @dots{}
  4707. struct intlistlink *
  4708. alloc_intlistlink ()
  4709. @{
  4710. struct intlistlink *p;
  4711. p = malloc (sizeof (struct intlistlink));
  4712. if (p == NULL)
  4713. fatal ("Ran out of storage");
  4714. /* @r{Initialize the contents.} */
  4715. p->datum = 0;
  4716. p->next = NULL;
  4717. return p;
  4718. @}
  4719. @end example
  4720. @noindent
  4721. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4722. will automatically convert it to type @code{struct intlistlink *}.
  4723. The return value of @code{malloc} is always sufficiently aligned
  4724. (@pxref{Type Alignment}) that it is valid for any data type.
  4725. The test for @code{p == NULL} is necessary because @code{malloc}
  4726. returns a null pointer if it cannot get any storage. We assume that
  4727. the program defines the function @code{fatal} to report a fatal error
  4728. to the user.
  4729. Here's how to add one more integer to the front of such a list:
  4730. @example
  4731. struct intlistlink *my_list = NULL;
  4732. void
  4733. add_to_mylist (int my_int)
  4734. @{
  4735. struct intlistlink *p = alloc_intlistlink ();
  4736. p->datum = my_int;
  4737. p->next = mylist;
  4738. mylist = p;
  4739. @}
  4740. @end example
  4741. The way to free the objects is by calling @code{free}. Here's
  4742. a function to free all the links in one of these lists:
  4743. @example
  4744. void
  4745. free_intlist (struct intlistlink *p)
  4746. @{
  4747. while (p)
  4748. @{
  4749. struct intlistlink *q = p;
  4750. p = p->next;
  4751. free (q);
  4752. @}
  4753. @}
  4754. @end example
  4755. We must extract the @code{next} pointer from the object before freeing
  4756. it, because @code{free} can clobber the data that was in the object.
  4757. For the same reason, the program must not use the list any more after
  4758. freeing its elements. To make sure it won't, it is best to clear out
  4759. the variable where the list was stored, like this:
  4760. @example
  4761. free_intlist (mylist);
  4762. mylist = NULL;
  4763. @end example
  4764. @node Field Offset
  4765. @section Field Offset
  4766. @cindex field offset
  4767. @cindex structure field offset
  4768. @cindex offset of structure fields
  4769. To determine the offset of a given field @var{field} in a structure
  4770. type @var{type}, use the macro @code{offsetof}, which is defined in
  4771. the file @file{stddef.h}. It is used like this:
  4772. @example
  4773. offsetof (@var{type}, @var{field})
  4774. @end example
  4775. Here is an example:
  4776. @example
  4777. struct foo
  4778. @{
  4779. int element;
  4780. struct foo *next;
  4781. @};
  4782. offsetof (struct foo, next)
  4783. /* @r{On most machines that is 4. It may be 8.} */
  4784. @end example
  4785. @node Structure Layout
  4786. @section Structure Layout
  4787. @cindex structure layout
  4788. @cindex layout of structures
  4789. The rest of this chapter covers advanced topics about structures. If
  4790. you are just learning C, you can skip it.
  4791. The precise layout of a @code{struct} type is crucial when using it to
  4792. overlay hardware registers, to access data structures in shared
  4793. memory, or to assemble and disassemble packets for network
  4794. communication. It is also important for avoiding memory waste when
  4795. the program makes many objects of that type. However, the layout
  4796. depends on the target platform. Each platform has conventions for
  4797. structure layout, which compilers need to follow.
  4798. Here are the conventions used on most platforms.
  4799. The structure's fields appear in the structure layout in the order
  4800. they are declared. When possible, consecutive fields occupy
  4801. consecutive bytes within the structure. However, if a field's type
  4802. demands more alignment than it would get that way, C gives it the
  4803. alignment it requires by leaving a gap after the previous field.
  4804. Once all the fields have been laid out, it is possible to determine
  4805. the structure's alignment and size. The structure's alignment is the
  4806. maximum alignment of any of the fields in it. Then the structure's
  4807. size is rounded up to a multiple of its alignment. That may require
  4808. leaving a gap at the end of the structure.
  4809. Here are some examples, where we assume that @code{char} has size and
  4810. alignment 1 (always true), and @code{int} has size and alignment 4
  4811. (true on most kinds of computers):
  4812. @example
  4813. struct foo
  4814. @{
  4815. char a, b;
  4816. int c;
  4817. @};
  4818. @end example
  4819. @noindent
  4820. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4821. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4822. There is a gap of 2 bytes before @code{c}.
  4823. Contrast that with this structure:
  4824. @example
  4825. struct foo
  4826. @{
  4827. char a;
  4828. int c;
  4829. char b;
  4830. @};
  4831. @end example
  4832. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4833. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4834. gaps: three bytes before @code{c}, and three bytes at the end.
  4835. These two structures have the same contents at the C level, but one
  4836. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4837. fields. A reliable way to avoid this sort of wastage is to order the
  4838. fields by size, biggest fields first.
  4839. @node Packed Structures
  4840. @section Packed Structures
  4841. @cindex packed structures
  4842. @cindex @code{__attribute__((packed))}
  4843. In GNU C you can force a structure to be laid out with no gaps by
  4844. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4845. end of the structure type declaration). Here's an example:
  4846. @example
  4847. struct __attribute__((packed)) foo
  4848. @{
  4849. char a;
  4850. int c;
  4851. char b;
  4852. @};
  4853. @end example
  4854. Without @code{__attribute__((packed))}, this structure occupies 12
  4855. bytes (as described in the previous section), assuming 4-byte
  4856. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4857. only 6 bytes long---the sum of the lengths of its fields.
  4858. Use of @code{__attribute__((packed))} often results in fields that
  4859. don't have the normal alignment for their types. Taking the address
  4860. of such a field can result in an invalid pointer because of its
  4861. improper alignment. Dereferencing such a pointer can cause a
  4862. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4863. unaligned pointers.
  4864. @xref{Attributes}.
  4865. @node Bit Fields
  4866. @section Bit Fields
  4867. @cindex bit fields
  4868. A structure field declaration with an integer type can specify the
  4869. number of bits the field should occupy. We call that a @dfn{bit
  4870. field}. These are useful because consecutive bit fields are packed
  4871. into a larger storage unit. For instance,
  4872. @example
  4873. unsigned char opcode: 4;
  4874. @end example
  4875. @noindent
  4876. specifies that this field takes just 4 bits.
  4877. Since it is unsigned, its possible values range
  4878. from 0 to 15. A signed field with 4 bits, such as this,
  4879. @example
  4880. signed char small: 4;
  4881. @end example
  4882. @noindent
  4883. can hold values from -8 to 7.
  4884. You can subdivide a single byte into those two parts by writing
  4885. @example
  4886. unsigned char opcode: 4;
  4887. signed char small: 4;
  4888. @end example
  4889. @noindent
  4890. in the structure. With bit fields, these two numbers fit into
  4891. a single @code{char}.
  4892. Here's how to declare a one-bit field that can hold either 0 or 1:
  4893. @example
  4894. unsigned char special_flag: 1;
  4895. @end example
  4896. You can also use the @code{bool} type for bit fields:
  4897. @example
  4898. bool special_flag: 1;
  4899. @end example
  4900. Except when using @code{bool} (which is always unsigned,
  4901. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4902. for a bit field. There is a default, if that's not specified: the bit
  4903. field is signed if plain @code{char} is signed, except that the option
  4904. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4905. is cleaner not to depend on this default.
  4906. Bit fields are special in that you cannot take their address with
  4907. @samp{&}. They are not stored with the size and alignment appropriate
  4908. for the specified type, so they cannot be addressed through pointers
  4909. to that type.
  4910. @node Bit Field Packing
  4911. @section Bit Field Packing
  4912. Programs to communicate with low-level hardware interfaces need to
  4913. define bit fields laid out to match the hardware data. This section
  4914. explains how to do that.
  4915. Consecutive bit fields are packed together, but each bit field must
  4916. fit within a single object of its specified type. In this example,
  4917. @example
  4918. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4919. @end example
  4920. @noindent
  4921. all five fields fit consecutively into one two-byte @code{short}.
  4922. They need 15 bits, and one @code{short} provides 16. By contrast,
  4923. @example
  4924. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4925. @end example
  4926. @noindent
  4927. needs three bytes. It fits @code{a} and @code{b} into one
  4928. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4929. add up to 9 bits). So @code{c} and @code{d} go into a second
  4930. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4931. Then @code{e} needs a third @code{char}. By contrast,
  4932. @example
  4933. unsigned char a : 3, b : 3;
  4934. unsigned int c : 3;
  4935. unsigned char d : 3, e : 3;
  4936. @end example
  4937. @noindent
  4938. needs only two bytes: the type @code{unsigned int}
  4939. allows @code{c} to straddle bytes that are in the same word.
  4940. You can leave a gap of a specified number of bits by defining a
  4941. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4942. It is allocated space in the structure just as a named bit field would
  4943. be allocated.
  4944. You can force the following bit field to advance to the following
  4945. aligned memory object with @code{@var{type} : 0;}.
  4946. Both of these constructs can syntactically share @var{type} with
  4947. ordinary bit fields. This example illustrates both:
  4948. @example
  4949. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4950. @end example
  4951. @noindent
  4952. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4953. between them. Then @code{: 0} advances to the next @code{int},
  4954. so @code{c} and @code{d} fit into that one.
  4955. These rules for packing bit fields apply to most target platforms,
  4956. including all the usual real computers. A few embedded controllers
  4957. have special layout rules.
  4958. @node const Fields
  4959. @section @code{const} Fields
  4960. @cindex const fields
  4961. @cindex structure fields, constant
  4962. @c ??? Is this a C standard feature?
  4963. A structure field declared @code{const} cannot be assigned to
  4964. (@pxref{const}). For instance, let's define this modified version of
  4965. @code{struct intlistlink}:
  4966. @example
  4967. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4968. @{
  4969. const int datum;
  4970. struct intlistlink *next;
  4971. @};
  4972. @end example
  4973. This structure can be used to prevent part of the code from modifying
  4974. the @code{datum} field:
  4975. @example
  4976. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4977. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4978. struct intlistlink_ro *q
  4979. = (struct intlistlink_ro *) p;
  4980. q->datum = 5; /* @r{Error!} */
  4981. p->datum = 5; /* @r{Valid since @code{*p} is}
  4982. @r{not a @code{struct intlistlink_ro}.} */
  4983. @end example
  4984. A @code{const} field can get a value in two ways: by initialization of
  4985. the whole structure, and by making a pointer-to-structure point to an object
  4986. in which that field already has a value.
  4987. Any @code{const} field in a structure type makes assignment impossible
  4988. for structures of that type (@pxref{Structure Assignment}). That is
  4989. because structure assignment works by assigning the structure's
  4990. fields, one by one.
  4991. @node Zero Length
  4992. @section Arrays of Length Zero
  4993. @cindex array of length zero
  4994. @cindex zero-length arrays
  4995. @cindex length-zero arrays
  4996. GNU C allows zero-length arrays. They are useful as the last element
  4997. of a structure that is really a header for a variable-length object.
  4998. Here's an example, where we construct a variable-size structure
  4999. to hold a line which is @code{this_length} characters long:
  5000. @example
  5001. struct line @{
  5002. int length;
  5003. char contents[0];
  5004. @};
  5005. struct line *thisline
  5006. = ((struct line *)
  5007. malloc (sizeof (struct line)
  5008. + this_length));
  5009. thisline->length = this_length;
  5010. @end example
  5011. In ISO C90, we would have to give @code{contents} a length of 1, which
  5012. means either wasting space or complicating the argument to @code{malloc}.
  5013. @node Flexible Array Fields
  5014. @section Flexible Array Fields
  5015. @cindex flexible array fields
  5016. @cindex array fields, flexible
  5017. The C99 standard adopted a more complex equivalent of zero-length
  5018. array fields. It's called a @dfn{flexible array}, and it's indicated
  5019. by omitting the length, like this:
  5020. @example
  5021. struct line
  5022. @{
  5023. int length;
  5024. char contents[];
  5025. @};
  5026. @end example
  5027. The flexible array has to be the last field in the structure, and there
  5028. must be other fields before it.
  5029. Under the C standard, a structure with a flexible array can't be part
  5030. of another structure, and can't be an element of an array.
  5031. GNU C allows static initialization of flexible array fields. The effect
  5032. is to ``make the array long enough'' for the initializer.
  5033. @example
  5034. struct f1 @{ int x; int y[]; @} f1
  5035. = @{ 1, @{ 2, 3, 4 @} @};
  5036. @end example
  5037. @noindent
  5038. This defines a structure variable named @code{f1}
  5039. whose type is @code{struct f1}. In C, a variable name or function name
  5040. never conflicts with a structure type tag.
  5041. Omitting the flexible array field's size lets the initializer
  5042. determine it. This is allowed only when the flexible array is defined
  5043. in the outermost structure and you declare a variable of that
  5044. structure type. For example:
  5045. @example
  5046. struct foo @{ int x; int y[]; @};
  5047. struct bar @{ struct foo z; @};
  5048. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  5049. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5050. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  5051. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5052. @end example
  5053. @node Overlaying Structures
  5054. @section Overlaying Different Structures
  5055. @cindex overlaying structures
  5056. @cindex structures, overlaying
  5057. Be careful about using different structure types to refer to the same
  5058. memory within one function, because GNU C can optimize code assuming
  5059. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5060. aliasing that can cause the problem:
  5061. @example
  5062. struct a @{ int size; char *data; @};
  5063. struct b @{ int size; char *data; @};
  5064. struct a foo;
  5065. struct b *q = (struct b *) &foo;
  5066. @end example
  5067. Here @code{q} points to the same memory that the variable @code{foo}
  5068. occupies, but they have two different types. The two types
  5069. @code{struct a} and @code{struct b} are defined alike, but they are
  5070. not the same type. Interspersing references using the two types,
  5071. like this,
  5072. @example
  5073. p->size = 0;
  5074. q->size = 1;
  5075. x = p->size;
  5076. @end example
  5077. @noindent
  5078. allows GNU C to assume that @code{p->size} is still zero when it is
  5079. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5080. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5081. Other compilers might also do this optimization. The ISO C standard
  5082. considers such code erroneous, precisely so that this optimization
  5083. will be valid.
  5084. @node Structure Assignment
  5085. @section Structure Assignment
  5086. @cindex structure assignment
  5087. @cindex assigning structures
  5088. Assignment operating on a structure type copies the structure. The
  5089. left and right operands must have the same type. Here is an example:
  5090. @example
  5091. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5092. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5093. @r{@dots{}}
  5094. struct point @{ double x, y; @};
  5095. struct point *
  5096. copy_point (struct point point)
  5097. @{
  5098. struct point *p
  5099. = (struct point *) malloc (sizeof (struct point));
  5100. if (p == NULL)
  5101. fatal ("Out of memory");
  5102. *p = point;
  5103. return p;
  5104. @}
  5105. @end example
  5106. Notionally, assignment on a structure type works by copying each of
  5107. the fields. Thus, if any of the fields has the @code{const}
  5108. qualifier, that structure type does not allow assignment:
  5109. @example
  5110. struct point @{ const double x, y; @};
  5111. struct point a, b;
  5112. a = b; /* @r{Error!} */
  5113. @end example
  5114. @xref{Assignment Expressions}.
  5115. @node Unions
  5116. @section Unions
  5117. @cindex unions
  5118. @findex union
  5119. A @dfn{union type} defines alternative ways of looking at the same
  5120. piece of memory. Each alternative view is defined with a data type,
  5121. and identified by a name. A union definition looks like this:
  5122. @example
  5123. union @var{name}
  5124. @{
  5125. @var{alternative declarations}@r{@dots{}}
  5126. @};
  5127. @end example
  5128. Each alternative declaration looks like a structure field declaration,
  5129. except that it can't be a bit field. For instance,
  5130. @example
  5131. union number
  5132. @{
  5133. long int integer;
  5134. double float;
  5135. @}
  5136. @end example
  5137. @noindent
  5138. lets you store either an integer (type @code{long int}) or a floating
  5139. point number (type @code{double}) in the same place in memory. The
  5140. length and alignment of the union type are the maximum of all the
  5141. alternatives---they do not have to be the same. In this union
  5142. example, @code{double} probably takes more space than @code{long int},
  5143. but that doesn't cause a problem in programs that use the union in the
  5144. normal way.
  5145. The members don't have to be different in data type. Sometimes
  5146. each member pertains to a way the data will be used. For instance,
  5147. @example
  5148. union datum
  5149. @{
  5150. double latitude;
  5151. double longitude;
  5152. double height;
  5153. double weight;
  5154. int continent;
  5155. @}
  5156. @end example
  5157. This union holds one of several kinds of data; most kinds are floating
  5158. points, but the value can also be a code for a continent which is an
  5159. integer. You @emph{could} use one member of type @code{double} to
  5160. access all the values which have that type, but the different member
  5161. names will make the program clearer.
  5162. The alignment of a union type is the maximum of the alignments of the
  5163. alternatives. The size of the union type is the maximum of the sizes
  5164. of the alternatives, rounded up to a multiple of the alignment
  5165. (because every type's size must be a multiple of its alignment).
  5166. All the union alternatives start at the address of the union itself.
  5167. If an alternative is shorter than the union as a whole, it occupies
  5168. the first part of the union's storage, leaving the last part unused
  5169. @emph{for that alternative}.
  5170. @strong{Warning:} if the code stores data using one union alternative
  5171. and accesses it with another, the results depend on the kind of
  5172. computer in use. Only wizards should try to do this. However, when
  5173. you need to do this, a union is a clean way to do it.
  5174. Assignment works on any union type by copying the entire value.
  5175. @node Packing With Unions
  5176. @section Packing With Unions
  5177. Sometimes we design a union with the intention of packing various
  5178. kinds of objects into a certain amount of memory space. For example.
  5179. @example
  5180. union bytes8
  5181. @{
  5182. long long big_int_elt;
  5183. double double_elt;
  5184. struct @{ int first, second; @} two_ints;
  5185. struct @{ void *first, *second; @} two_ptrs;
  5186. @};
  5187. union bytes8 *p;
  5188. @end example
  5189. This union makes it possible to look at 8 bytes of data that @code{p}
  5190. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5191. single floating-point number (@code{p->double_elt}), as a pair of
  5192. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5193. as a pair of pointers (@code{p->two_ptrs.first} and
  5194. @code{p->two_ptrs.second}).
  5195. To pack storage with such a union makes assumptions about the sizes of
  5196. all the types involved. This particular union was written expecting a
  5197. pointer to have the same size as @code{int}. On a machine where one
  5198. pointer takes 8 bytes, the code using this union probably won't work
  5199. as expected. The union, as such, will function correctly---if you
  5200. store two values through @code{two_ints} and extract them through
  5201. @code{two_ints}, you will get the same integers back---but the part of
  5202. the program that expects the union to be 8 bytes long could
  5203. malfunction, or at least use too much space.
  5204. The above example shows one case where a @code{struct} type with no
  5205. tag can be useful. Another way to get effectively the same result
  5206. is with arrays as members of the union:
  5207. @example
  5208. union eight_bytes
  5209. @{
  5210. long long big_int_elt;
  5211. double double_elt;
  5212. int two_ints[2];
  5213. void *two_ptrs[2];
  5214. @};
  5215. @end example
  5216. @node Cast to Union
  5217. @section Cast to a Union Type
  5218. @cindex cast to a union
  5219. @cindex union, casting to a
  5220. In GNU C, you can explicitly cast any of the alternative types to the
  5221. union type; for instance,
  5222. @example
  5223. (union eight_bytes) (long long) 5
  5224. @end example
  5225. @noindent
  5226. makes a value of type @code{union eight_bytes} which gets its contents
  5227. through the alternative named @code{big_int_elt}.
  5228. The value being cast must exactly match the type of the alternative,
  5229. so this is not valid:
  5230. @example
  5231. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5232. @end example
  5233. A cast to union type looks like any other cast, except that the type
  5234. specified is a union type. You can specify the type either with
  5235. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5236. Typedef Names}).
  5237. Using the cast as the right-hand side of an assignment to a variable of
  5238. union type is equivalent to storing in an alternative of the union:
  5239. @example
  5240. union foo u;
  5241. u = (union foo) x @r{means} u.i = x
  5242. u = (union foo) y @r{means} u.d = y
  5243. @end example
  5244. You can also use the union cast as a function argument:
  5245. @example
  5246. void hack (union foo);
  5247. @r{@dots{}}
  5248. hack ((union foo) x);
  5249. @end example
  5250. @node Structure Constructors
  5251. @section Structure Constructors
  5252. @cindex structure constructors
  5253. @cindex constructors, structure
  5254. You can construct a structure value by writing its type in
  5255. parentheses, followed by an initializer that would be valid in a
  5256. declaration for that type. For instance, given this declaration,
  5257. @example
  5258. struct foo @{int a; char b[2];@} structure;
  5259. @end example
  5260. @noindent
  5261. you can create a @code{struct foo} value as follows:
  5262. @example
  5263. ((struct foo) @{x + y, 'a', 0@})
  5264. @end example
  5265. @noindent
  5266. This specifies @code{x + y} for field @code{a},
  5267. the character @samp{a} for field @code{b}'s element 0,
  5268. and the null character for field @code{b}'s element 1.
  5269. The parentheses around that constructor are to necessary, but we
  5270. recommend writing them to make the nesting of the containing
  5271. expression clearer.
  5272. You can also show the nesting of the two by writing it like
  5273. this:
  5274. @example
  5275. ((struct foo) @{x + y, @{'a', 0@} @})
  5276. @end example
  5277. Each of those is equivalent to writing the following statement
  5278. expression (@pxref{Statement Exprs}):
  5279. @example
  5280. (@{
  5281. struct foo temp = @{x + y, 'a', 0@};
  5282. temp;
  5283. @})
  5284. @end example
  5285. You can also create a union value this way, but it is not especially
  5286. useful since that is equivalent to doing a cast:
  5287. @example
  5288. ((union whosis) @{@var{value}@})
  5289. @r{is equivalent to}
  5290. ((union whosis) (@var{value}))
  5291. @end example
  5292. @node Unnamed Types as Fields
  5293. @section Unnamed Types as Fields
  5294. @cindex unnamed structures
  5295. @cindex unnamed unions
  5296. @cindex structures, unnamed
  5297. @cindex unions, unnamed
  5298. A structure or a union can contain, as fields,
  5299. unnamed structures and unions. Here's an example:
  5300. @example
  5301. struct
  5302. @{
  5303. int a;
  5304. union
  5305. @{
  5306. int b;
  5307. float c;
  5308. @};
  5309. int d;
  5310. @} foo;
  5311. @end example
  5312. @noindent
  5313. You can access the fields of the unnamed union within @code{foo} as if they
  5314. were individual fields at the same level as the union definition:
  5315. @example
  5316. foo.a = 42;
  5317. foo.b = 47;
  5318. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5319. foo.d = 314;
  5320. @end example
  5321. Avoid using field names that could cause ambiguity. For example, with
  5322. this definition:
  5323. @example
  5324. struct
  5325. @{
  5326. int a;
  5327. struct
  5328. @{
  5329. int a;
  5330. float b;
  5331. @};
  5332. @} foo;
  5333. @end example
  5334. @noindent
  5335. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5336. an error when a definition is ambiguous in this way.
  5337. @node Incomplete Types
  5338. @section Incomplete Types
  5339. @cindex incomplete types
  5340. @cindex types, incomplete
  5341. A type that has not been fully defined is called an @dfn{incomplete
  5342. type}. Structure and union types are incomplete when the code makes a
  5343. forward reference, such as @code{struct foo}, before defining the
  5344. type. An array type is incomplete when its length is unspecified.
  5345. You can't use an incomplete type to declare a variable or field, or
  5346. use it for a function parameter or return type. The operators
  5347. @code{sizeof} and @code{_Alignof} give errors when used on an
  5348. incomplete type.
  5349. However, you can define a pointer to an incomplete type, and declare a
  5350. variable or field with such a pointer type. In general, you can do
  5351. everything with such pointers except dereference them. For example:
  5352. @example
  5353. extern void bar (struct mysterious_value *);
  5354. void
  5355. foo (struct mysterious_value *arg)
  5356. @{
  5357. bar (arg);
  5358. @}
  5359. @r{@dots{}}
  5360. @{
  5361. struct mysterious_value *p, **q;
  5362. p = *q;
  5363. foo (p);
  5364. @}
  5365. @end example
  5366. @noindent
  5367. These examples are valid because the code doesn't try to understand
  5368. what @code{p} points to; it just passes the pointer around.
  5369. (Presumably @code{bar} is defined in some other file that really does
  5370. have a definition for @code{struct mysterious_value}.) However,
  5371. dereferencing the pointer would get an error; that requires a
  5372. definition for the structure type.
  5373. @node Intertwined Incomplete Types
  5374. @section Intertwined Incomplete Types
  5375. When several structure types contain pointers to each other, you can
  5376. define the types in any order because pointers to types that come
  5377. later are incomplete types. Thus,
  5378. Here is an example.
  5379. @example
  5380. /* @r{An employee record points to a group.} */
  5381. struct employee
  5382. @{
  5383. char *name;
  5384. @r{@dots{}}
  5385. struct group *group; /* @r{incomplete type.} */
  5386. @r{@dots{}}
  5387. @};
  5388. /* @r{An employee list points to employees.} */
  5389. struct employee_list
  5390. @{
  5391. struct employee *this_one;
  5392. struct employee_list *next; /* @r{incomplete type.} */
  5393. @r{@dots{}}
  5394. @};
  5395. /* @r{A group points to one employee_list.} */
  5396. struct group
  5397. @{
  5398. char *name;
  5399. @r{@dots{}}
  5400. struct employee_list *employees;
  5401. @r{@dots{}}
  5402. @};
  5403. @end example
  5404. @node Type Tags
  5405. @section Type Tags
  5406. @cindex type tags
  5407. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5408. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5409. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5410. name or function name; the type tags have a separate @dfn{name space}.
  5411. Thus, there is no name conflict in this code:
  5412. @example
  5413. struct pair @{ int a, b; @};
  5414. int pair = 1;
  5415. @end example
  5416. @noindent
  5417. nor in this one:
  5418. @example
  5419. struct pair @{ int a, b; @} pair;
  5420. @end example
  5421. @noindent
  5422. where @code{pair} is both a structure type tag and a variable name.
  5423. However, @code{struct}, @code{union}, and @code{enum} share the same
  5424. name space of tags, so this is a conflict:
  5425. @example
  5426. struct pair @{ int a, b; @};
  5427. enum pair @{ c, d @};
  5428. @end example
  5429. @noindent
  5430. and so is this:
  5431. @example
  5432. struct pair @{ int a, b; @};
  5433. struct pair @{ int c, d; @};
  5434. @end example
  5435. When the code defines a type tag inside a block, the tag's scope is
  5436. limited to that block (as for local variables). Two definitions for
  5437. one type tag do not conflict if they are in different scopes; rather,
  5438. each is valid in its scope. For example,
  5439. @example
  5440. struct pair @{ int a, b; @};
  5441. void
  5442. pair_up_doubles (int len, double array[])
  5443. @{
  5444. struct pair @{ double a, b; @};
  5445. @r{@dots{}}
  5446. @}
  5447. @end example
  5448. @noindent
  5449. has two definitions for @code{struct pair} which do not conflict. The
  5450. one inside the function applies only within the definition of
  5451. @code{pair_up_doubles}. Within its scope, that definition
  5452. @dfn{shadows} the outer definition.
  5453. If @code{struct pair} appears inside the function body, before the
  5454. inner definition, it refers to the outer definition---the only one
  5455. that has been seen at that point. Thus, in this code,
  5456. @example
  5457. struct pair @{ int a, b; @};
  5458. void
  5459. pair_up_doubles (int len, double array[])
  5460. @{
  5461. struct two_pairs @{ struct pair *p, *q; @};
  5462. struct pair @{ double a, b; @};
  5463. @r{@dots{}}
  5464. @}
  5465. @end example
  5466. @noindent
  5467. the structure @code{two_pairs} has pointers to the outer definition of
  5468. @code{struct pair}, which is probably not desirable.
  5469. To prevent that, you can write @code{struct pair;} inside the function
  5470. body as a variable declaration with no variables. This is a
  5471. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5472. type tag local to the current block, with the details of the type to
  5473. come later. Here's an example:
  5474. @example
  5475. void
  5476. pair_up_doubles (int len, double array[])
  5477. @{
  5478. /* @r{Forward declaration for @code{pair}.} */
  5479. struct pair;
  5480. struct two_pairs @{ struct pair *p, *q; @};
  5481. /* @r{Give the details.} */
  5482. struct pair @{ double a, b; @};
  5483. @r{@dots{}}
  5484. @}
  5485. @end example
  5486. However, the cleanest practice is to avoid shadowing type tags.
  5487. @node Arrays
  5488. @chapter Arrays
  5489. @cindex array
  5490. @cindex elements of arrays
  5491. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5492. all of the same data type. Each element is identified by its numeric
  5493. @var{index} within the array.
  5494. We presented arrays of numbers in the sample programs early in this
  5495. manual (@pxref{Array Example}). However, arrays can have elements of
  5496. any data type, including pointers, structures, unions, and other
  5497. arrays.
  5498. If you know another programming language, you may suppose that you know all
  5499. about arrays, but C arrays have special quirks, so in this chapter we
  5500. collect all the information about arrays in C@.
  5501. The elements of a C array are allocated consecutively in memory,
  5502. with no gaps between them. Each element is aligned as required
  5503. for its data type (@pxref{Type Alignment}).
  5504. @menu
  5505. * Accessing Array Elements:: How to access individual elements of an array.
  5506. * Declaring an Array:: How to name and reserve space for a new array.
  5507. * Strings:: A string in C is a special case of array.
  5508. * Array Type Designators:: Referring to a specific array type.
  5509. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5510. * Limitations of C Arrays:: Arrays are not first-class objects.
  5511. * Multidimensional Arrays:: Arrays of arrays.
  5512. * Constructing Array Values:: Assigning values to an entire array at once.
  5513. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5514. @end menu
  5515. @node Accessing Array Elements
  5516. @section Accessing Array Elements
  5517. @cindex accessing array elements
  5518. @cindex array elements, accessing
  5519. If the variable @code{a} is an array, the @var{n}th element of
  5520. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5521. an element's value or to assign to it:
  5522. @example
  5523. x = a[5];
  5524. a[6] = 1;
  5525. @end example
  5526. @noindent
  5527. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5528. lvalue.
  5529. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5530. valid index is one less than the number of elements.
  5531. The C language does not check whether array indices are in bounds, so
  5532. if the code uses an out-of-range index, it will access memory outside the
  5533. array.
  5534. @strong{Warning:} Using only valid index values in C is the
  5535. programmer's responsibility.
  5536. Array indexing in C is not a primitive operation: it is defined in
  5537. terms of pointer arithmetic and dereferencing. Now that we know
  5538. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5539. its job.
  5540. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5541. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5542. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5543. When an expression with array type (such as @code{a}) appears as part
  5544. of a larger C expression, it is converted automatically to a pointer
  5545. to element zero of that array. For instance, @code{a} in an
  5546. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5547. computed as @code{*(&a[0]+i)}.
  5548. Now we can analyze how that expression gives us the desired element of
  5549. the array. It makes a pointer to element 0 of @code{a}, advances it
  5550. by the value of @code{i}, and dereferences that pointer.
  5551. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5552. @node Declaring an Array
  5553. @section Declaring an Array
  5554. @cindex declaring an array
  5555. @cindex array, declaring
  5556. To make an array declaration, write @code{[@var{length}]} after the
  5557. name being declared. This construct is valid in the declaration of a
  5558. variable, a function parameter, a function value type (the value can't
  5559. be an array, but it can be a pointer to one), a structure field, or a
  5560. union alternative.
  5561. The surrounding declaration specifies the element type of the array;
  5562. that can be any type of data, but not @code{void} or a function type.
  5563. For instance,
  5564. @example
  5565. double a[5];
  5566. @end example
  5567. @noindent
  5568. declares @code{a} as an array of 5 @code{double}s.
  5569. @example
  5570. struct foo bstruct[length];
  5571. @end example
  5572. @noindent
  5573. declares @code{bstruct} as an array of @code{length} objects of type
  5574. @code{struct foo}. A variable array size like this is allowed when
  5575. the array is not file-scope.
  5576. Other declaration constructs can nest within the array declaration
  5577. construct. For instance:
  5578. @example
  5579. struct foo *b[length];
  5580. @end example
  5581. @noindent
  5582. declares @code{b} as an array of @code{length} pointers to
  5583. @code{struct foo}. This shows that the length need not be a constant
  5584. (@pxref{Arrays of Variable Length}).
  5585. @example
  5586. double (*c)[5];
  5587. @end example
  5588. @noindent
  5589. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5590. @example
  5591. char *(*f (int))[5];
  5592. @end example
  5593. @noindent
  5594. declares @code{f} as a function taking an @code{int} argument and
  5595. returning a pointer to an array of 5 strings (pointers to
  5596. @code{char}s).
  5597. @example
  5598. double aa[5][10];
  5599. @end example
  5600. @noindent
  5601. declares @code{aa} as an array of 5 elements, each of which is an
  5602. array of 10 @code{double}s. This shows how to declare a
  5603. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5604. All these declarations specify the array's length, which is needed in
  5605. these cases in order to allocate storage for the array.
  5606. @node Strings
  5607. @section Strings
  5608. @cindex string
  5609. A string in C is a sequence of elements of type @code{char},
  5610. terminated with the null character, the character with code zero.
  5611. Programs often need to use strings with specific, fixed contents. To
  5612. write one in a C program, use a @dfn{string constant} such as
  5613. @code{"Take me to your leader!"}. The data type of a string constant
  5614. is @code{char *}. For the full syntactic details of writing string
  5615. constants, @ref{String Constants}.
  5616. To declare a place to store a non-constant string, declare an array of
  5617. @code{char}. Keep in mind that it must include one extra @code{char}
  5618. for the terminating null. For instance,
  5619. @example
  5620. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5621. @end example
  5622. @noindent
  5623. declares an array named @samp{text} with six elements---five letters
  5624. and the terminating null character. An equivalent way to get the same
  5625. result is this,
  5626. @example
  5627. char text[] = "Hello";
  5628. @end example
  5629. @noindent
  5630. which copies the elements of the string constant, including @emph{its}
  5631. terminating null character.
  5632. @example
  5633. char message[200];
  5634. @end example
  5635. @noindent
  5636. declares an array long enough to hold a string of 199 ASCII characters
  5637. plus the terminating null character.
  5638. When you store a string into @code{message} be sure to check or prove
  5639. that the length does not exceed its size. For example,
  5640. @example
  5641. void
  5642. set_message (char *text)
  5643. @{
  5644. int i;
  5645. for (i = 0; i < sizeof (message); i++)
  5646. @{
  5647. message[i] = text[i];
  5648. if (text[i] == 0)
  5649. return;
  5650. @}
  5651. fatal_error ("Message is too long for `message');
  5652. @}
  5653. @end example
  5654. It's easy to do this with the standard library function
  5655. @code{strncpy}, which fills out the whole destination array (up to a
  5656. specified length) with null characters. Thus, if the last character
  5657. of the destination is not null, the string did not fit. Many system
  5658. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5659. to run faster than an explicit @code{for}-loop.
  5660. Here's what the code looks like:
  5661. @example
  5662. void
  5663. set_message (char *text)
  5664. @{
  5665. strncpy (message, text, sizeof (message));
  5666. if (message[sizeof (message) - 1] != 0)
  5667. fatal_error ("Message is too long for `message');
  5668. @}
  5669. @end example
  5670. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5671. Library Reference Manual}, for more information about the standard
  5672. library functions for operating on strings.
  5673. You can avoid putting a fixed length limit on strings you construct or
  5674. operate on by allocating the space for them dynamically.
  5675. @xref{Dynamic Memory Allocation}.
  5676. @node Array Type Designators
  5677. @section Array Type Designators
  5678. Every C type has a type designator, which you make by deleting the
  5679. variable name and the semicolon from a declaration (@pxref{Type
  5680. Designators}). The designators for array types follow this rule, but
  5681. they may appear surprising.
  5682. @example
  5683. @r{type} int a[5]; @r{designator} int [5]
  5684. @r{type} double a[5][3]; @r{designator} double [5][3]
  5685. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5686. @end example
  5687. @node Incomplete Array Types
  5688. @section Incomplete Array Types
  5689. @cindex incomplete array types
  5690. @cindex array types, incomplete
  5691. An array is equivalent, for most purposes, to a pointer to its zeroth
  5692. element. When that is true, the length of the array is irrelevant.
  5693. The length needs to be known only for allocating space for the array, or
  5694. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5695. contexts C allows
  5696. @itemize @bullet
  5697. @item
  5698. An @code{extern} declaration says how to refer to a variable allocated
  5699. elsewhere. It does not need to allocate space for the variable,
  5700. so if it is an array, you can omit the length. For example,
  5701. @example
  5702. extern int foo[];
  5703. @end example
  5704. @item
  5705. When declaring a function parameter as an array, the argument value
  5706. passed to the function is really a pointer to the array's zeroth
  5707. element. This value does not say how long the array really is, there
  5708. is no need to declare it. For example,
  5709. @example
  5710. int
  5711. func (int foo[])
  5712. @end example
  5713. @end itemize
  5714. These declarations are examples of @dfn{incomplete} array types, types
  5715. that are not fully specified. The incompleteness makes no difference
  5716. for accessing elements of the array, but it matters for some other
  5717. things. For instance, @code{sizeof} is not allowed on an incomplete
  5718. type.
  5719. With multidimensional arrays, only the first dimension can be omitted:
  5720. @example
  5721. extern struct chesspiece *funnyboard foo[][8];
  5722. @end example
  5723. In other words, the code doesn't have to say how many rows there are,
  5724. but it must state how big each row is.
  5725. @node Limitations of C Arrays
  5726. @section Limitations of C Arrays
  5727. @cindex limitations of C arrays
  5728. @cindex first-class object
  5729. Arrays have quirks in C because they are not ``first-class objects'':
  5730. there is no way in C to operate on an array as a unit.
  5731. The other composite objects in C, structures and unions, are
  5732. first-class objects: a C program can copy a structure or union value
  5733. in an assignment, or pass one as an argument to a function, or make a
  5734. function return one. You can't do those things with an array in C@.
  5735. That is because a value you can operate on never has an array type.
  5736. An expression in C can have an array type, but that doesn't produce
  5737. the array as a value. Instead it is converted automatically to a
  5738. pointer to the array's element at index zero. The code can operate
  5739. on the pointer, and through that on individual elements of the array,
  5740. but it can't get and operate on the array as a unit.
  5741. There are three exceptions to this conversion rule, but none of them
  5742. offers a way to operate on the array as a whole.
  5743. First, @samp{&} applied to an expression with array type gives you the
  5744. address of the array, as an array type. However, you can't operate on the
  5745. whole array that way---if you apply @samp{*} to get the array back,
  5746. that expression converts, as usual, to a pointer to its zeroth
  5747. element.
  5748. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5749. @code{typeof} do not convert the array to a pointer; they leave it as
  5750. an array. But they don't operate on the array's data---they only give
  5751. information about its type.
  5752. Third, a string constant used as an initializer for an array is not
  5753. converted to a pointer---rather, the declaration copies the
  5754. @emph{contents} of that string in that one special case.
  5755. You @emph{can} copy the contents of an array, just not with an
  5756. assignment operator. You can do it by calling the library function
  5757. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5758. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5759. when a structure contains just an array, you can copy that structure.
  5760. An array itself is an lvalue if it is a declared variable, or part of
  5761. a structure or union that is an lvalue. When you construct an array
  5762. from elements (@pxref{Constructing Array Values}), that array is not
  5763. an lvalue.
  5764. @node Multidimensional Arrays
  5765. @section Multidimensional Arrays
  5766. @cindex multidimensional arrays
  5767. @cindex array, multidimensional
  5768. Strictly speaking, all arrays in C are unidimensional. However, you
  5769. can create an array of arrays, which is more or less equivalent to a
  5770. multidimensional array. For example,
  5771. @example
  5772. struct chesspiece *board[8][8];
  5773. @end example
  5774. @noindent
  5775. declares an array of 8 arrays of 8 pointers to @code{struct
  5776. chesspiece}. This data type could represent the state of a chess
  5777. game. To access one square's contents requires two array index
  5778. operations, one for each dimension. For instance, you can write
  5779. @code{board[row][column]}, assuming @code{row} and @code{column}
  5780. are variables with integer values in the proper range.
  5781. How does C understand @code{board[row][column]}? First of all,
  5782. @code{board} is converted automatically to a pointer to the zeroth
  5783. element (at index zero) of @code{board}. Adding @code{row} to that
  5784. makes it point to the desired element. Thus, @code{board[row]}'s
  5785. value is an element of @code{board}---an array of 8 pointers.
  5786. However, as an expression with array type, it is converted
  5787. automatically to a pointer to the array's zeroth element. The second
  5788. array index operation, @code{[column]}, accesses the chosen element
  5789. from that array.
  5790. As this shows, pointer-to-array types are meaningful in C@.
  5791. You can declare a variable that points to a row in a chess board
  5792. like this:
  5793. @example
  5794. struct chesspiece *(*rowptr)[8];
  5795. @end example
  5796. @noindent
  5797. This points to an array of 8 pointers to @code{struct chesspiece}.
  5798. You can assign to it as follows:
  5799. @example
  5800. rowptr = &board[5];
  5801. @end example
  5802. The dimensions don't have to be equal in length. Here we declare
  5803. @code{statepop} as an array to hold the population of each state in
  5804. the United States for each year since 1900:
  5805. @example
  5806. #define NSTATES 50
  5807. @{
  5808. int nyears = current_year - 1900 + 1;
  5809. int statepop[NSTATES][nyears];
  5810. @r{@dots{}}
  5811. @}
  5812. @end example
  5813. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5814. each indexed by the year (counting from 1900). Thus, to get the
  5815. element for a particular state and year, we must subscript it first
  5816. by the number that indicates the state, and second by the index for
  5817. the year:
  5818. @example
  5819. statepop[state][year - 1900]
  5820. @end example
  5821. @cindex array, layout in memory
  5822. The subarrays within the multidimensional array are allocated
  5823. consecutively in memory, and within each subarray, its elements are
  5824. allocated consecutively in memory. The most efficient way to process
  5825. all the elements in the array is to scan the last subscript in the
  5826. innermost loop. This means consecutive accesses go to consecutive
  5827. memory locations, which optimizes use of the processor's memory cache.
  5828. For example:
  5829. @example
  5830. int total = 0;
  5831. float average;
  5832. for (int state = 0; state < NSTATES, ++state)
  5833. @{
  5834. for (int year = 0; year < nyears; ++year)
  5835. @{
  5836. total += statepop[state][year];
  5837. @}
  5838. @}
  5839. average = total / nyears;
  5840. @end example
  5841. C's layout for multidimensional arrays is different from Fortran's
  5842. layout. In Fortran, a multidimensional array is not an array of
  5843. arrays; rather, multidimensional arrays are a primitive feature, and
  5844. it is the first index that varies most rapidly between consecutive
  5845. memory locations. Thus, the memory layout of a 50x114 array in C
  5846. matches that of a 114x50 array in Fortran.
  5847. @node Constructing Array Values
  5848. @section Constructing Array Values
  5849. @cindex constructing array values
  5850. @cindex array values, constructing
  5851. You can construct an array from elements by writing them inside
  5852. braces, and preceding all that with the array type's designator in
  5853. parentheses. There is no need to specify the array length, since the
  5854. number of elements determines that. The constructor looks like this:
  5855. @example
  5856. (@var{elttype}[]) @{ @var{elements} @};
  5857. @end example
  5858. Here is an example, which constructs an array of string pointers:
  5859. @example
  5860. (char *[]) @{ "x", "y", "z" @};
  5861. @end example
  5862. That's equivalent in effect to declaring an array with the same
  5863. initializer, like this:
  5864. @example
  5865. char *array[] = @{ "x", "y", "z" @};
  5866. @end example
  5867. and then using the array.
  5868. If all the elements are simple constant expressions, or made up of
  5869. such, then the compound literal can be coerced to a pointer to its
  5870. zeroth element and used to initialize a file-scope variable
  5871. (@pxref{File-Scope Variables}), as shown here:
  5872. @example
  5873. char **foo = (char *[]) @{ "x", "y", "z" @};
  5874. @end example
  5875. @noindent
  5876. The data type of @code{foo} is @code{char **}, which is a pointer
  5877. type, not an array type. The declaration is equivalent to defining
  5878. and then using an array-type variable:
  5879. @example
  5880. char *nameless_array[] = @{ "x", "y", "z" @};
  5881. char **foo = &nameless_array[0];
  5882. @end example
  5883. @node Arrays of Variable Length
  5884. @section Arrays of Variable Length
  5885. @cindex array of variable length
  5886. @cindex variable-length arrays
  5887. In GNU C, you can declare variable-length arrays like any other
  5888. arrays, but with a length that is not a constant expression. The
  5889. storage is allocated at the point of declaration and deallocated when
  5890. the block scope containing the declaration exits. For example:
  5891. @example
  5892. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5893. #include <string.h> /* @r{Declares @code{str}.} */
  5894. FILE *
  5895. concat_fopen (char *s1, char *s2, char *mode)
  5896. @{
  5897. char str[strlen (s1) + strlen (s2) + 1];
  5898. strcpy (str, s1);
  5899. strcat (str, s2);
  5900. return fopen (str, mode);
  5901. @}
  5902. @end example
  5903. @noindent
  5904. (This uses some standard library functions; see @ref{String and Array
  5905. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5906. The length of an array is computed once when the storage is allocated
  5907. and is remembered for the scope of the array in case it is used in
  5908. @code{sizeof}.
  5909. @strong{Warning:} don't allocate a variable-length array if the size
  5910. might be very large (more than 100,000), or in a recursive function,
  5911. because that is likely to cause stack overflow. Allocate the array
  5912. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5913. Jumping or breaking out of the scope of the array name deallocates the
  5914. storage. Jumping into the scope is not allowed; that gives an error
  5915. message.
  5916. You can also use variable-length arrays as arguments to functions:
  5917. @example
  5918. struct entry
  5919. tester (int len, char data[len][len])
  5920. @{
  5921. @r{@dots{}}
  5922. @}
  5923. @end example
  5924. As usual, a function argument declared with an array type
  5925. is really a pointer to an array that already exists.
  5926. Calling the function does not allocate the array, so there's no
  5927. particular danger of stack overflow in using this construct.
  5928. To pass the array first and the length afterward, use a forward
  5929. declaration in the function's parameter list (another GNU extension).
  5930. For example,
  5931. @example
  5932. struct entry
  5933. tester (int len; char data[len][len], int len)
  5934. @{
  5935. @r{@dots{}}
  5936. @}
  5937. @end example
  5938. The @code{int len} before the semicolon is a @dfn{parameter forward
  5939. declaration}, and it serves the purpose of making the name @code{len}
  5940. known when the declaration of @code{data} is parsed.
  5941. You can write any number of such parameter forward declarations in the
  5942. parameter list. They can be separated by commas or semicolons, but
  5943. the last one must end with a semicolon, which is followed by the
  5944. ``real'' parameter declarations. Each forward declaration must match
  5945. a ``real'' declaration in parameter name and data type. ISO C11 does
  5946. not support parameter forward declarations.
  5947. @node Enumeration Types
  5948. @chapter Enumeration Types
  5949. @cindex enumeration types
  5950. @cindex types, enumeration
  5951. @cindex enumerator
  5952. An @dfn{enumeration type} represents a limited set of integer values,
  5953. each with a name. It is effectively equivalent to a primitive integer
  5954. type.
  5955. Suppose we have a list of possible emotional states to store in an
  5956. integer variable. We can give names to these alternative values with
  5957. an enumeration:
  5958. @example
  5959. enum emotion_state @{ neutral, happy, sad, worried,
  5960. calm, nervous @};
  5961. @end example
  5962. @noindent
  5963. (Never mind that this is a simplistic way to classify emotional states;
  5964. it's just a code example.)
  5965. The names inside the enumeration are called @dfn{enumerators}. The
  5966. enumeration type defines them as constants, and their values are
  5967. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5968. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5969. the enumerators explicitly like this:
  5970. @example
  5971. enum emotion_state @{ neutral = 2, happy = 5,
  5972. sad = 20, worried = 10,
  5973. calm = -5, nervous = -300 @};
  5974. @end example
  5975. Each enumerator which does not specify a value gets value zero
  5976. (if it is at the beginning) or the next consecutive integer.
  5977. @example
  5978. /* @r{@code{neutral} is 0 by default,}
  5979. @r{and @code{worried} is 21 by default.} */
  5980. enum emotion_state @{ neutral,
  5981. happy = 5, sad = 20, worried,
  5982. calm = -5, nervous = -300 @};
  5983. @end example
  5984. If an enumerator is obsolete, you can specify that using it should
  5985. cause a warning, by including an attribute in the enumerator's
  5986. declaration. Here is how @code{happy} would look with this
  5987. attribute:
  5988. @example
  5989. happy __attribute__
  5990. ((deprecated
  5991. ("impossible under plutocratic rule")))
  5992. = 5,
  5993. @end example
  5994. @xref{Attributes}.
  5995. You can declare variables with the enumeration type:
  5996. @example
  5997. enum emotion_state feelings_now;
  5998. @end example
  5999. In the C code itself, this is equivalent to declaring the variable
  6000. @code{int}. (If all the enumeration values are positive, it is
  6001. equivalent to @code{unsigned int}.) However, declaring it with the
  6002. enumeration type has an advantage in debugging, because GDB knows it
  6003. should display the current value of the variable using the
  6004. corresponding name. If the variable's type is @code{int}, GDB can
  6005. only show the value as a number.
  6006. The identifier that follows @code{enum} is called a @dfn{type tag}
  6007. since it distinguishes different enumeration types. Type tags are in
  6008. a separate name space and belong to scopes like most other names in C@.
  6009. @xref{Type Tags}, for explanation.
  6010. You can predeclare an @code{enum} type tag like a structure or union
  6011. type tag, like this:
  6012. @example
  6013. enum foo;
  6014. @end example
  6015. @noindent
  6016. The @code{enum} type is incomplete until you finish defining it.
  6017. You can optionally include a trailing comma at the end of a list of
  6018. enumeration values:
  6019. @example
  6020. enum emotion_state @{ neutral, happy, sad, worried,
  6021. calm, nervous, @};
  6022. @end example
  6023. @noindent
  6024. This is useful in some macro definitions, since it enables you to
  6025. assemble the list of enumerators without knowing which one is last.
  6026. The extra comma does not change the meaning of the enumeration in any
  6027. way.
  6028. @node Defining Typedef Names
  6029. @chapter Defining Typedef Names
  6030. @cindex typedef names
  6031. @findex typedef
  6032. You can define a data type keyword as an alias for any type, and then
  6033. use the alias syntactically like a built-in type keyword such as
  6034. @code{int}. You do this using @code{typedef}, so these aliases are
  6035. also called @dfn{typedef names}.
  6036. @code{typedef} is followed by text that looks just like a variable
  6037. declaration, but instead of declaring variables it defines data type
  6038. keywords.
  6039. Here's how to define @code{fooptr} as a typedef alias for the type
  6040. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  6041. with that type:
  6042. @example
  6043. typedef struct foo *fooptr;
  6044. fooptr x, y;
  6045. @end example
  6046. @noindent
  6047. That declaration is equivalent to the following one:
  6048. @example
  6049. struct foo *x, *y;
  6050. @end example
  6051. You can define a typedef alias for any type. For instance, this makes
  6052. @code{frobcount} an alias for type @code{int}:
  6053. @example
  6054. typedef int frobcount;
  6055. @end example
  6056. @noindent
  6057. This doesn't define a new type distinct from @code{int}. Rather,
  6058. @code{frobcount} is another name for the type @code{int}. Once the
  6059. variable is declared, it makes no difference which name the
  6060. declaration used.
  6061. There is a syntactic difference, however, between @code{frobcount} and
  6062. @code{int}: A typedef name cannot be used with
  6063. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6064. to specify the type all by itself. So you can't write this:
  6065. @example
  6066. unsigned frobcount f1; /* @r{Error!} */
  6067. @end example
  6068. But you can write this:
  6069. @example
  6070. typedef unsigned int unsigned_frobcount;
  6071. unsigned_frobcount f1;
  6072. @end example
  6073. In other words, a typedef name is not an alias for @emph{a keyword}
  6074. such as @code{int}. It stands for a @emph{type}, and that could be
  6075. the type @code{int}.
  6076. Typedef names are in the same namespace as functions and variables, so
  6077. you can't use the same name for a typedef and a function, or a typedef
  6078. and a variable. When a typedef is declared inside a code block, it is
  6079. in scope only in that block.
  6080. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6081. because many of these have standard meanings.
  6082. You can redefine a typedef name to the exact same type as its first
  6083. definition, but you cannot redefine a typedef name to a
  6084. different type, even if the two types are compatible. For example, this
  6085. is valid:
  6086. @example
  6087. typedef int frobcount;
  6088. typedef int frotzcount;
  6089. typedef frotzcount frobcount;
  6090. typedef frobcount frotzcount;
  6091. @end example
  6092. @noindent
  6093. because each typedef name is always defined with the same type
  6094. (@code{int}), but this is not valid:
  6095. @example
  6096. enum foo @{f1, f2, f3@};
  6097. typedef enum foo frobcount;
  6098. typedef int frobcount;
  6099. @end example
  6100. @noindent
  6101. Even though the type @code{enum foo} is compatible with @code{int},
  6102. they are not the @emph{same} type.
  6103. @node Statements
  6104. @chapter Statements
  6105. @cindex statements
  6106. A @dfn{statement} specifies computations to be done for effect; it
  6107. does not produce a value, as an expression would. In general a
  6108. statement ends with a semicolon (@samp{;}), but blocks (which are
  6109. statements, more or less) are an exception to that rule.
  6110. @ifnottex
  6111. @xref{Blocks}.
  6112. @end ifnottex
  6113. The places to use statements are inside a block, and inside a
  6114. complex statement. A @dfn{complex statement} contains one or two
  6115. components that are nested statements. Each such component must
  6116. consist of one and only one statement. The way to put multiple
  6117. statements in such a component is to group them into a @dfn{block}
  6118. (@pxref{Blocks}), which counts as one statement.
  6119. The following sections describe the various kinds of statement.
  6120. @menu
  6121. * Expression Statement:: Evaluate an expression, as a statement,
  6122. usually done for a side effect.
  6123. * if Statement:: Basic conditional execution.
  6124. * if-else Statement:: Multiple branches for conditional execution.
  6125. * Blocks:: Grouping multiple statements together.
  6126. * return Statement:: Return a value from a function.
  6127. * Loop Statements:: Repeatedly executing a statement or block.
  6128. * switch Statement:: Multi-way conditional choices.
  6129. * switch Example:: A plausible example of using @code{switch}.
  6130. * Duffs Device:: A special way to use @code{switch}.
  6131. * Case Ranges:: Ranges of values for @code{switch} cases.
  6132. * Null Statement:: A statement that does nothing.
  6133. * goto Statement:: Jump to another point in the source code,
  6134. identified by a label.
  6135. * Local Labels:: Labels with limited scope.
  6136. * Labels as Values:: Getting the address of a label.
  6137. * Statement Exprs:: A series of statements used as an expression.
  6138. @end menu
  6139. @node Expression Statement
  6140. @section Expression Statement
  6141. @cindex expression statement
  6142. @cindex statement, expression
  6143. The most common kind of statement in C is an @dfn{expression statement}.
  6144. It consists of an expression followed by a
  6145. semicolon. The expression's value is discarded, so the expressions
  6146. that are useful are those that have side effects: assignment
  6147. expressions, increment and decrement expressions, and function calls.
  6148. Here are examples of expression statements:
  6149. @smallexample
  6150. x = 5; /* @r{Assignment expression.} */
  6151. p++; /* @r{Increment expression.} */
  6152. printf ("Done\n"); /* @r{Function call expression.} */
  6153. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6154. x + y; /* @r{Useless statement without effect.} */
  6155. @end smallexample
  6156. In very unusual circumstances we use an expression statement
  6157. whose purpose is to get a fault if an address is invalid:
  6158. @smallexample
  6159. volatile char *p;
  6160. @r{@dots{}}
  6161. *p; /* @r{Cause signal if @code{p} is null.} */
  6162. @end smallexample
  6163. If the target of @code{p} is not declared @code{volatile}, the
  6164. compiler might optimize away the memory access, since it knows that
  6165. the value isn't really used. @xref{volatile}.
  6166. @node if Statement
  6167. @section @code{if} Statement
  6168. @cindex @code{if} statement
  6169. @cindex statement, @code{if}
  6170. @findex if
  6171. An @code{if} statement computes an expression to decide
  6172. whether to execute the following statement or not.
  6173. It looks like this:
  6174. @example
  6175. if (@var{condition})
  6176. @var{execute-if-true}
  6177. @end example
  6178. The first thing this does is compute the value of @var{condition}. If
  6179. that is true (nonzero), then it executes the statement
  6180. @var{execute-if-true}. If the value of @var{condition} is false
  6181. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6182. nothing.
  6183. This is a @dfn{complex statement} because it contains a component
  6184. @var{if-true-substatement} that is a nested statement. It must be one
  6185. and only one statement. The way to put multiple statements there is
  6186. to group them into a @dfn{block} (@pxref{Blocks}).
  6187. @node if-else Statement
  6188. @section @code{if-else} Statement
  6189. @cindex @code{if}@dots{}@code{else} statement
  6190. @cindex statement, @code{if}@dots{}@code{else}
  6191. @findex else
  6192. An @code{if}-@code{else} statement computes an expression to decide
  6193. which of two nested statements to execute.
  6194. It looks like this:
  6195. @example
  6196. if (@var{condition})
  6197. @var{if-true-substatement}
  6198. else
  6199. @var{if-false-substatement}
  6200. @end example
  6201. The first thing this does is compute the value of @var{condition}. If
  6202. that is true (nonzero), then it executes the statement
  6203. @var{if-true-substatement}. If the value of @var{condition} is false
  6204. (zero), then it executes the statement @var{if-false-substatement} instead.
  6205. This is a @dfn{complex statement} because it contains components
  6206. @var{if-true-substatement} and @var{if-else-substatement} that are
  6207. nested statements. Each must be one and only one statement. The way
  6208. to put multiple statements in such a component is to group them into a
  6209. @dfn{block} (@pxref{Blocks}).
  6210. @node Blocks
  6211. @section Blocks
  6212. @cindex block
  6213. @cindex compound statement
  6214. A @dfn{block} is a construct that contains multiple statements of any
  6215. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6216. series of statements and declarations in between. Another name for
  6217. blocks is @dfn{compound statements}.
  6218. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6219. normal statement---it does not end with a semicolon. But you can
  6220. @emph{use} it like a statement; anywhere that a statement is required
  6221. or allowed, you can write a block and consider that block a statement.
  6222. So far it seems that a block is a kind of statement with an unusual
  6223. syntax. But that is not entirely true: a function body is also a
  6224. block, and that block is definitely not a statement. The text after a
  6225. function header is not treated as a statement; only a function body is
  6226. allowed there, and nothing else would be meaningful there.
  6227. In a formal grammar we would have to choose---either a block is a kind
  6228. of statement or it is not. But this manual is meant for humans, not
  6229. for parser generators. The clearest answer for humans is, ``a block
  6230. is a statement, in some ways.''
  6231. @cindex nested block
  6232. @cindex internal block
  6233. A block that isn't a function body is called an @dfn{internal block}
  6234. or a @dfn{nested block}. You can put a nested block directly inside
  6235. another block, but more often the nested block is inside some complex
  6236. statement, such as a @code{for} statement or an @code{if} statement.
  6237. There are two uses for nested blocks in C:
  6238. @itemize @bullet
  6239. @item
  6240. To specify the scope for local declarations. For instance, a local
  6241. variable's scope is the rest of the innermost containing block.
  6242. @item
  6243. To write a series of statements where, syntactically, one statement is
  6244. called for. For instance, the @var{execute-if-true} of an @code{if}
  6245. statement is one statement. To put multiple statements there, they
  6246. have to be wrapped in a block, like this:
  6247. @example
  6248. if (x < 0)
  6249. @{
  6250. printf ("x was negative\n");
  6251. x = -x;
  6252. @}
  6253. @end example
  6254. @end itemize
  6255. This example (repeated from above) shows a nested block which serves
  6256. both purposes: it includes two statements (plus a declaration) in the
  6257. body of a @code{while} statement, and it provides the scope for the
  6258. declaration of @code{q}.
  6259. @example
  6260. void
  6261. free_intlist (struct intlistlink *p)
  6262. @{
  6263. while (p)
  6264. @{
  6265. struct intlistlink *q = p;
  6266. p = p->next;
  6267. free (q);
  6268. @}
  6269. @}
  6270. @end example
  6271. @node return Statement
  6272. @section @code{return} Statement
  6273. @cindex @code{return} statement
  6274. @cindex statement, @code{return}
  6275. @findex return
  6276. The @code{return} statement makes the containing function return
  6277. immediately. It has two forms. This one specifies no value to
  6278. return:
  6279. @example
  6280. return;
  6281. @end example
  6282. @noindent
  6283. That form is meant for functions whose return type is @code{void}
  6284. (@pxref{The Void Type}). You can also use it in a function that
  6285. returns nonvoid data, but that's a bad idea, since it makes the
  6286. function return garbage.
  6287. The form that specifies a value looks like this:
  6288. @example
  6289. return @var{value};
  6290. @end example
  6291. @noindent
  6292. which computes the expression @var{value} and makes the function
  6293. return that. If necessary, the value undergoes type conversion to
  6294. the function's declared return value type, which works like
  6295. assigning the value to a variable of that type.
  6296. @node Loop Statements
  6297. @section Loop Statements
  6298. @cindex loop statements
  6299. @cindex statements, loop
  6300. @cindex iteration
  6301. You can use a loop statement when you need to execute a series of
  6302. statements repeatedly, making an @dfn{iteration}. C provides several
  6303. different kinds of loop statements, described in the following
  6304. subsections.
  6305. Every kind of loop statement is a complex statement because contains a
  6306. component, here called @var{body}, which is a nested statement.
  6307. Most often the body is a block.
  6308. @menu
  6309. * while Statement:: Loop as long as a test expression is true.
  6310. * do-while Statement:: Execute a loop once, with further looping
  6311. as long as a test expression is true.
  6312. * break Statement:: End a loop immediately.
  6313. * for Statement:: Iterative looping.
  6314. * Example of for:: An example of iterative looping.
  6315. * Omitted for-Expressions:: for-loop expression options.
  6316. * for-Index Declarations:: for-loop declaration options.
  6317. * continue Statement:: Begin the next cycle of a loop.
  6318. @end menu
  6319. @node while Statement
  6320. @subsection @code{while} Statement
  6321. @cindex @code{while} statement
  6322. @cindex statement, @code{while}
  6323. @findex while
  6324. The @code{while} statement is the simplest loop construct.
  6325. It looks like this:
  6326. @example
  6327. while (@var{test})
  6328. @var{body}
  6329. @end example
  6330. Here, @var{body} is a statement (often a nested block) to repeat, and
  6331. @var{test} is the test expression that controls whether to repeat it again.
  6332. Each iteration of the loop starts by computing @var{test} and, if it
  6333. is true (nonzero), that means the loop should execute @var{body} again
  6334. and then start over.
  6335. Here's an example of advancing to the last structure in a chain of
  6336. structures chained through the @code{next} field:
  6337. @example
  6338. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6339. @r{@dots{}}
  6340. while (chain->next != NULL)
  6341. chain = chain->next;
  6342. @end example
  6343. @noindent
  6344. This code assumes the chain isn't empty to start with; if the chain is
  6345. empty (that is, if @code{chain} is a null pointer), the code gets a
  6346. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6347. @node do-while Statement
  6348. @subsection @code{do-while} Statement
  6349. @cindex @code{do}--@code{while} statement
  6350. @cindex statement, @code{do}--@code{while}
  6351. @findex do
  6352. The @code{do}--@code{while} statement is a simple loop construct that
  6353. performs the test at the end of the iteration.
  6354. @example
  6355. do
  6356. @var{body}
  6357. while (@var{test});
  6358. @end example
  6359. Here, @var{body} is a statement (possibly a block) to repeat, and
  6360. @var{test} is an expression that controls whether to repeat it again.
  6361. Each iteration of the loop starts by executing @var{body}. Then it
  6362. computes @var{test} and, if it is true (nonzero), that means to go
  6363. back and start over with @var{body}. If @var{test} is false (zero),
  6364. then the loop stops repeating and execution moves on past it.
  6365. @node break Statement
  6366. @subsection @code{break} Statement
  6367. @cindex @code{break} statement
  6368. @cindex statement, @code{break}
  6369. @findex break
  6370. The @code{break} statement looks like @samp{break;}. Its effect is to
  6371. exit immediately from the innermost loop construct or @code{switch}
  6372. statement (@pxref{switch Statement}).
  6373. For example, this loop advances @code{p} until the next null
  6374. character or newline.
  6375. @example
  6376. while (*p)
  6377. @{
  6378. /* @r{End loop if we have reached a newline.} */
  6379. if (*p == '\n')
  6380. break;
  6381. p++
  6382. @}
  6383. @end example
  6384. When there are nested loops, the @code{break} statement exits from the
  6385. innermost loop containing it.
  6386. @example
  6387. struct list_if_tuples
  6388. @{
  6389. struct list_if_tuples next;
  6390. int length;
  6391. data *contents;
  6392. @};
  6393. void
  6394. process_all_elements (struct list_if_tuples *list)
  6395. @{
  6396. while (list)
  6397. @{
  6398. /* @r{Process all the elements in this node's vector,}
  6399. @r{stopping when we reach one that is null.} */
  6400. for (i = 0; i < list->length; i++
  6401. @{
  6402. /* @r{Null element terminates this node's vector.} */
  6403. if (list->contents[i] == NULL)
  6404. /* @r{Exit the @code{for} loop.} */
  6405. break;
  6406. /* @r{Operate on the next element.} */
  6407. process_element (list->contents[i]);
  6408. @}
  6409. list = list->next;
  6410. @}
  6411. @}
  6412. @end example
  6413. The only way in C to exit from an outer loop is with
  6414. @code{goto} (@pxref{goto Statement}).
  6415. @node for Statement
  6416. @subsection @code{for} Statement
  6417. @cindex @code{for} statement
  6418. @cindex statement, @code{for}
  6419. @findex for
  6420. A @code{for} statement uses three expressions written inside a
  6421. parenthetical group to define the repetition of the loop. The first
  6422. expression says how to prepare to start the loop. The second says how
  6423. to test, before each iteration, whether to continue looping. The
  6424. third says how to advance, at the end of an iteration, for the next
  6425. iteration. All together, it looks like this:
  6426. @example
  6427. for (@var{start}; @var{continue-test}; @var{advance})
  6428. @var{body}
  6429. @end example
  6430. The first thing the @code{for} statement does is compute @var{start}.
  6431. The next thing it does is compute the expression @var{continue-test}.
  6432. If that expression is false (zero), the @code{for} statement finishes
  6433. immediately, so @var{body} is executed zero times.
  6434. However, if @var{continue-test} is true (nonzero), the @code{for}
  6435. statement executes @var{body}, then @var{advance}. Then it loops back
  6436. to the not-quite-top to test @var{continue-test} again. But it does
  6437. not compute @var{start} again.
  6438. @node Example of for
  6439. @subsection Example of @code{for}
  6440. Here is the @code{for} statement from the iterative Fibonacci
  6441. function:
  6442. @example
  6443. int i;
  6444. for (i = 1; i < n; ++i)
  6445. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6446. /* @r{since @code{i < n} is false the first time.} */
  6447. @{
  6448. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6449. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6450. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6451. int next = prev + last;
  6452. /* @r{Shift the values down.} */
  6453. prev = last;
  6454. last = next;
  6455. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6456. @r{and @var{prev} is @code{fib (@var{i})}.}
  6457. @r{But that won't stay true for long,}
  6458. @r{because we are about to increment @var{i}.} */
  6459. @}
  6460. @end example
  6461. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6462. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6463. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6464. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6465. that contains a declaration and two statements.
  6466. @node Omitted for-Expressions
  6467. @subsection Omitted @code{for}-Expressions
  6468. A fully-fleshed @code{for} statement contains all these parts,
  6469. @example
  6470. for (@var{start}; @var{continue-test}; @var{advance})
  6471. @var{body}
  6472. @end example
  6473. @noindent
  6474. but you can omit any of the three expressions inside the parentheses.
  6475. The parentheses and the two semicolons are required syntactically, but
  6476. the expressions between them may be missing. A missing expression
  6477. means this loop doesn't use that particular feature of the @code{for}
  6478. statement.
  6479. @c ??? You can't do this if START is a declaration.
  6480. Instead of using @var{start}, you can do the loop preparation
  6481. before the @code{for} statement: the effect is the same. So we
  6482. could have written the beginning of the previous example this way:
  6483. @example
  6484. int i = 0;
  6485. for (; i < n; ++i)
  6486. @end example
  6487. @noindent
  6488. instead of this way:
  6489. @example
  6490. int i;
  6491. for (i = 0; i < n; ++i)
  6492. @end example
  6493. Omitting @var{continue-test} means the loop runs forever (or until
  6494. something else causes exit from it). Statements inside the loop can
  6495. test conditions for termination and use @samp{break;} to exit. This
  6496. is more flexible since you can put those tests anywhere in the loop,
  6497. not solely at the beginning.
  6498. Putting an expression in @var{advance} is almost equivalent to writing
  6499. it at the end of the loop body; it does almost the same thing. The
  6500. only difference is for the @code{continue} statement (@pxref{continue
  6501. Statement}). So we could have written this:
  6502. @example
  6503. for (i = 0; i < n;)
  6504. @{
  6505. @r{@dots{}}
  6506. ++i;
  6507. @}
  6508. @end example
  6509. @noindent
  6510. instead of this:
  6511. @example
  6512. for (i = 0; i < n; ++i)
  6513. @{
  6514. @r{@dots{}}
  6515. @}
  6516. @end example
  6517. The choice is mainly a matter of what is more readable for
  6518. programmers. However, there is also a syntactic difference:
  6519. @var{advance} is an expression, not a statement. It can't include
  6520. loops, blocks, declarations, etc.
  6521. @node for-Index Declarations
  6522. @subsection @code{for}-Index Declarations
  6523. You can declare loop-index variables directly in the @var{start}
  6524. portion of the @code{for}-loop, like this:
  6525. @example
  6526. for (int i = 0; i < n; ++i)
  6527. @{
  6528. @r{@dots{}}
  6529. @}
  6530. @end example
  6531. This kind of @var{start} is limited to a single declaration; it can
  6532. declare one or more variables, separated by commas, all of which are
  6533. the same @var{basetype} (@code{int}, in this example):
  6534. @example
  6535. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6536. @{
  6537. @r{@dots{}}
  6538. @}
  6539. @end example
  6540. @noindent
  6541. The scope of these variables is the @code{for} statement as a whole.
  6542. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6543. Variables declared in @code{for} statements should have initializers.
  6544. Omitting the initialization gives the variables unpredictable initial
  6545. values, so this code is erroneous.
  6546. @example
  6547. for (int i; i < n; ++i)
  6548. @{
  6549. @r{@dots{}}
  6550. @}
  6551. @end example
  6552. @node continue Statement
  6553. @subsection @code{continue} Statement
  6554. @cindex @code{continue} statement
  6555. @cindex statement, @code{continue}
  6556. @findex continue
  6557. The @code{continue} statement looks like @samp{continue;}, and its
  6558. effect is to jump immediately to the end of the innermost loop
  6559. construct. If it is a @code{for}-loop, the next thing that happens
  6560. is to execute the loop's @var{advance} expression.
  6561. For example, this loop increments @code{p} until the next null character
  6562. or newline, and operates (in some way not shown) on all the characters
  6563. in the line except for spaces. All it does with spaces is skip them.
  6564. @example
  6565. for (;*p; ++p)
  6566. @{
  6567. /* @r{End loop if we have reached a newline.} */
  6568. if (*p == '\n')
  6569. break;
  6570. /* @r{Pay no attention to spaces.} */
  6571. if (*p == ' ')
  6572. continue;
  6573. /* @r{Operate on the next character.} */
  6574. @r{@dots{}}
  6575. @}
  6576. @end example
  6577. @noindent
  6578. Executing @samp{continue;} skips the loop body but it does not
  6579. skip the @var{advance} expression, @code{p++}.
  6580. We could also write it like this:
  6581. @example
  6582. for (;*p; ++p)
  6583. @{
  6584. /* @r{Exit if we have reached a newline.} */
  6585. if (*p == '\n')
  6586. break;
  6587. /* @r{Pay no attention to spaces.} */
  6588. if (*p != ' ')
  6589. @{
  6590. /* @r{Operate on the next character.} */
  6591. @r{@dots{}}
  6592. @}
  6593. @}
  6594. @end example
  6595. The advantage of using @code{continue} is that it reduces the
  6596. depth of nesting.
  6597. Contrast @code{continue} with the @code{break} statement. @xref{break
  6598. Statement}.
  6599. @node switch Statement
  6600. @section @code{switch} Statement
  6601. @cindex @code{switch} statement
  6602. @cindex statement, @code{switch}
  6603. @findex switch
  6604. @findex case
  6605. @findex default
  6606. The @code{switch} statement selects code to run according to the value
  6607. of an expression. The expression, in parentheses, follows the keyword
  6608. @code{switch}. After that come all the cases to select among,
  6609. inside braces. It looks like this:
  6610. @example
  6611. switch (@var{selector})
  6612. @{
  6613. @var{cases}@r{@dots{}}
  6614. @}
  6615. @end example
  6616. A case can look like this:
  6617. @example
  6618. case @var{value}:
  6619. @var{statements}
  6620. break;
  6621. @end example
  6622. @noindent
  6623. which means ``come here if @var{selector} happens to have the value
  6624. @var{value},'' or like this (a GNU C extension):
  6625. @example
  6626. case @var{rangestart} ... @var{rangeend}:
  6627. @var{statements}
  6628. break;
  6629. @end example
  6630. @noindent
  6631. which means ``come here if @var{selector} happens to have a value
  6632. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6633. Ranges}.
  6634. The values in @code{case} labels must reduce to integer constants.
  6635. They can use arithmetic, and @code{enum} constants, but they cannot
  6636. refer to data in memory, because they have to be computed at compile
  6637. time. It is an error if two @code{case} labels specify the same
  6638. value, or ranges that overlap, or if one is a range and the other is a
  6639. value in that range.
  6640. You can also define a default case to handle ``any other value,'' like
  6641. this:
  6642. @example
  6643. default:
  6644. @var{statements}
  6645. break;
  6646. @end example
  6647. If the @code{switch} statement has no @code{default:} label, then it
  6648. does nothing when the value matches none of the cases.
  6649. The brace-group inside the @code{switch} statement is a block, and you
  6650. can declare variables with that scope just as in any other block
  6651. (@pxref{Blocks}). However, initializers in these declarations won't
  6652. necessarily be executed every time the @code{switch} statement runs,
  6653. so it is best to avoid giving them initializers.
  6654. @code{break;} inside a @code{switch} statement exits immediately from
  6655. the @code{switch} statement. @xref{break Statement}.
  6656. If there is no @code{break;} at the end of the code for a case,
  6657. execution continues into the code for the following case. This
  6658. happens more often by mistake than intentionally, but since this
  6659. feature is used in real code, we cannot eliminate it.
  6660. @strong{Warning:} When one case is intended to fall through to the
  6661. next, write a comment like @samp{falls through} to say it's
  6662. intentional. That way, other programmers won't assume it was an error
  6663. and ``fix'' it erroneously.
  6664. Consecutive @code{case} statements could, pedantically, be considered
  6665. an instance of falling through, but we don't consider or treat them that
  6666. way because they won't confuse anyone.
  6667. @node switch Example
  6668. @section Example of @code{switch}
  6669. Here's an example of using the @code{switch} statement
  6670. to distinguish among characters:
  6671. @cindex counting vowels and punctuation
  6672. @example
  6673. struct vp @{ int vowels, punct; @};
  6674. struct vp
  6675. count_vowels_and_punct (char *string)
  6676. @{
  6677. int c;
  6678. int vowels = 0;
  6679. int punct = 0;
  6680. /* @r{Don't change the parameter itself.} */
  6681. /* @r{That helps in debugging.} */
  6682. char *p = string;
  6683. struct vp value;
  6684. while (c = *p++)
  6685. switch (c)
  6686. @{
  6687. case 'y':
  6688. case 'Y':
  6689. /* @r{We assume @code{y_is_consonant} will check surrounding
  6690. letters to determine whether this y is a vowel.} */
  6691. if (y_is_consonant (p - 1))
  6692. break;
  6693. /* @r{Falls through} */
  6694. case 'a':
  6695. case 'e':
  6696. case 'i':
  6697. case 'o':
  6698. case 'u':
  6699. case 'A':
  6700. case 'E':
  6701. case 'I':
  6702. case 'O':
  6703. case 'U':
  6704. vowels++;
  6705. break;
  6706. case '.':
  6707. case ',':
  6708. case ':':
  6709. case ';':
  6710. case '?':
  6711. case '!':
  6712. case '\"':
  6713. case '\'':
  6714. punct++;
  6715. break;
  6716. @}
  6717. value.vowels = vowels;
  6718. value.punct = punct;
  6719. return value;
  6720. @}
  6721. @end example
  6722. @node Duffs Device
  6723. @section Duff's Device
  6724. @cindex Duff's device
  6725. The cases in a @code{switch} statement can be inside other control
  6726. constructs. For instance, we can use a technique known as @dfn{Duff's
  6727. device} to optimize this simple function,
  6728. @example
  6729. void
  6730. copy (char *to, char *from, int count)
  6731. @{
  6732. while (count > 0)
  6733. *to++ = *from++, count--;
  6734. @}
  6735. @end example
  6736. @noindent
  6737. which copies memory starting at @var{from} to memory starting at
  6738. @var{to}.
  6739. Duff's device involves unrolling the loop so that it copies
  6740. several characters each time around, and using a @code{switch} statement
  6741. to enter the loop body at the proper point:
  6742. @example
  6743. void
  6744. copy (char *to, char *from, int count)
  6745. @{
  6746. if (count <= 0)
  6747. return;
  6748. int n = (count + 7) / 8;
  6749. switch (count % 8)
  6750. @{
  6751. do @{
  6752. case 0: *to++ = *from++;
  6753. case 7: *to++ = *from++;
  6754. case 6: *to++ = *from++;
  6755. case 5: *to++ = *from++;
  6756. case 4: *to++ = *from++;
  6757. case 3: *to++ = *from++;
  6758. case 2: *to++ = *from++;
  6759. case 1: *to++ = *from++;
  6760. @} while (--n > 0);
  6761. @}
  6762. @}
  6763. @end example
  6764. @node Case Ranges
  6765. @section Case Ranges
  6766. @cindex case ranges
  6767. @cindex ranges in case statements
  6768. You can specify a range of consecutive values in a single @code{case} label,
  6769. like this:
  6770. @example
  6771. case @var{low} ... @var{high}:
  6772. @end example
  6773. @noindent
  6774. This has the same effect as the proper number of individual @code{case}
  6775. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6776. This feature is especially useful for ranges of ASCII character codes:
  6777. @example
  6778. case 'A' ... 'Z':
  6779. @end example
  6780. @strong{Be careful:} with integers, write spaces around the @code{...}
  6781. to prevent it from being parsed wrong. For example, write this:
  6782. @example
  6783. case 1 ... 5:
  6784. @end example
  6785. @noindent
  6786. rather than this:
  6787. @example
  6788. case 1...5:
  6789. @end example
  6790. @node Null Statement
  6791. @section Null Statement
  6792. @cindex null statement
  6793. @cindex statement, null
  6794. A @dfn{null statement} is just a semicolon. It does nothing.
  6795. A null statement is a placeholder for use where a statement is
  6796. grammatically required, but there is nothing to be done. For
  6797. instance, sometimes all the work of a @code{for}-loop is done in the
  6798. @code{for}-header itself, leaving no work for the body. Here is an
  6799. example that searches for the first newline in @code{array}:
  6800. @example
  6801. for (p = array; *p != '\n'; p++)
  6802. ;
  6803. @end example
  6804. @node goto Statement
  6805. @section @code{goto} Statement and Labels
  6806. @cindex @code{goto} statement
  6807. @cindex statement, @code{goto}
  6808. @cindex label
  6809. @findex goto
  6810. The @code{goto} statement looks like this:
  6811. @example
  6812. goto @var{label};
  6813. @end example
  6814. @noindent
  6815. Its effect is to transfer control immediately to another part of the
  6816. current function---where the label named @var{label} is defined.
  6817. An ordinary label definition looks like this:
  6818. @example
  6819. @var{label}:
  6820. @end example
  6821. @noindent
  6822. and it can appear before any statement. You can't use @code{default}
  6823. as a label, since that has a special meaning for @code{switch}
  6824. statements.
  6825. An ordinary label doesn't need a separate declaration; defining it is
  6826. enough.
  6827. Here's an example of using @code{goto} to implement a loop
  6828. equivalent to @code{do}--@code{while}:
  6829. @example
  6830. @{
  6831. loop_restart:
  6832. @var{body}
  6833. if (@var{condition})
  6834. goto loop_restart;
  6835. @}
  6836. @end example
  6837. The name space of labels is separate from that of variables and functions.
  6838. Thus, there is no error in using a single name in both ways:
  6839. @example
  6840. @{
  6841. int foo; // @r{Variable @code{foo}.}
  6842. foo: // @r{Label @code{foo}.}
  6843. @var{body}
  6844. if (foo > 0) // @r{Variable @code{foo}.}
  6845. goto foo; // @r{Label @code{foo}.}
  6846. @}
  6847. @end example
  6848. Blocks have no effect on ordinary labels; each label name is defined
  6849. throughout the whole of the function it appears in. It looks strange to
  6850. jump into a block with @code{goto}, but it works. For example,
  6851. @example
  6852. if (x < 0)
  6853. goto negative;
  6854. if (y < 0)
  6855. @{
  6856. negative:
  6857. printf ("Negative\n");
  6858. return;
  6859. @}
  6860. @end example
  6861. If the goto jumps into the scope of a variable, it does not
  6862. initialize the variable. For example, if @code{x} is negative,
  6863. @example
  6864. if (x < 0)
  6865. goto negative;
  6866. if (y < 0)
  6867. @{
  6868. int i = 5;
  6869. negative:
  6870. printf ("Negative, and i is %d\n", i);
  6871. return;
  6872. @}
  6873. @end example
  6874. @noindent
  6875. prints junk because @code{i} was not initialized.
  6876. If the block declares a variable-length automatic array, jumping into
  6877. it gives a compilation error. However, jumping out of the scope of a
  6878. variable-length array works fine, and deallocates its storage.
  6879. A label can't come directly before a declaration, so the code can't
  6880. jump directly to one. For example, this is not allowed:
  6881. @example
  6882. @{
  6883. goto foo;
  6884. foo:
  6885. int x = 5;
  6886. bar(&x);
  6887. @}
  6888. @end example
  6889. @noindent
  6890. The workaround is to add a statement, even an empty statement,
  6891. directly after the label. For example:
  6892. @example
  6893. @{
  6894. goto foo;
  6895. foo:
  6896. ;
  6897. int x = 5;
  6898. bar(&x);
  6899. @}
  6900. @end example
  6901. Likewise, a label can't be the last thing in a block. The workaround
  6902. solution is the same: add a semicolon after the label.
  6903. These unnecessary restrictions on labels make no sense, and ought in
  6904. principle to be removed; but they do only a little harm since labels
  6905. and @code{goto} are rarely the best way to write a program.
  6906. These examples are all artificial; it would be more natural to
  6907. write them in other ways, without @code{goto}. For instance,
  6908. the clean way to write the example that prints @samp{Negative} is this:
  6909. @example
  6910. if (x < 0 || y < 0)
  6911. @{
  6912. printf ("Negative\n");
  6913. return;
  6914. @}
  6915. @end example
  6916. @noindent
  6917. It is hard to construct simple examples where @code{goto} is actually
  6918. the best way to write a program. Its rare good uses tend to be in
  6919. complex code, thus not apt for the purpose of explaining the meaning
  6920. of @code{goto}.
  6921. The only good time to use @code{goto} is when it makes the code
  6922. simpler than any alternative. Jumping backward is rarely desirable,
  6923. because usually the other looping and control constructs give simpler
  6924. code. Using @code{goto} to jump forward is more often desirable, for
  6925. instance when a function needs to do some processing in an error case
  6926. and errors can occur at various different places within the function.
  6927. @node Local Labels
  6928. @section Locally Declared Labels
  6929. @cindex local labels
  6930. @cindex macros, local labels
  6931. @findex __label__
  6932. In GNU C you can declare @dfn{local labels} in any nested block
  6933. scope. A local label is used in a @code{goto} statement just like an
  6934. ordinary label, but you can only reference it within the block in
  6935. which it was declared.
  6936. A local label declaration looks like this:
  6937. @example
  6938. __label__ @var{label};
  6939. @end example
  6940. @noindent
  6941. or
  6942. @example
  6943. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6944. @end example
  6945. Local label declarations must come at the beginning of the block,
  6946. before any ordinary declarations or statements.
  6947. The label declaration declares the label @emph{name}, but does not define
  6948. the label itself. That's done in the usual way, with
  6949. @code{@var{label}:}, before one of the statements in the block.
  6950. The local label feature is useful for complex macros. If a macro
  6951. contains nested loops, a @code{goto} can be useful for breaking out of
  6952. them. However, an ordinary label whose scope is the whole function
  6953. cannot be used: if the macro can be expanded several times in one
  6954. function, the label will be multiply defined in that function. A
  6955. local label avoids this problem. For example:
  6956. @example
  6957. #define SEARCH(value, array, target) \
  6958. do @{ \
  6959. __label__ found; \
  6960. __auto_type _SEARCH_target = (target); \
  6961. __auto_type _SEARCH_array = (array); \
  6962. int i, j; \
  6963. int value; \
  6964. for (i = 0; i < max; i++) \
  6965. for (j = 0; j < max; j++) \
  6966. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6967. @{ (value) = i; goto found; @} \
  6968. (value) = -1; \
  6969. found:; \
  6970. @} while (0)
  6971. @end example
  6972. This could also be written using a statement expression
  6973. (@pxref{Statement Exprs}):
  6974. @example
  6975. #define SEARCH(array, target) \
  6976. (@{ \
  6977. __label__ found; \
  6978. __auto_type _SEARCH_target = (target); \
  6979. __auto_type _SEARCH_array = (array); \
  6980. int i, j; \
  6981. int value; \
  6982. for (i = 0; i < max; i++) \
  6983. for (j = 0; j < max; j++) \
  6984. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6985. @{ value = i; goto found; @} \
  6986. value = -1; \
  6987. found: \
  6988. value; \
  6989. @})
  6990. @end example
  6991. Ordinary labels are visible throughout the function where they are
  6992. defined, and only in that function. However, explicitly declared
  6993. local labels of a block are visible in nested function definitions
  6994. inside that block. @xref{Nested Functions}, for details.
  6995. @xref{goto Statement}.
  6996. @node Labels as Values
  6997. @section Labels as Values
  6998. @cindex labels as values
  6999. @cindex computed gotos
  7000. @cindex goto with computed label
  7001. @cindex address of a label
  7002. In GNU C, you can get the address of a label defined in the current
  7003. function (or a local label defined in the containing function) with
  7004. the unary operator @samp{&&}. The value has type @code{void *}. This
  7005. value is a constant and can be used wherever a constant of that type
  7006. is valid. For example:
  7007. @example
  7008. void *ptr;
  7009. @r{@dots{}}
  7010. ptr = &&foo;
  7011. @end example
  7012. To use these values requires a way to jump to one. This is done
  7013. with the computed goto statement@footnote{The analogous feature in
  7014. Fortran is called an assigned goto, but that name seems inappropriate in
  7015. C, since you can do more with label addresses than store them in special label
  7016. variables.}, @code{goto *@var{exp};}. For example,
  7017. @example
  7018. goto *ptr;
  7019. @end example
  7020. @noindent
  7021. Any expression of type @code{void *} is allowed.
  7022. @xref{goto Statement}.
  7023. @menu
  7024. * Label Value Uses:: Examples of using label values.
  7025. * Label Value Caveats:: Limitations of label values.
  7026. @end menu
  7027. @node Label Value Uses
  7028. @subsection Label Value Uses
  7029. One use for label-valued constants is to initialize a static array to
  7030. serve as a jump table:
  7031. @example
  7032. static void *array[] = @{ &&foo, &&bar, &&hack @};
  7033. @end example
  7034. Then you can select a label with indexing, like this:
  7035. @example
  7036. goto *array[i];
  7037. @end example
  7038. @noindent
  7039. Note that this does not check whether the subscript is in bounds---array
  7040. indexing in C never checks that.
  7041. You can make the table entries offsets instead of addresses
  7042. by subtracting one label from the others. Here is an example:
  7043. @example
  7044. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  7045. &&hack - &&foo @};
  7046. goto *(&&foo + array[i]);
  7047. @end example
  7048. @noindent
  7049. Using offsets is preferable in shared libraries, as it avoids the need
  7050. for dynamic relocation of the array elements; therefore, the array can
  7051. be read-only.
  7052. An array of label values or offsets serves a purpose much like that of
  7053. the @code{switch} statement. The @code{switch} statement is cleaner,
  7054. so use @code{switch} by preference when feasible.
  7055. Another use of label values is in an interpreter for threaded code.
  7056. The labels within the interpreter function can be stored in the
  7057. threaded code for super-fast dispatching.
  7058. @node Label Value Caveats
  7059. @subsection Label Value Caveats
  7060. Jumping to a label defined in another function does not work.
  7061. It can cause unpredictable results.
  7062. The best way to avoid this is to store label values only in
  7063. automatic variables, or static variables whose names are declared
  7064. within the function. Never pass them as arguments.
  7065. @cindex cloning
  7066. An optimization known as @dfn{cloning} generates multiple simplified
  7067. variants of a function's code, for use with specific fixed arguments.
  7068. Using label values in certain ways, such as saving the address in one
  7069. call to the function and using it again in another call, would make cloning
  7070. give incorrect results. These functions must disable cloning.
  7071. Inlining calls to the function would also result in multiple copies of
  7072. the code, each with its own value of the same label. Using the label
  7073. in a computed goto is no problem, because the computed goto inhibits
  7074. inlining. However, using the label value in some other way, such as
  7075. an indication of where an error occurred, would be optimized wrong.
  7076. These functions must disable inlining.
  7077. To prevent inlining or cloning of a function, specify
  7078. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7079. @xref{Attributes}.
  7080. When a function uses a label value in a static variable initializer,
  7081. that automatically prevents inlining or cloning the function.
  7082. @node Statement Exprs
  7083. @section Statements and Declarations in Expressions
  7084. @cindex statements inside expressions
  7085. @cindex declarations inside expressions
  7086. @cindex expressions containing statements
  7087. @c the above section title wrapped and causes an underfull hbox.. i
  7088. @c changed it from "within" to "in". --mew 4feb93
  7089. A block enclosed in parentheses can be used as an expression in GNU
  7090. C@. This provides a way to use local variables, loops and switches within
  7091. an expression. We call it a @dfn{statement expression}.
  7092. Recall that a block is a sequence of statements
  7093. surrounded by braces. In this construct, parentheses go around the
  7094. braces. For example:
  7095. @example
  7096. (@{ int y = foo (); int z;
  7097. if (y > 0) z = y;
  7098. else z = - y;
  7099. z; @})
  7100. @end example
  7101. @noindent
  7102. is a valid (though slightly more complex than necessary) expression
  7103. for the absolute value of @code{foo ()}.
  7104. The last statement in the block should be an expression statement; an
  7105. expression followed by a semicolon, that is. The value of this
  7106. expression serves as the value of statement expression. If the last
  7107. statement is anything else, the statement expression's value is
  7108. @code{void}.
  7109. This feature is mainly useful in making macro definitions compute each
  7110. operand exactly once. @xref{Macros and Auto Type}.
  7111. Statement expressions are not allowed in expressions that must be
  7112. constant, such as the value for an enumerator, the width of a
  7113. bit-field, or the initial value of a static variable.
  7114. Jumping into a statement expression---with @code{goto}, or using a
  7115. @code{switch} statement outside the statement expression---is an
  7116. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7117. compiler can't detect the error, but it still won't work.
  7118. Jumping out of a statement expression is permitted, but since
  7119. subexpressions in C are not computed in a strict order, it is
  7120. unpredictable which other subexpressions will have been computed by
  7121. then. For example,
  7122. @example
  7123. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7124. @end example
  7125. @noindent
  7126. calls @code{foo} and @code{bar1} before it jumps, and never
  7127. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7128. does get called, that occurs after @code{foo} and before @code{bar1}.
  7129. @node Variables
  7130. @chapter Variables
  7131. @cindex variables
  7132. Every variable used in a C program needs to be made known by a
  7133. @dfn{declaration}. It can be used only after it has been declared.
  7134. It is an error to declare a variable name more than once in the same
  7135. scope; an exception is that @code{extern} declarations and tentative
  7136. definitions can coexist with another declaration of the same
  7137. variable.
  7138. Variables can be declared anywhere within a block or file. (Older
  7139. versions of C required that all variable declarations within a block
  7140. occur before any statements.)
  7141. Variables declared within a function or block are @dfn{local} to
  7142. it. This means that the variable name is visible only until the end
  7143. of that function or block, and the memory space is allocated only
  7144. while control is within it.
  7145. Variables declared at the top level in a file are called @dfn{file-scope}.
  7146. They are assigned fixed, distinct memory locations, so they retain
  7147. their values for the whole execution of the program.
  7148. @menu
  7149. * Variable Declarations:: Name a variable and and reserve space for it.
  7150. * Initializers:: Assigning initial values to variables.
  7151. * Designated Inits:: Assigning initial values to array elements
  7152. at particular array indices.
  7153. * Auto Type:: Obtaining the type of a variable.
  7154. * Local Variables:: Variables declared in function definitions.
  7155. * File-Scope Variables:: Variables declared outside of
  7156. function definitions.
  7157. * Static Local Variables:: Variables declared within functions,
  7158. but with permanent storage allocation.
  7159. * Extern Declarations:: Declaring a variable
  7160. which is allocated somewhere else.
  7161. * Allocating File-Scope:: When is space allocated
  7162. for file-scope variables?
  7163. * auto and register:: Historically used storage directions.
  7164. * Omitting Types:: The bad practice of declaring variables
  7165. with implicit type.
  7166. @end menu
  7167. @node Variable Declarations
  7168. @section Variable Declarations
  7169. @cindex variable declarations
  7170. @cindex declaration of variables
  7171. Here's what a variable declaration looks like:
  7172. @example
  7173. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7174. @end example
  7175. The @var{keywords} specify how to handle the scope of the variable
  7176. name and the allocation of its storage. Most declarations have
  7177. no keywords because the defaults are right for them.
  7178. C allows these keywords to come before or after @var{basetype}, or
  7179. even in the middle of it as in @code{unsigned static int}, but don't
  7180. do that---it would surprise other programmers. Always write the
  7181. keywords first.
  7182. The @var{basetype} can be any of the predefined types of C, or a type
  7183. keyword defined with @code{typedef}. It can also be @code{struct
  7184. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7185. addition, it can include type qualifiers such as @code{const} and
  7186. @code{volatile} (@pxref{Type Qualifiers}).
  7187. In the simplest case, @var{decorated-variable} is just the variable
  7188. name. That declares the variable with the type specified by
  7189. @var{basetype}. For instance,
  7190. @example
  7191. int foo;
  7192. @end example
  7193. @noindent
  7194. uses @code{int} as the @var{basetype} and @code{foo} as the
  7195. @var{decorated-variable}. It declares @code{foo} with type
  7196. @code{int}.
  7197. @example
  7198. struct tree_node foo;
  7199. @end example
  7200. @noindent
  7201. declares @code{foo} with type @code{struct tree_node}.
  7202. @menu
  7203. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7204. array and pointer types.
  7205. * Combining Variable Declarations:: More than one variable declaration
  7206. in a single statement.
  7207. @end menu
  7208. @node Declaring Arrays and Pointers
  7209. @subsection Declaring Arrays and Pointers
  7210. @cindex declaring arrays and pointers
  7211. @cindex array, declaring
  7212. @cindex pointers, declaring
  7213. To declare a variable that is an array, write
  7214. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7215. @example
  7216. int foo[5];
  7217. @end example
  7218. To declare a variable that has a pointer type, write
  7219. @code{*@var{variable}} for @var{decorated-variable}:
  7220. @example
  7221. struct list_elt *foo;
  7222. @end example
  7223. These constructs nest. For instance,
  7224. @example
  7225. int foo[3][5];
  7226. @end example
  7227. @noindent
  7228. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7229. @example
  7230. struct list_elt *foo[5];
  7231. @end example
  7232. @noindent
  7233. declares @code{foo} as an array of 5 pointers to structures, and
  7234. @example
  7235. struct list_elt **foo;
  7236. @end example
  7237. @noindent
  7238. declares @code{foo} as a pointer to a pointer to a structure.
  7239. @example
  7240. int **(*foo[30])(int, double);
  7241. @end example
  7242. @noindent
  7243. declares @code{foo} as an array of 30 pointers to functions
  7244. (@pxref{Function Pointers}), each of which must accept two arguments
  7245. (one @code{int} and one @code{double}) and return type @code{int **}.
  7246. @example
  7247. void
  7248. bar (int size)
  7249. @{
  7250. int foo[size];
  7251. @r{@dots{}}
  7252. @}
  7253. @end example
  7254. @noindent
  7255. declares @code{foo} as an array of integers with a size specified at
  7256. run time when the function @code{bar} is called.
  7257. @node Combining Variable Declarations
  7258. @subsection Combining Variable Declarations
  7259. @cindex combining variable declarations
  7260. @cindex variable declarations, combining
  7261. @cindex declarations, combining
  7262. When multiple declarations have the same @var{keywords} and
  7263. @var{basetype}, you can combine them using commas. Thus,
  7264. @example
  7265. @var{keywords} @var{basetype}
  7266. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7267. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7268. @end example
  7269. @noindent
  7270. is equivalent to
  7271. @example
  7272. @var{keywords} @var{basetype}
  7273. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7274. @var{keywords} @var{basetype}
  7275. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7276. @end example
  7277. Here are some simple examples:
  7278. @example
  7279. int a, b;
  7280. int a = 1, b = 2;
  7281. int a, *p, array[5];
  7282. int a = 0, *p = &a, array[5] = @{1, 2@};
  7283. @end example
  7284. @noindent
  7285. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7286. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7287. Since the initializer for @code{array} specifies only two elements,
  7288. the other three elements are initialized to zero.
  7289. @node Initializers
  7290. @section Initializers
  7291. @cindex initializers
  7292. A variable's declaration, unless it is @code{extern}, should also
  7293. specify its initial value. For numeric and pointer-type variables,
  7294. the initializer is an expression for the value. If necessary, it is
  7295. converted to the variable's type, just as in an assignment.
  7296. You can also initialize a local structure-type (@pxref{Structures}) or
  7297. local union-type (@pxref{Unions}) variable this way, from an
  7298. expression whose value has the same type. But you can't initialize an
  7299. array this way (@pxref{Arrays}), since arrays are not first-class
  7300. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7301. assignment.
  7302. You can initialize arrays and structures componentwise,
  7303. with a list of the elements or components. You can initialize
  7304. a union with any one of its alternatives.
  7305. @itemize @bullet
  7306. @item
  7307. A component-wise initializer for an array consists of element values
  7308. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7309. don't cover all the elements in the array, the remaining elements are
  7310. initialized to zero.
  7311. You can omit the size of the array when you declare it, and let
  7312. the initializer specify the size:
  7313. @example
  7314. int array[] = @{ 3, 9, 12 @};
  7315. @end example
  7316. @item
  7317. A component-wise initializer for a structure consists of field values
  7318. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7319. order as the fields are declared in the structure. If the values in
  7320. the initializer don't cover all the fields in the structure, the
  7321. remaining fields are initialized to zero.
  7322. @item
  7323. The initializer for a union-type variable has the form @code{@{
  7324. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7325. in the union definition.
  7326. @end itemize
  7327. For an array of arrays, a structure containing arrays, an array of
  7328. structures, etc., you can nest these constructs. For example,
  7329. @example
  7330. struct point @{ double x, y; @};
  7331. struct point series[]
  7332. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7333. @end example
  7334. You can omit a pair of inner braces if they contain the right
  7335. number of elements for the sub-value they initialize, so that
  7336. no elements or fields need to be filled in with zeros.
  7337. But don't do that very much, as it gets confusing.
  7338. An array of @code{char} can be initialized using a string constant.
  7339. Recall that the string constant includes an implicit null character at
  7340. the end (@pxref{String Constants}). Using a string constant as
  7341. initializer means to use its contents as the initial values of the
  7342. array elements. Here are examples:
  7343. @example
  7344. char text[6] = "text!"; /* @r{Includes the null.} */
  7345. char text[5] = "text!"; /* @r{Excludes the null.} */
  7346. char text[] = "text!"; /* @r{Gets length 6.} */
  7347. char text[]
  7348. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7349. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7350. @end example
  7351. @noindent
  7352. and this kind of initializer can be nested inside braces to initialize
  7353. structures or arrays that contain a @code{char}-array.
  7354. In like manner, you can use a wide string constant to initialize
  7355. an array of @code{wchar_t}.
  7356. @node Designated Inits
  7357. @section Designated Initializers
  7358. @cindex initializers with labeled elements
  7359. @cindex labeled elements in initializers
  7360. @cindex case labels in initializers
  7361. @cindex designated initializers
  7362. In a complex structure or long array, it's useful to indicate
  7363. which field or element we are initializing.
  7364. To designate specific array elements during initialization, include
  7365. the array index in brackets, and an assignment operator, for each
  7366. element:
  7367. @example
  7368. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7369. @end example
  7370. @noindent
  7371. This does the same thing as:
  7372. @example
  7373. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7374. @end example
  7375. The array initialization can include non-designated element values
  7376. alongside designated indices; these follow the expected ordering
  7377. of the array initialization, so that
  7378. @example
  7379. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7380. @end example
  7381. @noindent
  7382. does the same thing as:
  7383. @example
  7384. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7385. @end example
  7386. Note that you can only use constant expressions as array index values,
  7387. not variables.
  7388. If you need to initialize a subsequence of sequential array elements to
  7389. the same value, you can specify a range:
  7390. @example
  7391. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7392. @end example
  7393. @noindent
  7394. Using a range this way is a GNU C extension.
  7395. When subsequence ranges overlap, each element is initialized by the
  7396. last specification that applies to it. Thus, this initialization is
  7397. equivalent to the previous one.
  7398. @example
  7399. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7400. @end example
  7401. @noindent
  7402. as the second overrides the first for elements 0 through 19.
  7403. The value used to initialize a range of elements is evaluated only
  7404. once, for the first element in the range. So for example, this code
  7405. @example
  7406. int random_values[100]
  7407. = @{ [0 ... 99] = get_random_number() @};
  7408. @end example
  7409. @noindent
  7410. would initialize all 100 elements of the array @code{random_values} to
  7411. the same value---probably not what is intended.
  7412. Similarly, you can initialize specific fields of a structure variable
  7413. by specifying the field name prefixed with a dot:
  7414. @example
  7415. struct point @{ int x; int y; @};
  7416. struct point foo = @{ .y = 42; @};
  7417. @end example
  7418. @noindent
  7419. The same syntax works for union variables as well:
  7420. @example
  7421. union int_double @{ int i; double d; @};
  7422. union int_double foo = @{ .d = 34 @};
  7423. @end example
  7424. @noindent
  7425. This casts the integer value 34 to a double and stores it
  7426. in the union variable @code{foo}.
  7427. You can designate both array elements and structure elements in
  7428. the same initialization; for example, here's an array of point
  7429. structures:
  7430. @example
  7431. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7432. @end example
  7433. Along with the capability to specify particular array and structure
  7434. elements to initialize comes the possibility of initializing the same
  7435. element more than once:
  7436. @example
  7437. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7438. @end example
  7439. @noindent
  7440. In such a case, the last initialization value is retained.
  7441. @node Auto Type
  7442. @section Referring to a Type with @code{__auto_type}
  7443. @findex __auto_type
  7444. @findex typeof
  7445. @cindex macros, types of arguments
  7446. You can declare a variable copying the type from
  7447. the initializer by using @code{__auto_type} instead of a particular type.
  7448. Here's an example:
  7449. @example
  7450. #define max(a,b) \
  7451. (@{ __auto_type _a = (a); \
  7452. __auto_type _b = (b); \
  7453. _a > _b ? _a : _b @})
  7454. @end example
  7455. This defines @code{_a} to be of the same type as @code{a}, and
  7456. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7457. to do in a macro that ought to be able to handle any type of data
  7458. (@pxref{Macros and Auto Type}).
  7459. The original GNU C method for obtaining the type of a value is to use
  7460. @code{typeof}, which takes as an argument either a value or the name of
  7461. a type. The previous example could also be written as:
  7462. @example
  7463. #define max(a,b) \
  7464. (@{ typeof(a) _a = (a); \
  7465. typeof(b) _b = (b); \
  7466. _a > _b ? _a : _b @})
  7467. @end example
  7468. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7469. principal use case for @code{typeof} is in variable declarations with
  7470. initialization, which is exactly what @code{__auto_type} handles.
  7471. @node Local Variables
  7472. @section Local Variables
  7473. @cindex local variables
  7474. @cindex variables, local
  7475. Declaring a variable inside a function definition (@pxref{Function
  7476. Definitions}) makes the variable name @dfn{local} to the containing
  7477. block---that is, the containing pair of braces. More precisely, the
  7478. variable's name is visible starting just after where it appears in the
  7479. declaration, and its visibility continues until the end of the block.
  7480. Local variables in C are generally @dfn{automatic} variables: each
  7481. variable's storage exists only from the declaration to the end of the
  7482. block. Execution of the declaration allocates the storage, computes
  7483. the initial value, and stores it in the variable. The end of the
  7484. block deallocates the storage.@footnote{Due to compiler optimizations,
  7485. allocation and deallocation don't necessarily really happen at
  7486. those times.}
  7487. @strong{Warning:} Two declarations for the same local variable
  7488. in the same scope are an error.
  7489. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7490. The total space for the program's stack may be limited; therefore,
  7491. in using very large arrays, it may be necessary to allocate
  7492. them in some other way to stop the program from crashing.
  7493. @strong{Warning:} If the declaration of an automatic variable does not
  7494. specify an initial value, the variable starts out containing garbage.
  7495. In this example, the value printed could be anything at all:
  7496. @example
  7497. @{
  7498. int i;
  7499. printf ("Print junk %d\n", i);
  7500. @}
  7501. @end example
  7502. In a simple test program, that statement is likely to print 0, simply
  7503. because every process starts with memory zeroed. But don't rely on it
  7504. to be zero---that is erroneous.
  7505. @strong{Note:} Make sure to store a value into each local variable (by
  7506. assignment, or by initialization) before referring to its value.
  7507. @node File-Scope Variables
  7508. @section File-Scope Variables
  7509. @cindex file-scope variables
  7510. @cindex global variables
  7511. @cindex variables, file-scope
  7512. @cindex variables, global
  7513. A variable declaration at the top level in a file (not inside a
  7514. function definition) declares a @dfn{file-scope variable}. Loading a
  7515. program allocates the storage for all the file-scope variables in it,
  7516. and initializes them too.
  7517. Each file-scope variable is either @dfn{static} (limited to one
  7518. compilation module) or @dfn{global} (shared with all compilation
  7519. modules in the program). To make the variable static, write the
  7520. keyword @code{static} at the start of the declaration. Omitting
  7521. @code{static} makes the variable global.
  7522. The initial value for a file-scope variable can't depend on the
  7523. contents of storage, and can't call any functions.
  7524. @example
  7525. int foo = 5; /* @r{Valid.} */
  7526. int bar = foo; /* @r{Invalid!} */
  7527. int bar = sin (1.0); /* @r{Invalid!} */
  7528. @end example
  7529. But it can use the address of another file-scope variable:
  7530. @example
  7531. int foo;
  7532. int *bar = &foo; /* @r{Valid.} */
  7533. int arr[5];
  7534. int *bar3 = &arr[3]; /* @r{Valid.} */
  7535. int *bar4 = arr + 4; /* @r{Valid.} */
  7536. @end example
  7537. It is valid for a module to have multiple declarations for a
  7538. file-scope variable, as long as they are all global or all static, but
  7539. at most one declaration can specify an initial value for it.
  7540. @node Static Local Variables
  7541. @section Static Local Variables
  7542. @cindex static local variables
  7543. @cindex variables, static local
  7544. @findex static
  7545. The keyword @code{static} in a local variable declaration says to
  7546. allocate the storage for the variable permanently, just like a
  7547. file-scope variable, even if the declaration is within a function.
  7548. Here's an example:
  7549. @example
  7550. int
  7551. increment_counter ()
  7552. @{
  7553. static int counter = 0;
  7554. return ++counter;
  7555. @}
  7556. @end example
  7557. The scope of the name @code{counter} runs from the declaration to the
  7558. end of the containing block, just like an automatic local variable,
  7559. but its storage is permanent, so the value persists from one call to
  7560. the next. As a result, each call to @code{increment_counter}
  7561. returns a different, unique value.
  7562. The initial value of a static local variable has the same limitations
  7563. as for file-scope variables: it can't depend on the contents of
  7564. storage or call any functions. It can use the address of a file-scope
  7565. variable or a static local variable, because those addresses are
  7566. determined before the program runs.
  7567. @node Extern Declarations
  7568. @section @code{extern} Declarations
  7569. @cindex @code{extern} declarations
  7570. @cindex declarations, @code{extern}
  7571. @findex extern
  7572. An @code{extern} declaration is used to refer to a global variable
  7573. whose principal declaration comes elsewhere---in the same module, or in
  7574. another compilation module. It looks like this:
  7575. @example
  7576. extern @var{basetype} @var{decorated-variable};
  7577. @end example
  7578. Its meaning is that, in the current scope, the variable name refers to
  7579. the file-scope variable of that name---which needs to be declared in a
  7580. non-@code{extern}, non-@code{static} way somewhere else.
  7581. For instance, if one compilation module has this global variable
  7582. declaration
  7583. @example
  7584. int error_count = 0;
  7585. @end example
  7586. @noindent
  7587. then other compilation modules can specify this
  7588. @example
  7589. extern int error_count;
  7590. @end example
  7591. @noindent
  7592. to allow reference to the same variable.
  7593. The usual place to write an @code{extern} declaration is at top level
  7594. in a source file, but you can write an @code{extern} declaration
  7595. inside a block to make a global or static file-scope variable
  7596. accessible in that block.
  7597. Since an @code{extern} declaration does not allocate space for the
  7598. variable, it can omit the size of an array:
  7599. @example
  7600. extern int array[];
  7601. @end example
  7602. You can use @code{array} normally in all contexts where it is
  7603. converted automatically to a pointer. However, to use it as the
  7604. operand of @code{sizeof} is an error, since the size is unknown.
  7605. It is valid to have multiple @code{extern} declarations for the same
  7606. variable, even in the same scope, if they give the same type. They do
  7607. not conflict---they agree. For an array, it is legitimate for some
  7608. @code{extern} declarations can specify the size while others omit it.
  7609. However, if two declarations give different sizes, that is an error.
  7610. Likewise, you can use @code{extern} declarations at file scope
  7611. (@pxref{File-Scope Variables}) followed by an ordinary global
  7612. (non-static) declaration of the same variable. They do not conflict,
  7613. because they say compatible things about the same meaning of the variable.
  7614. @node Allocating File-Scope
  7615. @section Allocating File-Scope Variables
  7616. @cindex allocation file-scope variables
  7617. @cindex file-scope variables, allocating
  7618. Some file-scope declarations allocate space for the variable, and some
  7619. don't.
  7620. A file-scope declaration with an initial value @emph{must} allocate
  7621. space for the variable; if there are two of such declarations for the
  7622. same variable, even in different compilation modules, they conflict.
  7623. An @code{extern} declaration @emph{never} allocates space for the variable.
  7624. If all the top-level declarations of a certain variable are
  7625. @code{extern}, the variable never gets memory space. If that variable
  7626. is used anywhere in the program, the use will be reported as an error,
  7627. saying that the variable is not defined.
  7628. @cindex tentative definition
  7629. A file-scope declaration without an initial value is called a
  7630. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7631. allocate space for the variable, but does not insist. So it causes no
  7632. conflict, no error, if the variable has another declaration that
  7633. allocates space for it, perhaps in another compilation module. But if
  7634. nothing else allocates space for the variable, the tentative
  7635. definition will do it. Any number of compilation modules can declare
  7636. the same variable in this way, and that is sufficient for all of them
  7637. to use the variable.
  7638. @c @opindex -fno-common
  7639. @c @opindex --warn_common
  7640. In programs that are very large or have many contributors, it may be
  7641. wise to adopt the convention of never using tentative definitions.
  7642. You can use the compilation option @option{-fno-common} to make them
  7643. an error, or @option{--warn-common} to warn about them.
  7644. If a file-scope variable gets its space through a tentative
  7645. definition, it starts out containing all zeros.
  7646. @node auto and register
  7647. @section @code{auto} and @code{register}
  7648. @cindex @code{auto} declarations
  7649. @cindex @code{register} declarations
  7650. @findex auto
  7651. @findex register
  7652. For historical reasons, you can write @code{auto} or @code{register}
  7653. before a local variable declaration. @code{auto} merely emphasizes
  7654. that the variable isn't static; it changes nothing.
  7655. @code{register} suggests to the compiler storing this variable in a
  7656. register. However, GNU C ignores this suggestion, since it can
  7657. choose the best variables to store in registers without any hints.
  7658. It is an error to take the address of a variable declared
  7659. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7660. If the variable is an array, you can't use it at all (other than as
  7661. the operand of @code{sizeof}), which makes it rather useless.
  7662. @node Omitting Types
  7663. @section Omitting Types in Declarations
  7664. @cindex omitting types in declarations
  7665. The syntax of C traditionally allows omitting the data type in a
  7666. declaration if it specifies a storage class, a type qualifier (see the
  7667. next chapter), or @code{auto} or @code{register}. Then the type
  7668. defaults to @code{int}. For example:
  7669. @example
  7670. auto foo = 42;
  7671. @end example
  7672. This is bad practice; if you see it, fix it.
  7673. @node Type Qualifiers
  7674. @chapter Type Qualifiers
  7675. A declaration can include type qualifiers to advise the compiler
  7676. about how the variable will be used. There are three different
  7677. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7678. pertain to different issues, so you can use more than one together.
  7679. For instance, @code{const volatile} describes a value that the
  7680. program is not allowed to change, but might have a different value
  7681. each time the program examines it. (This might perhaps be a special
  7682. hardware register, or part of shared memory.)
  7683. If you are just learning C, you can skip this chapter.
  7684. @menu
  7685. * const:: Variables whose values don't change.
  7686. * volatile:: Variables whose values may be accessed
  7687. or changed outside of the control of
  7688. this program.
  7689. * restrict Pointers:: Restricted pointers for code optimization.
  7690. * restrict Pointer Example:: Example of how that works.
  7691. @end menu
  7692. @node const
  7693. @section @code{const} Variables and Fields
  7694. @cindex @code{const} variables and fields
  7695. @cindex variables, @code{const}
  7696. @findex const
  7697. You can mark a variable as ``constant'' by writing @code{const} in
  7698. front of the declaration. This says to treat any assignment to that
  7699. variable as an error. It may also permit some compiler
  7700. optimizations---for instance, to fetch the value only once to satisfy
  7701. multiple references to it. The construct looks like this:
  7702. @example
  7703. const double pi = 3.14159;
  7704. @end example
  7705. After this definition, the code can use the variable @code{pi}
  7706. but cannot assign a different value to it.
  7707. @example
  7708. pi = 3.0; /* @r{Error!} */
  7709. @end example
  7710. Simple variables that are constant can be used for the same purposes
  7711. as enumeration constants, and they are not limited to integers. The
  7712. constantness of the variable propagates into pointers, too.
  7713. A pointer type can specify that the @emph{target} is constant. For
  7714. example, the pointer type @code{const double *} stands for a pointer
  7715. to a constant @code{double}. That's the type that results from taking
  7716. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7717. left side of an assignment.
  7718. @example
  7719. *(&pi) = 3.0; /* @r{Error!} */
  7720. @end example
  7721. Nonconstant pointers can be converted automatically to constant
  7722. pointers, but not vice versa. For instance,
  7723. @example
  7724. const double *cptr;
  7725. double *ptr;
  7726. cptr = &pi; /* @r{Valid.} */
  7727. cptr = ptr; /* @r{Valid.} */
  7728. ptr = cptr; /* @r{Error!} */
  7729. ptr = &pi; /* @r{Error!} */
  7730. @end example
  7731. This is not an ironclad protection against modifying the value. You
  7732. can always cast the constant pointer to a nonconstant pointer type:
  7733. @example
  7734. ptr = (double *)cptr; /* @r{Valid.} */
  7735. ptr = (double *)&pi; /* @r{Valid.} */
  7736. @end example
  7737. However, @code{const} provides a way to show that a certain function
  7738. won't modify the data structure whose address is passed to it. Here's
  7739. an example:
  7740. @example
  7741. int
  7742. string_length (const char *string)
  7743. @{
  7744. int count = 0;
  7745. while (*string++)
  7746. count++;
  7747. return count;
  7748. @}
  7749. @end example
  7750. @noindent
  7751. Using @code{const char *} for the parameter is a way of saying this
  7752. function never modifies the memory of the string itself.
  7753. In calling @code{string_length}, you can specify an ordinary
  7754. @code{char *} since that can be converted automatically to @code{const
  7755. char *}.
  7756. @node volatile
  7757. @section @code{volatile} Variables and Fields
  7758. @cindex @code{volatile} variables and fields
  7759. @cindex variables, @code{volatile}
  7760. @findex volatile
  7761. The GNU C compiler often performs optimizations that eliminate the
  7762. need to write or read a variable. For instance,
  7763. @example
  7764. int foo;
  7765. foo = 1;
  7766. foo++;
  7767. @end example
  7768. @noindent
  7769. might simply store the value 2 into @code{foo}, without ever storing 1.
  7770. These optimizations can also apply to structure fields in some cases.
  7771. If the memory containing @code{foo} is shared with another program,
  7772. or if it is examined asynchronously by hardware, such optimizations
  7773. could confuse the communication. Using @code{volatile} is one way
  7774. to prevent them.
  7775. Writing @code{volatile} with the type in a variable or field declaration
  7776. says that the value may be examined or changed for reasons outside the
  7777. control of the program at any moment. Therefore, the program must
  7778. execute in a careful way to assure correct interaction with those
  7779. accesses, whenever they may occur.
  7780. The simplest use looks like this:
  7781. @example
  7782. volatile int lock;
  7783. @end example
  7784. This directs the compiler not to do certain common optimizations on
  7785. use of the variable @code{lock}. All the reads and writes for a volatile
  7786. variable or field are really done, and done in the order specified
  7787. by the source code. Thus, this code:
  7788. @example
  7789. lock = 1;
  7790. list = list->next;
  7791. if (lock)
  7792. lock_broken (&lock);
  7793. lock = 0;
  7794. @end example
  7795. @noindent
  7796. really stores the value 1 in @code{lock}, even though there is no
  7797. sign it is really used, and the @code{if} statement reads and
  7798. checks the value of @code{lock}, rather than assuming it is still 1.
  7799. A limited amount of optimization can be done, in principle, on
  7800. @code{volatile} variables and fields: multiple references between two
  7801. sequence points (@pxref{Sequence Points}) can be simplified together.
  7802. Use of @code{volatile} does not eliminate the flexibility in ordering
  7803. the computation of the operands of most operators. For instance, in
  7804. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7805. @code{foo} is not specified, so they may be done in either order; the
  7806. fact that @code{lock} is @code{volatile} has no effect on that.
  7807. @node restrict Pointers
  7808. @section @code{restrict}-Qualified Pointers
  7809. @cindex @code{restrict} pointers
  7810. @cindex pointers, @code{restrict}-qualified
  7811. @findex restrict
  7812. You can declare a pointer as ``restricted'' using the @code{restrict}
  7813. type qualifier, like this:
  7814. @example
  7815. int *restrict p = x;
  7816. @end example
  7817. @noindent
  7818. This enables better optimization of code that uses the pointer.
  7819. If @code{p} is declared with @code{restrict}, and then the code
  7820. references the object that @code{p} points to (using @code{*p} or
  7821. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7822. code will not access that object in any other way---only through
  7823. @code{p}.
  7824. For instance, it means the code must not use another pointer
  7825. to access the same space, as shown here:
  7826. @example
  7827. int *restrict p = @var{whatever};
  7828. int *q = p;
  7829. foo (*p, *q);
  7830. @end example
  7831. @noindent
  7832. That contradicts the @code{restrict} promise by accessing the object
  7833. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7834. Likewise, it must not do this:
  7835. @example
  7836. int *restrict p = @var{whatever};
  7837. struct @{ int *a, *b; @} s;
  7838. s.a = p;
  7839. foo (*p, *s.a);
  7840. @end example
  7841. @noindent
  7842. This example uses a structure field instead of the variable @code{q}
  7843. to hold the other pointer, and that contradicts the promise just the
  7844. same.
  7845. The keyword @code{restrict} also promises that @code{p} won't point to
  7846. the allocated space of any automatic or static variable. So the code
  7847. must not do this:
  7848. @example
  7849. int a;
  7850. int *restrict p = &a;
  7851. foo (*p, a);
  7852. @end example
  7853. @noindent
  7854. because that does direct access to the object (@code{a}) that @code{p}
  7855. points to, which bypasses @code{p}.
  7856. If the code makes such promises with @code{restrict} then breaks them,
  7857. execution is unpredictable.
  7858. @node restrict Pointer Example
  7859. @section @code{restrict} Pointer Example
  7860. Here are examples where @code{restrict} enables real optimization.
  7861. In this example, @code{restrict} assures GCC that the array @code{out}
  7862. points to does not overlap with the array @code{in} points to.
  7863. @example
  7864. void
  7865. process_data (const char *in,
  7866. char * restrict out,
  7867. size_t size)
  7868. @{
  7869. for (i = 0; i < size; i++)
  7870. out[i] = in[i] + in[i + 1];
  7871. @}
  7872. @end example
  7873. Here's a simple tree structure, where each tree node holds data of
  7874. type @code{PAYLOAD} plus two subtrees.
  7875. @example
  7876. struct foo
  7877. @{
  7878. PAYLOAD payload;
  7879. struct foo *left;
  7880. struct foo *right;
  7881. @};
  7882. @end example
  7883. Now here's a function to null out both pointers in the @code{left}
  7884. subtree.
  7885. @example
  7886. void
  7887. null_left (struct foo *a)
  7888. @{
  7889. a->left->left = NULL;
  7890. a->left->right = NULL;
  7891. @}
  7892. @end example
  7893. Since @code{*a} and @code{*a->left} have the same data type,
  7894. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7895. the compiled code for @code{null_left} must read @code{a->left}
  7896. again from memory when executing the second assignment statement.
  7897. We can enable optimization, so that it does not need to read
  7898. @code{a->left} again, by writing @code{null_left} in a less
  7899. obvious way.
  7900. @example
  7901. void
  7902. null_left (struct foo *a)
  7903. @{
  7904. struct foo *b = a->left;
  7905. b->left = NULL;
  7906. b->right = NULL;
  7907. @}
  7908. @end example
  7909. A more elegant way to fix this is with @code{restrict}.
  7910. @example
  7911. void
  7912. null_left (struct foo *restrict a)
  7913. @{
  7914. a->left->left = NULL;
  7915. a->left->right = NULL;
  7916. @}
  7917. @end example
  7918. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7919. as @code{a->left} will not point to the same memory space as @code{a}.
  7920. Therefore, the memory location @code{a->left->left} cannot be the same
  7921. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7922. reloading @code{a->left} for the second statement.
  7923. @node Functions
  7924. @chapter Functions
  7925. @cindex functions
  7926. We have already presented many examples of functions, so if you've
  7927. read this far, you basically understand the concept of a function. It
  7928. is vital, nonetheless, to have a chapter in the manual that collects
  7929. all the information about functions.
  7930. @menu
  7931. * Function Definitions:: Writing the body of a function.
  7932. * Function Declarations:: Declaring the interface of a function.
  7933. * Function Calls:: Using functions.
  7934. * Function Call Semantics:: Call-by-value argument passing.
  7935. * Function Pointers:: Using references to functions.
  7936. * The main Function:: Where execution of a GNU C program begins.
  7937. * Advanced Definitions:: Advanced features of function definitions.
  7938. * Obsolete Definitions:: Obsolete features still used
  7939. in function definitions in old code.
  7940. @end menu
  7941. @node Function Definitions
  7942. @section Function Definitions
  7943. @cindex function definitions
  7944. @cindex defining functions
  7945. We have already presented many examples of function definitions. To
  7946. summarize the rules, a function definition looks like this:
  7947. @example
  7948. @var{returntype}
  7949. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7950. @{
  7951. @var{body}
  7952. @}
  7953. @end example
  7954. The part before the open-brace is called the @dfn{function header}.
  7955. Write @code{void} as the @var{returntype} if the function does
  7956. not return a value.
  7957. @menu
  7958. * Function Parameter Variables:: Syntax and semantics
  7959. of function parameters.
  7960. * Forward Function Declarations:: Functions can only be called after
  7961. they have been defined or declared.
  7962. * Static Functions:: Limiting visibility of a function.
  7963. * Arrays as Parameters:: Functions that accept array arguments.
  7964. * Structs as Parameters:: Functions that accept structure arguments.
  7965. @end menu
  7966. @node Function Parameter Variables
  7967. @subsection Function Parameter Variables
  7968. @cindex function parameter variables
  7969. @cindex parameter variables in functions
  7970. @cindex parameter list
  7971. A function parameter variable is a local variable (@pxref{Local
  7972. Variables}) used within the function to store the value passed as an
  7973. argument in a call to the function. Usually we say ``function
  7974. parameter'' or ``parameter'' for short, not mentioning the fact that
  7975. it's a variable.
  7976. We declare these variables in the beginning of the function
  7977. definition, in the @dfn{parameter list}. For example,
  7978. @example
  7979. fib (int n)
  7980. @end example
  7981. @noindent
  7982. has a parameter list with one function parameter @code{n}, which has
  7983. type @code{int}.
  7984. Function parameter declarations differ from ordinary variable
  7985. declarations in several ways:
  7986. @itemize @bullet
  7987. @item
  7988. Inside the function definition header, commas separate parameter
  7989. declarations, and each parameter needs a complete declaration
  7990. including the type. For instance, if a function @code{foo} has two
  7991. @code{int} parameters, write this:
  7992. @example
  7993. foo (int a, int b)
  7994. @end example
  7995. You can't share the common @code{int} between the two declarations:
  7996. @example
  7997. foo (int a, b) /* @r{Invalid!} */
  7998. @end example
  7999. @item
  8000. A function parameter variable is initialized to whatever value is
  8001. passed in the function call, so its declaration cannot specify an
  8002. initial value.
  8003. @item
  8004. Writing an array type in a function parameter declaration has the
  8005. effect of declaring it as a pointer. The size specified for the array
  8006. has no effect at all, and we normally omit the size. Thus,
  8007. @example
  8008. foo (int a[5])
  8009. foo (int a[])
  8010. foo (int *a)
  8011. @end example
  8012. @noindent
  8013. are equivalent.
  8014. @item
  8015. The scope of the parameter variables is the entire function body,
  8016. notwithstanding the fact that they are written in the function header,
  8017. which is just outside the function body.
  8018. @end itemize
  8019. If a function has no parameters, it would be most natural for the
  8020. list of parameters in its definition to be empty. But that, in C, has
  8021. a special meaning for historical reasons: ``Do not check that calls to
  8022. this function have the right number of arguments.'' Thus,
  8023. @example
  8024. int
  8025. foo ()
  8026. @{
  8027. return 5;
  8028. @}
  8029. int
  8030. bar (int x)
  8031. @{
  8032. return foo (x);
  8033. @}
  8034. @end example
  8035. @noindent
  8036. would not report a compilation error in passing @code{x} as an
  8037. argument to @code{foo}. By contrast,
  8038. @example
  8039. int
  8040. foo (void)
  8041. @{
  8042. return 5;
  8043. @}
  8044. int
  8045. bar (int x)
  8046. @{
  8047. return foo (x);
  8048. @}
  8049. @end example
  8050. @noindent
  8051. would report an error because @code{foo} is supposed to receive
  8052. no arguments.
  8053. @node Forward Function Declarations
  8054. @subsection Forward Function Declarations
  8055. @cindex forward function declarations
  8056. @cindex function declarations, forward
  8057. The order of the function definitions in the source code makes no
  8058. difference, except that each function needs to be defined or declared
  8059. before code uses it.
  8060. The definition of a function also declares its name for the rest of
  8061. the containing scope. But what if you want to call the function
  8062. before its definition? To permit that, write a compatible declaration
  8063. of the same function, before the first call. A declaration that
  8064. prefigures a subsequent definition in this way is called a
  8065. @dfn{forward declaration}. The function declaration can be at top
  8066. @c ??? file scope
  8067. level or within a block, and it applies until the end of the containing
  8068. scope.
  8069. @xref{Function Declarations}, for more information about these
  8070. declarations.
  8071. @node Static Functions
  8072. @subsection Static Functions
  8073. @cindex static functions
  8074. @cindex functions, static
  8075. @findex static
  8076. The keyword @code{static} in a function definition limits the
  8077. visibility of the name to the current compilation module. (That's the
  8078. same thing @code{static} does in variable declarations;
  8079. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8080. contains this code:
  8081. @example
  8082. static int
  8083. foo (void)
  8084. @{
  8085. @r{@dots{}}
  8086. @}
  8087. @end example
  8088. @noindent
  8089. then the code of that compilation module can call @code{foo} anywhere
  8090. after the definition, but other compilation modules cannot refer to it
  8091. at all.
  8092. @cindex forward declaration
  8093. @cindex static function, declaration
  8094. To call @code{foo} before its definition, it needs a forward
  8095. declaration, which should use @code{static} since the function
  8096. definition does. For this function, it looks like this:
  8097. @example
  8098. static int foo (void);
  8099. @end example
  8100. It is generally wise to use @code{static} on the definitions of
  8101. functions that won't be called from outside the same compilation
  8102. module. This makes sure that calls are not added in other modules.
  8103. If programmers decide to change the function's calling convention, or
  8104. understand all the consequences of its use, they will only have to
  8105. check for calls in the same compilation module.
  8106. @node Arrays as Parameters
  8107. @subsection Arrays as Parameters
  8108. @cindex array as parameters
  8109. @cindex functions with array parameters
  8110. Arrays in C are not first-class objects: it is impossible to copy
  8111. them. So they cannot be passed as arguments like other values.
  8112. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8113. a special way.
  8114. @menu
  8115. * Array Parm Pointer::
  8116. * Passing Array Args::
  8117. * Array Parm Qualifiers::
  8118. @end menu
  8119. @node Array Parm Pointer
  8120. @subsubsection Array parameters are pointers
  8121. Declaring a function parameter variable as an array really gives it a
  8122. pointer type. C does this because an expression with array type, if
  8123. used as an argument in a function call, is converted automatically to
  8124. a pointer (to the zeroth element of the array). If you declare the
  8125. corresponding parameter as an ``array'', it will work correctly with
  8126. the pointer value that really gets passed.
  8127. This relates to the fact that C does not check array bounds in access
  8128. to elements of the array (@pxref{Accessing Array Elements}).
  8129. For example, in this function,
  8130. @example
  8131. void
  8132. clobber4 (int array[20])
  8133. @{
  8134. array[4] = 0;
  8135. @}
  8136. @end example
  8137. @noindent
  8138. the parameter @code{array}'s real type is @code{int *}; the specified
  8139. length, 20, has no effect on the program. You can leave out the length
  8140. and write this:
  8141. @example
  8142. void
  8143. clobber4 (int array[])
  8144. @{
  8145. array[4] = 0;
  8146. @}
  8147. @end example
  8148. @noindent
  8149. or write the parameter declaration explicitly as a pointer:
  8150. @example
  8151. void
  8152. clobber4 (int *array)
  8153. @{
  8154. array[4] = 0;
  8155. @}
  8156. @end example
  8157. They are all equivalent.
  8158. @node Passing Array Args
  8159. @subsubsection Passing array arguments
  8160. The function call passes this pointer by
  8161. value, like all argument values in C@. However, the result is
  8162. paradoxical in that the array itself is passed by reference: its
  8163. contents are treated as shared memory---shared between the caller and
  8164. the called function, that is. When @code{clobber4} assigns to element
  8165. 4 of @code{array}, the effect is to alter element 4 of the array
  8166. specified in the call.
  8167. @example
  8168. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8169. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8170. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8171. int
  8172. main (void)
  8173. @{
  8174. int data[] = @{1, 2, 3, 4, 5, 6@};
  8175. int i;
  8176. /* @r{Show the initial value of element 4.} */
  8177. for (i = 0; i < 6; i++)
  8178. printf ("data[%d] = %d\n", i, data[i]);
  8179. printf ("\n");
  8180. clobber4 (data);
  8181. /* @r{Show that element 4 has been changed.} */
  8182. for (i = 0; i < 6; i++)
  8183. printf ("data[%d] = %d\n", i, data[i]);
  8184. printf ("\n");
  8185. return EXIT_SUCCESS;
  8186. @}
  8187. @end example
  8188. @noindent
  8189. shows that @code{data[4]} has become zero after the call to
  8190. @code{clobber4}.
  8191. The array @code{data} has 6 elements, but passing it to a function
  8192. whose argument type is written as @code{int [20]} is not an error,
  8193. because that really stands for @code{int *}. The pointer that is the
  8194. real argument carries no indication of the length of the array it
  8195. points into. It is not required to point to the beginning of the
  8196. array, either. For instance,
  8197. @example
  8198. clobber4 (data+1);
  8199. @end example
  8200. @noindent
  8201. passes an ``array'' that starts at element 1 of @code{data}, and the
  8202. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8203. If all calls to the function will provide an array of a particular
  8204. size, you can specify the size of the array to be @code{static}:
  8205. @example
  8206. void
  8207. clobber4 (int array[static 20])
  8208. @r{@dots{}}
  8209. @end example
  8210. @noindent
  8211. This is a promise to the compiler that the function will always be
  8212. called with an array of 20 elements, so that the compiler can optimize
  8213. code accordingly. If the code breaks this promise and calls the
  8214. function with, for example, a shorter array, unpredictable things may
  8215. happen.
  8216. @node Array Parm Qualifiers
  8217. @subsubsection Type qualifiers on array parameters
  8218. You can use the type qualifiers @code{const}, @code{restrict}, and
  8219. @code{volatile} with array parameters; for example:
  8220. @example
  8221. void
  8222. clobber4 (volatile int array[20])
  8223. @r{@dots{}}
  8224. @end example
  8225. @noindent
  8226. denotes that @code{array} is equivalent to a pointer to a volatile
  8227. @code{int}. Alternatively:
  8228. @example
  8229. void
  8230. clobber4 (int array[const 20])
  8231. @r{@dots{}}
  8232. @end example
  8233. @noindent
  8234. makes the array parameter equivalent to a constant pointer to an
  8235. @code{int}. If we want the @code{clobber4} function to succeed, it
  8236. would not make sense to write
  8237. @example
  8238. void
  8239. clobber4 (const int array[20])
  8240. @r{@dots{}}
  8241. @end example
  8242. @noindent
  8243. as this would tell the compiler that the parameter should point to an
  8244. array of constant @code{int} values, and then we would not be able to
  8245. store zeros in them.
  8246. In a function with multiple array parameters, you can use @code{restrict}
  8247. to tell the compiler that each array parameter passed in will be distinct:
  8248. @example
  8249. void
  8250. foo (int array1[restrict 10], int array2[restrict 10])
  8251. @r{@dots{}}
  8252. @end example
  8253. @noindent
  8254. Using @code{restrict} promises the compiler that callers will
  8255. not pass in the same array for more than one @code{restrict} array
  8256. parameter. Knowing this enables the compiler to perform better code
  8257. optimization. This is the same effect as using @code{restrict}
  8258. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8259. the code that an array of a specific size is expected.
  8260. @node Structs as Parameters
  8261. @subsection Functions That Accept Structure Arguments
  8262. Structures in GNU C are first-class objects, so using them as function
  8263. parameters and arguments works in the natural way. This function
  8264. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8265. and returns a structure of the same type but with the fields
  8266. exchanged.
  8267. @example
  8268. struct foo @{ int a, b; @};
  8269. struct foo x;
  8270. struct foo
  8271. swapfoo (struct foo inval)
  8272. @{
  8273. struct foo outval;
  8274. outval.a = inval.b;
  8275. outval.b = inval.a;
  8276. return outval;
  8277. @}
  8278. @end example
  8279. This simpler definition of @code{swapfoo} avoids using a local
  8280. variable to hold the result about to be return, by using a structure
  8281. constructor (@pxref{Structure Constructors}), like this:
  8282. @example
  8283. struct foo
  8284. swapfoo (struct foo inval)
  8285. @{
  8286. return (struct foo) @{ inval.b, inval.a @};
  8287. @}
  8288. @end example
  8289. It is valid to define a structure type in a function's parameter list,
  8290. as in
  8291. @example
  8292. int
  8293. frob_bar (struct bar @{ int a, b; @} inval)
  8294. @{
  8295. @var{body}
  8296. @}
  8297. @end example
  8298. @noindent
  8299. and @var{body} can access the fields of @var{inval} since the
  8300. structure type @code{struct bar} is defined for the whole function
  8301. body. However, there is no way to create a @code{struct bar} argument
  8302. to pass to @code{frob_bar}, except with kludges. As a result,
  8303. defining a structure type in a parameter list is useless in practice.
  8304. @node Function Declarations
  8305. @section Function Declarations
  8306. @cindex function declarations
  8307. @cindex declararing functions
  8308. To call a function, or use its name as a pointer, a @dfn{function
  8309. declaration} for the function name must be in effect at that point in
  8310. the code. The function's definition serves as a declaration of that
  8311. function for the rest of the containing scope, but to use the function
  8312. in code before the definition, or from another compilation module, a
  8313. separate function declaration must precede the use.
  8314. A function declaration looks like the start of a function definition.
  8315. It begins with the return value type (@code{void} if none) and the
  8316. function name, followed by argument declarations in parentheses
  8317. (though these can sometimes be omitted). But that's as far as the
  8318. similarity goes: instead of the function body, the declaration uses a
  8319. semicolon.
  8320. @cindex function prototype
  8321. @cindex prototype of a function
  8322. A declaration that specifies argument types is called a @dfn{function
  8323. prototype}. You can include the argument names or omit them. The
  8324. names, if included in the declaration, have no effect, but they may
  8325. serve as documentation.
  8326. This form of prototype specifies fixed argument types:
  8327. @example
  8328. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8329. @end example
  8330. @noindent
  8331. This form says the function takes no arguments:
  8332. @example
  8333. @var{rettype} @var{function} (void);
  8334. @end example
  8335. @noindent
  8336. This form declares types for some arguments, and allows additional
  8337. arguments whose types are not specified:
  8338. @example
  8339. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8340. @end example
  8341. For a parameter that's an array of variable length, you can write
  8342. its declaration with @samp{*} where the ``length'' of the array would
  8343. normally go; for example, these are all equivalent.
  8344. @example
  8345. double maximum (int n, int m, double a[n][m]);
  8346. double maximum (int n, int m, double a[*][*]);
  8347. double maximum (int n, int m, double a[ ][*]);
  8348. double maximum (int n, int m, double a[ ][m]);
  8349. @end example
  8350. @noindent
  8351. The old-fashioned form of declaration, which is not a prototype, says
  8352. nothing about the types of arguments or how many they should be:
  8353. @example
  8354. @var{rettype} @var{function} ();
  8355. @end example
  8356. @strong{Warning:} Arguments passed to a function declared without a
  8357. prototype are converted with the default argument promotions
  8358. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8359. types are unspecified.
  8360. Function declarations are usually written at the top level in a source file,
  8361. but you can also put them inside code blocks. Then the function name
  8362. is visible for the rest of the containing scope. For example:
  8363. @example
  8364. void
  8365. foo (char *file_name)
  8366. @{
  8367. void save_file (char *);
  8368. save_file (file_name);
  8369. @}
  8370. @end example
  8371. If another part of the code tries to call the function
  8372. @code{save_file}, this declaration won't be in effect there. So the
  8373. function will get an implicit declaration of the form @code{extern int
  8374. save_file ();}. That conflicts with the explicit declaration
  8375. here, and the discrepancy generates a warning.
  8376. The syntax of C traditionally allows omitting the data type in a
  8377. function declaration if it specifies a storage class or a qualifier.
  8378. Then the type defaults to @code{int}. For example:
  8379. @example
  8380. static foo (double x);
  8381. @end example
  8382. @noindent
  8383. defaults the return type to @code{int}.
  8384. This is bad practice; if you see it, fix it.
  8385. Calling a function that is undeclared has the effect of an creating
  8386. @dfn{implicit} declaration in the innermost containing scope,
  8387. equivalent to this:
  8388. @example
  8389. extern int @dfn{function} ();
  8390. @end example
  8391. @noindent
  8392. This declaration says that the function returns @code{int} but leaves
  8393. its argument types unspecified. If that does not accurately fit the
  8394. function, then the program @strong{needs} an explicit declaration of
  8395. the function with argument types in order to call it correctly.
  8396. Implicit declarations are deprecated, and a function call that creates one
  8397. causes a warning.
  8398. @node Function Calls
  8399. @section Function Calls
  8400. @cindex function calls
  8401. @cindex calling functions
  8402. Starting a program automatically calls the function named @code{main}
  8403. (@pxref{The main Function}). Aside from that, a function does nothing
  8404. except when it is @dfn{called}. That occurs during the execution of a
  8405. function-call expression specifying that function.
  8406. A function-call expression looks like this:
  8407. @example
  8408. @var{function} (@var{arguments}@r{@dots{}})
  8409. @end example
  8410. Most of the time, @var{function} is a function name. However, it can
  8411. also be an expression with a function pointer value; that way, the
  8412. program can determine at run time which function to call.
  8413. The @var{arguments} are a series of expressions separated by commas.
  8414. Each expression specifies one argument to pass to the function.
  8415. The list of arguments in a function call looks just like use of the
  8416. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8417. the parentheses of a function call gives it a different meaning.
  8418. Here's an example of a function call, taken from an example near the
  8419. beginning (@pxref{Complete Program}).
  8420. @example
  8421. printf ("Fibonacci series item %d is %d\n",
  8422. 19, fib (19));
  8423. @end example
  8424. The three arguments given to @code{printf} are a constant string, the
  8425. integer 19, and the integer returned by @code{fib (19)}.
  8426. @node Function Call Semantics
  8427. @section Function Call Semantics
  8428. @cindex function call semantics
  8429. @cindex semantics of function calls
  8430. @cindex call-by-value
  8431. The meaning of a function call is to compute the specified argument
  8432. expressions, convert their values according to the function's
  8433. declaration, then run the function giving it copies of the converted
  8434. values. (This method of argument passing is known as
  8435. @dfn{call-by-value}.) When the function finishes, the value it
  8436. returns becomes the value of the function-call expression.
  8437. Call-by-value implies that an assignment to the function argument
  8438. variable has no direct effect on the caller. For instance,
  8439. @example
  8440. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8441. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8442. void
  8443. subroutine (int x)
  8444. @{
  8445. x = 5;
  8446. @}
  8447. void
  8448. main (void)
  8449. @{
  8450. int y = 20;
  8451. subroutine (y);
  8452. printf ("y is %d\n", y);
  8453. return EXIT_SUCCESS;
  8454. @}
  8455. @end example
  8456. @noindent
  8457. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8458. from the value of @code{y}, but this does not establish any other
  8459. relationship between the two variables. Thus, the assignment to
  8460. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8461. If an argument's type is specified by the function's declaration, the
  8462. function call converts the argument expression to that type if
  8463. possible. If the conversion is impossible, that is an error.
  8464. If the function's declaration doesn't specify the type of that
  8465. argument, then the @emph{default argument promotions} apply.
  8466. @xref{Argument Promotions}.
  8467. @node Function Pointers
  8468. @section Function Pointers
  8469. @cindex function pointers
  8470. @cindex pointers to functions
  8471. A function name refers to a fixed function. Sometimes it is useful to
  8472. call a function to be determined at run time; to do this, you can use
  8473. a @dfn{function pointer value} that points to the chosen function
  8474. (@pxref{Pointers}).
  8475. Pointer-to-function types can be used to declare variables and other
  8476. data, including array elements, structure fields, and union
  8477. alternatives. They can also be used for function arguments and return
  8478. values. These types have the peculiarity that they are never
  8479. converted automatically to @code{void *} or vice versa. However, you
  8480. can do that conversion with a cast.
  8481. @menu
  8482. * Declaring Function Pointers:: How to declare a pointer to a function.
  8483. * Assigning Function Pointers:: How to assign values to function pointers.
  8484. * Calling Function Pointers:: How to call functions through pointers.
  8485. @end menu
  8486. @node Declaring Function Pointers
  8487. @subsection Declaring Function Pointers
  8488. @cindex declaring function pointers
  8489. @cindex function pointers, declaring
  8490. The declaration of a function pointer variable (or structure field)
  8491. looks almost like a function declaration, except it has an additional
  8492. @samp{*} just before the variable name. Proper nesting requires a
  8493. pair of parentheses around the two of them. For instance, @code{int
  8494. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8495. an @code{int}-returning function.''
  8496. Contrast these three declarations:
  8497. @example
  8498. /* @r{Declare a function returning @code{char *}.} */
  8499. char *a (char *);
  8500. /* @r{Declare a pointer to a function returning @code{char}.} */
  8501. char (*a) (char *);
  8502. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8503. char *(*a) (char *);
  8504. @end example
  8505. The possible argument types of the function pointed to are the same
  8506. as in a function declaration. You can write a prototype
  8507. that specifies all the argument types:
  8508. @example
  8509. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8510. @end example
  8511. @noindent
  8512. or one that specifies some and leaves the rest unspecified:
  8513. @example
  8514. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8515. @end example
  8516. @noindent
  8517. or one that says there are no arguments:
  8518. @example
  8519. @var{rettype} (*@var{function}) (void);
  8520. @end example
  8521. You can also write a non-prototype declaration that says
  8522. nothing about the argument types:
  8523. @example
  8524. @var{rettype} (*@var{function}) ();
  8525. @end example
  8526. For example, here's a declaration for a variable that should
  8527. point to some arithmetic function that operates on two @code{double}s:
  8528. @example
  8529. double (*binary_op) (double, double);
  8530. @end example
  8531. Structure fields, union alternatives, and array elements can be
  8532. function pointers; so can parameter variables. The function pointer
  8533. declaration construct can also be combined with other operators
  8534. allowed in declarations. For instance,
  8535. @example
  8536. int **(*foo)();
  8537. @end example
  8538. @noindent
  8539. declares @code{foo} as a pointer to a function that returns
  8540. type @code{int **}, and
  8541. @example
  8542. int **(*foo[30])();
  8543. @end example
  8544. @noindent
  8545. declares @code{foo} as an array of 30 pointers to functions that
  8546. return type @code{int **}.
  8547. @example
  8548. int **(**foo)();
  8549. @end example
  8550. @noindent
  8551. declares @code{foo} as a pointer to a pointer to a function that
  8552. returns type @code{int **}.
  8553. @node Assigning Function Pointers
  8554. @subsection Assigning Function Pointers
  8555. @cindex assigning function pointers
  8556. @cindex function pointers, assigning
  8557. Assuming we have declared the variable @code{binary_op} as in the
  8558. previous section, giving it a value requires a suitable function to
  8559. use. So let's define a function suitable for the variable to point
  8560. to. Here's one:
  8561. @example
  8562. double
  8563. double_add (double a, double b)
  8564. @{
  8565. return a+b;
  8566. @}
  8567. @end example
  8568. Now we can give it a value:
  8569. @example
  8570. binary_op = double_add;
  8571. @end example
  8572. The target type of the function pointer must be upward compatible with
  8573. the type of the function (@pxref{Compatible Types}).
  8574. There is no need for @samp{&} in front of @code{double_add}.
  8575. Using a function name such as @code{double_add} as an expression
  8576. automatically converts it to the function's address, with the
  8577. appropriate function pointer type. However, it is ok to use
  8578. @samp{&} if you feel that is clearer:
  8579. @example
  8580. binary_op = &double_add;
  8581. @end example
  8582. @node Calling Function Pointers
  8583. @subsection Calling Function Pointers
  8584. @cindex calling function pointers
  8585. @cindex function pointers, calling
  8586. To call the function specified by a function pointer, just write the
  8587. function pointer value in a function call. For instance, here's a
  8588. call to the function @code{binary_op} points to:
  8589. @example
  8590. binary_op (x, 5)
  8591. @end example
  8592. Since the data type of @code{binary_op} explicitly specifies type
  8593. @code{double} for the arguments, the call converts @code{x} and 5 to
  8594. @code{double}.
  8595. The call conceptually dereferences the pointer @code{binary_op} to
  8596. ``get'' the function it points to, and calls that function. If you
  8597. wish, you can explicitly represent the dereference by writing the
  8598. @code{*} operator:
  8599. @example
  8600. (*binary_op) (x, 5)
  8601. @end example
  8602. The @samp{*} reminds people reading the code that @code{binary_op} is
  8603. a function pointer rather than the name of a specific function.
  8604. @node The main Function
  8605. @section The @code{main} Function
  8606. @cindex @code{main} function
  8607. @findex main
  8608. Every complete executable program requires at least one function,
  8609. called @code{main}, which is where execution begins. You do not have
  8610. to explicitly declare @code{main}, though GNU C permits you to do so.
  8611. Conventionally, @code{main} should be defined to follow one of these
  8612. calling conventions:
  8613. @example
  8614. int main (void) @{@r{@dots{}}@}
  8615. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8616. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8617. @end example
  8618. @noindent
  8619. Using @code{void} as the parameter list means that @code{main} does
  8620. not use the arguments. You can write @code{char **argv} instead of
  8621. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8622. constructs are equivalent.
  8623. @ignore @c Not so at present
  8624. Defining @code{main} in any other way generates a warning. Your
  8625. program will still compile, but you may get unexpected results when
  8626. executing it.
  8627. @end ignore
  8628. You can call @code{main} from C code, as you can call any other
  8629. function, though that is an unusual thing to do. When you do that,
  8630. you must write the call to pass arguments that match the parameters in
  8631. the definition of @code{main}.
  8632. The @code{main} function is not actually the first code that runs when
  8633. a program starts. In fact, the first code that runs is system code
  8634. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8635. code, but in GNU we replaced it with C code. Its job is to find
  8636. the arguments for @code{main} and call that.
  8637. @menu
  8638. * Values from main:: Returning values from the main function.
  8639. * Command-line Parameters:: Accessing command-line parameters
  8640. provided to the program.
  8641. * Environment Variables:: Accessing system environment variables.
  8642. @end menu
  8643. @node Values from main
  8644. @subsection Returning Values from @code{main}
  8645. @cindex returning values from @code{main}
  8646. @cindex success
  8647. @cindex failure
  8648. @cindex exit status
  8649. When @code{main} returns, the process terminates. Whatever value
  8650. @code{main} returns becomes the exit status which is reported to the
  8651. parent process. While nominally the return value is of type
  8652. @code{int}, in fact the exit status gets truncated to eight bits; if
  8653. @code{main} returns the value 256, the exit status is 0.
  8654. Normally, programs return only one of two values: 0 for success,
  8655. and 1 for failure. For maximum portability, use the macro
  8656. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8657. @code{stdlib.h}. Here's an example:
  8658. @cindex @code{EXIT_FAILURE}
  8659. @cindex @code{EXIT_SUCCESS}
  8660. @example
  8661. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8662. /* @r{and @code{EXIT_FAILURE}.} */
  8663. int
  8664. main (void)
  8665. @{
  8666. @r{@dots{}}
  8667. if (foo)
  8668. return EXIT_SUCCESS;
  8669. else
  8670. return EXIT_FAILURE;
  8671. @}
  8672. @end example
  8673. Some types of programs maintain special conventions for various return
  8674. values; for example, comparison programs including @code{cmp} and
  8675. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8676. the comparison couldn't be performed.
  8677. @node Command-line Parameters
  8678. @subsection Accessing Command-line Parameters
  8679. @cindex command-line parameters
  8680. @cindex parameters, command-line
  8681. If the program was invoked with any command-line arguments, it can
  8682. access them through the arguments of @code{main}, @code{argc} and
  8683. @code{argv}. (You can give these arguments any names, but the names
  8684. @code{argc} and @code{argv} are customary.)
  8685. The value of @code{argv} is an array containing all of the
  8686. command-line arguments as strings, with the name of the command
  8687. invoked as the first string. @code{argc} is an integer that says how
  8688. many strings @code{argv} contains. Here is an example of accessing
  8689. the command-line parameters, retrieving the program's name and
  8690. checking for the standard @option{--version} and @option{--help} options:
  8691. @example
  8692. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8693. int
  8694. main (int argc, char *argv[])
  8695. @{
  8696. char *program_name = argv[0];
  8697. for (int i = 1; i < argc; i++)
  8698. @{
  8699. if (!strcmp (argv[i], "--version"))
  8700. @{
  8701. /* @r{Print version information and exit.} */
  8702. @r{@dots{}}
  8703. @}
  8704. else if (!strcmp (argv[i], "--help"))
  8705. @{
  8706. /* @r{Print help information and exit.} */
  8707. @r{@dots{}}
  8708. @}
  8709. @}
  8710. @r{@dots{}}
  8711. @}
  8712. @end example
  8713. @node Environment Variables
  8714. @subsection Accessing Environment Variables
  8715. @cindex environment variables
  8716. You can optionally include a third parameter to @code{main}, another
  8717. array of strings, to capture the environment variables available to
  8718. the program. Unlike what happens with @code{argv}, there is no
  8719. additional parameter for the count of environment variables; rather,
  8720. the array of environment variables concludes with a null pointer.
  8721. @example
  8722. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8723. int
  8724. main (int argc, char *argv[], char *envp[])
  8725. @{
  8726. /* @r{Print out all environment variables.} */
  8727. int i = 0;
  8728. while (envp[i])
  8729. @{
  8730. printf ("%s\n", envp[i]);
  8731. i++;
  8732. @}
  8733. @}
  8734. @end example
  8735. Another method of retrieving environment variables is to use the
  8736. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8737. Using @code{getenv} does not require defining @code{main} to accept the
  8738. @code{envp} pointer. For example, here is a program that fetches and prints
  8739. the user's home directory (if defined):
  8740. @example
  8741. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8742. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8743. int
  8744. main (void)
  8745. @{
  8746. char *home_directory = getenv ("HOME");
  8747. if (home_directory)
  8748. printf ("My home directory is: %s\n", home_directory);
  8749. else
  8750. printf ("My home directory is not defined!\n");
  8751. @}
  8752. @end example
  8753. @node Advanced Definitions
  8754. @section Advanced Function Features
  8755. This section describes some advanced or obscure features for GNU C
  8756. function definitions. If you are just learning C, you can skip the
  8757. rest of this chapter.
  8758. @menu
  8759. * Variable-Length Array Parameters:: Functions that accept arrays
  8760. of variable length.
  8761. * Variable Number of Arguments:: Variadic functions.
  8762. * Nested Functions:: Defining functions within functions.
  8763. * Inline Function Definitions:: A function call optimization technique.
  8764. @end menu
  8765. @node Variable-Length Array Parameters
  8766. @subsection Variable-Length Array Parameters
  8767. @cindex variable-length array parameters
  8768. @cindex array parameters, variable-length
  8769. @cindex functions that accept variable-length arrays
  8770. An array parameter can have variable length: simply declare the array
  8771. type with a size that isn't constant. In a nested function, the
  8772. length can refer to a variable defined in a containing scope. In any
  8773. function, it can refer to a previous parameter, like this:
  8774. @example
  8775. struct entry
  8776. tester (int len, char data[len][len])
  8777. @{
  8778. @r{@dots{}}
  8779. @}
  8780. @end example
  8781. Alternatively, in function declarations (but not in function
  8782. definitions), you can use @code{[*]} to denote that the array
  8783. parameter is of a variable length, such that these two declarations
  8784. mean the same thing:
  8785. @example
  8786. struct entry
  8787. tester (int len, char data[len][len]);
  8788. @end example
  8789. @example
  8790. struct entry
  8791. tester (int len, char data[*][*]);
  8792. @end example
  8793. @noindent
  8794. The two forms of input are equivalent in GNU C, but emphasizing that
  8795. the array parameter is variable-length may be helpful to those
  8796. studying the code.
  8797. You can also omit the length parameter, and instead use some other
  8798. in-scope variable for the length in the function definition:
  8799. @example
  8800. struct entry
  8801. tester (char data[*][*]);
  8802. @r{@dots{}}
  8803. int dataLength = 20;
  8804. @r{@dots{}}
  8805. struct entry
  8806. tester (char data[dataLength][dataLength])
  8807. @{
  8808. @r{@dots{}}
  8809. @}
  8810. @end example
  8811. @c ??? check text above
  8812. @cindex parameter forward declaration
  8813. In GNU C, to pass the array first and the length afterward, you can
  8814. use a @dfn{parameter forward declaration}, like this:
  8815. @example
  8816. struct entry
  8817. tester (int len; char data[len][len], int len)
  8818. @{
  8819. @r{@dots{}}
  8820. @}
  8821. @end example
  8822. The @samp{int len} before the semicolon is the parameter forward
  8823. declaration; it serves the purpose of making the name @code{len} known
  8824. when the declaration of @code{data} is parsed.
  8825. You can write any number of such parameter forward declarations in the
  8826. parameter list. They can be separated by commas or semicolons, but
  8827. the last one must end with a semicolon, which is followed by the
  8828. ``real'' parameter declarations. Each forward declaration must match
  8829. a subsequent ``real'' declaration in parameter name and data type.
  8830. Standard C does not support parameter forward declarations.
  8831. @node Variable Number of Arguments
  8832. @subsection Variable-Length Parameter Lists
  8833. @cindex variable-length parameter lists
  8834. @cindex parameters lists, variable length
  8835. @cindex function parameter lists, variable length
  8836. @cindex variadic function
  8837. A function that takes a variable number of arguments is called a
  8838. @dfn{variadic function}. In C, a variadic function must specify at
  8839. least one fixed argument with an explicitly declared data type.
  8840. Additional arguments can follow, and can vary in both quantity and
  8841. data type.
  8842. In the function header, declare the fixed parameters in the normal
  8843. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8844. example of a variadic function header:
  8845. @example
  8846. int add_multiple_values (int number, ...)
  8847. @end example
  8848. @cindex @code{va_list}
  8849. @cindex @code{va_start}
  8850. @cindex @code{va_end}
  8851. The function body can refer to fixed arguments by their parameter
  8852. names, but the additional arguments have no names. Accessing them in
  8853. the function body uses certain standard macros. They are defined in
  8854. the library header file @file{stdarg.h}, so the code must
  8855. @code{#include} that file.
  8856. In the body, write
  8857. @example
  8858. va_list ap;
  8859. va_start (ap, @var{last_fixed_parameter});
  8860. @end example
  8861. @noindent
  8862. This declares the variable @code{ap} (you can use any name for it)
  8863. and then sets it up to point before the first additional argument.
  8864. Then, to fetch the next consecutive additional argument, write this:
  8865. @example
  8866. va_arg (ap, @var{type})
  8867. @end example
  8868. After fetching all the additional arguments (or as many as need to be
  8869. used), write this:
  8870. @example
  8871. va_end (ap);
  8872. @end example
  8873. Here's an example of a variadic function definition that adds any
  8874. number of @code{int} arguments. The first (fixed) argument says how
  8875. many more arguments follow.
  8876. @example
  8877. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8878. @r{@dots{}}
  8879. int
  8880. add_multiple_values (int argcount, ...)
  8881. @{
  8882. int counter, total = 0;
  8883. /* @r{Declare a variable of type @code{va_list}.} */
  8884. va_list argptr;
  8885. /* @r{Initialize that variable..} */
  8886. va_start (argptr, argcount);
  8887. for (counter = 0; counter < argcount; counter++)
  8888. @{
  8889. /* @r{Get the next additional argument.} */
  8890. total += va_arg (argptr, int);
  8891. @}
  8892. /* @r{End use of the @code{argptr} variable.} */
  8893. va_end (argptr);
  8894. return total;
  8895. @}
  8896. @end example
  8897. With GNU C, @code{va_end} is superfluous, but some other compilers
  8898. might make @code{va_start} allocate memory so that calling
  8899. @code{va_end} is necessary to avoid a memory leak. Before doing
  8900. @code{va_start} again with the same variable, do @code{va_end}
  8901. first.
  8902. @cindex @code{va_copy}
  8903. Because of this possible memory allocation, it is risky (in principle)
  8904. to copy one @code{va_list} variable to another with assignment.
  8905. Instead, use @code{va_copy}, which copies the substance but allocates
  8906. separate memory in the variable you copy to. The call looks like
  8907. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8908. @var{from} should be variables of type @code{va_list}. In principle,
  8909. do @code{va_end} on each of these variables before its scope ends.
  8910. Since the additional arguments' types are not specified in the
  8911. function's definition, the default argument promotions
  8912. (@pxref{Argument Promotions}) apply to them in function calls. The
  8913. function definition must take account of this; thus, if an argument
  8914. was passed as @code{short}, the function should get it as @code{int}.
  8915. If an argument was passed as @code{float}, the function should get it
  8916. as @code{double}.
  8917. C has no mechanism to tell the variadic function how many arguments
  8918. were passed to it, so its calling convention must give it a way to
  8919. determine this. That's why @code{add_multiple_values} takes a fixed
  8920. argument that says how many more arguments follow. Thus, you can
  8921. call the function like this:
  8922. @example
  8923. sum = add_multiple_values (3, 12, 34, 190);
  8924. /* @r{Value is 12+34+190.} */
  8925. @end example
  8926. In GNU C, there is no actual need to use the @code{va_end} function.
  8927. In fact, it does nothing. It's used for compatibility with other
  8928. compilers, when that matters.
  8929. It is a mistake to access variables declared as @code{va_list} except
  8930. in the specific ways described here. Just what that type consists of
  8931. is an implementation detail, which could vary from one platform to
  8932. another.
  8933. @node Nested Functions
  8934. @subsection Nested Functions
  8935. @cindex nested functions
  8936. @cindex functions, nested
  8937. @cindex downward funargs
  8938. @cindex thunks
  8939. A @dfn{nested function} is a function defined inside another function.
  8940. (The ability to do this indispensable for automatic translation of
  8941. certain programming languages into C.) The nested function's name is
  8942. local to the block where it is defined. For example, here we define a
  8943. nested function named @code{square}, then call it twice:
  8944. @example
  8945. @group
  8946. foo (double a, double b)
  8947. @{
  8948. double square (double z) @{ return z * z; @}
  8949. return square (a) + square (b);
  8950. @}
  8951. @end group
  8952. @end example
  8953. The nested function definition can access all the variables of the containing
  8954. function that are visible at the point of its definition. This is
  8955. called @dfn{lexical scoping}. For example, here we show a nested
  8956. function that uses an inherited variable named @code{offset}:
  8957. @example
  8958. @group
  8959. bar (int *array, int offset, int size)
  8960. @{
  8961. int access (int *array, int index)
  8962. @{ return array[index + offset]; @}
  8963. int i;
  8964. @r{@dots{}}
  8965. for (i = 0; i < size; i++)
  8966. @r{@dots{}} access (array, i) @r{@dots{}}
  8967. @}
  8968. @end group
  8969. @end example
  8970. Nested function definitions can appear wherever automatic variable
  8971. declarations are allowed; that is, in any block, interspersed with the
  8972. other declarations and statements in the block.
  8973. The nested function's name is visible only within the parent block;
  8974. the name's scope starts from its definition and continues to the end
  8975. of the containing block. If the nested function's name
  8976. is the same as the parent function's name, there will be
  8977. no way to refer to the parent function inside the scope of the
  8978. name of the nested function.
  8979. Using @code{extern} or @code{static} on a nested function definition
  8980. is an error.
  8981. It is possible to call the nested function from outside the scope of its
  8982. name by storing its address or passing the address to another function.
  8983. You can do this safely, but you must be careful:
  8984. @example
  8985. @group
  8986. hack (int *array, int size, int addition)
  8987. @{
  8988. void store (int index, int value)
  8989. @{ array[index] = value + addition; @}
  8990. intermediate (store, size);
  8991. @}
  8992. @end group
  8993. @end example
  8994. Here, the function @code{intermediate} receives the address of
  8995. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8996. the arguments given to @code{store} are used to store into @code{array}.
  8997. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8998. It is safe for @code{intermediate} to call @code{store} because
  8999. @code{hack}'s stack frame, with its arguments and local variables,
  9000. continues to exist during the call to @code{intermediate}.
  9001. Calling the nested function through its address after the containing
  9002. function has exited is asking for trouble. If it is called after a
  9003. containing scope level has exited, and if it refers to some of the
  9004. variables that are no longer in scope, it will refer to memory
  9005. containing junk or other data. It's not wise to take the risk.
  9006. The GNU C Compiler implements taking the address of a nested function
  9007. using a technique called @dfn{trampolines}. This technique was
  9008. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  9009. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  9010. A nested function can jump to a label inherited from a containing
  9011. function, provided the label was explicitly declared in the containing
  9012. function (@pxref{Local Labels}). Such a jump returns instantly to the
  9013. containing function, exiting the nested function that did the
  9014. @code{goto} and any intermediate function invocations as well. Here
  9015. is an example:
  9016. @example
  9017. @group
  9018. bar (int *array, int offset, int size)
  9019. @{
  9020. /* @r{Explicitly declare the label @code{failure}.} */
  9021. __label__ failure;
  9022. int access (int *array, int index)
  9023. @{
  9024. if (index > size)
  9025. /* @r{Exit this function,}
  9026. @r{and return to @code{bar}.} */
  9027. goto failure;
  9028. return array[index + offset];
  9029. @}
  9030. @end group
  9031. @group
  9032. int i;
  9033. @r{@dots{}}
  9034. for (i = 0; i < size; i++)
  9035. @r{@dots{}} access (array, i) @r{@dots{}}
  9036. @r{@dots{}}
  9037. return 0;
  9038. /* @r{Control comes here from @code{access}
  9039. if it does the @code{goto}.} */
  9040. failure:
  9041. return -1;
  9042. @}
  9043. @end group
  9044. @end example
  9045. To declare the nested function before its definition, use
  9046. @code{auto} (which is otherwise meaningless for function declarations;
  9047. @pxref{auto and register}). For example,
  9048. @example
  9049. bar (int *array, int offset, int size)
  9050. @{
  9051. auto int access (int *, int);
  9052. @r{@dots{}}
  9053. @r{@dots{}} access (array, i) @r{@dots{}}
  9054. @r{@dots{}}
  9055. int access (int *array, int index)
  9056. @{
  9057. @r{@dots{}}
  9058. @}
  9059. @r{@dots{}}
  9060. @}
  9061. @end example
  9062. @node Inline Function Definitions
  9063. @subsection Inline Function Definitions
  9064. @cindex inline function definitions
  9065. @cindex function definitions, inline
  9066. @findex inline
  9067. To declare a function inline, use the @code{inline} keyword in its
  9068. definition. Here's a simple function that takes a pointer-to-@code{int}
  9069. and increments the integer stored there---declared inline.
  9070. @example
  9071. struct list
  9072. @{
  9073. struct list *first, *second;
  9074. @};
  9075. inline struct list *
  9076. list_first (struct list *p)
  9077. @{
  9078. return p->first;
  9079. @}
  9080. inline struct list *
  9081. list_second (struct list *p)
  9082. @{
  9083. return p->second;
  9084. @}
  9085. @end example
  9086. optimized compilation can substitute the inline function's body for
  9087. any call to it. This is called @emph{inlining} the function. It
  9088. makes the code that contains the call run faster, significantly so if
  9089. the inline function is small.
  9090. Here's a function that uses @code{pair_second}:
  9091. @example
  9092. int
  9093. pairlist_length (struct list *l)
  9094. @{
  9095. int length = 0;
  9096. while (l)
  9097. @{
  9098. length++;
  9099. l = pair_second (l);
  9100. @}
  9101. return length;
  9102. @}
  9103. @end example
  9104. Substituting the code of @code{pair_second} into the definition of
  9105. @code{pairlist_length} results in this code, in effect:
  9106. @example
  9107. int
  9108. pairlist_length (struct list *l)
  9109. @{
  9110. int length = 0;
  9111. while (l)
  9112. @{
  9113. length++;
  9114. l = l->second;
  9115. @}
  9116. return length;
  9117. @}
  9118. @end example
  9119. Since the definition of @code{pair_second} does not say @code{extern}
  9120. or @code{static}, that definition is used only for inlining. It
  9121. doesn't generate code that can be called at run time. If not all the
  9122. calls to the function are inlined, there must be a definition of the
  9123. same function name in another module for them to call.
  9124. @cindex inline functions, omission of
  9125. @c @opindex fkeep-inline-functions
  9126. Adding @code{static} to an inline function definition means the
  9127. function definition is limited to this compilation module. Also, it
  9128. generates run-time code if necessary for the sake of any calls that
  9129. were not inlined. If all calls are inlined then the function
  9130. definition does not generate run-time code, but you can force
  9131. generation of run-time code with the option
  9132. @option{-fkeep-inline-functions}.
  9133. @cindex extern inline function
  9134. Specifying @code{extern} along with @code{inline} means the function is
  9135. external and generates run-time code to be called from other
  9136. separately compiled modules, as well as inlined. You can define the
  9137. function as @code{inline} without @code{extern} in other modules so as
  9138. to inline calls to the same function in those modules.
  9139. Why are some calls not inlined? First of all, inlining is an
  9140. optimization, so non-optimized compilation does not inline.
  9141. Some calls cannot be inlined for technical reasons. Also, certain
  9142. usages in a function definition can make it unsuitable for inline
  9143. substitution. Among these usages are: variadic functions, use of
  9144. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9145. use of nonlocal goto. The option @option{-Winline} requests a warning
  9146. when a function marked @code{inline} is unsuitable to be inlined. The
  9147. warning explains what obstacle makes it unsuitable.
  9148. Just because a call @emph{can} be inlined does not mean it
  9149. @emph{should} be inlined. The GNU C compiler weighs costs and
  9150. benefits to decide whether inlining a particular call is advantageous.
  9151. You can force inlining of all calls to a given function that can be
  9152. inlined, even in a non-optimized compilation. by specifying the
  9153. @samp{always_inline} attribute for the function, like this:
  9154. @example
  9155. /* @r{Prototype.} */
  9156. inline void foo (const char) __attribute__((always_inline));
  9157. @end example
  9158. @noindent
  9159. This is a GNU C extension. @xref{Attributes}.
  9160. A function call may be inlined even if not declared @code{inline} in
  9161. special cases where the compiler can determine this is correct and
  9162. desirable. For instance, when a static function is called only once,
  9163. it will very likely be inlined. With @option{-flto}, link-time
  9164. optimization, any function might be inlined. To absolutely prevent
  9165. inlining of a specific function, specify
  9166. @code{__attribute__((__noinline__))} in the function's definition.
  9167. @node Obsolete Definitions
  9168. @section Obsolete Function Features
  9169. These features of function definitions are still used in old
  9170. programs, but you shouldn't write code this way today.
  9171. If you are just learning C, you can skip this section.
  9172. @menu
  9173. * Old GNU Inlining:: An older inlining technique.
  9174. * Old-Style Function Definitions:: Original K&R style functions.
  9175. @end menu
  9176. @node Old GNU Inlining
  9177. @subsection Older GNU C Inlining
  9178. The GNU C spec for inline functions, before GCC version 5, defined
  9179. @code{extern inline} on a function definition to mean to inline calls
  9180. to it but @emph{not} generate code for the function that could be
  9181. called at run time. By contrast, @code{inline} without @code{extern}
  9182. specified to generate run-time code for the function. In effect, ISO
  9183. incompatibly flipped the meanings of these two cases. We changed GCC
  9184. in version 5 to adopt the ISO specification.
  9185. Many programs still use these cases with the previous GNU C meanings.
  9186. You can specify use of those meanings with the option
  9187. @option{-fgnu89-inline}. You can also specify this for a single
  9188. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9189. @example
  9190. inline __attribute__ ((gnu_inline))
  9191. int
  9192. inc (int *a)
  9193. @{
  9194. (*a)++;
  9195. @}
  9196. @end example
  9197. @node Old-Style Function Definitions
  9198. @subsection Old-Style Function Definitions
  9199. @cindex old-style function definitions
  9200. @cindex function definitions, old-style
  9201. @cindex K&R-style function definitions
  9202. The syntax of C traditionally allows omitting the data type in a
  9203. function declaration if it specifies a storage class or a qualifier.
  9204. Then the type defaults to @code{int}. For example:
  9205. @example
  9206. static foo (double x);
  9207. @end example
  9208. @noindent
  9209. defaults the return type to @code{int}. This is bad practice; if you
  9210. see it, fix it.
  9211. An @dfn{old-style} (or ``K&R'') function definition is the way
  9212. function definitions were written in the 1980s. It looks like this:
  9213. @example
  9214. @var{rettype}
  9215. @var{function} (@var{parmnames})
  9216. @var{parm_declarations}
  9217. @{
  9218. @var{body}
  9219. @}
  9220. @end example
  9221. In @var{parmnames}, only the parameter names are listed, separated by
  9222. commas. Then @var{parm_declarations} declares their data types; these
  9223. declarations look just like variable declarations. If a parameter is
  9224. listed in @var{parmnames} but has no declaration, it is implicitly
  9225. declared @code{int}.
  9226. There is no reason to write a definition this way nowadays, but they
  9227. can still be seen in older GNU programs.
  9228. An old-style variadic function definition looks like this:
  9229. @example
  9230. #include <varargs.h>
  9231. int
  9232. add_multiple_values (va_alist)
  9233. va_dcl
  9234. @{
  9235. int argcount;
  9236. int counter, total = 0;
  9237. /* @r{Declare a variable of type @code{va_list}.} */
  9238. va_list argptr;
  9239. /* @r{Initialize that variable.} */
  9240. va_start (argptr);
  9241. /* @r{Get the first argument (fixed).} */
  9242. argcount = va_arg (int);
  9243. for (counter = 0; counter < argcount; counter++)
  9244. @{
  9245. /* @r{Get the next additional argument.} */
  9246. total += va_arg (argptr, int);
  9247. @}
  9248. /* @r{End use of the @code{argptr} variable.} */
  9249. va_end (argptr);
  9250. return total;
  9251. @}
  9252. @end example
  9253. Note that the old-style variadic function definition has no fixed
  9254. parameter variables; all arguments must be obtained with
  9255. @code{va_arg}.
  9256. @node Compatible Types
  9257. @chapter Compatible Types
  9258. @cindex compatible types
  9259. @cindex types, compatible
  9260. Declaring a function or variable twice is valid in C only if the two
  9261. declarations specify @dfn{compatible} types. In addition, some
  9262. operations on pointers require operands to have compatible target
  9263. types.
  9264. In C, two different primitive types are never compatible. Likewise for
  9265. the defined types @code{struct}, @code{union} and @code{enum}: two
  9266. separately defined types are incompatible unless they are defined
  9267. exactly the same way.
  9268. However, there are a few cases where different types can be
  9269. compatible:
  9270. @itemize @bullet
  9271. @item
  9272. Every enumeration type is compatible with some integer type. In GNU
  9273. C, the choice of integer type depends on the largest enumeration
  9274. value.
  9275. @c ??? Which one, in GCC?
  9276. @c ??? ... it varies, depending on the enum values. Testing on
  9277. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9278. @c ??? then moves on to an 8-byte signed integer. These details
  9279. @c ??? might be platform-dependent, as the C standard says that even
  9280. @c ??? char could be used as an enum type, but it's at least true
  9281. @c ??? that GCC chooses a type that is at least large enough to
  9282. @c ??? hold the largest enum value.
  9283. @item
  9284. Array types are compatible if the element types are compatible
  9285. and the sizes (when specified) match.
  9286. @item
  9287. Pointer types are compatible if the pointer target types are
  9288. compatible.
  9289. @item
  9290. Function types that specify argument types are compatible if the
  9291. return types are compatible and the argument types are compatible,
  9292. argument by argument. In addition, they must all agree in whether
  9293. they use @code{...} to allow additional arguments.
  9294. @item
  9295. Function types that don't specify argument types are compatible if the
  9296. return types are.
  9297. @item
  9298. Function types that specify the argument types are compatible with
  9299. function types that omit them, if the return types are compatible and
  9300. the specified argument types are unaltered by the argument promotions
  9301. (@pxref{Argument Promotions}).
  9302. @end itemize
  9303. In order for types to be compatible, they must agree in their type
  9304. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9305. It follows that @code{const int *} and @code{int *} are incompatible
  9306. too (they are pointers to types that are not compatible).
  9307. If two types are compatible ignoring the qualifiers, we call them
  9308. @dfn{nearly compatible}. (If they are array types, we ignore
  9309. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9310. Comparison of pointers is valid if the pointers' target types are
  9311. nearly compatible. Likewise, the two branches of a conditional
  9312. expression may be pointers to nearly compatible target types.
  9313. If two types are compatible ignoring the qualifiers, and the first
  9314. type has all the qualifiers of the second type, we say the first is
  9315. @dfn{upward compatible} with the second. Assignment of pointers
  9316. requires the assigned pointer's target type to be upward compatible
  9317. with the right operand (the new value)'s target type.
  9318. @node Type Conversions
  9319. @chapter Type Conversions
  9320. @cindex type conversions
  9321. @cindex conversions, type
  9322. C converts between data types automatically when that seems clearly
  9323. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9324. @menu
  9325. * Explicit Type Conversion:: Casting a value from one type to another.
  9326. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9327. * Argument Promotions:: Automatic conversion of function parameters.
  9328. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9329. * Common Type:: When operand types differ, which one is used?
  9330. @end menu
  9331. @node Explicit Type Conversion
  9332. @section Explicit Type Conversion
  9333. @cindex cast
  9334. @cindex explicit type conversion
  9335. You can do explicit conversions using the unary @dfn{cast} operator,
  9336. which is written as a type designator (@pxref{Type Designators}) in
  9337. parentheses. For example, @code{(int)} is the operator to cast to
  9338. type @code{int}. Here's an example of using it:
  9339. @example
  9340. @{
  9341. double d = 5.5;
  9342. printf ("Floating point value: %f\n", d);
  9343. printf ("Rounded to integer: %d\n", (int) d);
  9344. @}
  9345. @end example
  9346. Using @code{(int) d} passes an @code{int} value as argument to
  9347. @code{printf}, so you can print it with @samp{%d}. Using just
  9348. @code{d} without the cast would pass the value as @code{double}.
  9349. That won't work at all with @samp{%d}; the results would be gibberish.
  9350. To divide one integer by another without rounding,
  9351. cast either of the integers to @code{double} first:
  9352. @example
  9353. (double) @var{dividend} / @var{divisor}
  9354. @var{dividend} / (double) @var{divisor}
  9355. @end example
  9356. It is enough to cast one of them, because that forces the common type
  9357. to @code{double} so the other will be converted automatically.
  9358. The valid cast conversions are:
  9359. @itemize @bullet
  9360. @item
  9361. One numerical type to another.
  9362. @item
  9363. One pointer type to another.
  9364. (Converting between pointers that point to functions
  9365. and pointers that point to data is not standard C.)
  9366. @item
  9367. A pointer type to an integer type.
  9368. @item
  9369. An integer type to a pointer type.
  9370. @item
  9371. To a union type, from the type of any alternative in the union
  9372. (@pxref{Unions}). (This is a GNU extension.)
  9373. @item
  9374. Anything, to @code{void}.
  9375. @end itemize
  9376. @node Assignment Type Conversions
  9377. @section Assignment Type Conversions
  9378. @cindex assignment type conversions
  9379. Certain type conversions occur automatically in assignments
  9380. and certain other contexts. These are the conversions
  9381. assignments can do:
  9382. @itemize @bullet
  9383. @item
  9384. Converting any numeric type to any other numeric type.
  9385. @item
  9386. Converting @code{void *} to any other pointer type
  9387. (except pointer-to-function types).
  9388. @item
  9389. Converting any other pointer type to @code{void *}.
  9390. (except pointer-to-function types).
  9391. @item
  9392. Converting 0 (a null pointer constant) to any pointer type.
  9393. @item
  9394. Converting any pointer type to @code{bool}. (The result is
  9395. 1 if the pointer is not null.)
  9396. @item
  9397. Converting between pointer types when the left-hand target type is
  9398. upward compatible with the right-hand target type. @xref{Compatible
  9399. Types}.
  9400. @end itemize
  9401. These type conversions occur automatically in certain contexts,
  9402. which are:
  9403. @itemize @bullet
  9404. @item
  9405. An assignment converts the type of the right-hand expression
  9406. to the type wanted by the left-hand expression. For example,
  9407. @example
  9408. double i;
  9409. i = 5;
  9410. @end example
  9411. @noindent
  9412. converts 5 to @code{double}.
  9413. @item
  9414. A function call, when the function specifies the type for that
  9415. argument, converts the argument value to that type. For example,
  9416. @example
  9417. void foo (double);
  9418. foo (5);
  9419. @end example
  9420. @noindent
  9421. converts 5 to @code{double}.
  9422. @item
  9423. A @code{return} statement converts the specified value to the type
  9424. that the function is declared to return. For example,
  9425. @example
  9426. double
  9427. foo ()
  9428. @{
  9429. return 5;
  9430. @}
  9431. @end example
  9432. @noindent
  9433. also converts 5 to @code{double}.
  9434. @end itemize
  9435. In all three contexts, if the conversion is impossible, that
  9436. constitutes an error.
  9437. @node Argument Promotions
  9438. @section Argument Promotions
  9439. @cindex argument promotions
  9440. @cindex promotion of arguments
  9441. When a function's definition or declaration does not specify the type
  9442. of an argument, that argument is passed without conversion in whatever
  9443. type it has, with these exceptions:
  9444. @itemize @bullet
  9445. @item
  9446. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9447. expression is a narrow integer, such as @code{char} or @code{short},
  9448. the call converts it automatically to @code{int} (@pxref{Integer
  9449. Types}).@footnote{On an embedded controller where @code{char}
  9450. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9451. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9452. never occurs in GNU C on real computers.}
  9453. In this example, the expression @code{c} is passed as an @code{int}:
  9454. @example
  9455. char c = '$';
  9456. printf ("Character c is '%c'\n", c);
  9457. @end example
  9458. @item
  9459. If the expression
  9460. has type @code{float}, the call converts it automatically to
  9461. @code{double}.
  9462. @item
  9463. An array as argument is converted to a pointer to its zeroth element.
  9464. @item
  9465. A function name as argument is converted to a pointer to that function.
  9466. @end itemize
  9467. @node Operand Promotions
  9468. @section Operand Promotions
  9469. @cindex operand promotions
  9470. The operands in arithmetic operations undergo type conversion automatically.
  9471. These @dfn{operand promotions} are the same as the argument promotions
  9472. except without converting @code{float} to @code{double}. In other words,
  9473. the operand promotions convert
  9474. @itemize @bullet
  9475. @item
  9476. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9477. @item
  9478. an array to a pointer to its zeroth element, and
  9479. @item
  9480. a function name to a pointer to that function.
  9481. @end itemize
  9482. @node Common Type
  9483. @section Common Type
  9484. @cindex common type
  9485. Arithmetic binary operators (except the shift operators) convert their
  9486. operands to the @dfn{common type} before operating on them.
  9487. Conditional expressions also convert the two possible results to their
  9488. common type. Here are the rules for determining the common type.
  9489. If one of the numbers has a floating-point type and the other is an
  9490. integer, the common type is that floating-point type. For instance,
  9491. @example
  9492. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9493. @end example
  9494. If both are floating point, the type with the larger range is the
  9495. common type.
  9496. If both are integers but of different widths, the common type
  9497. is the wider of the two.
  9498. If they are integer types of the same width, the common type is
  9499. unsigned if either operand is unsigned, and it's @code{long} if either
  9500. operand is @code{long}. It's @code{long long} if either operand is
  9501. @code{long long}.
  9502. These rules apply to addition, subtraction, multiplication, division,
  9503. remainder, comparisons, and bitwise operations. They also apply to
  9504. the two branches of a conditional expression, and to the arithmetic
  9505. done in a modifying assignment operation.
  9506. @node Scope
  9507. @chapter Scope
  9508. @cindex scope
  9509. @cindex block scope
  9510. @cindex function scope
  9511. @cindex function prototype scope
  9512. Each definition or declaration of an identifier is visible
  9513. in certain parts of the program, which is typically less than the whole
  9514. of the program. The parts where it is visible are called its @dfn{scope}.
  9515. Normally, declarations made at the top-level in the source -- that is,
  9516. not within any blocks and function definitions -- are visible for the
  9517. entire contents of the source file after that point. This is called
  9518. @dfn{file scope} (@pxref{File-Scope Variables}).
  9519. Declarations made within blocks of code, including within function
  9520. definitions, are visible only within those blocks. This is called
  9521. @dfn{block scope}. Here is an example:
  9522. @example
  9523. @group
  9524. void
  9525. foo (void)
  9526. @{
  9527. int x = 42;
  9528. @}
  9529. @end group
  9530. @end example
  9531. @noindent
  9532. In this example, the variable @code{x} has block scope; it is visible
  9533. only within the @code{foo} function definition block. Thus, other
  9534. blocks could have their own variables, also named @code{x}, without
  9535. any conflict between those variables.
  9536. A variable declared inside a subblock has a scope limited to
  9537. that subblock,
  9538. @example
  9539. @group
  9540. void
  9541. foo (void)
  9542. @{
  9543. @{
  9544. int x = 42;
  9545. @}
  9546. // @r{@code{x} is out of scope here.}
  9547. @}
  9548. @end group
  9549. @end example
  9550. If a variable declared within a block has the same name as a variable
  9551. declared outside of that block, the definition within the block
  9552. takes precedence during its scope:
  9553. @example
  9554. @group
  9555. int x = 42;
  9556. void
  9557. foo (void)
  9558. @{
  9559. int x = 17;
  9560. printf ("%d\n", x);
  9561. @}
  9562. @end group
  9563. @end example
  9564. @noindent
  9565. This prints 17, the value of the variable @code{x} declared in the
  9566. function body block, rather than the value of the variable @code{x} at
  9567. file scope. We say that the inner declaration of @code{x}
  9568. @dfn{shadows} the outer declaration, for the extent of the inner
  9569. declaration's scope.
  9570. A declaration with block scope can be shadowed by another declaration
  9571. with the same name in a subblock.
  9572. @example
  9573. @group
  9574. void
  9575. foo (void)
  9576. @{
  9577. char *x = "foo";
  9578. @{
  9579. int x = 42;
  9580. @r{@dots{}}
  9581. exit (x / 6);
  9582. @}
  9583. @}
  9584. @end group
  9585. @end example
  9586. A function parameter's scope is the entire function body, but it can
  9587. be shadowed. For example:
  9588. @example
  9589. @group
  9590. int x = 42;
  9591. void
  9592. foo (int x)
  9593. @{
  9594. printf ("%d\n", x);
  9595. @}
  9596. @end group
  9597. @end example
  9598. @noindent
  9599. This prints the value of @code{x} the function parameter, rather than
  9600. the value of the file-scope variable @code{x}.
  9601. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9602. is visible for the whole of the containing function body, both before
  9603. and after the label declaration:
  9604. @example
  9605. @group
  9606. void
  9607. foo (void)
  9608. @{
  9609. @r{@dots{}}
  9610. goto bar;
  9611. @r{@dots{}}
  9612. @{ // @r{Subblock does not affect labels.}
  9613. bar:
  9614. @r{@dots{}}
  9615. @}
  9616. goto bar;
  9617. @}
  9618. @end group
  9619. @end example
  9620. Except for labels, a declared identifier is not
  9621. visible to code before its declaration. For example:
  9622. @example
  9623. @group
  9624. int x = 5;
  9625. int y = x + 10;
  9626. @end group
  9627. @end example
  9628. @noindent
  9629. will work, but:
  9630. @example
  9631. @group
  9632. int x = y + 10;
  9633. int y = 5;
  9634. @end group
  9635. @end example
  9636. @noindent
  9637. cannot refer to the variable @code{y} before its declaration.
  9638. @include cpp.texi
  9639. @node Integers in Depth
  9640. @chapter Integers in Depth
  9641. This chapter explains the machine-level details of integer types: how
  9642. they are represented as bits in memory, and the range of possible
  9643. values for each integer type.
  9644. @menu
  9645. * Integer Representations:: How integer values appear in memory.
  9646. * Maximum and Minimum Values:: Value ranges of integer types.
  9647. @end menu
  9648. @node Integer Representations
  9649. @section Integer Representations
  9650. @cindex integer representations
  9651. @cindex representation of integers
  9652. Modern computers store integer values as binary (base-2) numbers that
  9653. occupy a single unit of storage, typically either as an 8-bit
  9654. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9655. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9656. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9657. any of these types could have some other size, bit it's not worth even
  9658. a minute to cater to that possibility. It never happens on
  9659. GNU/Linux.}
  9660. @cindex @code{CHAR_BIT}
  9661. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9662. of bits in type @code{char}. On any real operating system, the value
  9663. is 8.
  9664. The fixed sizes of numeric types necessarily limits their @dfn{range
  9665. of values}, and the particular encoding of integers decides what that
  9666. range is.
  9667. @cindex two's-complement representation
  9668. For unsigned integers, the entire space is used to represent a
  9669. nonnegative value. Signed integers are stored using
  9670. @dfn{two's-complement representation}: a signed integer with @var{n}
  9671. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9672. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9673. high-order, bit is called the @dfn{sign bit}.
  9674. @c ??? Needs correcting
  9675. There is only one value that means zero, and the most negative number
  9676. lacks a positive counterpart. As a result, negating that number
  9677. causes overflow; in practice, its result is that number back again.
  9678. For example, a two's-complement signed 8-bit integer can represent all
  9679. decimal numbers from @minus{}128 to +127. We will revisit that
  9680. peculiarity shortly.
  9681. Decades ago, there were computers that didn't use two's-complement
  9682. representation for integers (@pxref{Integers in Depth}), but they are
  9683. long gone and not worth any effort to support.
  9684. @c ??? Is this duplicate?
  9685. When an arithmetic operation produces a value that is too big to
  9686. represent, the operation is said to @dfn{overflow}. In C, integer
  9687. overflow does not interrupt the control flow or signal an error.
  9688. What it does depends on signedness.
  9689. For unsigned arithmetic, the result of an operation that overflows is
  9690. the @var{n} low-order bits of the correct value. If the correct value
  9691. is representable in @var{n} bits, that is always the result;
  9692. thus we often say that ``integer arithmetic is exact,'' omitting the
  9693. crucial qualifying phrase ``as long as the exact result is
  9694. representable.''
  9695. In principle, a C program should be written so that overflow never
  9696. occurs for signed integers, but in GNU C you can specify various ways
  9697. of handling such overflow (@pxref{Integer Overflow}).
  9698. Integer representations are best understood by looking at a table for
  9699. a tiny integer size; here are the possible values for an integer with
  9700. three bits:
  9701. @multitable @columnfractions .25 .25 .25 .25
  9702. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9703. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9704. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9705. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9706. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9707. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9708. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9709. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9710. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9711. @end multitable
  9712. The parenthesized decimal numbers in the last column represent the
  9713. signed meanings of the two's-complement of the line's value. Recall
  9714. that, in two's-complement encoding, the high-order bit is 0 when
  9715. the number is nonnegative.
  9716. We can now understand the peculiar behavior of negation of the
  9717. most negative two's-complement integer: start with 0b100,
  9718. invert the bits to get 0b011, and add 1: we get
  9719. 0b100, the value we started with.
  9720. We can also see overflow behavior in two's-complement:
  9721. @example
  9722. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9723. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9724. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9725. @end example
  9726. @noindent
  9727. A sum of two nonnegative signed values that overflows has a 1 in the
  9728. sign bit, so the exact positive result is truncated to a negative
  9729. value.
  9730. @c =====================================================================
  9731. @node Maximum and Minimum Values
  9732. @section Maximum and Minimum Values
  9733. @cindex maximum integer values
  9734. @cindex minimum integer values
  9735. @cindex integer ranges
  9736. @cindex ranges of integer types
  9737. @findex INT_MAX
  9738. @findex UINT_MAX
  9739. @findex SHRT_MAX
  9740. @findex LONG_MAX
  9741. @findex LLONG_MAX
  9742. @findex USHRT_MAX
  9743. @findex ULONG_MAX
  9744. @findex ULLONG_MAX
  9745. @findex CHAR_MAX
  9746. @findex SCHAR_MAX
  9747. @findex UCHAR_MAX
  9748. For each primitive integer type, there is a standard macro defined in
  9749. @file{limits.h} that gives the largest value that type can hold. For
  9750. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9751. On a 32-bit computer, that is equal to 2,147,483,647. The
  9752. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9753. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9754. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9755. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9756. @code{ULLONG_MAX}.
  9757. Since there are three ways to specify a @code{char} type, there are
  9758. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9759. @code{UCHAR_MAX}.
  9760. For each type that is or might be signed, there is another symbol that
  9761. gives the minimum value it can hold. (Just replace @code{MAX} with
  9762. @code{MIN} in the names listed above.) There is no minimum limit
  9763. symbol for types specified with @code{unsigned} because the
  9764. minimum for them is universally zero.
  9765. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9766. two's-complement representation, the most negative number is 1 less
  9767. than the negative of the most positive number. Thus, @code{INT_MIN}
  9768. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9769. actually write the value that way in C, since it would overflow.
  9770. That's a good reason to use @code{INT_MIN} to specify
  9771. that value. Its definition is written to avoid overflow.
  9772. @include fp.texi
  9773. @node Compilation
  9774. @chapter Compilation
  9775. @cindex object file
  9776. @cindex compilation module
  9777. @cindex make rules
  9778. @cindex link
  9779. Early in the manual we explained how to compile a simple C program
  9780. that consists of a single source file (@pxref{Compile Example}).
  9781. However, we handle only short programs that way. A typical C program
  9782. consists of many source files, each of which is usually a separate
  9783. @dfn{compilation module}---meaning that it has to be compiled
  9784. separately. (The source files that are not separate compilation
  9785. modules are those that are used via @code{#include}; see @ref{Header
  9786. Files}.)
  9787. To compile a multi-module program, you compile each of the program's
  9788. compilation modules, making an @dfn{object file} for that module. The
  9789. last step is to @dfn{link} the many object files together into a
  9790. single executable for the whole program.
  9791. The full details of how to compile C programs (and other programs)
  9792. with GCC are documented in xxxx.
  9793. @c ??? ref
  9794. Here we give only a simple introduction.
  9795. These commands compile two compilation modules, @file{foo.c} and
  9796. @file{bar.c}, running the compiler for each module:
  9797. @example
  9798. gcc -c -O -g foo.c
  9799. gcc -c -O -g bar.c
  9800. @end example
  9801. @noindent
  9802. In these commands, @option{-g} says to generate debugging information,
  9803. @option{-O} says to do some optimization, and @option{-c} says to put
  9804. the compiled code for that module into a corresponding object file and
  9805. go no further. The object file for @file{foo.c} is automatically
  9806. called @file{foo.o}, and so on.
  9807. If you wish, you can specify the additional compilation options. For
  9808. instance, @option{-Wformat -Wparenthesis -Wstrict-prototypes} request
  9809. additional warnings.
  9810. @cindex linking object files
  9811. After you compile all the program's modules, you link the object files
  9812. into a combined executable, like this:
  9813. @example
  9814. gcc -o foo foo.o bar.o
  9815. @end example
  9816. @noindent
  9817. In this command, @option{-o foo} species the file name for the
  9818. executable file, and the other arguments are the object files to link.
  9819. Always specify the executable file name in a command that generates
  9820. one.
  9821. One reason to divide a large program into multiple compilation modules
  9822. is to control how each module can access the internals of the others.
  9823. When a module declares a function or variable @code{extern}, other
  9824. modules can access it. The other functions and variables defined in a
  9825. module can't be accessed from outside that module.
  9826. The other reason for using multiple modules is so that changing one
  9827. source file does not require recompiling all of them in order to try
  9828. the modified program. It is sufficient to recompile the source file
  9829. that you changed, then link them all again. Dividing a large program
  9830. into many substantial modules in this way typically makes
  9831. recompilation much faster.
  9832. Normally we don't run any of these commands directly. Instead we
  9833. write a set of @dfn{make rules} for the program, then use the
  9834. @command{make} program to recompile only the source files that need to
  9835. be recompiled, by following those rules. @xref{Top, The GNU Make
  9836. Manual, , make, The GNU Make Manual}.
  9837. @node Directing Compilation
  9838. @chapter Directing Compilation
  9839. This chapter describes C constructs that don't alter the program's
  9840. meaning @emph{as such}, but rather direct the compiler how to treat
  9841. some aspects of the program.
  9842. @menu
  9843. * Pragmas:: Controlling compilation of some constructs.
  9844. * Static Assertions:: Compile-time tests for conditions.
  9845. @end menu
  9846. @node Pragmas
  9847. @section Pragmas
  9848. A @dfn{pragma} is an annotation in a program that gives direction to
  9849. the compiler.
  9850. @menu
  9851. * Pragma Basics:: Pragma syntax and usage.
  9852. * Severity Pragmas:: Settings for compile-time pragma output.
  9853. * Optimization Pragmas:: Controlling optimizations.
  9854. @end menu
  9855. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9856. @node Pragma Basics
  9857. @subsection Pragma Basics
  9858. C defines two syntactical forms for pragmas, the line form and the
  9859. token form. You can write any pragma in either form, with the same
  9860. meaning.
  9861. The line form is a line in the source code, like this:
  9862. @example
  9863. #pragma @var{line}
  9864. @end example
  9865. @noindent
  9866. The line pragma has no effect on the parsing of the lines around it.
  9867. This form has the drawback that it can't be generated by a macro expansion.
  9868. The token form is a series of tokens; it can appear anywhere in the
  9869. program between the other tokens.
  9870. @example
  9871. _Pragma (@var{stringconstant})
  9872. @end example
  9873. @noindent
  9874. The pragma has no effect on the syntax of the tokens that surround it;
  9875. thus, here's a pragma in the middle of an @code{if} statement:
  9876. @example
  9877. if _Pragma ("hello") (x > 1)
  9878. @end example
  9879. @noindent
  9880. However, that's an unclear thing to do; for the sake of
  9881. understandability, it is better to put a pragma on a line by itself
  9882. and not embedded in the middle of another construct.
  9883. Both forms of pragma have a textual argument. In a line pragma, the
  9884. text is the rest of the line. The textual argument to @code{_Pragma}
  9885. uses the same syntax as a C string constant: surround the text with
  9886. two @samp{"} characters, and add a backslash before each @samp{"} or
  9887. @samp{\} character in it.
  9888. With either syntax, the textual argument specifies what to do.
  9889. It begins with one or several words that specify the operation.
  9890. If the compiler does not recognize them, it ignores the pragma.
  9891. Here are the pragma operations supported in GNU C@.
  9892. @c ??? Verify font for []
  9893. @table @code
  9894. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9895. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9896. Declares that the current source file depends on @var{file}, so GNU C
  9897. compares the file times and gives a warning if @var{file} is newer
  9898. than the current source file.
  9899. This directive searches for @var{file} the way @code{#include}
  9900. searches for a non-system header file.
  9901. If @var{message} is given, the warning message includes that text.
  9902. Examples:
  9903. @example
  9904. #pragma GCC dependency "parse.y"
  9905. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9906. rerun fixincludes")
  9907. @end example
  9908. @item #pragma GCC poison @var{identifiers}
  9909. @itemx _Pragma ("GCC poison @var{identifiers}")
  9910. Poisons the identifiers listed in @var{identifiers}.
  9911. This is useful to make sure all mention of @var{identifiers} has been
  9912. deleted from the program and that no reference to them creeps back in.
  9913. If any of those identifiers appears anywhere in the source after the
  9914. directive, it causes a compilation error. For example,
  9915. @example
  9916. #pragma GCC poison printf sprintf fprintf
  9917. sprintf(some_string, "hello");
  9918. @end example
  9919. @noindent
  9920. generates an error.
  9921. If a poisoned identifier appears as part of the expansion of a macro
  9922. that was defined before the identifier was poisoned, it will @emph{not}
  9923. cause an error. Thus, system headers that define macros that use
  9924. the identifier will not cause errors.
  9925. For example,
  9926. @example
  9927. #define strrchr rindex
  9928. _Pragma ("GCC poison rindex")
  9929. strrchr(some_string, 'h');
  9930. @end example
  9931. @noindent
  9932. does not cause a compilation error.
  9933. @item #pragma GCC system_header
  9934. @itemx _Pragma ("GCC system_header")
  9935. Specify treating the rest of the current source file as if it came
  9936. from a system header file. @xref{System Headers, System Headers,
  9937. System Headers, gcc, Using the GNU Compiler Collection}.
  9938. @item #pragma GCC warning @var{message}
  9939. @itemx _Pragma ("GCC warning @var{message}")
  9940. Equivalent to @code{#warning}. Its advantage is that the
  9941. @code{_Pragma} form can be included in a macro definition.
  9942. @item #pragma GCC error @var{message}
  9943. @itemx _Pragma ("GCC error @var{message}")
  9944. Equivalent to @code{#error}. Its advantage is that the
  9945. @code{_Pragma} form can be included in a macro definition.
  9946. @item #pragma GCC message @var{message}
  9947. @itemx _Pragma ("GCC message @var{message}")
  9948. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9949. informational message, and could be used to include additional warning
  9950. or error text without triggering more warnings or errors. (Note that
  9951. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9952. @samp{GCC} as part of the pragma.)
  9953. @end table
  9954. @node Severity Pragmas
  9955. @subsection Severity Pragmas
  9956. These pragmas control the severity of classes of diagnostics.
  9957. You can specify the class of diagnostic with the GCC option that causes
  9958. those diagnostics to be generated.
  9959. @table @code
  9960. @item #pragma GCC diagnostic error @var{option}
  9961. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9962. For code following this pragma, treat diagnostics of the variety
  9963. specified by @var{option} as errors. For example:
  9964. @example
  9965. _Pragma ("GCC diagnostic error -Wformat")
  9966. @end example
  9967. @noindent
  9968. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9969. as errors rather than warnings.
  9970. @item #pragma GCC diagnostic warning @var{option}
  9971. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9972. For code following this pragma, treat diagnostics of the variety
  9973. specified by @var{option} as warnings. This overrides the
  9974. @var{-Werror} option which says to treat warnings as errors.
  9975. @item #pragma GCC diagnostic ignore @var{option}
  9976. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9977. For code following this pragma, refrain from reporting any diagnostics
  9978. of the variety specified by @var{option}.
  9979. @item #pragma GCC diagnostic push
  9980. @itemx _Pragma ("GCC diagnostic push")
  9981. @itemx #pragma GCC diagnostic pop
  9982. @itemx _Pragma ("GCC diagnostic pop")
  9983. These pragmas maintain a stack of states for severity settings.
  9984. @samp{GCC diagnostic push} saves the current settings on the stack,
  9985. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9986. the current settings from that.
  9987. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9988. restores the settings to what they were at the start of compilation.
  9989. Here is an example:
  9990. @example
  9991. _Pragma ("GCC diagnostic error -Wformat")
  9992. /* @r{@option{-Wformat} messages treated as errors. } */
  9993. _Pragma ("GCC diagnostic push")
  9994. _Pragma ("GCC diagnostic warning -Wformat")
  9995. /* @r{@option{-Wformat} messages treated as warnings. } */
  9996. _Pragma ("GCC diagnostic push")
  9997. _Pragma ("GCC diagnostic ignored -Wformat")
  9998. /* @r{@option{-Wformat} messages suppressed. } */
  9999. _Pragma ("GCC diagnostic pop")
  10000. /* @r{@option{-Wformat} messages treated as warnings again. } */
  10001. _Pragma ("GCC diagnostic pop")
  10002. /* @r{@option{-Wformat} messages treated as errors again. } */
  10003. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  10004. _Pragma ("GCC diagnostic pop")
  10005. /* @r{@option{-Wformat} messages treated once again}
  10006. @r{as specified by the GCC command-line options.} */
  10007. @end example
  10008. @end table
  10009. @node Optimization Pragmas
  10010. @subsection Optimization Pragmas
  10011. These pragmas enable a particular optimization for specific function
  10012. definitions. The settings take effect at the end of a function
  10013. definition, so the clean place to use these pragmas is between
  10014. function definitions.
  10015. @table @code
  10016. @item #pragma GCC optimize @var{optimization}
  10017. @itemx _Pragma ("GCC optimize @var{optimization}")
  10018. These pragmas enable the optimization @var{optimization} for the
  10019. following functions. For example,
  10020. @example
  10021. _Pragma ("GCC optimize -fforward-propagate")
  10022. @end example
  10023. @noindent
  10024. says to apply the @samp{forward-propagate} optimization to all
  10025. following function definitions. Specifying optimizations for
  10026. individual functions, rather than for the entire program, is rare but
  10027. can be useful for getting around a bug in the compiler.
  10028. If @var{optimization} does not correspond to a defined optimization
  10029. option, the pragma is erroneous. To turn off an optimization, use the
  10030. corresponding @samp{-fno-} option, such as
  10031. @samp{-fno-forward-propagate}.
  10032. @item #pragma GCC target @var{optimizations}
  10033. @itemx _Pragma ("GCC target @var{optimizations}")
  10034. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  10035. used for platform-specific optimizations. Thus,
  10036. @example
  10037. _Pragma ("GCC target popcnt")
  10038. @end example
  10039. @noindent
  10040. activates the optimization @samp{popcnt} for all
  10041. following function definitions. This optimization is supported
  10042. on a few common targets but not on others.
  10043. @item #pragma GCC push_options
  10044. @itemx _Pragma ("GCC push_options")
  10045. The @samp{push_options} pragma saves on a stack the current settings
  10046. specified with the @samp{target} and @samp{optimize} pragmas.
  10047. @item #pragma GCC pop_options
  10048. @itemx _Pragma ("GCC pop_options")
  10049. The @samp{pop_options} pragma pops saved settings from that stack.
  10050. Here's an example of using this stack.
  10051. @example
  10052. _Pragma ("GCC push_options")
  10053. _Pragma ("GCC optimize forward-propagate")
  10054. /* @r{Functions to compile}
  10055. @r{with the @code{forward-propagate} optimization.} */
  10056. _Pragma ("GCC pop_options")
  10057. /* @r{Ends enablement of @code{forward-propagate}.} */
  10058. @end example
  10059. @item #pragma GCC reset_options
  10060. @itemx _Pragma ("GCC reset_options")
  10061. Clears all pragma-defined @samp{target} and @samp{optimize}
  10062. optimization settings.
  10063. @end table
  10064. @node Static Assertions
  10065. @section Static Assertions
  10066. @cindex static assertions
  10067. @findex _Static_assert
  10068. You can add compiler-time tests for necessary conditions into your
  10069. code using @code{_Static_assert}. This can be useful, for example, to
  10070. check that the compilation target platform supports the type sizes
  10071. that the code expects. For example,
  10072. @example
  10073. _Static_assert ((sizeof (long int) >= 8),
  10074. "long int needs to be at least 8 bytes");
  10075. @end example
  10076. @noindent
  10077. reports a compile-time error if compiled on a system with long
  10078. integers smaller than 8 bytes, with @samp{long int needs to be at
  10079. least 8 bytes} as the error message.
  10080. Since calls @code{_Static_assert} are processed at compile time, the
  10081. expression must be computable at compile time and the error message
  10082. must be a literal string. The expression can refer to the sizes of
  10083. variables, but can't refer to their values. For example, the
  10084. following static assertion is invalid for two reasons:
  10085. @example
  10086. char *error_message
  10087. = "long int needs to be at least 8 bytes";
  10088. int size_of_long_int = sizeof (long int);
  10089. _Static_assert (size_of_long_int == 8, error_message);
  10090. @end example
  10091. @noindent
  10092. The expression @code{size_of_long_int == 8} isn't computable at
  10093. compile time, and the error message isn't a literal string.
  10094. You can, though, use preprocessor definition values with
  10095. @code{_Static_assert}:
  10096. @example
  10097. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10098. at least 8 bytes"
  10099. _Static_assert ((sizeof (long int) == 8),
  10100. LONG_INT_ERROR_MESSAGE);
  10101. @end example
  10102. Static assertions are permitted wherever a statement or declaration is
  10103. permitted, including at top level in the file, and also inside the
  10104. definition of a type.
  10105. @example
  10106. union y
  10107. @{
  10108. int i;
  10109. int *ptr;
  10110. _Static_assert (sizeof (int *) == sizeof (int),
  10111. "Pointer and int not same size");
  10112. @};
  10113. @end example
  10114. @node Type Alignment
  10115. @appendix Type Alignment
  10116. @cindex type alignment
  10117. @cindex alignment of type
  10118. @findex _Alignof
  10119. @findex __alignof__
  10120. Code for device drivers and other communication with low-level
  10121. hardware sometimes needs to be concerned with the alignment of
  10122. data objects in memory.
  10123. Each data type has a required @dfn{alignment}, always a power of 2,
  10124. that says at which memory addresses an object of that type can validly
  10125. start. A valid address for the type must be a multiple of its
  10126. alignment. If a type's alignment is 1, that means it can validly
  10127. start at any address. If a type's alignment is 2, that means it can
  10128. only start at an even address. If a type's alignment is 4, that means
  10129. it can only start at an address that is a multiple of 4.
  10130. The alignment of a type (except @code{char}) can vary depending on the
  10131. kind of computer in use. To refer to the alignment of a type in a C
  10132. program, use @code{_Alignof}, whose syntax parallels that of
  10133. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10134. operation, and it doesn't compute the value of the expression used
  10135. as its argument.
  10136. Nominally, each integer and floating-point type has an alignment equal to
  10137. the largest power of 2 that divides its size. Thus, @code{int} with
  10138. size 4 has a nominal alignment of 4, and @code{long long int} with
  10139. size 8 has a nominal alignment of 8.
  10140. However, each kind of computer generally has a maximum alignment, and
  10141. no type needs more alignment than that. If the computer's maximum
  10142. alignment is 4 (which is common), then no type's alignment is more
  10143. than 4.
  10144. The size of any type is always a multiple of its alignment; that way,
  10145. in an array whose elements have that type, all the elements are
  10146. properly aligned if the first one is.
  10147. These rules apply to all real computers today, but some embedded
  10148. controllers have odd exceptions. We don't have references to cite for
  10149. them.
  10150. @c We can't cite a nonfree manual as documentation.
  10151. Ordinary C code guarantees that every object of a given type is in
  10152. fact aligned as that type requires.
  10153. If the operand of @code{_Alignof} is a structure field, the value
  10154. is the alignment it requires. It may have a greater alignment by
  10155. coincidence, due to the other fields, but @code{_Alignof} is not
  10156. concerned about that. @xref{Structures}.
  10157. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10158. but now that the feature has been standardized, it is better
  10159. to use the standard keyword @code{_Alignof}.
  10160. @findex _Alignas
  10161. @findex __aligned__
  10162. You can explicitly specify an alignment requirement for a particular
  10163. variable or structure field by adding @code{_Alignas
  10164. (@var{alignment})} to the declaration, where @var{alignment} is a
  10165. power of 2 or a type name. For instance:
  10166. @example
  10167. char _Alignas (8) x;
  10168. @end example
  10169. @noindent
  10170. or
  10171. @example
  10172. char _Alignas (double) x;
  10173. @end example
  10174. @noindent
  10175. specifies that @code{x} must start on an address that is a multiple of
  10176. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10177. machine, that maximum is how much alignment @code{x} will get.
  10178. The older GNU C syntax for this feature looked like
  10179. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10180. declaration, and was added after the variable. For instance:
  10181. @example
  10182. char x __attribute__ ((__aligned__ 8));
  10183. @end example
  10184. @xref{Attributes}.
  10185. @node Aliasing
  10186. @appendix Aliasing
  10187. @cindex aliasing (of storage)
  10188. @cindex pointer type conversion
  10189. @cindex type conversion, pointer
  10190. We have already presented examples of casting a @code{void *} pointer
  10191. to another pointer type, and casting another pointer type to
  10192. @code{void *}.
  10193. One common kind of pointer cast is guaranteed safe: casting the value
  10194. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10195. Allocation}). It is safe because these functions do not save the
  10196. pointer anywhere else; the only way the program will access the newly
  10197. allocated memory is via the pointer just returned.
  10198. In fact, C allows casting any pointer type to any other pointer type.
  10199. Using this to access the same place in memory using two
  10200. different data types is called @dfn{aliasing}.
  10201. Aliasing is necessary in some programs that do sophisticated memory
  10202. management, such as GNU Emacs, but most C programs don't need to do
  10203. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10204. aliasing correctly requires following the rules stated below.
  10205. Otherwise, the aliasing may result in malfunctions when the program
  10206. runs.
  10207. The rest of this appendix explains the pitfalls and rules of aliasing.
  10208. @menu
  10209. * Aliasing Alignment:: Memory alignment considerations for
  10210. casting between pointer types.
  10211. * Aliasing Length:: Type size considerations for
  10212. casting between pointer types.
  10213. * Aliasing Type Rules:: Even when type alignment and size matches,
  10214. aliasing can still have surprising results.
  10215. @end menu
  10216. @node Aliasing Alignment
  10217. @appendixsection Aliasing and Alignment
  10218. In order for a type-converted pointer to be valid, it must have the
  10219. alignment that the new pointer type requires. For instance, on most
  10220. computers, @code{int} has alignment 4; the address of an @code{int}
  10221. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10222. address of a @code{char} is usually not a multiple of 4. Taking the
  10223. address of such a @code{char} and casting it to @code{int *} probably
  10224. results in an invalid pointer. Trying to dereference it may cause a
  10225. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10226. @example
  10227. foo ()
  10228. @{
  10229. char i[4];
  10230. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10231. return *p; /* @r{Crash!} */
  10232. @}
  10233. @end example
  10234. This requirement is never a problem when casting the return value
  10235. of @code{malloc} because that function always returns a pointer
  10236. with as much alignment as any type can require.
  10237. @node Aliasing Length
  10238. @appendixsection Aliasing and Length
  10239. When converting a pointer to a different pointer type, make sure the
  10240. object it really points to is at least as long as the target of the
  10241. converted pointer. For instance, suppose @code{p} has type @code{int
  10242. *} and it's cast as follows:
  10243. @example
  10244. int *p;
  10245. struct
  10246. @{
  10247. double d, e, f;
  10248. @} foo;
  10249. struct foo *q = (struct foo *)p;
  10250. q->f = 5.14159;
  10251. @end example
  10252. @noindent
  10253. the value @code{q->f} will run past the end of the @code{int} that
  10254. @code{p} points to. If @code{p} was initialized to the start of an
  10255. array of type @code{int[6]}, the object is long enough for three
  10256. @code{double}s. But if @code{p} points to something shorter,
  10257. @code{q->f} will run on beyond the end of that, overlaying some other
  10258. data. Storing that will garble that other data. Or it could extend
  10259. past the end of memory space and cause a @code{SIGSEGV} signal
  10260. (@pxref{Signals}).
  10261. @node Aliasing Type Rules
  10262. @appendixsection Type Rules for Aliasing
  10263. C code that converts a pointer to a different pointer type can use the
  10264. pointers to access the same memory locations with two different data
  10265. types. If the same address is accessed with different types in a
  10266. single control thread, optimization can make the code do surprising
  10267. things (in effect, make it malfunction).
  10268. Here's a concrete example where aliasing that can change the code's
  10269. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10270. long, like @code{int}, and so is every pointer. Thus, the structures
  10271. @code{struct a} and @code{struct b} are both 8 bytes.
  10272. @example
  10273. #include <stdio.h>
  10274. struct a @{ int size; char *data; @};
  10275. struct b @{ float size; char *data; @};
  10276. void sub (struct a *p, struct b *q)
  10277. @{
  10278.   int x;
  10279.   p->size = 0;
  10280.   q->size = 1;
  10281.   x = p->size;
  10282.   printf("x       =%d\n", x);
  10283.   printf("p->size =%d\n", (int)p->size);
  10284.   printf("q->size =%d\n", (int)q->size);
  10285. @}
  10286. int main(void)
  10287. @{
  10288.   struct a foo;
  10289.   struct a *p = &foo;
  10290.   struct b *q = (struct b *) &foo;
  10291.   sub (p, q);
  10292. @}
  10293. @end example
  10294. This code works as intended when compiled without optimization. All
  10295. the operations are carried out sequentially as written. The code
  10296. sets @code{x} to @code{p->size}, but what it actually gets is the
  10297. bits of the floating point number 1, as type @code{int}.
  10298. However, when optimizing, the compiler is allowed to assume
  10299. (mistakenly, here) that @code{q} does not point to the same storage as
  10300. @code{p}, because their data types are not allowed to alias.
  10301. From this assumption, the compiler can deduce (falsely, here) that the
  10302. assignment into @code{q->size} has no effect on the value of
  10303. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10304. be set to 0.
  10305. GNU C, following the C standard, @emph{defines} this optimization as
  10306. legitimate. Code that misbehaves when optimized following these rules
  10307. is, by definition, incorrect C code.
  10308. The rules for storage aliasing in C are based on the two data types:
  10309. the type of the object, and the type it is accessed through. The
  10310. rules permit accessing part of a storage object of type @var{t} using
  10311. only these types:
  10312. @itemize @bullet
  10313. @item
  10314. @var{t}.
  10315. @item
  10316. A type compatible with @var{t}. @xref{Compatible Types}.
  10317. @item
  10318. A signed or unsigned version of one of the above.
  10319. @item
  10320. A qualified version of one of the above.
  10321. @xref{Type Qualifiers}.
  10322. @item
  10323. An array, structure (@pxref{Structures}), or union type
  10324. (@code{Unions}) that contains one of the above, either directly as a
  10325. field or through multiple levels of fields. If @var{t} is
  10326. @code{double}, this would include @code{struct s @{ union @{ double
  10327. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10328. inside it somewhere.
  10329. @item
  10330. A character type.
  10331. @end itemize
  10332. What do these rules say about the example in this subsection?
  10333. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10334. @code{int}. The type @code{float} is not allowed as an aliasing type
  10335. by those rules, so @code{b->size} is not supposed to alias with
  10336. elements of @code{j}. Based on that assumption, GNU C makes a
  10337. permitted optimization that was not, in this case, consistent with
  10338. what the programmer intended the program to do.
  10339. Whether GCC actually performs type-based aliasing analysis depends on
  10340. the details of the code. GCC has other ways to determine (in some cases)
  10341. whether objects alias, and if it gets a reliable answer that way, it won't
  10342. fall back on type-based heuristics.
  10343. @c @opindex -fno-strict-aliasing
  10344. The importance of knowing the type-based aliasing rules is not so as
  10345. to ensure that the optimization is done where it would be safe, but so
  10346. as to ensure it is @emph{not} done in a way that would break the
  10347. program. You can turn off type-based aliasing analysis by giving GCC
  10348. the option @option{-fno-strict-aliasing}.
  10349. @node Digraphs
  10350. @appendix Digraphs
  10351. @cindex digraphs
  10352. C accepts aliases for certain characters. Apparently in the 1990s
  10353. some computer systems had trouble inputting these characters, or
  10354. trouble displaying them. These digraphs almost never appear in C
  10355. programs nowadays, but we mention them for completeness.
  10356. @table @samp
  10357. @item <:
  10358. An alias for @samp{[}.
  10359. @item :>
  10360. An alias for @samp{]}.
  10361. @item <%
  10362. An alias for @samp{@{}.
  10363. @item %>
  10364. An alias for @samp{@}}.
  10365. @item %:
  10366. An alias for @samp{#},
  10367. used for preprocessing directives (@pxref{Directives}) and
  10368. macros (@pxref{Macros}).
  10369. @end table
  10370. @node Attributes
  10371. @appendix Attributes in Declarations
  10372. @cindex attributes
  10373. @findex __attribute__
  10374. You can specify certain additional requirements in a declaration, to
  10375. get fine-grained control over code generation, and helpful
  10376. informational messages during compilation. We use a few attributes in
  10377. code examples throughout this manual, including
  10378. @table @code
  10379. @item aligned
  10380. The @code{aligned} attribute specifies a minimum alignment for a
  10381. variable or structure field, measured in bytes:
  10382. @example
  10383. int foo __attribute__ ((aligned (8))) = 0;
  10384. @end example
  10385. @noindent
  10386. This directs GNU C to allocate @code{foo} at an address that is a
  10387. multiple of 8 bytes. However, you can't force an alignment bigger
  10388. than the computer's maximum meaningful alignment.
  10389. @item packed
  10390. The @code{packed} attribute specifies to compact the fields of a
  10391. structure by not leaving gaps between fields. For example,
  10392. @example
  10393. struct __attribute__ ((packed)) bar
  10394. @{
  10395. char a;
  10396. int b;
  10397. @};
  10398. @end example
  10399. @noindent
  10400. allocates the integer field @code{b} at byte 1 in the structure,
  10401. immediately after the character field @code{a}. The packed structure
  10402. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10403. alignment is 1, that of @code{char}.
  10404. @item deprecated
  10405. Applicable to both variables and functions, the @code{deprecated}
  10406. attribute tells the compiler to issue a warning if the variable or
  10407. function is ever used in the source file.
  10408. @example
  10409. int old_foo __attribute__ ((deprecated));
  10410. int old_quux () __attribute__ ((deprecated));
  10411. @end example
  10412. @item __noinline__
  10413. The @code{__noinline__} attribute, in a function's declaration or
  10414. definition, specifies never to inline calls to that function. All
  10415. calls to that function, in a compilation unit where it has this
  10416. attribute, will be compiled to invoke the separately compiled
  10417. function. @xref{Inline Function Definitions}.
  10418. @item __noclone__
  10419. The @code{__noclone__} attribute, in a function's declaration or
  10420. definition, specifies never to clone that function. Thus, there will
  10421. be only one compiled version of the function. @xref{Label Value
  10422. Caveats}, for more information about cloning.
  10423. @item always_inline
  10424. The @code{always_inline} attribute, in a function's declaration or
  10425. definition, specifies to inline all calls to that function (unless
  10426. something about the function makes inlining impossible). This applies
  10427. to all calls to that function in a compilation unit where it has this
  10428. attribute. @xref{Inline Function Definitions}.
  10429. @item gnu_inline
  10430. The @code{gnu_inline} attribute, in a function's declaration or
  10431. definition, specifies to handle the @code{inline} keyword the way GNU
  10432. C originally implemented it, many years before ISO C said anything
  10433. about inlining. @xref{Inline Function Definitions}.
  10434. @end table
  10435. For full documentation of attributes, see the GCC manual.
  10436. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10437. the GNU Compiler Collection}.
  10438. @node Signals
  10439. @appendix Signals
  10440. @cindex signal
  10441. @cindex handler (for signal)
  10442. @cindex @code{SIGSEGV}
  10443. @cindex @code{SIGFPE}
  10444. @cindex @code{SIGBUS}
  10445. Some program operations bring about an error condition called a
  10446. @dfn{signal}. These signals terminate the program, by default.
  10447. There are various different kinds of signals, each with a name. We
  10448. have seen several such error conditions through this manual:
  10449. @table @code
  10450. @item SIGSEGV
  10451. This signal is generated when a program tries to read or write outside
  10452. the memory that is allocated for it, or to write memory that can only
  10453. be read. The name is an abbreviation for ``segmentation violation''.
  10454. @item SIGFPE
  10455. This signal indicates a fatal arithmetic error. The name is an
  10456. abbreviation for ``floating-point exception'', but covers all types of
  10457. arithmetic errors, including division by zero and overflow.
  10458. @item SIGBUS
  10459. This signal is generated when an invalid pointer is dereferenced,
  10460. typically the result of dereferencing an uninitialized pointer. It is
  10461. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10462. invalid access to valid memory, while @code{SIGBUS} indicates an
  10463. attempt to access an invalid address.
  10464. @end table
  10465. These kinds of signal allow the program to specify a function as a
  10466. @dfn{signal handler}. When a signal has a handler, it doesn't
  10467. terminate the program; instead it calls the handler.
  10468. There are many other kinds of signal; here we list only those that
  10469. come from run-time errors in C operations. The rest have to do with
  10470. the functioning of the operating system. The GNU C Library Reference
  10471. Manual gives more explanation about signals (@pxref{Program Signal
  10472. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10473. Manual}).
  10474. @node GNU Free Documentation License
  10475. @appendix GNU Free Documentation License
  10476. @include fdl.texi
  10477. @node Symbol Index
  10478. @unnumbered Index of Symbols and Keywords
  10479. @printindex fn
  10480. @node Concept Index
  10481. @unnumbered Concept Index
  10482. @printindex cp
  10483. @bye