c.texi 419 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011
  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. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language 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 to 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 focuses on the GNU C language supported by the GNU
  94. Compiler Collection, version ???. When a construct may be absent or
  95. work differently in other C compilers, we say so. When it is not part
  96. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  97. useful to know that; however, other dialects and standards are not the
  98. focus of this manual. We keep those notes short, unless it is vital
  99. to say more. For the same reason, we hardly mention C@t{++} or other
  100. languages that the GNU Compiler Collection supports.
  101. Some aspects of the meaning of C programs depend on the target
  102. platform: which computer, and which operating system, the compiled
  103. code will run on. Where this is the case, we say so.
  104. The C language provides no built-in facilities for performing such
  105. common operations as input/output, memory management, string
  106. manipulation, and the like. Instead, these facilities are defined in
  107. a standard library, which is automatically available in every C
  108. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  109. Reference Manual}.
  110. This manual incorporates the former GNU C Preprocessor Manual, which
  111. was among the earliest GNU Manuals. It also uses some text from the
  112. earlier GNU C Manual that was written by Trevis Rothwell and James
  113. Youngman.
  114. GNU C has many obscure features, each one either for historical
  115. compatibility or meant for very special situations. We have left them
  116. to a companion manual, the GNU C Obscurities Manual, which will be
  117. published digitally later.
  118. Please report errors and suggestions to c-manual@@gnu.org.
  119. @menu
  120. * The First Example:: Getting started with basic C code.
  121. * Complete Program:: A whole example program
  122. that can be compiled and run.
  123. * Storage:: Basic layout of storage; bytes.
  124. * Beyond Integers:: Exploring different numeric types.
  125. * Lexical Syntax:: The various lexical components of C programs.
  126. * Arithmetic:: Numeric computations.
  127. * Assignment Expressions:: Storing values in variables.
  128. * Execution Control Expressions:: Expressions combining values in various ways.
  129. * Binary Operator Grammar:: An overview of operator precedence.
  130. * Order of Execution:: The order of program execution.
  131. * Primitive Types:: More details about primitive data types.
  132. * Constants:: Explicit constant values:
  133. details and examples.
  134. * Type Size:: The memory space occupied by a type.
  135. * Pointers:: Creating and manipulating memory pointers.
  136. * Structures:: Compound data types built
  137. by grouping other types.
  138. * Arrays:: Creating and manipulating arrays.
  139. * Enumeration Types:: Sets of integers with named values.
  140. * Defining Typedef Names:: Using @code{typedef} to define type names.
  141. * Statements:: Controling program flow.
  142. * Variables:: Details about declaring, initializing,
  143. and using variables.
  144. * Type Qualifiers:: Mark variables for certain intended uses.
  145. * Functions:: Declaring, defining, and calling functions.
  146. * Compatible Types:: How to tell if two types are compatible
  147. with each other.
  148. * Type Conversions:: Converting between types.
  149. * Scope:: Different categories of identifier scope.
  150. * Preprocessing:: Using the GNU C preprocessor.
  151. * Integers in Depth:: How integer numbers are represented.
  152. * Floating Point in Depth:: How floating-point numbers are represented.
  153. * Compilation:: How to compile multi-file programs.
  154. * Directing Compilation:: Operations that affect compilation
  155. but don't change the program.
  156. Appendices
  157. * Type Alignment:: Where in memory a type can validly start.
  158. * Aliasing:: Accessing the same data in two types.
  159. * Digraphs:: Two-character aliases for some characters.
  160. * Attributes:: Specifying additional information
  161. in a declaration.
  162. * Signals:: Fatal errors triggered in various scenarios.
  163. * GNU Free Documentation License:: The license for this manual.
  164. * Symbol Index:: Keyword and symbol index.
  165. * Concept Index:: Detailed topical index.
  166. @detailmenu
  167. --- The Detailed Node Listing ---
  168. * Recursive Fibonacci:: Writing a simple function recursively.
  169. * Stack:: Each function call uses space in the stack.
  170. * Iterative Fibonacci:: Writing the same function iteratively.
  171. * Complete Example:: Turn the simple function into a full program.
  172. * Complete Explanation:: Explanation of each part of the example.
  173. * Complete Line-by-Line:: Explaining each line of the example.
  174. * Compile Example:: Using GCC to compile the example.
  175. * Float Example:: A function that uses floating-point numbers.
  176. * Array Example:: A function that works with arrays.
  177. * Array Example Call:: How to call that function.
  178. * Array Example Variations:: Different ways to write the call example.
  179. Lexical Syntax
  180. * English:: Write programs in English!
  181. * Characters:: The characters allowed in C programs.
  182. * Whitespace:: The particulars of whitespace characters.
  183. * Comments:: How to include comments in C code.
  184. * Identifiers:: How to form identifiers (names).
  185. * Operators/Punctuation:: Characters used as operators or punctuation.
  186. * Line Continuation:: Splitting one line into multiple lines.
  187. * Digraphs:: Two-character substitutes for some characters.
  188. Arithmetic
  189. * Basic Arithmetic:: Addition, subtraction, multiplication,
  190. and division.
  191. * Integer Arithmetic:: How C performs arithmetic with integer values.
  192. * Integer Overflow:: When an integer value exceeds the range
  193. of its type.
  194. * Mixed Mode:: Calculating with both integer values
  195. and floating-point values.
  196. * Division and Remainder:: How integer division works.
  197. * Numeric Comparisons:: Comparing numeric values for
  198. equality or order.
  199. * Shift Operations:: Shift integer bits left or right.
  200. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  201. Assignment Expressions
  202. * Simple Assignment:: The basics of storing a value.
  203. * Lvalues:: Expressions into which a value can be stored.
  204. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  205. * Increment/Decrement:: Shorthand for incrementing and decrementing
  206. an lvalue's contents.
  207. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  208. * Assignment in Subexpressions:: How to avoid ambiguity.
  209. * Write Assignments Separately:: Write assignments as separate statements.
  210. Execution Control Expressions
  211. * Logical Operators:: Logical conjunction, disjunction, negation.
  212. * Logicals and Comparison:: Logical operators with comparison operators.
  213. * Logicals and Assignments:: Assignments with logical operators.
  214. * Conditional Expression:: An if/else construct inside expressions.
  215. * Comma Operator:: Build a sequence of subexpressions.
  216. Order of Execution
  217. * Reordering of Operands:: Operations in C are not necessarily computed
  218. in the order they are written.
  219. * Associativity and Ordering:: Some associative operations are performed
  220. in a particular order; others are not.
  221. * Sequence Points:: Some guarantees about the order of operations.
  222. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  223. * Ordering of Operands:: Evaluation order of operands
  224. and function arguments.
  225. * Optimization and Ordering:: Compiler optimizations can reorder operations
  226. only if it has no impact on program results.
  227. Primitive Data Types
  228. * Integer Types:: Description of integer types.
  229. * Floating-Point Data Types:: Description of floating-point types.
  230. * Complex Data Types:: Description of complex number types.
  231. * The Void Type:: A type indicating no value at all.
  232. * Other Data Types:: A brief summary of other types.
  233. Constants
  234. * Integer Constants:: Literal integer values.
  235. * Integer Const Type:: Types of literal integer values.
  236. * Floating Constants:: Literal floating-point values.
  237. * Imaginary Constants:: Literal imaginary number values.
  238. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  239. * Character Constants:: Literal character values.
  240. * Unicode Character Codes:: Unicode characters represented
  241. in either UTF-16 or UTF-32.
  242. * Wide Character Constants:: Literal characters values larger than 8 bits.
  243. * String Constants:: Literal string values.
  244. * UTF-8 String Constants:: Literal UTF-8 string values.
  245. * Wide String Constants:: Literal string values made up of
  246. 16- or 32-bit characters.
  247. Pointers
  248. * Address of Data:: Using the ``address-of'' operator.
  249. * Pointer Types:: For each type, there is a pointer type.
  250. * Pointer Declarations:: Declaring variables with pointer types.
  251. * Pointer Type Designators:: Designators for pointer types.
  252. * Pointer Dereference:: Accessing what a pointer points at.
  253. * Null Pointers:: Pointers which do not point to any object.
  254. * Invalid Dereference:: Dereferencing null or invalid pointers.
  255. * Void Pointers:: Totally generic pointers, can cast to any.
  256. * Pointer Comparison:: Comparing memory address values.
  257. * Pointer Arithmetic:: Computing memory address values.
  258. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  259. * Pointer Arithmetic Low Level:: More about computing memory address values.
  260. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  261. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  262. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  263. * Printing Pointers:: Using @code{printf} for a pointer's value.
  264. Structures
  265. * Referencing Fields:: Accessing field values in a structure object.
  266. * Dynamic Memory Allocation:: Allocating space for objects
  267. while the program is running.
  268. * Field Offset:: Memory layout of fields within a structure.
  269. * Structure Layout:: Planning the memory layout of fields.
  270. * Packed Structures:: Packing structure fields as close as possible.
  271. * Bit Fields:: Dividing integer fields
  272. into fields with fewer bits.
  273. * Bit Field Packing:: How bit fields pack together in integers.
  274. * const Fields:: Making structure fields immutable.
  275. * Zero Length:: Zero-length array as a variable-length object.
  276. * Flexible Array Fields:: Another approach to variable-length objects.
  277. * Overlaying Structures:: Casting one structure type
  278. over an object of another structure type.
  279. * Structure Assignment:: Assigning values to structure objects.
  280. * Unions:: Viewing the same object in different types.
  281. * Packing With Unions:: Using a union type to pack various types into
  282. the same memory space.
  283. * Cast to Union:: Casting a value one of the union's alternative
  284. types to the type of the union itself.
  285. * Structure Constructors:: Building new structure objects.
  286. * Unnamed Types as Fields:: Fields' types do not always need names.
  287. * Incomplete Types:: Types which have not been fully defined.
  288. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  289. * Type Tags:: Scope of structure and union type tags.
  290. Arrays
  291. * Accessing Array Elements:: How to access individual elements of an array.
  292. * Declaring an Array:: How to name and reserve space for a new array.
  293. * Strings:: A string in C is a special case of array.
  294. * Incomplete Array Types:: Naming, but not allocating, a new array.
  295. * Limitations of C Arrays:: Arrays are not first-class objects.
  296. * Multidimensional Arrays:: Arrays of arrays.
  297. * Constructing Array Values:: Assigning values to an entire array at once.
  298. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  299. Statements
  300. * Expression Statement:: Evaluate an expression, as a statement,
  301. usually done for a side effect.
  302. * if Statement:: Basic conditional execution.
  303. * if-else Statement:: Multiple branches for conditional execution.
  304. * Blocks:: Grouping multiple statements together.
  305. * return Statement:: Return a value from a function.
  306. * Loop Statements:: Repeatedly executing a statement or block.
  307. * switch Statement:: Multi-way conditional choices.
  308. * switch Example:: A plausible example of using @code{switch}.
  309. * Duffs Device:: A special way to use @code{switch}.
  310. * Case Ranges:: Ranges of values for @code{switch} cases.
  311. * Null Statement:: A statement that does nothing.
  312. * goto Statement:: Jump to another point in the source code,
  313. identified by a label.
  314. * Local Labels:: Labels with limited scope.
  315. * Labels as Values:: Getting the address of a label.
  316. * Statement Exprs:: A series of statements used as an expression.
  317. Variables
  318. * Variable Declarations:: Name a variable and and reserve space for it.
  319. * Initializers:: Assigning inital values to variables.
  320. * Designated Inits:: Assigning initial values to array elements
  321. at particular array indices.
  322. * Auto Type:: Obtaining the type of a variable.
  323. * Local Variables:: Variables declared in function definitions.
  324. * File-Scope Variables:: Variables declared outside of
  325. function definitions.
  326. * Static Local Variables:: Variables declared within functions,
  327. but with permanent storage allocation.
  328. * Extern Declarations:: Declaring a variable
  329. which is allocated somewhere else.
  330. * Allocating File-Scope:: When is space allocated
  331. for file-scope variables?
  332. * auto and register:: Historically used storage directions.
  333. * Omitting Types:: The bad practice of declaring variables
  334. with implicit type.
  335. Type Qualifiers
  336. * const:: Variables whose values don't change.
  337. * volatile:: Variables whose values may be accessed
  338. or changed outside of the control of
  339. this program.
  340. * restrict Pointers:: Restricted pointers for code optimization.
  341. * restrict Pointer Example:: Example of how that works.
  342. Functions
  343. * Function Definitions:: Writing the body of a function.
  344. * Function Declarations:: Declaring the interface of a function.
  345. * Function Calls:: Using functions.
  346. * Function Call Semantics:: Call-by-value argument passing.
  347. * Function Pointers:: Using references to functions.
  348. * The main Function:: Where execution of a GNU C program begins.
  349. Type Conversions
  350. * Explicit Type Conversion:: Casting a value from one type to another.
  351. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  352. * Argument Promotions:: Automatic conversion of function parameters.
  353. * Operand Promotions:: Automatic conversion of arithmetic operands.
  354. * Common Type:: When operand types differ, which one is used?
  355. Scope
  356. * Scope:: Different categories of identifier scope.
  357. Preprocessing
  358. * Preproc Overview:: Introduction to the C preprocessor.
  359. * Directives:: The form of preprocessor directives.
  360. * Preprocessing Tokens:: The lexical elements of preprocessing.
  361. * Header Files:: Including one source file in another.
  362. * Macros:: Macro expansion by the preprocessor.
  363. * Conditionals:: Controling whether to compile some lines
  364. or ignore them.
  365. * Diagnostics:: Reporting warnings and errors.
  366. * Line Control:: Reporting source line numbers.
  367. * Null Directive:: A preprocessing no-op.
  368. Integers in Depth
  369. * Integer Representations:: How integer values appear in memory.
  370. * Maximum and Minimum Values:: Value ranges of integer types.
  371. Floating Point in Depth
  372. * Floating Representations:: How floating-point values appear in memory.
  373. * Floating Type Specs:: Precise details of memory representations.
  374. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  375. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  376. * Exception Flags:: Handling certain conditions in floating point.
  377. * Exact Floating-Point:: Not all floating calculations lose precision.
  378. * Rounding:: When a floating result can't be represented
  379. exactly in the floating-point type in use.
  380. * Rounding Issues:: Avoid magnifying rounding errors.
  381. * Significance Loss:: Subtracting numbers that are almost equal.
  382. * Fused Multiply-Add:: Taking advantage of a special floating-point
  383. instruction for faster execution.
  384. * Error Recovery:: Determining rounding errors.
  385. * Exact Floating Constants:: Precisely specified floating-point numbers.
  386. * Handling Infinity:: When floating calculation is out of range.
  387. * Handling NaN:: What floating calculation is undefined.
  388. * Signed Zeros:: Positive zero vs. negative zero.
  389. * Scaling by the Base:: A useful exact floating-point operation.
  390. * Rounding Control:: Specifying some rounding behaviors.
  391. * Machine Epsilon:: The smallest number you can add to 1.0
  392. and get a sum which is larger than 1.0.
  393. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  394. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  395. * Further Reading:: References for floating-point numbers.
  396. Directing Compilation
  397. * Pragmas:: Controling compilation of some constructs.
  398. * Static Assertions:: Compile-time tests for conditions.
  399. @end detailmenu
  400. @end menu
  401. @node The First Example
  402. @chapter The First Example
  403. This chapter presents the source code for a very simple C program and
  404. uses it to explain a few features of the language. If you already
  405. know the basic points of C presented in this chapter, you can skim it
  406. or skip it.
  407. @menu
  408. * Recursive Fibonacci:: Writing a simple function recursively.
  409. * Stack:: Each function call uses space in the stack.
  410. * Iterative Fibonacci:: Writing the same function iteratively.
  411. @end menu
  412. @node Recursive Fibonacci
  413. @section Example: Recursive Fibonacci
  414. @cindex recursive Fibonacci function
  415. @cindex Fibonacci function, recursive
  416. To introduce the most basic features of C, let's look at code for a
  417. simple mathematical function that does calculations on integers. This
  418. function calculates the @var{n}th number in the Fibonacci series, in
  419. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  420. 13, 21, 34, 55, @dots{}.
  421. @example
  422. int
  423. fib (int n)
  424. @{
  425. if (n <= 2) /* @r{This avoids infinite recursion.} */
  426. return 1;
  427. else
  428. return fib (n - 1) + fib (n - 2);
  429. @}
  430. @end example
  431. This very simple program illustrates several features of C:
  432. @itemize @bullet
  433. @item
  434. A function definition, whose first two lines constitute the function
  435. header. @xref{Function Definitions}.
  436. @item
  437. A function parameter @code{n}, referred to as the variable @code{n}
  438. inside the function body. @xref{Function Parameter Variables}.
  439. A function definition uses parameters to refer to the argument
  440. values provided in a call to that function.
  441. @item
  442. Arithmetic. C programs add with @samp{+} and subtract with
  443. @samp{-}. @xref{Arithmetic}.
  444. @item
  445. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  446. equal.'' @xref{Numeric Comparisons}.
  447. @item
  448. Integer constants written in base 10.
  449. @xref{Integer Constants}.
  450. @item
  451. A function call. The function call @code{fib (n - 1)} calls the
  452. function @code{fib}, passing as its argument the value @code{n - 1}.
  453. @xref{Function Calls}.
  454. @item
  455. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  456. comment has no effect on the execution of the program. Its purpose is
  457. to provide explanations to people reading the source code. Including
  458. comments in the code is tremendously important---they provide
  459. background information so others can understand the code more quickly.
  460. @xref{Comments}.
  461. @item
  462. Two kinds of statements, the @code{return} statement and the
  463. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  464. @item
  465. Recursion. The function @code{fib} calls itself; that is called a
  466. @dfn{recursive call}. These are valid in C, and quite common.
  467. The @code{fib} function would not be useful if it didn't return.
  468. Thus, recursive definitions, to be of any use, must avoid infinite
  469. recursion.
  470. This function definition prevents infinite recursion by specially
  471. handling the case where @code{n} is two or less. Thus the maximum
  472. depth of recursive calls is less than @code{n}.
  473. @end itemize
  474. @menu
  475. * Function Header:: The function's name and how it is called.
  476. * Function Body:: Declarations and statements that implement the function.
  477. @end menu
  478. @node Function Header
  479. @subsection Function Header
  480. @cindex function header
  481. In our example, the first two lines of the function definition are the
  482. @dfn{header}. Its purpose is to state the function's name and say how
  483. it is called:
  484. @example
  485. int
  486. fib (int n)
  487. @end example
  488. @noindent
  489. says that the function returns an integer (type @code{int}), its name is
  490. @code{fib}, and it takes one argument named @code{n} which is also an
  491. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  492. @node Function Body
  493. @subsection Function Body
  494. @cindex function body
  495. @cindex recursion
  496. The rest of the function definition is called the @dfn{function body}.
  497. Like every function body, this one starts with @samp{@{}, ends with
  498. @samp{@}}, and contains zero or more @dfn{statements} and
  499. @dfn{declarations}. Statements specify actions to take, whereas
  500. declarations define names of variables, functions, and so on. Each
  501. statement and each declaration ends with a semicolon (@samp{;}).
  502. Statements and declarations often contain @dfn{expressions}; an
  503. expression is a construct whose execution produces a @dfn{value} of
  504. some data type, but may also take actions through ``side effects''
  505. that alter subsequent execution. A statement, by contrast, does not
  506. have a value; it affects further execution of the program only through
  507. the actions it takes.
  508. This function body contains no declarations, and just one statement,
  509. but that one is a complex statement in that it contains nested
  510. statements. This function uses two kinds of statements:
  511. @table @code
  512. @item return
  513. The @code{return} statement makes the function return immediately.
  514. It looks like this:
  515. @example
  516. return @var{value};
  517. @end example
  518. Its meaning is to compute the expression @var{value} and exit the
  519. function, making it return whatever value that expression produced.
  520. For instance,
  521. @example
  522. return 1;
  523. @end example
  524. @noindent
  525. returns the integer 1 from the function, and
  526. @example
  527. return fib (n - 1) + fib (n - 2);
  528. @end example
  529. @noindent
  530. returns a value computed by performing two function calls
  531. as specified and adding their results.
  532. @item @code{if}@dots{}@code{else}
  533. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  534. Each time it executes, it chooses one of its two substatements to execute
  535. and ignores the other. It looks like this:
  536. @example
  537. if (@var{condition})
  538. @var{if-true-statement}
  539. else
  540. @var{if-false-statement}
  541. @end example
  542. Its meaning is to compute the expression @var{condition} and, if it's
  543. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  544. @var{if-false-statement}. @xref{if-else Statement}.
  545. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  546. simply an expression. It's considered ``true'' if its value is
  547. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  548. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  549. Comparisons}.) Thus,
  550. @example
  551. if (n <= 2)
  552. return 1;
  553. else
  554. return fib (n - 1) + fib (n - 2);
  555. @end example
  556. @noindent
  557. first tests whether the value of @code{n} is less than or equal to 2.
  558. If so, the expression @code{n <= 2} has the value 1. So execution
  559. continues with the statement
  560. @example
  561. return 1;
  562. @end example
  563. @noindent
  564. Otherwise, execution continues with this statement:
  565. @example
  566. return fib (n - 1) + fib (n - 2);
  567. @end example
  568. Each of these statements ends the execution of the function and
  569. provides a value for it to return. @xref{return Statement}.
  570. @end table
  571. Calculating @code{fib} using ordinary integers in C works only for
  572. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  573. in type @code{int}. The addition operation that tries to add
  574. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  575. This occurrence is called @dfn{integer overflow}.
  576. Overflow can manifest itself in various ways, but one thing that can't
  577. possibly happen is to produce the correct value, since that can't fit
  578. in the space for the value. @xref{Integer Overflow}.
  579. @xref{Functions}, for a full explanation about functions.
  580. @node Stack
  581. @section The Stack, And Stack Overflow
  582. @cindex stack
  583. @cindex stack frame
  584. @cindex stack overflow
  585. @cindex recursion, drawbacks of
  586. @cindex stack frame
  587. Recursion has a drawback: there are limits to how many nested function
  588. calls a program can make. In C, each function call allocates a block
  589. of memory which it uses until the call returns. C allocates these
  590. blocks consecutively within a large area of memory known as the
  591. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  592. The size of the stack is limited; if the program tries to use too
  593. much, that causes the program to fail because the stack is full. This
  594. is called @dfn{stack overflow}.
  595. @cindex crash
  596. @cindex segmentation fault
  597. Stack overflow on GNU/Linux typically manifests itself as the
  598. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  599. fault.'' By default, this signal terminates the program immediately,
  600. rather than letting the program try to recover, or reach an expected
  601. ending point. (We commonly say in this case that the program
  602. ``crashes''). @xref{Signals}.
  603. It is inconvenient to observe a crash by passing too large
  604. an argument to recursive Fibonacci, because the program would run a
  605. long time before it crashes. This algorithm is simple but
  606. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  607. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  608. the final result.
  609. However, you can observe stack overflow very quickly if you use
  610. this function instead:
  611. @example
  612. int
  613. fill_stack (int n)
  614. @{
  615. if (n <= 1) /* @r{This limits the depth of recursion.} */
  616. return 1;
  617. else
  618. return fill_stack (n - 1);
  619. @}
  620. @end example
  621. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  622. and using the default configuration, an experiment showed there is
  623. enough stack space to do 261906 nested calls to that function. One
  624. more, and the stack overflows and the program crashes. On another
  625. platform, with a different configuration, or with a different
  626. function, the limit might be bigger or smaller.
  627. @node Iterative Fibonacci
  628. @section Example: Iterative Fibonacci
  629. @cindex iterative Fibonacci function
  630. @cindex Fibonacci function, iterative
  631. Here's a much faster algorithm for computing the same Fibonacci
  632. series. It is faster for two reasons. First, it uses @dfn{iteration}
  633. (that is, repetition or looping) rather than recursion, so it doesn't
  634. take time for a large number of function calls. But mainly, it is
  635. faster because the number of repetitions is small---only @code{@var{n}}.
  636. @c If you change this, change the duplicate in node Example of for.
  637. @example
  638. int
  639. fib (int n)
  640. @{
  641. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  642. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  643. int i;
  644. for (i = 1; i < n; ++i)
  645. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  646. /* @r{since @code{i < n} is false the first time.} */
  647. @{
  648. /* @r{Now @code{last} is @code{fib (@code{i})}}
  649. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  650. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  651. int next = prev + last;
  652. /* @r{Shift the values down.} */
  653. prev = last;
  654. last = next;
  655. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  656. @r{and @code{prev} is @code{fib (@code{i})}.}
  657. @r{But that won't stay true for long,}
  658. @r{because we are about to increment @code{i}.} */
  659. @}
  660. return last;
  661. @}
  662. @end example
  663. This definition computes @code{fib (@var{n})} in a time proportional
  664. to @code{@var{n}}. The comments in the definition explain how it works: it
  665. advances through the series, always keeps the last two values in
  666. @code{last} and @code{prev}, and adds them to get the next value.
  667. Here are the additional C features that this definition uses:
  668. @table @asis
  669. @item Internal blocks
  670. Within a function, wherever a statement is called for, you can write a
  671. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  672. more statements and declarations. (You can also use additional
  673. blocks as statements in a block.)
  674. The function body also counts as a block, which is why it can contain
  675. statements and declarations.
  676. @xref{Blocks}.
  677. @item Declarations of local variables
  678. This function body contains declarations as well as statements. There
  679. are three declarations directly in the function body, as well as a
  680. fourth declaration in an internal block. Each starts with @code{int}
  681. because it declares a variable whose type is integer. One declaration
  682. can declare several variables, but each of these declarations is
  683. simple and declares just one variable.
  684. Variables declared inside a block (either a function body or an
  685. internal block) are @dfn{local variables}. These variables exist only
  686. within that block; their names are not defined outside the block, and
  687. exiting the block deallocates their storage. This example declares
  688. four local variables: @code{last}, @code{prev}, @code{i}, and
  689. @code{next}.
  690. The most basic local variable declaration looks like this:
  691. @example
  692. @var{type} @var{variablename};
  693. @end example
  694. For instance,
  695. @example
  696. int i;
  697. @end example
  698. @noindent
  699. declares the local variable @code{i} as an integer.
  700. @xref{Variable Declarations}.
  701. @item Initializers
  702. When you declare a variable, you can also specify its initial value,
  703. like this:
  704. @example
  705. @var{type} @var{variablename} = @var{value};
  706. @end example
  707. For instance,
  708. @example
  709. int last = 1;
  710. @end example
  711. @noindent
  712. declares the local variable @code{last} as an integer (type
  713. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  714. @item Assignment
  715. Assignment: a specific kind of expression, written with the @samp{=}
  716. operator, that stores a new value in a variable or other place. Thus,
  717. @example
  718. @var{variable} = @var{value}
  719. @end example
  720. @noindent
  721. is an expression that computes @code{@var{value}} and stores the value in
  722. @code{@var{variable}}. @xref{Assignment Expressions}.
  723. @item Expression statements
  724. An expression statement is an expression followed by a semicolon.
  725. That computes the value of the expression, then ignores the value.
  726. An expression statement is useful when the expression changes some
  727. data or has other side effects---for instance, with function calls, or
  728. with assignments as in this example. @xref{Expression Statement}.
  729. Using an expression with no side effects in an expression statement is
  730. pointless except in very special cases. For instance, the expression
  731. statement @code{x;} would examine the value of @code{x} and ignore it.
  732. That is not useful.
  733. @item Increment operator
  734. The increment operator is @samp{++}. @code{++i} is an
  735. expression that is short for @code{i = i + 1}.
  736. @xref{Increment/Decrement}.
  737. @item @code{for} statements
  738. A @code{for} statement is a clean way of executing a statement
  739. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  740. @example
  741. for (i = 1; i < n; ++i)
  742. @var{body}
  743. @end example
  744. @noindent
  745. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  746. for the loop. The loop itself consists of
  747. @itemize @bullet
  748. @item
  749. Testing @code{i < n} and exiting the loop if that's false.
  750. @item
  751. Executing @var{body}.
  752. @item
  753. Advancing the loop (executing @code{++i}, which increments @code{i}).
  754. @end itemize
  755. The net result is to execute @var{body} with 0 in @code{i},
  756. then with 1 in @code{i}, and so on, stopping just before the repetition
  757. where @code{i} would equal @code{n}.
  758. The body of the @code{for} statement must be one and only one
  759. statement. You can't write two statements in a row there; if you try
  760. to, only the first of them will be treated as part of the loop.
  761. The way to put multiple statements in those places is to group them
  762. with a block, and that's what we do in this example.
  763. @end table
  764. @node Complete Program
  765. @chapter A Complete Program
  766. @cindex complete example program
  767. @cindex example program, complete
  768. It's all very well to write a Fibonacci function, but you cannot run
  769. it by itself. It is a useful program, but it is not a complete
  770. program.
  771. In this chapter we present a complete program that contains the
  772. @code{fib} function. This example shows how to make the program
  773. start, how to make it finish, how to do computation, and how to print
  774. a result.
  775. @menu
  776. * Complete Example:: Turn the simple function into a full program.
  777. * Complete Explanation:: Explanation of each part of the example.
  778. * Complete Line-by-Line:: Explaining each line of the example.
  779. * Compile Example:: Using GCC to compile the example.
  780. @end menu
  781. @node Complete Example
  782. @section Complete Program Example
  783. Here is the complete program that uses the simple, recursive version
  784. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  785. @example
  786. #include <stdio.h>
  787. int
  788. fib (int n)
  789. @{
  790. if (n <= 2) /* @r{This avoids infinite recursion.} */
  791. return 1;
  792. else
  793. return fib (n - 1) + fib (n - 2);
  794. @}
  795. int
  796. main (void)
  797. @{
  798. printf ("Fibonacci series item %d is %d\n",
  799. 20, fib (20));
  800. return 0;
  801. @}
  802. @end example
  803. @noindent
  804. This program prints a message that shows the value of @code{fib (20)}.
  805. Now for an explanation of what that code means.
  806. @node Complete Explanation
  807. @section Complete Program Explanation
  808. @ifnottex
  809. Here's the explanation of the code of the example in the
  810. previous section.
  811. @end ifnottex
  812. This sample program prints a message that shows the value of @code{fib
  813. (20)}, and exits with code 0 (which stands for successful execution).
  814. Every C program is started by running the function named @code{main}.
  815. Therefore, the example program defines a function named @code{main} to
  816. provide a way to start it. Whatever that function does is what the
  817. program does. @xref{The main Function}.
  818. The @code{main} function is the first one called when the program
  819. runs, but it doesn't come first in the example code. The order of the
  820. function definitions in the source code makes no difference to the
  821. program's meaning.
  822. The initial call to @code{main} always passes certain arguments, but
  823. @code{main} does not have to pay attention to them. To ignore those
  824. arguments, define @code{main} with @code{void} as the parameter list.
  825. (@code{void} as a function's parameter list normally means ``call with
  826. no arguments,'' but @code{main} is a special case.)
  827. The function @code{main} returns 0 because that is
  828. the conventional way for @code{main} to indicate successful execution.
  829. It could instead return a positive integer to indicate failure, and
  830. some utility programs have specific conventions for the meaning of
  831. certain numeric @dfn{failure codes}. @xref{Values from main}.
  832. @cindex @code{printf}
  833. The simplest way to print text in C is by calling the @code{printf}
  834. function, so here we explain what that does.
  835. @cindex standard output
  836. The first argument to @code{printf} is a @dfn{string constant}
  837. (@pxref{String Constants}) that is a template for output. The
  838. function @code{printf} copies most of that string directly as output,
  839. including the newline character at the end of the string, which is
  840. written as @samp{\n}. The output goes to the program's @dfn{standard
  841. output} destination, which in the usual case is the terminal.
  842. @samp{%} in the template introduces a code that substitutes other text
  843. into the output. Specifically, @samp{%d} means to take the next
  844. argument to @code{printf} and substitute it into the text as a decimal
  845. number. (The argument for @samp{%d} must be of type @code{int}; if it
  846. isn't, @code{printf} will malfunction.) So the output is a line that
  847. looks like this:
  848. @example
  849. Fibonacci series item 20 is 6765
  850. @end example
  851. This program does not contain a definition for @code{printf} because
  852. it is defined by the C library, which makes it available in all C
  853. programs. However, each program does need to @dfn{declare}
  854. @code{printf} so it will be called correctly. The @code{#include}
  855. line takes care of that; it includes a @dfn{header file} called
  856. @file{stdio.h} into the program's code. That file is provided by the
  857. operating system and it contains declarations for the many standard
  858. input/output functions in the C library, one of which is
  859. @code{printf}.
  860. Don't worry about header files for now; we'll explain them later in
  861. @ref{Header Files}.
  862. The first argument of @code{printf} does not have to be a string
  863. constant; it can be any string (@pxref{Strings}). However, using a
  864. constant is the most common case.
  865. To learn more about @code{printf} and other facilities of the C
  866. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  867. Reference Manual}.
  868. @node Complete Line-by-Line
  869. @section Complete Program, Line by Line
  870. Here's the same example, explained line by line.
  871. @strong{Beginners, do you find this helpful or not?
  872. Would you prefer a different layout for the example?
  873. Please tell rms@@gnu.org.}
  874. @example
  875. #include <stdio.h> /* @r{Include declaration of usual} */
  876. /* @r{I/O functions such as @code{printf}.} */
  877. /* @r{Most programs need these.} */
  878. int /* @r{This function returns an @code{int}.} */
  879. fib (int n) /* @r{Its name is @code{fib};} */
  880. /* @r{its argument is called @code{n}.} */
  881. @{ /* @r{Start of function body.} */
  882. /* @r{This stops the recursion from being infinite.} */
  883. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  884. return 1; /* @r{make @code{fib} return 1.} */
  885. else /* @r{otherwise, add the two previous} */
  886. /* @r{fibonacci numbers.} */
  887. return fib (n - 1) + fib (n - 2);
  888. @}
  889. int /* @r{This function returns an @code{int}.} */
  890. main (void) /* @r{Start here; ignore arguments.} */
  891. @{ /* @r{Print message with numbers in it.} */
  892. printf ("Fibonacci series item %d is %d\n",
  893. 20, fib (20));
  894. return 0; /* @r{Terminate program, report success.} */
  895. @}
  896. @end example
  897. @node Compile Example
  898. @section Compiling the Example Program
  899. @cindex compiling
  900. @cindex executable file
  901. To run a C program requires converting the source code into an
  902. @dfn{executable file}. This is called @dfn{compiling} the program,
  903. and the command to do that using GNU C is @command{gcc}.
  904. This example program consists of a single source file. If we
  905. call that file @file{fib1.c}, the complete command to compile it is
  906. this:
  907. @example
  908. gcc -g -O -o fib1 fib1.c
  909. @end example
  910. @noindent
  911. Here, @option{-g} says to generate debugging information, @option{-O}
  912. says to optimize at the basic level, and @option{-o fib1} says to put
  913. the executable program in the file @file{fib1}.
  914. To run the program, use its file name as a shell command.
  915. For instance,
  916. @example
  917. ./fib1
  918. @end example
  919. @noindent
  920. However, unless you are sure the program is correct, you should
  921. expect to need to debug it. So use this command,
  922. @example
  923. gdb fib1
  924. @end example
  925. @noindent
  926. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  927. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  928. debug the executable program @code{fib1}.
  929. @xref{Compilation}, for an introduction to compiling more complex
  930. programs which consist of more than one source file.
  931. @node Storage
  932. @chapter Storage and Data
  933. @cindex bytes
  934. @cindex storage organization
  935. @cindex memory organization
  936. Storage in C programs is made up of units called @dfn{bytes}. On
  937. nearly all computers, a byte consists of 8 bits, but there are a few
  938. peculiar computers (mostly ``embedded controllers'' for very small
  939. systems) where a byte is longer than that. This manual does not try
  940. to explain the peculiarity of those computers; we assume that a byte
  941. is 8 bits.
  942. Every C data type is made up of a certain number of bytes; that number
  943. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  944. types @code{signed char} and @code{unsigned char} are one byte long;
  945. use those types to operate on data byte by byte. @xref{Signed and
  946. Unsigned Types}. You can refer to a series of consecutive bytes as an
  947. array of @code{char} elements; that's what an ASCII string looks like
  948. in memory. @xref{String Constants}.
  949. @node Beyond Integers
  950. @chapter Beyond Integers
  951. So far we've presented programs that operate on integers. In this
  952. chapter we'll present examples of handling non-integral numbers and
  953. arrays of numbers.
  954. @menu
  955. * Float Example:: A function that uses floating-point numbers.
  956. * Array Example:: A function that works with arrays.
  957. * Array Example Call:: How to call that function.
  958. * Array Example Variations:: Different ways to write the call example.
  959. @end menu
  960. @node Float Example
  961. @section An Example with Non-Integer Numbers
  962. @cindex floating point example
  963. Here's a function that operates on and returns @dfn{floating point}
  964. numbers that don't have to be integers. Floating point represents a
  965. number as a fraction together with a power of 2. (For more detail,
  966. @pxref{Floating-Point Data Types}.) This example calculates the
  967. average of three floating point numbers that are passed to it as
  968. arguments:
  969. @example
  970. double
  971. average_of_three (double a, double b, double c)
  972. @{
  973. return (a + b + c) / 3;
  974. @}
  975. @end example
  976. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  977. integers, and even when they happen to be integers, most likely their
  978. average is not an integer.
  979. @code{double} is the usual data type in C for calculations on
  980. floating-point numbers.
  981. To print a @code{double} with @code{printf}, we must use @samp{%f}
  982. instead of @samp{%d}:
  983. @example
  984. printf ("Average is %f\n",
  985. average_of_three (1.1, 9.8, 3.62));
  986. @end example
  987. The code that calls @code{printf} must pass a @code{double} for
  988. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  989. If the argument has the wrong type, @code{printf} will produce garbage
  990. output.
  991. Here's a complete program that computes the average of three
  992. specific numbers and prints the result:
  993. @example
  994. double
  995. average_of_three (double a, double b, double c)
  996. @{
  997. return (a + b + c) / 3;
  998. @}
  999. int
  1000. main (void)
  1001. @{
  1002. printf ("Average is %f\n",
  1003. average_of_three (1.1, 9.8, 3.62));
  1004. return 0;
  1005. @}
  1006. @end example
  1007. From now on we will not present examples of calls to @code{main}.
  1008. Instead we encourage you to write them for yourself when you want
  1009. to test executing some code.
  1010. @node Array Example
  1011. @section An Example with Arrays
  1012. @cindex array example
  1013. A function to take the average of three numbers is very specific and
  1014. limited. A more general function would take the average of any number
  1015. of numbers. That requires passing the numbers in an array. An array
  1016. is an object in memory that contains a series of values of the same
  1017. data type. This chapter presents the basic concepts and use of arrays
  1018. through an example; for the full explanation, see @ref{Arrays}.
  1019. Here's a function definition to take the average of several
  1020. floating-point numbers, passed as type @code{double}. The first
  1021. parameter, @code{length}, specifies how many numbers are passed. The
  1022. second parameter, @code{input_data}, is an array that holds those
  1023. numbers.
  1024. @example
  1025. double
  1026. avg_of_double (int length, double input_data[])
  1027. @{
  1028. double sum = 0;
  1029. int i;
  1030. for (i = 0; i < length; i++)
  1031. sum = sum + input_data[i];
  1032. return sum / length;
  1033. @}
  1034. @end example
  1035. This introduces the expression to refer to an element of an array:
  1036. @code{input_data[i]} means the element at index @code{i} in
  1037. @code{input_data}. The index of the element can be any expression
  1038. with an integer value; in this case, the expression is @code{i}.
  1039. @xref{Accessing Array Elements}.
  1040. @cindex zero-origin indexing
  1041. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1042. valid index is one less than the number of elements. (This is known
  1043. as @dfn{zero-origin indexing}.)
  1044. This example also introduces the way to declare that a function
  1045. parameter is an array. Such declarations are modeled after the syntax
  1046. for an element of the array. Just as @code{double foo} declares that
  1047. @code{foo} is of type @code{double}, @code{double input_data[]}
  1048. declares that each element of @code{input_data} is of type
  1049. @code{double}. Therefore, @code{input_data} itself has type ``array
  1050. of @code{double}.''
  1051. When declaring an array parameter, it's not necessary to say how long
  1052. the array is. In this case, the parameter @code{input_data} has no
  1053. length information. That's why the function needs another parameter,
  1054. @code{length}, for the caller to provide that information to the
  1055. function @code{avg_of_double}.
  1056. @node Array Example Call
  1057. @section Calling the Array Example
  1058. To call the function @code{avg_of_double} requires making an
  1059. array and then passing it as an argument. Here is an example.
  1060. @example
  1061. @{
  1062. /* @r{The array of values to average.} */
  1063. double nums_to_average[5];
  1064. /* @r{The average, once we compute it.} */
  1065. double average;
  1066. /* @r{Fill in elements of @code{nums_to_average}.} */
  1067. nums_to_average[0] = 58.7;
  1068. nums_to_average[1] = 5.1;
  1069. nums_to_average[2] = 7.7;
  1070. nums_to_average[3] = 105.2;
  1071. nums_to_average[4] = -3.14159;
  1072. average = avg_of_double (5, nums_to_average);
  1073. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1074. @}
  1075. @end example
  1076. This shows an array subscripting expression again, this time
  1077. on the left side of an assignment, storing a value into an
  1078. element of an array.
  1079. It also shows how to declare a local variable that is an array:
  1080. @code{double nums_to_average[5];}. Since this declaration allocates the
  1081. space for the array, it needs to know the array's length. You can
  1082. specify the length with any expression whose value is an integer, but
  1083. in this declaration the length is a constant, the integer 5.
  1084. The name of the array, when used by itself as an expression, stands
  1085. for the address of the array's data, and that's what gets passed to
  1086. the function @code{avg_of_double} in @code{avg_of_double (5,
  1087. nums_to_average)}.
  1088. We can make the code easier to maintain by avoiding the need to write
  1089. 5, the array length, when calling @code{avg_of_double}. That way, if
  1090. we change the array to include more elements, we won't have to change
  1091. that call. One way to do this is with the @code{sizeof} operator:
  1092. @example
  1093. average = avg_of_double ((sizeof (nums_to_average)
  1094. / sizeof (nums_to_average[0])),
  1095. nums_to_average);
  1096. @end example
  1097. This computes the number of elements in @code{nums_to_average} by dividing
  1098. its total size by the size of one element. @xref{Type Size}, for more
  1099. details of using @code{sizeof}.
  1100. We don't show in this example what happens after storing the result of
  1101. @code{avg_of_double} in the variable @code{average}. Presumably
  1102. more code would follow that uses that result somehow. (Why compute
  1103. the average and not use it?) But that isn't part of this topic.
  1104. @node Array Example Variations
  1105. @section Variations for Array Example
  1106. The code to call @code{avg_of_double} has two declarations that
  1107. start with the same data type:
  1108. @example
  1109. /* @r{The array of values to average.} */
  1110. double nums_to_average[5];
  1111. /* @r{The average, once we compute it.} */
  1112. double average;
  1113. @end example
  1114. In C, you can combine the two, like this:
  1115. @example
  1116. double nums_to_average[5], average;
  1117. @end example
  1118. This declares @code{nums_to_average} so each of its elements is a
  1119. @code{double}, and @code{average} so that it simply is a
  1120. @code{double}.
  1121. However, while you @emph{can} combine them, that doesn't mean you
  1122. @emph{should}. If it is useful to write comments about the variables,
  1123. and usually it is, then it's clearer to keep the declarations separate
  1124. so you can put a comment on each one.
  1125. We set all of the elements of the array @code{nums_to_average} with
  1126. assignments, but it is more convenient to use an initializer in the
  1127. declaration:
  1128. @example
  1129. @{
  1130. /* @r{The array of values to average.} */
  1131. double nums_to_average[]
  1132. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1133. /* @r{The average, once we compute it.} */
  1134. average = avg_of_double ((sizeof (nums_to_average)
  1135. / sizeof (nums_to_average[0])),
  1136. nums_to_average);
  1137. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1138. @}
  1139. @end example
  1140. The array initializer is a comma-separated list of values, delimited
  1141. by braces. @xref{Initializers}.
  1142. Note that the declaration does not specify a size for
  1143. @code{nums_to_average}, so the size is determined from the
  1144. initializer. There are five values in the initializer, so
  1145. @code{nums_to_average} gets length 5. If we add another element to
  1146. the initializer, @code{nums_to_average} will have six elements.
  1147. Because the code computes the number of elements from the size of
  1148. the array, using @code{sizeof}, the program will operate on all the
  1149. elements in the initializer, regardless of how many those are.
  1150. @node Lexical Syntax
  1151. @chapter Lexical Syntax
  1152. @cindex lexical syntax
  1153. @cindex token
  1154. To start the full description of the C language, we explain the
  1155. lexical syntax and lexical units of C code. The lexical units of a
  1156. programming language are known as @dfn{tokens}. This chapter covers
  1157. all the tokens of C except for constants, which are covered in a later
  1158. chapter (@pxref{Constants}). One vital kind of token is the
  1159. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1160. kind.
  1161. @menu
  1162. * English:: Write programs in English!
  1163. * Characters:: The characters allowed in C programs.
  1164. * Whitespace:: The particulars of whitespace characters.
  1165. * Comments:: How to include comments in C code.
  1166. * Identifiers:: How to form identifiers (names).
  1167. * Operators/Punctuation:: Characters used as operators or punctuation.
  1168. * Line Continuation:: Splitting one line into multiple lines.
  1169. @end menu
  1170. @node English
  1171. @section Write Programs in English!
  1172. In principle, you can write the function and variable names in a
  1173. program, and the comments, in any human language. C allows any kinds
  1174. of characters in comments, and you can put non-ASCII characters into
  1175. identifiers with a special prefix. However, to enable programmers in
  1176. all countries to understand and develop the program, it is best given
  1177. today's circumstances to write identifiers and comments in
  1178. English.
  1179. English is the one language that programmers in all countries
  1180. generally study. If a program's names are in English, most
  1181. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1182. understand them. Most programmers in those countries can speak
  1183. English, or at least read it, but they do not read each other's
  1184. languages at all. In India, with so many languages, two programmers
  1185. may have no common language other than English.
  1186. If you don't feel confident in writing English, do the best you can,
  1187. and follow each English comment with a version in a language you
  1188. write better; add a note asking others to translate that to English.
  1189. Someone will eventually do that.
  1190. The program's user interface is a different matter. We don't need to
  1191. choose one language for that; it is easy to support multiple languages
  1192. and let each user choose the language to use. This requires writing
  1193. the program to support localization of its interface. (The
  1194. @code{gettext} package exists to support this; @pxref{Message
  1195. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1196. Manual}.) Then a community-based translation effort can provide
  1197. support for all the languages users want to use.
  1198. @node Characters
  1199. @section Characters
  1200. @cindex character set
  1201. @cindex Unicode
  1202. @c ??? How to express ¶?
  1203. GNU C source files are usually written in the
  1204. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1205. was defined in the 1960s for English. However, they can also include
  1206. Unicode characters represented in the
  1207. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1208. This makes it possible to represent accented letters such as @samp{á},
  1209. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1210. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1211. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1212. manual.}
  1213. In C source code, non-ASCII characters are valid in comments, in wide
  1214. character constants (@pxref{Wide Character Constants}), and in string
  1215. constants (@pxref{String Constants}).
  1216. @c ??? valid in identifiers?
  1217. Another way to specify non-ASCII characters in constants (character or
  1218. string) and identifiers is with an escape sequence starting with
  1219. backslash, specifying the intended Unicode character. (@xref{Unicode
  1220. Character Codes}.) This specifies non-ASCII characters without
  1221. putting a real non-ASCII character in the source file itself.
  1222. C accepts two-character aliases called @dfn{digraphs} for certain
  1223. characters. @xref{Digraphs}.
  1224. @node Whitespace
  1225. @section Whitespace
  1226. @cindex whitespace characters in source files
  1227. @cindex space character in source
  1228. @cindex tab character in source
  1229. @cindex formfeed in source
  1230. @cindex linefeed in source
  1231. @cindex newline in source
  1232. @cindex carriage return in source
  1233. @cindex vertical tab in source
  1234. Whitespace means characters that exist in a file but appear blank in a
  1235. printed listing of a file (or traditionally did appear blank, several
  1236. decades ago). The C language requires whitespace in order to separate
  1237. two consecutive identifiers, or to separate an identifier from a
  1238. numeric constant. Other than that, and a few special situations
  1239. described later, whitespace is optional; you can put it in when you
  1240. wish, to make the code easier to read.
  1241. Space and tab in C code are treated as whitespace characters. So are
  1242. line breaks. You can represent a line break with the newline
  1243. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1244. the CRLF sequence (two characters: carriage return followed by a
  1245. newline character).
  1246. The @dfn{formfeed} character, Control-L, was traditionally used to
  1247. divide a file into pages. It is still used this way in source code,
  1248. and the tools that generate nice printouts of source code still start
  1249. a new page after each ``formfeed'' character. Dividing code into
  1250. pages separated by formfeed characters is a good way to break it up
  1251. into comprehensible pieces and show other programmers where they start
  1252. and end.
  1253. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1254. make printing advance down to the next section of a page. We know of
  1255. no particular reason to use it in source code, but it is still
  1256. accepted as whitespace in C.
  1257. Comments are also syntactically equivalent to whitespace.
  1258. @ifinfo
  1259. @xref{Comments}.
  1260. @end ifinfo
  1261. @node Comments
  1262. @section Comments
  1263. @cindex comments
  1264. A comment encapsulates text that has no effect on the program's
  1265. execution or meaning.
  1266. The purpose of comments is to explain the code to people that read it.
  1267. Writing good comments for your code is tremendously important---they
  1268. should provide background information that helps programmers
  1269. understand the reasons why the code is written the way it is. You,
  1270. returning to the code six months from now, will need the help of these
  1271. comments to remember why you wrote it this way.
  1272. Outdated comments that become incorrect are counterproductive, so part
  1273. of the software developer's responsibility is to update comments as
  1274. needed to correspond with changes to the program code.
  1275. C allows two kinds of comment syntax, the traditional style and the
  1276. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1277. with @samp{*/}. For instance,
  1278. @example
  1279. /* @r{This is a comment in traditional C syntax.} */
  1280. @end example
  1281. A traditional comment can contain @samp{/*}, but these delimiters do
  1282. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1283. whether it contains @samp{/*} sequences.
  1284. @example
  1285. /* @r{This} /* @r{is a comment} */ But this is not! */
  1286. @end example
  1287. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1288. For instance,
  1289. @example
  1290. // @r{This is a comment in C@t{++} style.}
  1291. @end example
  1292. Line comments do nest, in effect, because @samp{//} inside a line
  1293. comment is part of that comment:
  1294. @example
  1295. // @r{this whole line is} // @r{one comment}
  1296. This is code, not comment.
  1297. @end example
  1298. It is safe to put line comments inside block comments, or vice versa.
  1299. @example
  1300. @group
  1301. /* @r{traditional comment}
  1302. // @r{contains line comment}
  1303. @r{more traditional comment}
  1304. */ text here is not a comment
  1305. // @r{line comment} /* @r{contains traditional comment} */
  1306. @end group
  1307. @end example
  1308. But beware of commenting out one end of a traditional comment with a line
  1309. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1310. inside an already-started comment.
  1311. @example
  1312. @group
  1313. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1314. Oops! The line comment has ended;
  1315. this isn't a comment any more. */
  1316. @end group
  1317. @end example
  1318. Comments are not recognized within string constants. @t{@w{"/* blah
  1319. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1320. string.
  1321. In this manual we show the text in comments in a variable-width font,
  1322. for readability, but this font distinction does not exist in source
  1323. files.
  1324. A comment is syntactically equivalent to whitespace, so it always
  1325. separates tokens. Thus,
  1326. @example
  1327. @group
  1328. int/* @r{comment} */foo;
  1329. @r{is equivalent to}
  1330. int foo;
  1331. @end group
  1332. @end example
  1333. @noindent
  1334. but clean code always uses real whitespace to separate the comment
  1335. visually from surrounding code.
  1336. @node Identifiers
  1337. @section Identifiers
  1338. @cindex identifiers
  1339. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1340. as well as @samp{_}, that does not start with a digit. Most compilers
  1341. also allow @samp{$}. An identifier can be as long as you like; for
  1342. example,
  1343. @example
  1344. int anti_dis_establishment_arian_ism;
  1345. @end example
  1346. @cindex case of letters in identifiers
  1347. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1348. and @code{A} are two different identifiers.
  1349. @cindex keyword
  1350. @cindex reserved words
  1351. Identifiers in C are used as variable names, function names, typedef
  1352. names, enumeration constants, type tags, field names, and labels.
  1353. Certain identifiers in C are @dfn{keywords}, which means they have
  1354. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1355. meaning you cannot use them in any other way. For instance, you can't
  1356. define a variable or function named @code{return} or @code{if}.
  1357. You can also include other characters, even non-ASCII characters, in
  1358. identifiers by writing their Unicode character names, which start with
  1359. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1360. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1361. characters in identifiers, and when they are written in English, they
  1362. never need non-ASCII characters. @xref{English}.
  1363. Whitespace is required to separate two consecutive identifiers, or to
  1364. separate an identifier from a preceding or following numeric
  1365. constant.
  1366. @node Operators/Punctuation
  1367. @section Operators and Punctuation
  1368. @cindex operators
  1369. @cindex punctuation
  1370. Here we describe the lexical syntax of operators and punctuation in C.
  1371. The specific operators of C and their meanings are presented in
  1372. subsequent chapters.
  1373. Most operators in C consist of one or two characters that can't be
  1374. used in identifiers. The characters used for operators in C are
  1375. @samp{!~^&|*/%+-=<>,.?:}.
  1376. Some operators are a single character. For instance, @samp{-} is the
  1377. operator for negation (with one operand) and the operator for
  1378. subtraction (with two operands).
  1379. Some operators are two characters. For example, @samp{++} is the
  1380. increment operator. Recognition of multicharacter operators works by
  1381. grouping together as many consecutive characters as can constitute one
  1382. operator.
  1383. For instance, the character sequence @samp{++} is always interpreted
  1384. as the increment operator; therefore, if we want to write two
  1385. consecutive instances of the operator @samp{+}, we must separate them
  1386. with a space so that they do not combine as one token. Applying the
  1387. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1388. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1389. of a valid C program and the former could not (since @code{a++}
  1390. is not an lvalue and thus can't be the operand of @code{++}).
  1391. A few C operators are keywords rather than special characters. They
  1392. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1393. (@pxref{Type Alignment}).
  1394. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1395. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1396. @samp{@}}) begin and end a block at the statement level
  1397. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1398. for a variable with multiple elements or components (such as arrays or
  1399. structures).
  1400. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1401. @code{array[5]}.
  1402. Parentheses are used in expressions for explicit nesting of
  1403. expressions (@pxref{Basic Arithmetic}), around the parameter
  1404. declarations in a function declaration or definition, and around the
  1405. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1406. (@pxref{Function Calls}). Several kinds of statements also use
  1407. parentheses as part of their syntax---for instance, @code{if}
  1408. statements, @code{for} statements, @code{while} statements, and
  1409. @code{switch} statements. @xref{if Statement}, and following
  1410. sections.
  1411. Parentheses are also required around the operand of the operator
  1412. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1413. type rather than a value. @xref{Type Size}.
  1414. @node Line Continuation
  1415. @section Line Continuation
  1416. @cindex line continuation
  1417. @cindex continuation of lines
  1418. The sequence of a backslash and a newline is ignored absolutely
  1419. anywhere in a C program. This makes it possible to split a single
  1420. source line into multiple lines in the source file. GNU C tolerates
  1421. and ignores other whitespace between the backslash and the newline.
  1422. In particular, it always ignores a CR (carriage return) character
  1423. there, in case some text editor decided to end the line with the CRLF
  1424. sequence.
  1425. The main use of line continuation in C is for macro definitions that
  1426. would be inconveniently long for a single line (@pxref{Macros}).
  1427. It is possible to continue a line comment onto another line with
  1428. backslash-newline. You can put backslash-newline in the middle of an
  1429. identifier, even a keyword, or an operator. You can even split
  1430. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1431. backslash-newline. Here's an ugly example:
  1432. @example
  1433. @group
  1434. /\
  1435. *
  1436. */ fo\
  1437. o +\
  1438. = 1\
  1439. 0;
  1440. @end group
  1441. @end example
  1442. @noindent
  1443. That's equivalent to @samp{/* */ foo += 10;}.
  1444. Don't do those things in real programs, since they make code hard to
  1445. read.
  1446. @strong{Note:} For the sake of using certain tools on the source code, it is
  1447. wise to end every source file with a newline character which is not
  1448. preceded by a backslash, so that it really ends the last line.
  1449. @node Arithmetic
  1450. @chapter Arithmetic
  1451. @cindex arithmetic operators
  1452. @cindex operators, arithmetic
  1453. @c ??? Duplication with other sections -- get rid of that?
  1454. Arithmetic operators in C attempt to be as similar as possible to the
  1455. abstract arithmetic operations, but it is impossible to do this
  1456. perfectly. Numbers in a computer have a finite range of possible
  1457. values, and non-integer values have a limit on their possible
  1458. accuracy. Nonetheless, in most cases you will encounter no surprises
  1459. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1460. for multiplication.
  1461. Each C operator has a @dfn{precedence}, which is its rank in the
  1462. grammatical order of the various operators. The operators with the
  1463. highest precedence grab adjoining operands first; these expressions
  1464. then become operands for operators of lower precedence. We give some
  1465. information about precedence of operators in this chapter where we
  1466. describe the operators; for the full explanation, see @ref{Binary
  1467. Operator Grammar}.
  1468. The arithmetic operators always @dfn{promote} their operands before
  1469. operating on them. This means converting narrow integer data types to
  1470. a wider data type (@pxref{Operand Promotions}). If you are just
  1471. learning C, don't worry about this yet.
  1472. Given two operands that have different types, most arithmetic
  1473. operations convert them both to their @dfn{common type}. For
  1474. instance, if one is @code{int} and the other is @code{double}, the
  1475. common type is @code{double}. (That's because @code{double} can
  1476. represent all the values that an @code{int} can hold, but not vice
  1477. versa.) For the full details, see @ref{Common Type}.
  1478. @menu
  1479. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1480. and division.
  1481. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1482. * Integer Overflow:: When an integer value exceeds the range
  1483. of its type.
  1484. * Mixed Mode:: Calculating with both integer values
  1485. and floating-point values.
  1486. * Division and Remainder:: How integer division works.
  1487. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1488. * Shift Operations:: Shift integer bits left or right.
  1489. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1490. @end menu
  1491. @node Basic Arithmetic
  1492. @section Basic Arithmetic
  1493. @cindex addition operator
  1494. @cindex subtraction operator
  1495. @cindex multiplication operator
  1496. @cindex division operator
  1497. @cindex negation operator
  1498. @cindex operator, addition
  1499. @cindex operator, subtraction
  1500. @cindex operator, multiplication
  1501. @cindex operator, division
  1502. @cindex operator, negation
  1503. Basic arithmetic in C is done with the usual binary operators of
  1504. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1505. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1506. used to change the sign of a number. The unary @code{+} operator also
  1507. exists; it yields its operand unaltered.
  1508. @samp{/} is the division operator, but dividing integers may not give
  1509. the result you expect. Its value is an integer, which is not equal to
  1510. the mathematical quotient when that is a fraction. Use @samp{%} to
  1511. get the corresponding integer remainder when necessary.
  1512. @xref{Division and Remainder}. Floating point division yields value
  1513. as close as possible to the mathematical quotient.
  1514. These operators use algebraic syntax with the usual algebraic
  1515. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1516. and division are done before addition and subtraction, but you can use
  1517. parentheses to explicitly specify how the operators nest. They are
  1518. left-associative (@pxref{Associativity and Ordering}). Thus,
  1519. @example
  1520. -a + b - c + d * e / f
  1521. @end example
  1522. @noindent
  1523. is equivalent to
  1524. @example
  1525. (((-a) + b) - c) + ((d * e) / f)
  1526. @end example
  1527. @node Integer Arithmetic
  1528. @section Integer Arithmetic
  1529. @cindex integer arithmetic
  1530. Each of the basic arithmetic operations in C has two variants for
  1531. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1532. by the data types of their operands.
  1533. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1534. A signed type can hold a range of positive and negative numbers, with
  1535. zero near the middle of the range. An unsigned type can hold only
  1536. nonnegative numbers; its range starts with zero and runs upward.
  1537. The most basic integer types are @code{int}, which normally can hold
  1538. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1539. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1540. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1541. computers but not always on embedded controllers.) @xref{Integer
  1542. Types}, for full information about integer types.
  1543. When a basic arithmetic operation is given two signed operands, it
  1544. does signed arithmetic. Given two unsigned operands, it does
  1545. unsigned arithmetic.
  1546. If one operand is @code{unsigned int} and the other is @code{int}, the
  1547. operator treats them both as unsigned. More generally, the common
  1548. type of the operands determines whether the operation is signed or
  1549. not. @xref{Common Type}.
  1550. Printing the results of unsigned arithmetic with @code{printf} using
  1551. @samp{%d} can produce surprising results for values far away from
  1552. zero. Even though the rules above say that the computation was done
  1553. with unsigned arithmetic, the printed result may appear to be signed!
  1554. The explanation is that the bit pattern resulting from addition,
  1555. subtraction or multiplication is actually the same for signed and
  1556. unsigned operations. The difference is only in the data type of the
  1557. result, which affects the @emph{interpretation} of the result bit pattern,
  1558. and whether the arithmetic operation can overflow (see the next section).
  1559. But @samp{%d} doesn't know its argument's data type. It sees only the
  1560. value's bit pattern, and it is defined to interpret that as
  1561. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1562. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1563. libc, The GNU C Library Reference Manual}.
  1564. Arithmetic in C never operates directly on narrow integer types (those
  1565. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1566. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1567. @node Integer Overflow
  1568. @section Integer Overflow
  1569. @cindex integer overflow
  1570. @cindex overflow, integer
  1571. When the mathematical value of an arithmetic operation doesn't fit in
  1572. the range of the data type in use, that's called @dfn{overflow}.
  1573. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1574. Integer overflow happens only in arithmetic operations. Type conversion
  1575. operations, by definition, do not cause overflow, not even when the
  1576. result can't fit in its new type. @xref{Integer Conversion}.
  1577. Signed numbers use two's-complement representation, in which the most
  1578. negative number lacks a positive counterpart (@pxref{Integers in
  1579. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1580. overflow.
  1581. @menu
  1582. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1583. * Signed Overflow:: Overlow in signed integer arithmetic.
  1584. @end menu
  1585. @node Unsigned Overflow
  1586. @subsection Overflow with Unsigned Integers
  1587. Unsigned arithmetic in C ignores overflow; it produces the true result
  1588. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1589. in the data type. We say it ``truncates'' the true result to the
  1590. lowest @var{n} bits.
  1591. A true result that is negative, when taken modulo the @var{n}th power
  1592. of 2, yields a positive number. For instance,
  1593. @example
  1594. unsigned int x = 1;
  1595. unsigned int y;
  1596. y = -x;
  1597. @end example
  1598. @noindent
  1599. causes overflow because the negative number @minus{}1 can't be stored
  1600. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1601. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1602. is the largest value that the unsigned data type can store. For a
  1603. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1604. and Minimum Values}.
  1605. Adding that number to itself, as here,
  1606. @example
  1607. unsigned int z;
  1608. z = y + y;
  1609. @end example
  1610. @noindent
  1611. ought to yield 8,489,934,590; however, that is again too large to fit,
  1612. so overflow truncates the value to 4,294,967,294. If that were a
  1613. signed integer, it would mean @minus{}2, which (not by coincidence)
  1614. equals @minus{}1 + @minus{}1.
  1615. @node Signed Overflow
  1616. @subsection Overflow with Signed Integers
  1617. @cindex compiler options for integer overflow
  1618. @cindex integer overflow, compiler options
  1619. @cindex overflow, compiler options
  1620. For signed integers, the result of overflow in C is @emph{in
  1621. principle} undefined, meaning that anything whatsoever could happen.
  1622. Therefore, C compilers can do optimizations that treat the overflow
  1623. case with total unconcern. (Since the result of overflow is undefined
  1624. in principle, one cannot claim that these optimizations are
  1625. erroneous.)
  1626. @strong{Watch out:} These optimizations can do surprising things. For
  1627. instance,
  1628. @example
  1629. int i;
  1630. @r{@dots{}}
  1631. if (i < i + 1)
  1632. x = 5;
  1633. @end example
  1634. @noindent
  1635. could be optimized to do the assignment unconditionally, because the
  1636. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1637. GCC offers compiler options to control handling signed integer
  1638. overflow. These options operate per module; that is, each module
  1639. behaves according to the options it was compiled with.
  1640. These two options specify particular ways to handle signed integer
  1641. overflow, other than the default way:
  1642. @table @option
  1643. @item -fwrapv
  1644. Make signed integer operations well-defined, like unsigned integer
  1645. operations: they produce the @var{n} low-order bits of the true
  1646. result. The highest of those @var{n} bits is the sign bit of the
  1647. result. With @option{-fwrapv}, these out-of-range operations are not
  1648. considered overflow, so (strictly speaking) integer overflow never
  1649. happens.
  1650. The option @option{-fwrapv} enables some optimizations based on the
  1651. defined values of out-of-range results. In GCC 8, it disables
  1652. optimizations that are based on assuming signed integer operations
  1653. will not overflow.
  1654. @item -ftrapv
  1655. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1656. This terminates the program unless the program handles the signal.
  1657. @xref{Signals}.
  1658. @end table
  1659. One other option is useful for finding where overflow occurs:
  1660. @ignore
  1661. @item -fno-strict-overflow
  1662. Disable optimizations that are based on assuming signed integer
  1663. operations will not overflow.
  1664. @end ignore
  1665. @table @option
  1666. @item -fsanitize=signed-integer-overflow
  1667. Output a warning message at run time when signed integer overflow
  1668. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1669. This takes priority over @option{-ftrapv}.
  1670. @end table
  1671. @node Mixed Mode
  1672. @section Mixed-Mode Arithmetic
  1673. Mixing integers and floating-point numbers in a basic arithmetic
  1674. operation converts the integers automatically to floating point.
  1675. In most cases, this gives exactly the desired results.
  1676. But sometimes it matters precisely where the conversion occurs.
  1677. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1678. as an integer, then converts the sum to floating point for the
  1679. multiplication. If the addition gets an overflow, that is not
  1680. equivalent to converting both integers to floating point and then
  1681. adding them. You can get the latter result by explicitly converting
  1682. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1683. @xref{Explicit Type Conversion}.
  1684. @c Eggert's report
  1685. Adding or multiplying several values, including some integers and some
  1686. floating point, does the operations left to right. Thus, @code{3.0 +
  1687. i + j} converts @code{i} to floating point, then adds 3.0, then
  1688. converts @code{j} to floating point and adds that. You can specify a
  1689. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1690. and @code{j} first and then adds that result (converting to floating
  1691. point) to 3.0. In this respect, C differs from other languages, such
  1692. as Fortran.
  1693. @node Division and Remainder
  1694. @section Division and Remainder
  1695. @cindex remainder operator
  1696. @cindex modulus
  1697. @cindex operator, remainder
  1698. Division of integers in C rounds the result to an integer. The result
  1699. is always rounded towards zero.
  1700. @example
  1701. 16 / 3 @result{} 5
  1702. -16 / 3 @result{} -5
  1703. 16 / -3 @result{} -5
  1704. -16 / -3 @result{} 5
  1705. @end example
  1706. @noindent
  1707. To get the corresponding remainder, use the @samp{%} operator:
  1708. @example
  1709. 16 % 3 @result{} 1
  1710. -16 % 3 @result{} -1
  1711. 16 % -3 @result{} 1
  1712. -16 % -3 @result{} -1
  1713. @end example
  1714. @noindent
  1715. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1716. From the rounded quotient and the remainder, you can reconstruct
  1717. the dividend, like this:
  1718. @example
  1719. int
  1720. original_dividend (int divisor, int quotient, int remainder)
  1721. @{
  1722. return divisor * quotient + remainder;
  1723. @}
  1724. @end example
  1725. To do unrounded division, use floating point. If only one operand is
  1726. floating point, @samp{/} converts the other operand to floating
  1727. point.
  1728. @example
  1729. 16.0 / 3 @result{} 5.333333333333333
  1730. 16 / 3.0 @result{} 5.333333333333333
  1731. 16.0 / 3.0 @result{} 5.333333333333333
  1732. 16 / 3 @result{} 5
  1733. @end example
  1734. The remainder operator @samp{%} is not allowed for floating-point
  1735. operands, because it is not needed. The concept of remainder makes
  1736. sense for integers because the result of division of integers has to
  1737. be an integer. For floating point, the result of division is a
  1738. floating-point number, in other words a fraction, which will differ
  1739. from the exact result only by a very small amount.
  1740. There are functions in the standard C library to calculate remainders
  1741. from integral-values division of floating-point numbers.
  1742. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1743. Reference Manual}.
  1744. Integer division overflows in one specific case: dividing the smallest
  1745. negative value for the data type (@pxref{Maximum and Minimum Values})
  1746. by @minus{}1. That's because the correct result, which is the
  1747. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1748. in the same number of bits. On some computers now in use, this always
  1749. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1750. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1751. Division by zero leads to unpredictable results---depending on the
  1752. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1753. produce a numeric result.
  1754. @cindex division by zero
  1755. @cindex zero, division by
  1756. @strong{Watch out:} Make sure the program does not divide by zero. If
  1757. you can't prove that the divisor is not zero, test whether it is zero,
  1758. and skip the division if so.
  1759. @node Numeric Comparisons
  1760. @section Numeric Comparisons
  1761. @cindex numeric comparisons
  1762. @cindex comparisons
  1763. @cindex operators, comparison
  1764. @cindex equal operator
  1765. @cindex not-equal operator
  1766. @cindex less-than operator
  1767. @cindex greater-than operator
  1768. @cindex less-or-equal operator
  1769. @cindex greater-or-equal operator
  1770. @cindex operator, equal
  1771. @cindex operator, not-equal
  1772. @cindex operator, less-than
  1773. @cindex operator, greater-than
  1774. @cindex operator, less-or-equal
  1775. @cindex operator, greater-or-equal
  1776. @cindex truth value
  1777. There are two kinds of comparison operators: @dfn{equality} and
  1778. @dfn{ordering}. Equality comparisons test whether two expressions
  1779. have the same value. The result is a @dfn{truth value}: a number that
  1780. is 1 for ``true'' and 0 for ``false.''
  1781. @example
  1782. a == b /* @r{Test for equal.} */
  1783. a != b /* @r{Test for not equal.} */
  1784. @end example
  1785. The equality comparison is written @code{==} because plain @code{=}
  1786. is the assignment operator.
  1787. Ordering comparisons test which operand is greater or less. Their
  1788. results are truth values. These are the ordering comparisons of C:
  1789. @example
  1790. a < b /* @r{Test for less-than.} */
  1791. a > b /* @r{Test for greater-than.} */
  1792. a <= b /* @r{Test for less-than-or-equal.} */
  1793. a >= b /* @r{Test for greater-than-or-equal.} */
  1794. @end example
  1795. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1796. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1797. mathematics. However, if @code{a} and @code{b} are special floating
  1798. point values (not ordinary numbers), all three can be false.
  1799. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1800. @node Shift Operations
  1801. @section Shift Operations
  1802. @cindex shift operators
  1803. @cindex operators, shift
  1804. @cindex operators, shift
  1805. @cindex shift count
  1806. @dfn{Shifting} an integer means moving the bit values to the left or
  1807. right within the bits of the data type. Shifting is defined only for
  1808. integers. Here's the way to write it:
  1809. @example
  1810. /* @r{Left shift.} */
  1811. 5 << 2 @result{} 20
  1812. /* @r{Right shift.} */
  1813. 5 >> 2 @result{} 1
  1814. @end example
  1815. @noindent
  1816. The left operand is the value to be shifted, and the right operand
  1817. says how many bits to shift it (the @dfn{shift count}). The left
  1818. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1819. operates on a narrow integer type; it's always either @code{int} or
  1820. wider. The value of the shift operator has the same type as the
  1821. promoted left operand.
  1822. @menu
  1823. * Bits Shifted In:: How shifting makes new bits to shift in.
  1824. * Shift Caveats:: Caveats of shift operations.
  1825. * Shift Hacks:: Clever tricks with shift operations.
  1826. @end menu
  1827. @node Bits Shifted In
  1828. @subsection Shifting Makes New Bits
  1829. A shift operation shifts towards one end of the number and has to
  1830. generate new bits at the other end.
  1831. Shifting left one bit must generate a new least significant bit. It
  1832. always brings in zero there. It is equivalent to multiplying by the
  1833. appropriate power of 2. For example,
  1834. @example
  1835. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1836. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1837. @end example
  1838. The meaning of shifting right depends on whether the data type is
  1839. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1840. data type, it performs ``arithmetic shift,'' which keeps the number's
  1841. sign unchanged by duplicating the sign bit. For an unsigned data
  1842. type, it performs ``logical shift,'' which always shifts in zeros at
  1843. the most significant bit.
  1844. In both cases, shifting right one bit is division by two, rounding
  1845. towards negative infinity. For example,
  1846. @example
  1847. (unsigned) 19 >> 2 @result{} 4
  1848. (unsigned) 20 >> 2 @result{} 5
  1849. (unsigned) 21 >> 2 @result{} 5
  1850. @end example
  1851. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1852. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1853. zero.
  1854. The shift count must be zero or greater. Shifting by a negative
  1855. number of bits gives machine-dependent results.
  1856. @node Shift Caveats
  1857. @subsection Caveats for Shift Operations
  1858. @strong{Warning:} If the shift count is greater than or equal to the
  1859. width in bits of the first operand, the results are machine-dependent.
  1860. Logically speaking, the ``correct'' value would be either -1 (for
  1861. right shift of a negative number) or 0 (in all other cases), but what
  1862. it really generates is whatever the machine's shift instruction does in
  1863. that case. So unless you can prove that the second operand is not too
  1864. large, write code to check it at run time.
  1865. @strong{Warning:} Never rely on how the shift operators relate in
  1866. precedence to other arithmetic binary operators. Programmers don't
  1867. remember these precedences, and won't understand the code. Always use
  1868. parentheses to explicitly specify the nesting, like this:
  1869. @example
  1870. a + (b << 5) /* @r{Shift first, then add.} */
  1871. (a + b) << 5 /* @r{Add first, then shift.} */
  1872. @end example
  1873. Note: according to the C standard, shifting of signed values isn't
  1874. guaranteed to work properly when the value shifted is negative, or
  1875. becomes negative during the operation of shifting left. However, only
  1876. pedants have a reason to be concerned about this; only computers with
  1877. strange shift instructions could plausibly do this wrong. In GNU C,
  1878. the operation always works as expected,
  1879. @node Shift Hacks
  1880. @subsection Shift Hacks
  1881. You can use the shift operators for various useful hacks. For
  1882. example, given a date specified by day of the month @code{d}, month
  1883. @code{m}, and year @code{y}, you can store the entire date in a single
  1884. integer @code{date}:
  1885. @example
  1886. unsigned int d = 12;
  1887. unsigned int m = 6;
  1888. unsigned int y = 1983;
  1889. unsigned int date = ((y << 4) + m) << 5) + d;
  1890. @end example
  1891. @noindent
  1892. To extract the original day, month, and year out of
  1893. @code{date}, use a combination of shift and remainder.
  1894. @example
  1895. d = date % 32;
  1896. m = (date >> 5) % 16;
  1897. y = date >> 9;
  1898. @end example
  1899. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1900. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1901. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1902. multiplication, since negating a value is equivalent to multiplying it
  1903. by @minus{}1.
  1904. @node Bitwise Operations
  1905. @section Bitwise Operations
  1906. @cindex bitwise operators
  1907. @cindex operators, bitwise
  1908. @cindex negation, bitwise
  1909. @cindex conjunction, bitwise
  1910. @cindex disjunction, bitwise
  1911. Bitwise operators operate on integers, treating each bit independently.
  1912. They are not allowed for floating-point types.
  1913. The examples in this section use binary constants, starting with
  1914. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1915. of type @code{int}.
  1916. @table @code
  1917. @item ~@code{a}
  1918. Unary operator for bitwise negation; this changes each bit of
  1919. @code{a} from 1 to 0 or from 0 to 1.
  1920. @example
  1921. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1922. ~0 @result{} 0b11111111111111111111111111111111
  1923. ~0b11111111111111111111111111111111 @result{} 0
  1924. ~ (-1) @result{} 0
  1925. @end example
  1926. It is useful to remember that @code{~@var{x} + 1} equals
  1927. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1928. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1929. as @var{x}.
  1930. @item @code{a} & @code{b}
  1931. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1932. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1933. @example
  1934. 0b10101010 & 0b11001100 @result{} 0b10001000
  1935. @end example
  1936. @item @code{a} | @code{b}
  1937. Binary operator for bitwise ``or'' (``inclusive or'' or
  1938. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1939. either @code{a} or @code{b}.
  1940. @example
  1941. 0b10101010 | 0b11001100 @result{} 0b11101110
  1942. @end example
  1943. @item @code{a} ^ @code{b}
  1944. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1945. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1946. @example
  1947. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1948. @end example
  1949. @end table
  1950. To understand the effect of these operators on signed integers, keep
  1951. in mind that all modern computers use two's-complement representation
  1952. (@pxref{Integer Representations}) for negative integers. This means
  1953. that the highest bit of the number indicates the sign; it is 1 for a
  1954. negative number and 0 for a positive number. In a negative number,
  1955. the value in the other bits @emph{increases} as the number gets closer
  1956. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1957. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1958. @strong{Warning:} C defines a precedence ordering for the bitwise
  1959. binary operators, but you should never rely on it. You should
  1960. never rely on how bitwise binary operators relate in precedence to the
  1961. arithmetic and shift binary operators. Other programmers don't
  1962. remember this precedence ordering, so always use parentheses to
  1963. explicitly specify the nesting.
  1964. For example, suppose @code{offset} is an integer that specifies
  1965. the offset within shared memory of a table, except that its bottom few
  1966. bits (@code{LOWBITS} says how many) are special flags. Here's
  1967. how to get just that offset and add it to the base address.
  1968. @example
  1969. shared_mem_base + (offset & (-1 << LOWBITS))
  1970. @end example
  1971. Thanks to the outer set of parentheses, we don't need to know whether
  1972. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1973. set, we don't need to know whether @samp{&} has higher precedence than
  1974. @samp{<<}. But we can rely on all unary operators to have higher
  1975. precedence than any binary operator, so we don't need parentheses
  1976. around the left operand of @samp{<<}.
  1977. @node Assignment Expressions
  1978. @chapter Assignment Expressions
  1979. @cindex assignment expressions
  1980. @cindex operators, assignment
  1981. As a general concept in programming, an @dfn{assignment} is a
  1982. construct that stores a new value into a place where values can be
  1983. stored---for instance, in a variable. Such places are called
  1984. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1985. An assignment in C is an expression because it has a value; we call
  1986. it an @dfn{assignment expression}. A simple assignment looks like
  1987. @example
  1988. @var{lvalue} = @var{value-to-store}
  1989. @end example
  1990. @noindent
  1991. We say it assigns the value of the expression @var{value-to-store} to
  1992. the location @var{lvalue}, or that it stores @var{value-to-store}
  1993. there. You can think of the ``l'' in ``lvalue'' as standing for
  1994. ``left,'' since that's what you put on the left side of the assignment
  1995. operator.
  1996. However, that's not the only way to use an lvalue, and not all lvalues
  1997. can be assigned to. To use the lvalue in the left side of an
  1998. assignment, it has to be @dfn{modifiable}. In C, that means it was
  1999. not declared with the type qualifier @code{const} (@pxref{const}).
  2000. The value of the assignment expression is that of @var{lvalue} after
  2001. the new value is stored in it. This means you can use an assignment
  2002. inside other expressions. Assignment operators are right-associative
  2003. so that
  2004. @example
  2005. x = y = z = 0;
  2006. @end example
  2007. @noindent
  2008. is equivalent to
  2009. @example
  2010. x = (y = (z = 0));
  2011. @end example
  2012. This is the only useful way for them to associate;
  2013. the other way,
  2014. @example
  2015. ((x = y) = z) = 0;
  2016. @end example
  2017. @noindent
  2018. would be invalid since an assignment expression such as @code{x = y}
  2019. is not valid as an lvalue.
  2020. @strong{Warning:} Write parentheses around an assignment if you nest
  2021. it inside another expression, unless that is a conditional expression,
  2022. or comma-separated series, or another assignment.
  2023. @menu
  2024. * Simple Assignment:: The basics of storing a value.
  2025. * Lvalues:: Expressions into which a value can be stored.
  2026. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2027. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2028. an lvalue's contents.
  2029. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2030. * Assignment in Subexpressions:: How to avoid ambiguity.
  2031. * Write Assignments Separately:: Write assignments as separate statements.
  2032. @end menu
  2033. @node Simple Assignment
  2034. @section Simple Assignment
  2035. @cindex simple assignment
  2036. @cindex assignment, simple
  2037. A @dfn{simple assignment expression} computes the value of the right
  2038. operand and stores it into the lvalue on the left. Here is a simple
  2039. assignment expression that stores 5 in @code{i}:
  2040. @example
  2041. i = 5
  2042. @end example
  2043. @noindent
  2044. We say that this is an @dfn{assignment to} the variable @code{i} and
  2045. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2046. because it is an expression (so it has a value). Adding a semicolon
  2047. at the end would make it a statement (@pxref{Expression Statement}).
  2048. Here is another example of a simple assignment expression. Its
  2049. operands are not simple, but the kind of assignment done here is
  2050. simple assignment.
  2051. @example
  2052. x[foo ()] = y + 6
  2053. @end example
  2054. A simple assignment with two different numeric data types converts the
  2055. right operand value to the lvalue's type, if possible. It can convert
  2056. any numeric type to any other numeric type.
  2057. Simple assignment is also allowed on some non-numeric types: pointers
  2058. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2059. unions (@pxref{Unions}).
  2060. @strong{Warning:} Assignment is not allowed on arrays because
  2061. there are no array values in C; C variables can be arrays, but these
  2062. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2063. Arrays}.
  2064. @xref{Assignment Type Conversions}, for the complete rules about data
  2065. types used in assignments.
  2066. @node Lvalues
  2067. @section Lvalues
  2068. @cindex lvalues
  2069. An expression that identifies a memory space that holds a value is
  2070. called an @dfn{lvalue}, because it is a location that can hold a value.
  2071. The standard kinds of lvalues are:
  2072. @itemize @bullet
  2073. @item
  2074. A variable.
  2075. @item
  2076. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2077. unary @samp{*}.
  2078. @item
  2079. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2080. the structure value is an lvalue.
  2081. @item
  2082. A structure field reference using @samp{->}. This is always an lvalue
  2083. since @samp{->} implies pointer dereference.
  2084. @item
  2085. A union alternative reference (@pxref{Unions}), on the same conditions
  2086. as for structure fields.
  2087. @item
  2088. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2089. is an lvalue.
  2090. @end itemize
  2091. If an expression's outermost operation is any other operator, that
  2092. expression is not an lvalue. Thus, the variable @code{x} is an
  2093. lvalue, but @code{x + 0} is not, even though these two expressions
  2094. compute the same value (assuming @code{x} is a number).
  2095. An array can be an lvalue (the rules above determine whether it is
  2096. one), but using the array in an expression converts it automatically
  2097. to a pointer to the first element. The result of this conversion is
  2098. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2099. use @code{a} by itself as the left operand of an assignment. But you
  2100. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2101. lvalue since @code{a} is an lvalue.
  2102. @node Modifying Assignment
  2103. @section Modifying Assignment
  2104. @cindex modifying assignment
  2105. @cindex assignment, modifying
  2106. You can abbreviate the common construct
  2107. @example
  2108. @var{lvalue} = @var{lvalue} + @var{expression}
  2109. @end example
  2110. @noindent
  2111. as
  2112. @example
  2113. @var{lvalue} += @var{expression}
  2114. @end example
  2115. This is known as a @dfn{modifying assignment}. For instance,
  2116. @example
  2117. i = i + 5;
  2118. i += 5;
  2119. @end example
  2120. @noindent
  2121. shows two statements that are equivalent. The first uses
  2122. simple assignment; the second uses modifying assignment.
  2123. Modifying assignment works with any binary arithmetic operator. For
  2124. instance, you can subtract something from an lvalue like this,
  2125. @example
  2126. @var{lvalue} -= @var{expression}
  2127. @end example
  2128. @noindent
  2129. or multiply it by a certain amount like this,
  2130. @example
  2131. @var{lvalue} *= @var{expression}
  2132. @end example
  2133. @noindent
  2134. or shift it by a certain amount like this.
  2135. @example
  2136. @var{lvalue} <<= @var{expression}
  2137. @var{lvalue} >>= @var{expression}
  2138. @end example
  2139. In most cases, this feature adds no power to the language, but it
  2140. provides substantial convenience. Also, when @var{lvalue} contains
  2141. code that has side effects, the simple assignment performs those side
  2142. effects twice, while the modifying assignment performs them once. For
  2143. instance,
  2144. @example
  2145. x[foo ()] = x[foo ()] + 5;
  2146. @end example
  2147. @noindent
  2148. calls @code{foo} twice, and it could return different values each
  2149. time. If @code{foo ()} returns 1 the first time and 3 the second
  2150. time, then the effect could be to add @code{x[3]} and 5 and store the
  2151. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2152. result in @code{x[3]}. We don't know which of the two it will do,
  2153. because C does not specify which call to @code{foo} is computed first.
  2154. Such a statement is not well defined, and shouldn't be used.
  2155. By contrast,
  2156. @example
  2157. x[foo ()] += 5;
  2158. @end example
  2159. @noindent
  2160. is well defined: it calls @code{foo} only once to determine which
  2161. element of @code{x} to adjust, and it adjusts that element by adding 5
  2162. to it.
  2163. @node Increment/Decrement
  2164. @section Increment and Decrement Operators
  2165. @cindex increment operator
  2166. @cindex decrement operator
  2167. @cindex operator, increment
  2168. @cindex operator, decrement
  2169. @cindex preincrement expression
  2170. @cindex predecrement expression
  2171. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2172. @dfn{decrement} operators. When used on a numeric value, they add or
  2173. subtract 1. We don't consider them assignments, but they are
  2174. equivalent to assignments.
  2175. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2176. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2177. and the result becomes the expression's value. For instance,
  2178. @example
  2179. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2180. int
  2181. main (void)
  2182. @{
  2183. int i = 5;
  2184. printf ("%d\n", i);
  2185. printf ("%d\n", ++i);
  2186. printf ("%d\n", i);
  2187. return 0;
  2188. @}
  2189. @end example
  2190. @noindent
  2191. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2192. increments @code{i} from 5 to 6, and has the value 6, so the output
  2193. from @code{printf} on that line says @samp{6}.
  2194. Using @samp{--} instead, for predecrement,
  2195. @example
  2196. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2197. int
  2198. main (void)
  2199. @{
  2200. int i = 5;
  2201. printf ("%d\n", i);
  2202. printf ("%d\n", --i);
  2203. printf ("%d\n", i);
  2204. return 0;
  2205. @}
  2206. @end example
  2207. @noindent
  2208. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2209. again @samp{4}.
  2210. @node Postincrement/Postdecrement
  2211. @section Postincrement and Postdecrement
  2212. @cindex postincrement expression
  2213. @cindex postdecrement expression
  2214. @cindex operator, postincrement
  2215. @cindex operator, postdecrement
  2216. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2217. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2218. increments or decrement it. Thus, the value of @code{i++} is the same
  2219. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2220. little later.'' This is called @dfn{postincrement} or
  2221. @dfn{postdecrement}.
  2222. For example,
  2223. @example
  2224. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2225. int
  2226. main (void)
  2227. @{
  2228. int i = 5;
  2229. printf ("%d\n", i);
  2230. printf ("%d\n", i++);
  2231. printf ("%d\n", i);
  2232. return 0;
  2233. @}
  2234. @end example
  2235. @noindent
  2236. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2237. has the value 5, which is the value of @code{i} at the time,
  2238. but it increments @code{i} from 5 to 6 just a little later.
  2239. How much later is ``just a little later''? That is flexible. The
  2240. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2241. that means by the end of the statement. @xref{Sequence Points}.
  2242. If a unary operator precedes a postincrement or postincrement expression,
  2243. the increment nests inside:
  2244. @example
  2245. -a++ @r{is equivalent to} -(a++)
  2246. @end example
  2247. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2248. it can't be incremented.
  2249. @node Assignment in Subexpressions
  2250. @section Pitfall: Assignment in Subexpressions
  2251. @cindex assignment in subexpressions
  2252. @cindex subexpressions, assignment in
  2253. In C, the order of computing parts of an expression is not fixed.
  2254. Aside from a few special cases, the operations can be computed in any
  2255. order. If one part of the expression has an assignment to @code{x}
  2256. and another part of the expression uses @code{x}, the result is
  2257. unpredictable because that use might be computed before or after the
  2258. assignment.
  2259. Here's an example of ambiguous code:
  2260. @example
  2261. x = 20;
  2262. printf ("%d %d\n", x, x = 4);
  2263. @end example
  2264. @noindent
  2265. If the second argument, @code{x}, is computed before the third argument,
  2266. @code{x = 4}, the second argument's value will be 20. If they are
  2267. computed in the other order, the second argument's value will be 4.
  2268. Here's one way to make that code unambiguous:
  2269. @example
  2270. y = 20;
  2271. printf ("%d %d\n", y, x = 4);
  2272. @end example
  2273. Here's another way, with the other meaning:
  2274. @example
  2275. x = 4;
  2276. printf ("%d %d\n", x, x);
  2277. @end example
  2278. This issue applies to all kinds of assignments, and to the increment
  2279. and decrement operators, which are equivalent to assignments.
  2280. @xref{Order of Execution}, for more information about this.
  2281. However, it can be useful to write assignments inside an
  2282. @code{if}-condition or @code{while}-test along with logical operators.
  2283. @xref{Logicals and Assignments}.
  2284. @node Write Assignments Separately
  2285. @section Write Assignments in Separate Statements
  2286. It is often convenient to write an assignment inside an
  2287. @code{if}-condition, but that can reduce the readability of the
  2288. program. Here's an example of what to avoid:
  2289. @example
  2290. if (x = advance (x))
  2291. @r{@dots{}}
  2292. @end example
  2293. The idea here is to advance @code{x} and test if the value is nonzero.
  2294. However, readers might miss the fact that it uses @samp{=} and not
  2295. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2296. inside a condition is a common error, so GNU C can give warnings when
  2297. @samp{=} appears in a way that suggests it's an error.
  2298. It is much clearer to write the assignment as a separate statement, like this:
  2299. @example
  2300. x = advance (x);
  2301. if (x != 0)
  2302. @r{@dots{}}
  2303. @end example
  2304. @noindent
  2305. This makes it unmistakably clear that @code{x} is assigned a new value.
  2306. Another method is to use the comma operator (@pxref{Comma Operator}),
  2307. like this:
  2308. @example
  2309. if (x = advance (x), x != 0)
  2310. @r{@dots{}}
  2311. @end example
  2312. @noindent
  2313. However, putting the assignment in a separate statement is usually clearer
  2314. unless the assignment is very short, because it reduces nesting.
  2315. @node Execution Control Expressions
  2316. @chapter Execution Control Expressions
  2317. @cindex execution control expressions
  2318. @cindex expressions, execution control
  2319. This chapter describes the C operators that combine expressions to
  2320. control which of those expressions execute, or in which order.
  2321. @menu
  2322. * Logical Operators:: Logical conjunction, disjunction, negation.
  2323. * Logicals and Comparison:: Logical operators with comparison operators.
  2324. * Logicals and Assignments:: Assignments with logical operators.
  2325. * Conditional Expression:: An if/else construct inside expressions.
  2326. * Comma Operator:: Build a sequence of subexpressions.
  2327. @end menu
  2328. @node Logical Operators
  2329. @section Logical Operators
  2330. @cindex logical operators
  2331. @cindex operators, logical
  2332. @cindex conjunction operator
  2333. @cindex disjunction operator
  2334. @cindex negation operator, logical
  2335. The @dfn{logical operators} combine truth values, which are normally
  2336. represented in C as numbers. Any expression with a numeric value is a
  2337. valid truth value: zero means false, and any other value means true.
  2338. A pointer type is also meaningful as a truth value; a null pointer
  2339. (which is zero) means false, and a non-null pointer means true
  2340. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2341. or 0 and has type @code{int} (@pxref{Integer Types}).
  2342. The logical operators are used mainly in the condition of an @code{if}
  2343. statement, or in the end test in a @code{for} statement or
  2344. @code{while} statement (@pxref{Statements}). However, they are valid
  2345. in any context where an integer-valued expression is allowed.
  2346. @table @samp
  2347. @item ! @var{exp}
  2348. Unary operator for logical ``not.'' The value is 1 (true) if
  2349. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2350. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2351. function call, you should write parentheses around it.
  2352. @item @var{left} && @var{right}
  2353. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2354. @var{right}. If both of the operands are true, the @samp{&&} expression
  2355. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2356. gives the value 0 (false). If @var{left} yields a false value,
  2357. that determines the overall result, so @var{right} is not computed.
  2358. @item @var{left} || @var{right}
  2359. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2360. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2361. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2362. gives the value 0 (false). If @var{left} yields a true value,
  2363. that determines the overall result, so @var{right} is not computed.
  2364. @end table
  2365. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2366. and @samp{||}. When you use them together, always use parentheses to
  2367. specify explicitly how they nest, as shown here:
  2368. @example
  2369. if ((r != 0 && x % r == 0)
  2370. ||
  2371. (s != 0 && x % s == 0))
  2372. @end example
  2373. @node Logicals and Comparison
  2374. @section Logical Operators and Comparisons
  2375. The most common thing to use inside the logical operators is a
  2376. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2377. precedence than comparison operators and arithmetic operators, so we
  2378. can write expressions like this without parentheses and get the
  2379. nesting that is natural: two comparison operations that must both be
  2380. true.
  2381. @example
  2382. if (r != 0 && x % r == 0)
  2383. @end example
  2384. @noindent
  2385. This example also shows how it is useful that @samp{&&} guarantees to
  2386. skip the right operand if the left one turns out false. Because of
  2387. that, this code never tries to divide by zero.
  2388. This is equivalent:
  2389. @example
  2390. if (r && x % r == 0)
  2391. @end example
  2392. @noindent
  2393. A truth value is simply a number, so @code{r}
  2394. as a truth value tests whether it is nonzero.
  2395. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2396. So it is better style to write the explicit @code{!= 0}.
  2397. Here's another equivalent way to write it:
  2398. @example
  2399. if (!(r == 0) && x % r == 0)
  2400. @end example
  2401. @noindent
  2402. This illustrates the unary @samp{!} operator, and the need to
  2403. write parentheses around its operand.
  2404. @node Logicals and Assignments
  2405. @section Logical Operators and Assignments
  2406. There are cases where assignments nested inside the condition can
  2407. actually make a program @emph{easier} to read. Here is an example
  2408. using a hypothetical type @code{list} which represents a list; it
  2409. tests whether the list has at least two links, using hypothetical
  2410. functions, @code{nonempty} which is true of the argument is a nonempty
  2411. list, and @code{list_next} which advances from one list link to the
  2412. next. We assume that a list is never a null pointer, so that the
  2413. assignment expressions are always ``true.''
  2414. @example
  2415. if (nonempty (list)
  2416. && (temp1 = list_next (list))
  2417. && nonempty (temp1)
  2418. && (temp2 = list_next (temp1)))
  2419. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2420. @end example
  2421. @noindent
  2422. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2423. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2424. only natural place to put the assignments is among those calls.
  2425. It would be possible to rewrite this as several statements, but that
  2426. could make it much more cumbersome. On the other hand, when the test
  2427. is even more complex than this one, splitting it into multiple
  2428. statements might be necessary for clarity.
  2429. If an empty list is a null pointer, we can dispense with calling
  2430. @code{nonempty}:
  2431. @example
  2432. if ((temp1 = list_next (list))
  2433. && (temp2 = list_next (temp1)))
  2434. @r{@dots{}}
  2435. @end example
  2436. @node Conditional Expression
  2437. @section Conditional Expression
  2438. @cindex conditional expression
  2439. @cindex expression, conditional
  2440. C has a conditional expression that selects one of two expressions
  2441. to compute and get the value from. It looks like this:
  2442. @example
  2443. @var{condition} ? @var{iftrue} : @var{iffalse}
  2444. @end example
  2445. @menu
  2446. * Conditional Rules:: Rules for the conditional operator.
  2447. * Conditional Branches:: About the two branches in a conditional.
  2448. @end menu
  2449. @node Conditional Rules
  2450. @subsection Rules for Conditional Operator
  2451. The first operand, @var{condition}, should be a value that can be
  2452. compared with zero---a number or a pointer. If it is true (nonzero),
  2453. then the conditional expression computes @var{iftrue} and its value
  2454. becomes the value of the conditional expression. Otherwise the
  2455. conditional expression computes @var{iffalse} and its value becomes
  2456. the value of the conditional expression. The conditional expression
  2457. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2458. of them.
  2459. Here's an example: the absolute value of a number @code{x}
  2460. can be written as @code{(x >= 0 ? x : -x)}.
  2461. @strong{Warning:} The conditional expression operators have rather low
  2462. syntactic precedence. Except when the conditional expression is used
  2463. as an argument in a function call, write parentheses around it. For
  2464. clarity, always write parentheses around it if it extends across more
  2465. than one line.
  2466. Assignment operators and the comma operator (@pxref{Comma Operator})
  2467. have lower precedence than conditional expression operators, so write
  2468. parentheses around those when they appear inside a conditional
  2469. expression. @xref{Order of Execution}.
  2470. @node Conditional Branches
  2471. @subsection Conditional Operator Branches
  2472. @cindex branches of conditional expression
  2473. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2474. conditional.
  2475. The two branches should normally have the same type, but a few
  2476. exceptions are allowed. If they are both numeric types, the
  2477. conditional converts both to their common type (@pxref{Common Type}).
  2478. With pointers (@pxref{Pointers}), the two values can be pointers to
  2479. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2480. result type is a similar pointer whose target type combines all the
  2481. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2482. If one branch has type @code{void *} and the other is a pointer to an
  2483. object (not to a function), the conditional converts the @code{void *}
  2484. branch to the type of the other.
  2485. If one branch is an integer constant with value zero and the other is
  2486. a pointer, the conditional converts zero to the pointer's type.
  2487. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2488. that case, if @var{condition} is nonzero, its value becomes the value of
  2489. the conditional expression, after conversion to the common type.
  2490. Thus,
  2491. @example
  2492. x ? : y
  2493. @end example
  2494. @noindent
  2495. has the value of @code{x} if that is nonzero; otherwise, the value of
  2496. @code{y}.
  2497. @cindex side effect in ?:
  2498. @cindex ?: side effect
  2499. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2500. In that case, writing that expression twice would carry out the side
  2501. effects twice, but writing it once does them just once. For example,
  2502. if we suppose that the function @code{next_element} advances a pointer
  2503. variable to point to the next element in a list and returns the new
  2504. pointer,
  2505. @example
  2506. next_element () ? : default_pointer
  2507. @end example
  2508. @noindent
  2509. is a way to advance the pointer and use its new value if it isn't
  2510. null, but use @code{default_pointer} if that is null. We must not do
  2511. it this way,
  2512. @example
  2513. next_element () ? next_element () : default_pointer
  2514. @end example
  2515. @noindent
  2516. because it would advance the pointer a second time.
  2517. @node Comma Operator
  2518. @section Comma Operator
  2519. @cindex comma operator
  2520. @cindex operator, comma
  2521. The comma operator stands for sequential execution of expressions.
  2522. The value of the comma expression comes from the last expression in
  2523. the sequence; the previous expressions are computed only for their
  2524. side effects. It looks like this:
  2525. @example
  2526. @var{exp1}, @var{exp2} @r{@dots{}}
  2527. @end example
  2528. @noindent
  2529. You can bundle any number of expressions together this way, by putting
  2530. commas between them.
  2531. @menu
  2532. * Uses of Comma:: When to use the comma operator.
  2533. * Clean Comma:: Clean use of the comma operator.
  2534. * Avoid Comma:: When to not use the comma operator.
  2535. @end menu
  2536. @node Uses of Comma
  2537. @subsection The Uses of the Comma Operator
  2538. With commas, you can put several expressions into a place that
  2539. requires just one expression---for example, in the header of a
  2540. @code{for} statement. This statement
  2541. @example
  2542. for (i = 0, j = 10, k = 20; i < n; i++)
  2543. @end example
  2544. @noindent
  2545. contains three assignment expressions, to initialize @code{i}, @code{j}
  2546. and @code{k}. The syntax of @code{for} requires just one expression
  2547. for initialization; to include three assignments, we use commas to
  2548. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2549. 20}. This technique is also useful in the loop-advance expression,
  2550. the last of the three inside the @code{for} parentheses.
  2551. In the @code{for} statement and the @code{while} statement
  2552. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2553. effect before the loop-exit test. For example,
  2554. @example
  2555. while (printf ("At the test, x = %d\n", x), x != 0)
  2556. @end example
  2557. @node Clean Comma
  2558. @subsection Clean Use of the Comma Operator
  2559. Always write parentheses around a series of comma operators, except
  2560. when it is at top level in an expression statement, or within the
  2561. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2562. statement (@pxref{Statements}). For instance, in
  2563. @example
  2564. for (i = 0, j = 10, k = 20; i < n; i++)
  2565. @end example
  2566. @noindent
  2567. the commas between the assignments are clear because they are between
  2568. a parenthesis and a semicolon.
  2569. The arguments in a function call are also separated by commas, but that is
  2570. not an instance of the comma operator. Note the difference between
  2571. @example
  2572. foo (4, 5, 6)
  2573. @end example
  2574. @noindent
  2575. which passes three arguments to @code{foo} and
  2576. @example
  2577. foo ((4, 5, 6))
  2578. @end example
  2579. @noindent
  2580. which uses the comma operator and passes just one argument
  2581. (with value 6).
  2582. @strong{Warning:} don't use the comma operator around an argument
  2583. of a function unless it helps understand the code. When you do so,
  2584. don't put part of another argument on the same line. Instead, add a
  2585. line break to make the parentheses around the comma operator easier to
  2586. see, like this.
  2587. @example
  2588. foo ((mumble (x, y), frob (z)),
  2589. *p)
  2590. @end example
  2591. @node Avoid Comma
  2592. @subsection When Not to Use the Comma Operator
  2593. You can use a comma in any subexpression, but in most cases it only
  2594. makes the code confusing, and it is clearer to raise all but the last
  2595. of the comma-separated expressions to a higher level. Thus, instead
  2596. of this:
  2597. @example
  2598. x = (y += 4, 8);
  2599. @end example
  2600. @noindent
  2601. it is much clearer to write this:
  2602. @example
  2603. y += 4, x = 8;
  2604. @end example
  2605. @noindent
  2606. or this:
  2607. @example
  2608. y += 4;
  2609. x = 8;
  2610. @end example
  2611. Use commas only in the cases where there is no clearer alternative
  2612. involving multiple statements.
  2613. By contrast, don't hesitate to use commas in the expansion in a macro
  2614. definition. The trade-offs of code clarity are different in that
  2615. case, because the @emph{use} of the macro may improve overall clarity
  2616. so much that the ugliness of the macro's @emph{definition} is a small
  2617. price to pay. @xref{Macros}.
  2618. @node Binary Operator Grammar
  2619. @chapter Binary Operator Grammar
  2620. @cindex binary operator grammar
  2621. @cindex grammar, binary operator
  2622. @cindex operator precedence
  2623. @cindex precedence, operator
  2624. @cindex left-associative
  2625. @dfn{Binary operators} are those that take two operands, one
  2626. on the left and one on the right.
  2627. All the binary operators in C are syntactically left-associative.
  2628. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2629. @var{op} b) @var{op} c}}. However, you should only write repeated
  2630. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2631. @samp{/}, because those cases are clear from algebra. So it is ok to
  2632. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2633. c} or @code{a % b % c}.
  2634. Each C operator has a @dfn{precedence}, which is its rank in the
  2635. grammatical order of the various operators. The operators with the
  2636. highest precedence grab adjoining operands first; these expressions
  2637. then become operands for operators of lower precedence.
  2638. The precedence order of operators in C is fully specified, so any
  2639. combination of operations leads to a well-defined nesting. We state
  2640. only part of the full precedence ordering here because it is bad
  2641. practice for C code to depend on the other cases. For cases not
  2642. specified in this chapter, always use parentheses to make the nesting
  2643. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2644. remembering anything about the C precedence order beyond what's stated
  2645. here. I studied the full precedence table to write the parser, and
  2646. promptly forgot it again. If you need to look up the full precedence order
  2647. to understand some C code, fix the code with parentheses so nobody else
  2648. needs to do that.}
  2649. You can depend on this subsequence of the precedence ordering
  2650. (stated from highest precedence to lowest):
  2651. @enumerate
  2652. @item
  2653. Component access (@samp{.} and @samp{->}).
  2654. @item
  2655. Unary prefix operators.
  2656. @item
  2657. Unary postfix operators.
  2658. @item
  2659. Multiplication, division, and remainder (they have the same precedence).
  2660. @item
  2661. Addition and subtraction (they have the same precedence).
  2662. @item
  2663. Comparisons---but watch out!
  2664. @item
  2665. Logical operators @samp{&&} and @samp{||}---but watch out!
  2666. @item
  2667. Conditional expression with @samp{?} and @samp{:}.
  2668. @item
  2669. Assignments.
  2670. @item
  2671. Sequential execution (the comma operator, @samp{,}).
  2672. @end enumerate
  2673. Two of the lines in the above list say ``but watch out!'' That means
  2674. that the line covers operators with subtly different precedence.
  2675. Never depend on the grammar of C to decide how two comparisons nest;
  2676. instead, always use parentheses to specify their nesting.
  2677. You can let several @samp{&&} operators associate, or several
  2678. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2679. and @samp{||} nest with each other. @xref{Logical Operators}.
  2680. There is one other precedence ordering that code can depend on:
  2681. @enumerate
  2682. @item
  2683. Unary postfix operators.
  2684. @item
  2685. Bitwise and shift operators---but watch out!
  2686. @item
  2687. Conditional expression with @samp{?} and @samp{:}.
  2688. @end enumerate
  2689. The caveat for bitwise and shift operators is like that for logical
  2690. operators: you can let multiple uses of one bitwise operator
  2691. associate, but always use parentheses to control nesting of dissimilar
  2692. operators.
  2693. These lists do not specify any precedence ordering between the bitwise
  2694. and shift operators of the second list and the binary operators above
  2695. conditional expressions in the first list. When they come together,
  2696. parenthesize them. @xref{Bitwise Operations}.
  2697. @node Order of Execution
  2698. @chapter Order of Execution
  2699. @cindex order of execution
  2700. The order of execution of a C program is not always obvious, and not
  2701. necessarily predictable. This chapter describes what you can count on.
  2702. @menu
  2703. * Reordering of Operands:: Operations in C are not necessarily computed
  2704. in the order they are written.
  2705. * Associativity and Ordering:: Some associative operations are performed
  2706. in a particular order; others are not.
  2707. * Sequence Points:: Some guarantees about the order of operations.
  2708. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2709. * Ordering of Operands:: Evaluation order of operands
  2710. and function arguments.
  2711. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2712. only if it has no impact on program results.
  2713. @end menu
  2714. @node Reordering of Operands
  2715. @section Reordering of Operands
  2716. @cindex ordering of operands
  2717. @cindex reordering of operands
  2718. @cindex operand execution ordering
  2719. The C language does not necessarily carry out operations within an
  2720. expression in the order they appear in the code. For instance, in
  2721. this expression,
  2722. @example
  2723. foo () + bar ()
  2724. @end example
  2725. @noindent
  2726. @code{foo} might be called first or @code{bar} might be called first.
  2727. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2728. results can be unpredictable.
  2729. The unpredictable order of computation of subexpressions also makes a
  2730. difference when one of them contains an assignment. We already saw
  2731. this example of bad code,
  2732. @example
  2733. x = 20;
  2734. printf ("%d %d\n", x, x = 4);
  2735. @end example
  2736. @noindent
  2737. in which the second argument, @code{x}, has a different value
  2738. depending on whether it is computed before or after the assignment in
  2739. the third argument.
  2740. @node Associativity and Ordering
  2741. @section Associativity and Ordering
  2742. @cindex associativity and ordering
  2743. An associative binary operator, such as @code{+}, when used repeatedly
  2744. can combine any number of operands. The operands' values may be
  2745. computed in any order.
  2746. If the values are integers and overflow can be ignored, they may be
  2747. combined in any order. Thus, given four functions that return
  2748. @code{unsigned int}, calling them and adding their results as here
  2749. @example
  2750. (foo () + bar ()) + (baz () + quux ())
  2751. @end example
  2752. @noindent
  2753. may add up the results in any order.
  2754. By contrast, arithmetic on signed integers, with overflow significant,
  2755. is not really associative (@pxref{Integer Overflow}). Thus, the
  2756. additions must be done in the order specified, obeying parentheses and
  2757. left-association. That means computing @code{(foo () + bar ())} and
  2758. @code{(baz () + quux ())} first (in either order), then adding the
  2759. two.
  2760. The same applies to arithmetic on floating-point values, since that
  2761. too is not really associative. However, the GCC option
  2762. @option{-funsafe-math-optimizations} allows the compiler to change the
  2763. order of calculation when an associative operation (associative in
  2764. exact mathematics) combines several operands. The option takes effect
  2765. when compiling a module (@pxref{Compilation}). Changing the order
  2766. of association can enable the program to pipeline the floating point
  2767. operations.
  2768. In all these cases, the four function calls can be done in any order.
  2769. There is no right or wrong about that.
  2770. @node Sequence Points
  2771. @section Sequence Points
  2772. @cindex sequence points
  2773. @cindex full expression
  2774. There are some points in the code where C makes limited guarantees
  2775. about the order of operations. These are called @dfn{sequence
  2776. points}. Here is where they occur:
  2777. @itemize @bullet
  2778. @item
  2779. At the end of a @dfn{full expression}; that is to say, an expression
  2780. that is not part of a larger expression. All side effects specified
  2781. by that expression are carried out before execution moves
  2782. on to subsequent code.
  2783. @item
  2784. At the end of the first operand of certain operators: @samp{,},
  2785. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2786. that expression are carried out before any execution of the
  2787. next operand.
  2788. The commas that separate arguments in a function call are @emph{not}
  2789. comma operators, and they do not create sequence points. The rule
  2790. for function arguments and the rule for operands are different
  2791. (@pxref{Ordering of Operands}).
  2792. @item
  2793. Just before calling a function. All side effects specified by the
  2794. argument expressions are carried out before calling the function.
  2795. If the function to be called is not constant---that is, if it is
  2796. computed by an expression---all side effects in that expression are
  2797. carried out before calling the function.
  2798. @end itemize
  2799. The ordering imposed by a sequence point applies locally to a limited
  2800. range of code, as stated above in each case. For instance, the
  2801. ordering imposed by the comma operator does not apply to code outside
  2802. that comma operator. Thus, in this code,
  2803. @example
  2804. (x = 5, foo (x)) + x * x
  2805. @end example
  2806. @noindent
  2807. the sequence point of the comma operator orders @code{x = 5} before
  2808. @code{foo (x)}, but @code{x * x} could be computed before or after
  2809. them.
  2810. @node Postincrement and Ordering
  2811. @section Postincrement and Ordering
  2812. @cindex postincrement and ordering
  2813. @cindex ordering and postincrement
  2814. Ordering requirements are loose with the postincrement and
  2815. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2816. specify side effects to happen ``a little later.'' They must happen
  2817. before the next sequence point, but that still leaves room for various
  2818. meanings. In this expression,
  2819. @example
  2820. z = x++ - foo ()
  2821. @end example
  2822. @noindent
  2823. it's unpredictable whether @code{x} gets incremented before or after
  2824. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2825. it might see the old value or it might see the incremented value.
  2826. In this perverse expression,
  2827. @example
  2828. x = x++
  2829. @end example
  2830. @noindent
  2831. @code{x} will certainly be incremented but the incremented value may
  2832. not stick. If the incrementation of @code{x} happens after the
  2833. assignment to @code{x}, the incremented value will remain in place.
  2834. But if the incrementation happens first, the assignment will overwrite
  2835. that with the not-yet-incremented value, so the expression as a whole
  2836. will leave @code{x} unchanged.
  2837. @node Ordering of Operands
  2838. @section Ordering of Operands
  2839. @cindex ordering of operands
  2840. @cindex operand ordering
  2841. Operands and arguments can be computed in any order, but there are limits to
  2842. this intermixing in GNU C:
  2843. @itemize @bullet
  2844. @item
  2845. The operands of a binary arithmetic operator can be computed in either
  2846. order, but they can't be intermixed: one of them has to come first,
  2847. followed by the other. Any side effects in the operand that's computed
  2848. first are executed before the other operand is computed.
  2849. @item
  2850. That applies to assignment operators too, except that in simple assignment
  2851. the previous value of the left operand is unused.
  2852. @item
  2853. The arguments in a function call can be computed in any order, but
  2854. they can't be intermixed. Thus, one argument is fully computed, then
  2855. another, and so on until they are all done. Any side effects in one argument
  2856. are executed before computation of another argument begins.
  2857. @end itemize
  2858. These rules don't cover side effects caused by postincrement and
  2859. postdecrement operators---those can be deferred up to the next
  2860. sequence point.
  2861. If you want to get pedantic, the fact is that GCC can reorder the
  2862. computations in many other ways provided that doesn't alter the result
  2863. of running the program. However, because they don't alter the result
  2864. of running the program, they are negligible, unless you are concerned
  2865. with the values in certain variables at various times as seen by other
  2866. processes. In those cases, you can use @code{volatile} to prevent
  2867. optimizations that would make them behave strangely. @xref{volatile}.
  2868. @node Optimization and Ordering
  2869. @section Optimization and Ordering
  2870. @cindex optimization and ordering
  2871. @cindex ordering and optimization
  2872. Sequence points limit the compiler's freedom to reorder operations
  2873. arbitrarily, but optimizations can still reorder them if the compiler
  2874. concludes that this won't alter the results. Thus, in this code,
  2875. @example
  2876. x++;
  2877. y = z;
  2878. x++;
  2879. @end example
  2880. @noindent
  2881. there is a sequence point after each statement, so the code is
  2882. supposed to increment @code{x} once before the assignment to @code{y}
  2883. and once after. However, incrementing @code{x} has no effect on
  2884. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2885. the code could be optimized into this:
  2886. @example
  2887. y = z;
  2888. x += 2;
  2889. @end example
  2890. Normally that has no effect except to make the program faster. But
  2891. there are special situations where it can cause trouble due to things
  2892. that the compiler cannot know about, such as shared memory. To limit
  2893. optimization in those places, use the @code{volatile} type qualifier
  2894. (@pxref{volatile}).
  2895. @node Primitive Types
  2896. @chapter Primitive Data Types
  2897. @cindex primitive types
  2898. @cindex types, primitive
  2899. This chapter describes all the primitive data types of C---that is,
  2900. all the data types that aren't built up from other types. They
  2901. include the types @code{int} and @code{double} that we've already covered.
  2902. @menu
  2903. * Integer Types:: Description of integer types.
  2904. * Floating-Point Data Types:: Description of floating-point types.
  2905. * Complex Data Types:: Description of complex number types.
  2906. * The Void Type:: A type indicating no value at all.
  2907. * Other Data Types:: A brief summary of other types.
  2908. * Type Designators:: Referring to a data type abstractly.
  2909. @end menu
  2910. These types are all made up of bytes (@pxref{Storage}).
  2911. @node Integer Types
  2912. @section Integer Data Types
  2913. @cindex integer types
  2914. @cindex types, integer
  2915. Here we describe all the integer types and their basic
  2916. characteristics. @xref{Integers in Depth}, for more information about
  2917. the bit-level integer data representations and arithmetic.
  2918. @menu
  2919. * Basic Integers:: Overview of the various kinds of integers.
  2920. * Signed and Unsigned Types:: Integers can either hold both negative and
  2921. non-negative values, or only non-negative.
  2922. * Narrow Integers:: When to use smaller integer types.
  2923. * Integer Conversion:: Casting a value from one integer type
  2924. to another.
  2925. * Boolean Type:: An integer type for boolean values.
  2926. * Integer Variations:: Sizes of integer types can vary
  2927. across platforms.
  2928. @end menu
  2929. @node Basic Integers
  2930. @subsection Basic Integers
  2931. @findex char
  2932. @findex int
  2933. @findex short int
  2934. @findex long int
  2935. @findex long long int
  2936. Integer data types in C can be signed or unsigned. An unsigned type
  2937. can represent only positive numbers and zero. A signed type can
  2938. represent both positive and negative numbers, in a range spread almost
  2939. equally on both sides of zero.
  2940. Aside from signedness, the integer data types vary in size: how many
  2941. bytes long they are. The size determines how many different integer
  2942. values the type can hold.
  2943. Here's a list of the signed integer data types, with the sizes they
  2944. have on most computers. Each has a corresponding unsigned type; see
  2945. @ref{Signed and Unsigned Types}.
  2946. @table @code
  2947. @item signed char
  2948. One byte (8 bits). This integer type is used mainly for integers that
  2949. represent characters, as part of arrays or other data structures.
  2950. @item short
  2951. @itemx short int
  2952. Two bytes (16 bits).
  2953. @item int
  2954. Four bytes (32 bits).
  2955. @item long
  2956. @itemx long int
  2957. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2958. platform. Typically it is 32 bits on 32-bit computers
  2959. and 64 bits on 64-bit computers, but there are exceptions.
  2960. @item long long
  2961. @itemx long long int
  2962. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2963. incorporated into standard C as of ISO C99.
  2964. @end table
  2965. You can omit @code{int} when you use @code{long} or @code{short}.
  2966. This is harmless and customary.
  2967. @node Signed and Unsigned Types
  2968. @subsection Signed and Unsigned Types
  2969. @cindex signed types
  2970. @cindex unsigned types
  2971. @cindex types, signed
  2972. @cindex types, unsigned
  2973. @findex signed
  2974. @findex unsigned
  2975. An unsigned integer type can represent only positive numbers and zero.
  2976. A signed type can represent both positive and negative number, in a
  2977. range spread almost equally on both sides of zero. For instance,
  2978. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2979. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2980. these types holds 256 different possible values, since they are both 8
  2981. bits wide.
  2982. Write @code{signed} or @code{unsigned} before the type keyword to
  2983. specify a signed or an unsigned type. However, the integer types
  2984. other than @code{char} are signed by default; with them, @code{signed}
  2985. is a no-op.
  2986. Plain @code{char} may be signed or unsigned; this depends on the
  2987. compiler, the machine in use, and its operating system.
  2988. In many programs, it makes no difference whether @code{char} is
  2989. signed. When it does matter, don't leave it to chance; write
  2990. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2991. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2992. Arctic Char. When my meal arrived, I noted that the chef had not
  2993. signed it. So I complained, ``This char is unsigned---I wanted a
  2994. signed char!'' Or rather, I would have said this if I had thought of
  2995. it fast enough.}
  2996. @node Narrow Integers
  2997. @subsection Narrow Integers
  2998. The types that are narrower than @code{int} are rarely used for
  2999. ordinary variables---we declare them @code{int} instead. This is
  3000. because C converts those narrower types to @code{int} for any
  3001. arithmetic. There is literally no reason to declare a local variable
  3002. @code{char}, for instance.
  3003. In particular, if the value is really a character, you should declare
  3004. the variable @code{int}. Not @code{char}! Using that narrow type can
  3005. force the compiler to truncate values for conversion, which is a
  3006. waste. Furthermore, some functions return either a character value,
  3007. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3008. values distinct.
  3009. The narrow integer types are useful as parts of other objects, such as
  3010. arrays and structures. Compare these array declarations, whose sizes
  3011. on 32-bit processors are shown:
  3012. @example
  3013. signed char ac[1000]; /* @r{1000 bytes} */
  3014. short as[1000]; /* @r{2000 bytes} */
  3015. int ai[1000]; /* @r{4000 bytes} */
  3016. long long all[1000]; /* @r{8000 bytes} */
  3017. @end example
  3018. In addition, character strings must be made up of @code{char}s,
  3019. because that's what all the standard library string functions expect.
  3020. Thus, array @code{ac} could be used as a character string, but the
  3021. others could not be.
  3022. @node Integer Conversion
  3023. @subsection Conversion among Integer Types
  3024. C converts between integer types implicitly in many situations. It
  3025. converts the narrow integer types, @code{char} and @code{short}, to
  3026. @code{int} whenever they are used in arithmetic. Assigning a new
  3027. value to an integer variable (or other lvalue) converts the value to
  3028. the variable's type.
  3029. You can also convert one integer type to another explicitly with a
  3030. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3031. The process of conversion to a wider type is straightforward: the
  3032. value is unchanged. The only exception is when converting a negative
  3033. value (in a signed type, obviously) to a wider unsigned type. In that
  3034. case, the result is a positive value with the same bits
  3035. (@pxref{Integers in Depth}).
  3036. @cindex truncation
  3037. Converting to a narrower type, also called @dfn{truncation}, involves
  3038. discarding some of the value's bits. This is not considered overflow
  3039. (@pxref{Integer Overflow}) because loss of significant bits is a
  3040. normal consequence of truncation. Likewise for conversion between
  3041. signed and unsigned types of the same width.
  3042. More information about conversion for assignment is in
  3043. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3044. see @ref{Argument Promotions}.
  3045. @node Boolean Type
  3046. @subsection Boolean Type
  3047. @cindex boolean type
  3048. @cindex type, boolean
  3049. @findex bool
  3050. The unsigned integer type @code{bool} holds truth values: its possible
  3051. values are 0 and 1. Converting any nonzero value to @code{bool}
  3052. results in 1. For example:
  3053. @example
  3054. bool a = 0;
  3055. bool b = 1;
  3056. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3057. @end example
  3058. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3059. the header file @file{stdbool.h}.
  3060. @node Integer Variations
  3061. @subsection Integer Variations
  3062. The integer types of C have standard @emph{names}, but what they
  3063. @emph{mean} varies depending on the kind of platform in use:
  3064. which kind of computer, which operating system, and which compiler.
  3065. It may even depend on the compiler options used.
  3066. Plain @code{char} may be signed or unsigned; this depends on the
  3067. platform, too. Even for GNU C, there is no general rule.
  3068. In theory, all of the integer types' sizes can vary. @code{char} is
  3069. always considered one ``byte'' for C, but it is not necessarily an
  3070. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3071. specifies only that none of these types is narrower than the ones
  3072. above it in the list in @ref{Basic Integers}, and that @code{short}
  3073. has at least 16 bits.
  3074. It is possible that in the future GNU C will support platforms where
  3075. @code{int} is 64 bits long. In practice, however, on today's real
  3076. computers, there is little variation; you can rely on the table
  3077. given previously (@pxref{Basic Integers}).
  3078. To be completely sure of the size of an integer type,
  3079. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3080. Their corresponding unsigned types add @samp{u} at the front.
  3081. To define these, include the header file @file{stdint.h}.
  3082. The GNU C Compiler compiles for some embedded controllers that use two
  3083. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3084. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3085. 32 bits. These processors can't support an ordinary operating system
  3086. (they may have their own specialized operating systems), and most C
  3087. programs do not try to support them.
  3088. @node Floating-Point Data Types
  3089. @section Floating-Point Data Types
  3090. @cindex floating-point types
  3091. @cindex types, floating-point
  3092. @findex double
  3093. @findex float
  3094. @findex long double
  3095. @dfn{Floating point} is the binary analogue of scientific notation:
  3096. internally it represents a number as a fraction and a binary exponent; the
  3097. value is that fraction multiplied by the specified power of 2.
  3098. For instance, to represent 6, the fraction would be 0.75 and the
  3099. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3100. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3101. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3102. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3103. -1 as the exponent.
  3104. These binary exponents are used by machine instructions. You can
  3105. write a floating-point constant this way if you wish, using
  3106. hexadecimal; but normally we write floating-point numbers in decimal.
  3107. @xref{Floating Constants}.
  3108. C has three floating-point data types:
  3109. @table @code
  3110. @item double
  3111. ``Double-precision'' floating point, which uses 64 bits. This is the
  3112. normal floating-point type, and modern computers normally do
  3113. their floating-point computations in this type, or some wider type.
  3114. Except when there is a special reason to do otherwise, this is the
  3115. type to use for floating-point values.
  3116. @item float
  3117. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3118. for floating-point values stored in structures and arrays, to save
  3119. space when the full precision of @code{double} is not needed. In
  3120. addition, single-precision arithmetic is faster on some computers, and
  3121. occasionally that is useful. But not often---most programs don't use
  3122. the type @code{float}.
  3123. C would be cleaner if @code{float} were the name of the type we
  3124. use for most floating-point values; however, for historical reasons,
  3125. that's not so.
  3126. @item long double
  3127. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3128. precision, depending on the machine in use. On some machines, which
  3129. have no floating-point format wider than @code{double}, this is
  3130. equivalent to @code{double}.
  3131. @end table
  3132. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3133. Point in Depth}, for more information.
  3134. @node Complex Data Types
  3135. @section Complex Data Types
  3136. @cindex complex numbers
  3137. @cindex types, complex
  3138. @cindex @code{_Complex} keyword
  3139. @cindex @code{__complex__} keyword
  3140. @findex _Complex
  3141. @findex __complex__
  3142. Complex numbers can include both a real part and an imaginary part.
  3143. The numeric constants covered above have real-numbered values. An
  3144. imaginary-valued constant is an ordinary real-valued constant followed
  3145. by @samp{i}.
  3146. To declare numeric variables as complex, use the @code{_Complex}
  3147. keyword.@footnote{For compatibility with older versions of GNU C, the
  3148. keyword @code{__complex__} is also allowed. Going forward, however,
  3149. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3150. standard C complex data types are floating point,
  3151. @example
  3152. _Complex float foo;
  3153. _Complex double bar;
  3154. _Complex long double quux;
  3155. @end example
  3156. @noindent
  3157. but GNU C supports integer complex types as well.
  3158. Since @code{_Complex} is a keyword just like @code{float} and
  3159. @code{double} and @code{long}, the keywords can appear in any order,
  3160. but the order shown above seems most logical.
  3161. GNU C supports constants for complex values; for instance, @code{4.0 +
  3162. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3163. @xref{Imaginary Constants}.
  3164. To pull the real and imaginary parts of the number back out, GNU C
  3165. provides the keywords @code{__real__} and @code{__imag__}:
  3166. @example
  3167. _Complex double foo = 4.0 + 3.0i;
  3168. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3169. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3170. @end example
  3171. @noindent
  3172. Standard C does not include these keywords, and instead relies on
  3173. functions defined in @code{complex.h} for accessing the real and
  3174. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3175. @code{creall} extract the real part of a float, double, or long double
  3176. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3177. @code{cimagl} extract the imaginary part.
  3178. @cindex complex conjugation
  3179. GNU C also defines @samp{~} as an operator for complex conjugation,
  3180. which means negating the imaginary part of a complex number:
  3181. @example
  3182. _Complex double foo = 4.0 + 3.0i;
  3183. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3184. @end example
  3185. @noindent
  3186. For standard C compatibility, you can use the appropriate library
  3187. function: @code{conjf}, @code{conj}, or @code{confl}.
  3188. @node The Void Type
  3189. @section The Void Type
  3190. @cindex void type
  3191. @cindex type, void
  3192. @findex void
  3193. The data type @code{void} is a dummy---it allows no operations. It
  3194. really means ``no value at all.'' When a function is meant to return
  3195. no value, we write @code{void} for its return type. Then
  3196. @code{return} statements in that function should not specify a value
  3197. (@pxref{return Statement}). Here's an example:
  3198. @example
  3199. void
  3200. print_if_positive (double x, double y)
  3201. @{
  3202. if (x <= 0)
  3203. return;
  3204. if (y <= 0)
  3205. return;
  3206. printf ("Next point is (%f,%f)\n", x, y);
  3207. @}
  3208. @end example
  3209. A @code{void}-returning function is comparable to what some other languages
  3210. call a ``procedure'' instead of a ``function.''
  3211. @c ??? Already presented
  3212. @c @samp{%f} in an output template specifies to format a @code{double} value
  3213. @c as a decimal number, using a decimal point if needed.
  3214. @node Other Data Types
  3215. @section Other Data Types
  3216. Beyond the primitive types, C provides several ways to construct new
  3217. data types. For instance, you can define @dfn{pointers}, values that
  3218. represent the addresses of other data (@pxref{Pointers}). You can
  3219. define @dfn{structures}, as in many other languages
  3220. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3221. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3222. are collections of named integer codes (@pxref{Enumeration Types}).
  3223. @dfn{Array types} in C are used for allocating space for objects,
  3224. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3225. @node Type Designators
  3226. @section Type Designators
  3227. @cindex type designator
  3228. Some C constructs require a way to designate a specific data type
  3229. independent of any particular variable or expression which has that
  3230. type. The way to do this is with a @dfn{type designator}. The
  3231. constucts that need one include casts (@pxref{Explicit Type
  3232. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3233. We also use type designators to talk about the type of a value in C,
  3234. so you will see many type designators in this manual. When we say,
  3235. ``The value has type @code{int},'' @code{int} is a type designator.
  3236. To make the designator for any type, imagine a variable declaration
  3237. for a variable of that type and delete the variable name and the final
  3238. semicolon.
  3239. For example, to designate the type of full-word integers, we start
  3240. with the declaration for a variable @code{foo} with that type,
  3241. which is this:
  3242. @example
  3243. int foo;
  3244. @end example
  3245. @noindent
  3246. Then we delete the variable name @code{foo} and the semicolon, leaving
  3247. @code{int}---exactly the keyword used in such a declaration.
  3248. Therefore, the type designator for this type is @code{int}.
  3249. What about long unsigned integers? From the declaration
  3250. @example
  3251. unsigned long int foo;
  3252. @end example
  3253. @noindent
  3254. we determine that the designator is @code{unsigned long int}.
  3255. Following this procedure, the designator for any primitive type is
  3256. simply the set of keywords which specifies that type in a declaration.
  3257. The same is true for compound types such as structures, unions, and
  3258. enumerations.
  3259. Designators for pointer types do follow the rule of deleting the
  3260. variable name and semicolon, but the result is not so simple.
  3261. @xref{Pointer Type Designators}, as part of the chapter about
  3262. pointers. @xref{Array Type Designators}), for designators for array
  3263. types.
  3264. To understand what type a designator stands for, imagine a variable
  3265. name inserted into the right place in the designator to make a valid
  3266. declaration. What type would that variable be declared as? That is the
  3267. type the designator designates.
  3268. @node Constants
  3269. @chapter Constants
  3270. @cindex constants
  3271. A @dfn{constant} is an expression that stands for a specific value by
  3272. explicitly representing the desired value. C allows constants for
  3273. numbers, characters, and strings. We have already seen numeric and
  3274. string constants in the examples.
  3275. @menu
  3276. * Integer Constants:: Literal integer values.
  3277. * Integer Const Type:: Types of literal integer values.
  3278. * Floating Constants:: Literal floating-point values.
  3279. * Imaginary Constants:: Literal imaginary number values.
  3280. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3281. * Character Constants:: Literal character values.
  3282. * String Constants:: Literal string values.
  3283. * UTF-8 String Constants:: Literal UTF-8 string values.
  3284. * Unicode Character Codes:: Unicode characters represented
  3285. in either UTF-16 or UTF-32.
  3286. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3287. * Wide String Constants:: Literal string values made up of
  3288. 16- or 32-bit characters.
  3289. @end menu
  3290. @node Integer Constants
  3291. @section Integer Constants
  3292. @cindex integer constants
  3293. @cindex constants, integer
  3294. An integer constant consists of a number to specify the value,
  3295. followed optionally by suffix letters to specify the data type.
  3296. The simplest integer constants are numbers written in base 10
  3297. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3298. constant cannot start with the character @samp{0} (zero) because
  3299. that makes the constant octal.
  3300. You can get the effect of a negative integer constant by putting a
  3301. minus sign at the beginning. Grammatically speaking, that is an
  3302. arithmetic expression rather than a constant, but it behaves just like
  3303. a true constant.
  3304. Integer constants can also be written in octal (base 8), hexadecimal
  3305. (base 16), or binary (base 2). An octal constant starts with the
  3306. character @samp{0} (zero), followed by any number of octal digits
  3307. (@samp{0} to @samp{7}):
  3308. @example
  3309. 0 // @r{zero}
  3310. 077 // @r{63}
  3311. 0403 // @r{259}
  3312. @end example
  3313. @noindent
  3314. Pedantically speaking, the constant @code{0} is an octal constant, but
  3315. we can think of it as decimal; it has the same value either way.
  3316. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3317. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3318. through @samp{f} in upper or lower case):
  3319. @example
  3320. 0xff // @r{255}
  3321. 0XA0 // @r{160}
  3322. 0xffFF // @r{65535}
  3323. @end example
  3324. @cindex binary integer constants
  3325. A binary constant starts with @samp{0b} (upper or lower case) followed
  3326. by bits (each represented by the characters @samp{0} or @samp{1}):
  3327. @example
  3328. 0b101 // @r{5}
  3329. @end example
  3330. Binary constants are a GNU C extension, not part of the C standard.
  3331. Sometimes a space is needed after an integer constant to avoid
  3332. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3333. @node Integer Const Type
  3334. @section Integer Constant Data Types
  3335. @cindex integer constant data types
  3336. @cindex constant data types, integer
  3337. @cindex types of integer constants
  3338. The type of an integer constant is normally @code{int}, if the value
  3339. fits in that type, but here are the complete rules. The type
  3340. of an integer constant is the first one in this sequence that can
  3341. properly represent the value,
  3342. @enumerate
  3343. @item
  3344. @code{int}
  3345. @item
  3346. @code{unsigned int}
  3347. @item
  3348. @code{long int}
  3349. @item
  3350. @code{unsigned long int}
  3351. @item
  3352. @code{long long int}
  3353. @item
  3354. @code{unsigned long long int}
  3355. @end enumerate
  3356. @noindent
  3357. and that isn't excluded by the following rules.
  3358. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3359. first two types (non-@code{long}).
  3360. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3361. first four types (non-@code{long long}).
  3362. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3363. the signed types.
  3364. Otherwise, if the constant is decimal, that excludes the unsigned
  3365. types.
  3366. @c ### This said @code{unsigned int} is excluded.
  3367. @c ### See 17 April 2016
  3368. Here are some examples of the suffixes.
  3369. @example
  3370. 3000000000u // @r{three billion as @code{unsigned int}.}
  3371. 0LL // @r{zero as a @code{long long int}.}
  3372. 0403l // @r{259 as a @code{long int}.}
  3373. @end example
  3374. Suffixes in integer constants are rarely used. When the precise type
  3375. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3376. Type Conversion}).
  3377. @xref{Integer Types}.
  3378. @node Floating Constants
  3379. @section Floating-Point Constants
  3380. @cindex floating-point constants
  3381. @cindex constants, floating-point
  3382. A floating-point constant must have either a decimal point, an
  3383. exponent-of-ten, or both; they distinguish it from an integer
  3384. constant.
  3385. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3386. value follows. It is always written as a decimal number; it can
  3387. optionally start with a sign. The exponent @var{n} means to multiply
  3388. the constant's value by ten to the @var{n}th power.
  3389. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3390. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3391. writing a floating-point number whose value is 1500. They are all
  3392. equivalent.
  3393. Here are more examples with decimal points:
  3394. @example
  3395. 1.0
  3396. 1000.
  3397. 3.14159
  3398. .05
  3399. .0005
  3400. @end example
  3401. For each of them, here are some equivalent constants written with
  3402. exponents:
  3403. @example
  3404. 1e0, 1.0000e0
  3405. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3406. 3.14159e0
  3407. 5e-2, .0005e+2, 5E-2, .0005E2
  3408. .05e-2
  3409. @end example
  3410. A floating-point constant normally has type @code{double}. You can
  3411. force it to type @code{float} by adding @samp{f} or @samp{F}
  3412. at the end. For example,
  3413. @example
  3414. 3.14159f
  3415. 3.14159e0f
  3416. 1000.f
  3417. 100E1F
  3418. .0005f
  3419. .05e-2f
  3420. @end example
  3421. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3422. to type @code{long double}.
  3423. You can use exponents in hexadecimal floating constants, but since
  3424. @samp{e} would be interpreted as a hexadecimal digit, the character
  3425. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3426. The exponent in a hexadecimal floating constant is a possibly-signed
  3427. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3428. multiply into the number.
  3429. Here are some examples:
  3430. @example
  3431. @group
  3432. 0xAp2 // @r{40 in decimal}
  3433. 0xAp-1 // @r{5 in decimal}
  3434. 0x2.0Bp4 // @r{16.75 decimal}
  3435. 0xE.2p3 // @r{121 decimal}
  3436. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3437. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3438. 0x100p-8 // @r{1}
  3439. 0x10p-4 // @r{1}
  3440. 0x1p+4 // @r{16}
  3441. 0x1p+8 // @r{256}
  3442. @end group
  3443. @end example
  3444. @xref{Floating-Point Data Types}.
  3445. @node Imaginary Constants
  3446. @section Imaginary Constants
  3447. @cindex imaginary constants
  3448. @cindex complex constants
  3449. @cindex constants, imaginary
  3450. A complex number consists of a real part plus an imaginary part.
  3451. (Either or both parts may be zero.) This section explains how to
  3452. write numeric constants with imaginary values. By adding these to
  3453. ordinary real-valued numeric constants, we can make constants with
  3454. complex values.
  3455. The simple way to write an imaginary-number constant is to attach the
  3456. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3457. floating-point constant. For example, @code{2.5fi} has type
  3458. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3459. The four alternative suffix letters are all equivalent.
  3460. @cindex _Complex_I
  3461. The other way to write an imaginary constant is to multiply a real
  3462. constant by @code{_Complex_I}, which represents the imaginary number
  3463. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3464. this clunky way is needed.
  3465. To write a complex constant with a nonzero real part and a nonzero
  3466. imaginary part, write the two separately and add them, like this:
  3467. @example
  3468. 4.0 + 3.0i
  3469. @end example
  3470. @noindent
  3471. That gives the value 4 + 3i, with type @code{_Complex double}.
  3472. Such a sum can include multiple real constants, or none. Likewise, it
  3473. can include multiple imaginary constants, or none. For example:
  3474. @example
  3475. _Complex double foo, bar, quux;
  3476. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3477. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3478. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3479. @end example
  3480. @xref{Complex Data Types}.
  3481. @node Invalid Numbers
  3482. @section Invalid Numbers
  3483. Some number-like constructs which are not really valid as numeric
  3484. constants are treated as numbers in preprocessing directives. If
  3485. these constructs appear outside of preprocessing, they are erroneous.
  3486. @xref{Preprocessing Tokens}.
  3487. Sometimes we need to insert spaces to separate tokens so that they
  3488. won't be combined into a single number-like construct. For example,
  3489. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3490. constant, so it is a syntax error. If what we want is the three
  3491. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3492. @node Character Constants
  3493. @section Character Constants
  3494. @cindex character constants
  3495. @cindex constants, character
  3496. @cindex escape sequence
  3497. A @dfn{character constant} is written with single quotes, as in
  3498. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3499. character that the constant should represent. The constant has type
  3500. @code{int}, and its value is the character code of that character.
  3501. For instance, @code{'a'} represents the character code for the letter
  3502. @samp{a}: 97, that is.
  3503. To put the @samp{'} character (single quote) in the character
  3504. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3505. constant looks like @code{'\''}. This sort of sequence, starting with
  3506. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3507. here functions as a kind of @dfn{escape character}.
  3508. To put the @samp{\} character (backslash) in the character constant,
  3509. quote it likewise with @samp{\} (another backslash). This character
  3510. constant looks like @code{'\\'}.
  3511. @cindex bell character
  3512. @cindex @samp{\a}
  3513. @cindex backspace
  3514. @cindex @samp{\b}
  3515. @cindex tab (ASCII character)
  3516. @cindex @samp{\t}
  3517. @cindex vertical tab
  3518. @cindex @samp{\v}
  3519. @cindex formfeed
  3520. @cindex @samp{\f}
  3521. @cindex newline
  3522. @cindex @samp{\n}
  3523. @cindex return (ASCII character)
  3524. @cindex @samp{\r}
  3525. @cindex escape (ASCII character)
  3526. @cindex @samp{\e}
  3527. Here are all the escape sequences that represent specific
  3528. characters in a character constant. The numeric values shown are
  3529. the corresponding ASCII character codes, as decimal numbers.
  3530. @example
  3531. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3532. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3533. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3534. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3535. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3536. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3537. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3538. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3539. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3540. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3541. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3542. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3543. @end example
  3544. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3545. You can also write octal and hex character codes as
  3546. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3547. option here, so octal codes do not need to start with @samp{0}.
  3548. The character constant's value has type @code{int}. However, the
  3549. character code is treated initially as a @code{char} value, which is
  3550. then converted to @code{int}. If the character code is greater than
  3551. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3552. on a platform where the type @code{char} is 8 bits long and signed.
  3553. @node String Constants
  3554. @section String Constants
  3555. @cindex string constants
  3556. @cindex constants, string
  3557. A @dfn{string constant} represents a series of characters. It starts
  3558. with @samp{"} and ends with @samp{"}; in between are the contents of
  3559. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3560. newline in the contents works in string constants as in character
  3561. constants. In a string constant, @samp{'} does not need to be quoted.
  3562. A string constant defines an array of characters which contains the
  3563. specified characters followed by the null character (code 0). Using
  3564. the string constant is equivalent to using the name of an array with
  3565. those contents. In simple cases, the length in bytes of the string
  3566. constant is one greater than the number of characters written in it.
  3567. As with any array in C, using the string constant in an expression
  3568. converts the array to a pointer (@pxref{Pointers}) to the array's
  3569. first element (@pxref{Accessing Array Elements}). This pointer will
  3570. have type @code{char *} because it points to an element of type
  3571. @code{char}. @code{char *} is an example of a type designator for a
  3572. pointer type (@pxref{Pointer Type Designators}). That type is used
  3573. for strings generally, not just the strings expressed as constants
  3574. in a program.
  3575. Thus, the string constant @code{"Foo!"} is almost
  3576. equivalent to declaring an array like this
  3577. @example
  3578. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3579. @end example
  3580. @noindent
  3581. and then using @code{string_array_1} in the program. There
  3582. are two differences, however:
  3583. @itemize @bullet
  3584. @item
  3585. The string constant doesn't define a name for the array.
  3586. @item
  3587. The string constant is probably stored in a read-only area of memory.
  3588. @end itemize
  3589. Newlines are not allowed in the text of a string constant. The motive
  3590. for this prohibition is to catch the error of omitting the closing
  3591. @samp{"}. To put a newline in a constant string, write it as
  3592. @samp{\n} in the string constant.
  3593. A real null character in the source code inside a string constant
  3594. causes a warning. To put a null character in the middle of a string
  3595. constant, write @samp{\0} or @samp{\000}.
  3596. Consecutive string constants are effectively concatenated. Thus,
  3597. @example
  3598. "Fo" "o!" @r{is equivalent to} "Foo!"
  3599. @end example
  3600. This is useful for writing a string containing multiple lines,
  3601. like this:
  3602. @example
  3603. "This message is so long that it needs more than\n"
  3604. "a single line of text. C does not allow a newline\n"
  3605. "to represent itself in a string constant, so we have to\n"
  3606. "write \\n to put it in the string. For readability of\n"
  3607. "the source code, it is advisable to put line breaks in\n"
  3608. "the source where they occur in the contents of the\n"
  3609. "constant.\n"
  3610. @end example
  3611. The sequence of a backslash and a newline is ignored anywhere
  3612. in a C program, and that includes inside a string constant.
  3613. Thus, you can write multi-line string constants this way:
  3614. @example
  3615. "This is another way to put newlines in a string constant\n\
  3616. and break the line after them in the source code."
  3617. @end example
  3618. @noindent
  3619. However, concatenation is the recommended way to do this.
  3620. You can also write perverse string constants like this,
  3621. @example
  3622. "Fo\
  3623. o!"
  3624. @end example
  3625. @noindent
  3626. but don't do that---write it like this instead:
  3627. @example
  3628. "Foo!"
  3629. @end example
  3630. Be careful to avoid passing a string constant to a function that
  3631. modifies the string it receives. The memory where the string constant
  3632. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3633. signal that normally terminates the function (@pxref{Signals}. Even
  3634. worse, the memory may not be read-only. Then the function might
  3635. modify the string constant, thus spoiling the contents of other string
  3636. constants that are supposed to contain the same value and are unified
  3637. by the compiler.
  3638. @node UTF-8 String Constants
  3639. @section UTF-8 String Constants
  3640. @cindex UTF-8 String Constants
  3641. Writing @samp{u8} immediately before a string constant, with no
  3642. intervening space, means to represent that string in UTF-8 encoding as
  3643. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3644. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3645. as multibyte sequences. Here is an example of a UTF-8 constant:
  3646. @example
  3647. u8"A cónstàñt"
  3648. @end example
  3649. This constant occupies 13 bytes plus the terminating null,
  3650. because each of the accented letters is a two-byte sequence.
  3651. Concatenating an ordinary string with a UTF-8 string conceptually
  3652. produces another UTF-8 string. However, if the ordinary string
  3653. contains character codes 128 and up, the results cannot be relied on.
  3654. @node Unicode Character Codes
  3655. @section Unicode Character Codes
  3656. @cindex Unicode character codes
  3657. @cindex universal character names
  3658. You can specify Unicode characters, for individual character constants
  3659. or as part of string constants (@pxref{String Constants}), using
  3660. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3661. hexadecimal Unicode character code. If the code value is too big for
  3662. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3663. Unicode character code. (These codes are called @dfn{universal
  3664. character names}.) For example,
  3665. @example
  3666. \u6C34 /* @r{16-bit code (UTF-16)} */
  3667. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3668. @end example
  3669. @noindent
  3670. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3671. Constants}). For instance,
  3672. @example
  3673. u8"fóó \u6C34 \U0010ABCD"
  3674. @end example
  3675. You can also use them in wide character constants (@pxref{Wide
  3676. Character Constants}), like this:
  3677. @example
  3678. u'\u6C34' /* @r{16-bit code} */
  3679. U'\U0010ABCD' /* @r{32-bit code} */
  3680. @end example
  3681. @noindent
  3682. and in wide string constants (@pxref{Wide String Constants}), like
  3683. this:
  3684. @example
  3685. u"\u6C34\u6C33" /* @r{16-bit code} */
  3686. U"\U0010ABCD" /* @r{32-bit code} */
  3687. @end example
  3688. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3689. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3690. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3691. actually ASCII control characters, and you can specify them with other
  3692. escape sequences (@pxref{Character Constants}).
  3693. @node Wide Character Constants
  3694. @section Wide Character Constants
  3695. @cindex wide character constants
  3696. @cindex constants, wide character
  3697. A @dfn{wide character constant} represents characters with more than 8
  3698. bits of character code. This is an obscure feature that we need to
  3699. document but that you probably won't ever use. If you're just
  3700. learning C, you may as well skip this section.
  3701. The original C wide character constant looks like @samp{L} (upper
  3702. case!) followed immediately by an ordinary character constant (with no
  3703. intervening space). Its data type is @code{wchar_t}, which is an
  3704. alias defined in @file{stddef.h} for one of the standard integer
  3705. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3706. it is 16 bits, these character constants use the UTF-16 form of
  3707. Unicode; if 32 bits, UTF-32.
  3708. There are also Unicode wide character constants which explicitly
  3709. specify the width. These constants start with @samp{u} or @samp{U}
  3710. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3711. character constant, and @samp{U} a 32-bit Unicode wide character
  3712. constant. Their types are, respectively, @code{char16_t} and
  3713. @w{@code{char32_t}}; they are declared in the header file
  3714. @file{uchar.h}. These character constants are valid even if
  3715. @file{uchar.h} is not included, but some uses of them may be
  3716. inconvenient without including it to declare those type names.
  3717. The character represented in a wide character constant can be an
  3718. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3719. are all valid, and they are all equal to @code{'a'}.
  3720. In all three kinds of wide character constants, you can write a
  3721. non-ASCII Unicode character in the constant itself; the constant's
  3722. value is the character's Unicode character code. Or you can specify
  3723. the Unicode character with an escape sequence (@pxref{Unicode
  3724. Character Codes}).
  3725. @node Wide String Constants
  3726. @section Wide String Constants
  3727. @cindex wide string constants
  3728. @cindex constants, wide string
  3729. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3730. characters. They are rarely used; if you're just
  3731. learning C, you may as well skip this section.
  3732. There are three kinds of wide string constants, which differ in the
  3733. data type used for each character in the string. Each wide string
  3734. constant is equivalent to an array of integers, but the data type of
  3735. those integers depends on the kind of wide string. Using the constant
  3736. in an expression will convert the array to a pointer to its first
  3737. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3738. For each kind of wide string constant, we state here what type that
  3739. pointer will be.
  3740. @table @code
  3741. @item char16_t
  3742. This is a 16-bit Unicode wide string constant: each element is a
  3743. 16-bit Unicode character code with type @code{char16_t}, so the string
  3744. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3745. @pxref{Pointer Type Designators}.) The constant is written as
  3746. @samp{u} (which must be lower case) followed (with no intervening
  3747. space) by a string constant with the usual syntax.
  3748. @item char32_t
  3749. This is a 32-bit Unicode wide string constant: each element is a
  3750. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3751. It's written as @samp{U} (which must be upper case) followed (with no
  3752. intervening space) by a string constant with the usual syntax.
  3753. @item wchar_t
  3754. This is the original kind of wide string constant. It's written as
  3755. @samp{L} (which must be upper case) followed (with no intervening
  3756. space) by a string constant with the usual syntax, and the string has
  3757. type @code{wchar_t@ *}.
  3758. The width of the data type @code{wchar_t} depends on the target
  3759. platform, which makes this kind of wide string somewhat less useful
  3760. than the newer kinds.
  3761. @end table
  3762. @code{char16_t} and @code{char32_t} are declared in the header file
  3763. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3764. Consecutive wide string constants of the same kind concatenate, just
  3765. like ordinary string constants. A wide string constant concatenated
  3766. with an ordinary string constant results in a wide string constant.
  3767. You can't concatenate two wide string constants of different kinds.
  3768. You also can't concatenate a wide string constant (of any kind) with a
  3769. UTF-8 string constant.
  3770. @node Type Size
  3771. @chapter Type Size
  3772. @cindex type size
  3773. @cindex size of type
  3774. @findex sizeof
  3775. Each data type has a @dfn{size}, which is the number of bytes
  3776. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3777. a C program, use @code{sizeof}. There are two ways to use it:
  3778. @table @code
  3779. @item sizeof @var{expression}
  3780. This gives the size of @var{expression}, based on its data type. It
  3781. does not calculate the value of @var{expression}, only its size, so if
  3782. @var{expression} includes side effects or function calls, they do not
  3783. happen. Therefore, @code{sizeof} is always a compile-time operation
  3784. that has zero run-time cost.
  3785. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3786. operand of @code{sizeof}.
  3787. For example,
  3788. @example
  3789. double a;
  3790. i = sizeof a + 10;
  3791. @end example
  3792. @noindent
  3793. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3794. Here's how to determine the number of elements in an array
  3795. @code{array}:
  3796. @example
  3797. (sizeof array / sizeof array[0])
  3798. @end example
  3799. @noindent
  3800. The expression @code{sizeof array} gives the size of the array, not
  3801. the size of a pointer to an element. However, if @var{expression} is
  3802. a function parameter that was declared as an array, that
  3803. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3804. the result is the size of that pointer.
  3805. @item sizeof (@var{type})
  3806. This gives the size of @var{type}.
  3807. For example,
  3808. @example
  3809. i = sizeof (double) + 10;
  3810. @end example
  3811. @noindent
  3812. is equivalent to the previous example.
  3813. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3814. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3815. C, which makes adding an integer to a function pointer work as desired
  3816. (@pxref{Pointer Arithmetic}).
  3817. @end table
  3818. @strong{Warning}: When you use @code{sizeof} with a type
  3819. instead of an expression, you must write parentheses around the type.
  3820. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3821. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3822. the cast expression to avoid an ambiguity in the grammar of C@.
  3823. Specifically,
  3824. @example
  3825. sizeof (int) -x
  3826. @end example
  3827. @noindent
  3828. parses as
  3829. @example
  3830. (sizeof (int)) - x
  3831. @end example
  3832. @noindent
  3833. If what you want is
  3834. @example
  3835. sizeof ((int) -x)
  3836. @end example
  3837. @noindent
  3838. you must write it that way, with parentheses.
  3839. The data type of the value of the @code{sizeof} operator is always one
  3840. of the unsigned integer types; which one of those types depends on the
  3841. machine. The header file @code{stddef.h} defines the typedef name
  3842. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3843. Names}.
  3844. @node Pointers
  3845. @chapter Pointers
  3846. @cindex pointers
  3847. Among high-level languages, C is rather low level, close to the
  3848. machine. This is mainly because it has explicit @dfn{pointers}. A
  3849. pointer value is the numeric address of data in memory. The type of
  3850. data to be found at that address is specified by the data type of the
  3851. pointer itself. The unary operator @samp{*} gets the data that a
  3852. pointer points to---this is called @dfn{dereferencing the pointer}.
  3853. C also allows pointers to functions, but since there are some
  3854. differences in how they work, we treat them later. @xref{Function
  3855. Pointers}.
  3856. @menu
  3857. * Address of Data:: Using the ``address-of'' operator.
  3858. * Pointer Types:: For each type, there is a pointer type.
  3859. * Pointer Declarations:: Declaring variables with pointer types.
  3860. * Pointer Type Designators:: Designators for pointer types.
  3861. * Pointer Dereference:: Accessing what a pointer points at.
  3862. * Null Pointers:: Pointers which do not point to any object.
  3863. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3864. * Void Pointers:: Totally generic pointers, can cast to any.
  3865. * Pointer Comparison:: Comparing memory address values.
  3866. * Pointer Arithmetic:: Computing memory address values.
  3867. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3868. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3869. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3870. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3871. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3872. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3873. @end menu
  3874. @node Address of Data
  3875. @section Address of Data
  3876. @cindex address-of operator
  3877. The most basic way to make a pointer is with the ``address-of''
  3878. operator, @samp{&}. Let's suppose we have these variables available:
  3879. @example
  3880. int i;
  3881. double a[5];
  3882. @end example
  3883. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3884. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3885. address of the element 3 of @code{a}. (It is actually the fourth
  3886. element in the array, since the first element has index 0.)
  3887. The address-of operator is unusual because it operates on a place to
  3888. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3889. stored there. (The left argument of a simple assignment is unusual in
  3890. the same way.) You can use it on any lvalue except a bit field
  3891. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3892. Constructors}).
  3893. @node Pointer Types
  3894. @section Pointer Types
  3895. For each data type @var{t}, there is a type for pointers to type
  3896. @var{t}. For these variables,
  3897. @example
  3898. int i;
  3899. double a[5];
  3900. @end example
  3901. @itemize @bullet
  3902. @item
  3903. @code{i} has type @code{int}; we say
  3904. @code{&i} is a ``pointer to @code{int}.''
  3905. @item
  3906. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3907. arrays of five @code{double}s.''
  3908. @item
  3909. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3910. to @code{double}.''
  3911. @end itemize
  3912. @node Pointer Declarations
  3913. @section Pointer-Variable Declarations
  3914. The way to declare that a variable @code{foo} points to type @var{t} is
  3915. @example
  3916. @var{t} *foo;
  3917. @end example
  3918. To remember this syntax, think ``if you dereference @code{foo}, using
  3919. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3920. points to type @var{t}.''
  3921. Thus, we can declare variables that hold pointers to these three
  3922. types, like this:
  3923. @example
  3924. int *ptri; /* @r{Pointer to @code{int}.} */
  3925. double *ptrd; /* @r{Pointer to @code{double}.} */
  3926. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3927. @end example
  3928. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3929. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3930. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3931. @code{double}.'' The parentheses express the point that you would
  3932. dereference it first, then subscript it.
  3933. Contrast the last one with this:
  3934. @example
  3935. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3936. @end example
  3937. @noindent
  3938. Because @samp{*} has higher syntactic precedence than subscripting,
  3939. you would subscript @code{aptrd} then dereference it. Therefore, it
  3940. declares an array of pointers, not a pointer.
  3941. @node Pointer Type Designators
  3942. @section Pointer-Type Designators
  3943. Every type in C has a designator; you make it by deleting the variable
  3944. name and the semicolon from a declaration (@pxref{Type
  3945. Designators}). Here are the designators for the pointer
  3946. types of the example declarations in the previous section:
  3947. @example
  3948. int * /* @r{Pointer to @code{int}.} */
  3949. double * /* @r{Pointer to @code{double}.} */
  3950. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3951. @end example
  3952. Remember, to understand what type a designator stands for, imagine the
  3953. variable name that would be in the declaration, and figure out what
  3954. type it would declare that variable with. @code{double (*)[5]} can
  3955. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3956. which, when dereferenced, gives an array of 5 @code{double}s.
  3957. @node Pointer Dereference
  3958. @section Dereferencing Pointers
  3959. @cindex dereferencing pointers
  3960. @cindex pointer dereferencing
  3961. The main use of a pointer value is to @dfn{dereference it} (access the
  3962. data it points at) with the unary @samp{*} operator. For instance,
  3963. @code{*&i} is the value at @code{i}'s address---which is just
  3964. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3965. valid.
  3966. A pointer-dereference expression whose type is data (not a function)
  3967. is an lvalue.
  3968. Pointers become really useful when we store them somewhere and use
  3969. them later. Here's a simple example to illustrate the practice:
  3970. @example
  3971. @{
  3972. int i;
  3973. int *ptr;
  3974. ptr = &i;
  3975. i = 5;
  3976. @r{@dots{}}
  3977. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3978. @}
  3979. @end example
  3980. This shows how to declare the variable @code{ptr} as type
  3981. @code{int *} (pointer to @code{int}), store a pointer value into it
  3982. (pointing at @code{i}), and use it later to get the value of the
  3983. object it points at (the value in @code{i}).
  3984. If anyone can provide a useful example which is this basic,
  3985. I would be grateful.
  3986. @node Null Pointers
  3987. @section Null Pointers
  3988. @cindex null pointers
  3989. @cindex pointers, null
  3990. @c ???stdio loads sttddef
  3991. A pointer value can be @dfn{null}, which means it does not point to
  3992. any object. The cleanest way to get a null pointer is by writing
  3993. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3994. also do it by casting 0 to the desired pointer type, as in
  3995. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  3996. @xref{Explicit Type Conversion}.)
  3997. You can store a null pointer in any lvalue whose data type
  3998. is a pointer type:
  3999. @example
  4000. char *foo;
  4001. foo = NULL;
  4002. @end example
  4003. These two, if consecutive, can be combined into a declaration with
  4004. initializer,
  4005. @example
  4006. char *foo = NULL;
  4007. @end example
  4008. You can also explicitly cast @code{NULL} to the specific pointer type
  4009. you want---it makes no difference.
  4010. @example
  4011. char *foo;
  4012. foo = (char *) NULL;
  4013. @end example
  4014. To test whether a pointer is null, compare it with zero or
  4015. @code{NULL}, as shown here:
  4016. @example
  4017. if (p != NULL)
  4018. /* @r{@code{p} is not null.} */
  4019. operate (p);
  4020. @end example
  4021. Since testing a pointer for not being null is basic and frequent, all
  4022. but beginners in C will understand the conditional without need for
  4023. @code{!= NULL}:
  4024. @example
  4025. if (p)
  4026. /* @r{@code{p} is not null.} */
  4027. operate (p);
  4028. @end example
  4029. @node Invalid Dereference
  4030. @section Dereferencing Null or Invalid Pointers
  4031. Trying to dereference a null pointer is an error. On most platforms,
  4032. it generally causes a signal, usually @code{SIGSEGV}
  4033. (@pxref{Signals}).
  4034. @example
  4035. char *foo = NULL;
  4036. c = *foo; /* @r{This causes a signal and terminates.} */
  4037. @end example
  4038. @noindent
  4039. Likewise a pointer that has the wrong alignment for the target data type
  4040. (on most types of computer), or points to a part of memory that has
  4041. not been allocated in the process's address space.
  4042. The signal terminates the program, unless the program has arranged to
  4043. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4044. The GNU C Library Reference Manual}).
  4045. However, the signal might not happen if the dereference is optimized
  4046. away. In the example above, if you don't subsequently use the value
  4047. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4048. can prevent such optimization using the @code{volatile} qualifier, as
  4049. shown here:
  4050. @example
  4051. volatile char *p;
  4052. volatile char c;
  4053. c = *p;
  4054. @end example
  4055. You can use this to test whether @code{p} points to unallocated
  4056. memory. Set up a signal handler first, so the signal won't terminate
  4057. the program.
  4058. @node Void Pointers
  4059. @section Void Pointers
  4060. @cindex void pointers
  4061. @cindex pointers, void
  4062. The peculiar type @code{void *}, a pointer whose target type is
  4063. @code{void}, is used often in C@. It represents a pointer to
  4064. we-don't-say-what. Thus,
  4065. @example
  4066. void *numbered_slot_pointer (int);
  4067. @end example
  4068. @noindent
  4069. declares a function @code{numbered_slot_pointer} that takes an
  4070. integer parameter and returns a pointer, but we don't say what type of
  4071. data it points to.
  4072. With type @code{void *}, you can pass the pointer around and test
  4073. whether it is null. However, dereferencing it gives a @code{void}
  4074. value that can't be used (@pxref{The Void Type}). To dereference the
  4075. pointer, first convert it to some other pointer type.
  4076. Assignments convert @code{void *} automatically to any other pointer
  4077. type, if the left operand has a pointer type; for instance,
  4078. @example
  4079. @{
  4080. int *p;
  4081. /* @r{Converts return value to @code{int *}.} */
  4082. p = numbered_slot_pointer (5);
  4083. @r{@dots{}}
  4084. @}
  4085. @end example
  4086. Passing an argument of type @code{void *} for a parameter that has a
  4087. pointer type also converts. For example, supposing the function
  4088. @code{hack} is declared to require type @code{float *} for its
  4089. argument, this will convert the null pointer to that type.
  4090. @example
  4091. /* @r{Declare @code{hack} that way.}
  4092. @r{We assume it is defined somewhere else.} */
  4093. void hack (float *);
  4094. @dots{}
  4095. /* @r{Now call @code{hack}.} */
  4096. @{
  4097. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4098. @r{to @code{float *} to pass it to @code{hack}.} */
  4099. hack (numbered_slot_pointer (5));
  4100. @r{@dots{}}
  4101. @}
  4102. @end example
  4103. You can also convert to another pointer type with an explicit cast
  4104. (@pxref{Explicit Type Conversion}), like this:
  4105. @example
  4106. (int *) numbered_slot_pointer (5)
  4107. @end example
  4108. Here is an example which decides at run time which pointer
  4109. type to convert to:
  4110. @example
  4111. void
  4112. extract_int_or_double (void *ptr, bool its_an_int)
  4113. @{
  4114. if (its_an_int)
  4115. handle_an_int (*(int *)ptr);
  4116. else
  4117. handle_a_double (*(double *)ptr);
  4118. @}
  4119. @end example
  4120. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4121. to type @code{int *}, then dereference it.
  4122. @node Pointer Comparison
  4123. @section Pointer Comparison
  4124. @cindex pointer comparison
  4125. @cindex comparison, pointer
  4126. Two pointer values are equal if they point to the same location, or if
  4127. they are both null. You can test for this with @code{==} and
  4128. @code{!=}. Here's a trivial example:
  4129. @example
  4130. @{
  4131. int i;
  4132. int *p, *q;
  4133. p = &i;
  4134. q = &i;
  4135. if (p == q)
  4136. printf ("This will be printed.\n");
  4137. if (p != q)
  4138. printf ("This won't be printed.\n");
  4139. @}
  4140. @end example
  4141. Ordering comparisons such as @code{>} and @code{>=} operate on
  4142. pointers by converting them to unsigned integers. The C standard says
  4143. the two pointers must point within the same object in memory, but on
  4144. GNU/Linux systems these operations simply compare the numeric values
  4145. of the pointers.
  4146. The pointer values to be compared should in principle have the same type, but
  4147. they are allowed to differ in limited cases. First of all, if the two
  4148. pointers' target types are nearly compatible (@pxref{Compatible
  4149. Types}), the comparison is allowed.
  4150. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4151. the other is another pointer type, the comparison operator converts
  4152. the @code{void *} pointer to the other type so as to compare them.
  4153. (In standard C, this is not allowed if the other type is a function
  4154. pointer type, but that works in GNU C@.)
  4155. Comparison operators also allow comparing the integer 0 with a pointer
  4156. value. Thus works by converting 0 to a null pointer of the same type
  4157. as the other operand.
  4158. @node Pointer Arithmetic
  4159. @section Pointer Arithmetic
  4160. @cindex pointer arithmetic
  4161. @cindex arithmetic, pointer
  4162. Adding an integer (positive or negative) to a pointer is valid in C@.
  4163. It assumes that the pointer points to an element in an array, and
  4164. advances or retracts the pointer across as many array elements as the
  4165. integer specifies. Here is an example, in which adding a positive
  4166. integer advances the pointer to a later element in the same array.
  4167. @example
  4168. void
  4169. incrementing_pointers ()
  4170. @{
  4171. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4172. int elt0, elt1, elt4;
  4173. int *p = &array[0];
  4174. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4175. elt0 = *p;
  4176. ++p;
  4177. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4178. elt1 = *p;
  4179. p += 3;
  4180. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4181. elt4 = *p;
  4182. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4183. elt0, elt1, elt4);
  4184. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4185. @}
  4186. @end example
  4187. Here's an example where adding a negative integer retracts the pointer
  4188. to an earlier element in the same array.
  4189. @example
  4190. void
  4191. decrementing_pointers ()
  4192. @{
  4193. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4194. int elt0, elt3, elt4;
  4195. int *p = &array[4];
  4196. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4197. elt4 = *p;
  4198. --p;
  4199. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4200. elt3 = *p;
  4201. p -= 3;
  4202. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4203. elt0 = *p;
  4204. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4205. elt0, elt3, elt4);
  4206. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4207. @}
  4208. @end example
  4209. If one pointer value was made by adding an integer to another
  4210. pointer value, it should be possible to subtract the pointer values
  4211. and recover that integer. That works too in C@.
  4212. @example
  4213. void
  4214. subtract_pointers ()
  4215. @{
  4216. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4217. int *p0, *p3, *p4;
  4218. int *p = &array[4];
  4219. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4220. p4 = p;
  4221. --p;
  4222. /* @r{Now @code{p} points at element 3. Save the value.} */
  4223. p3 = p;
  4224. p -= 3;
  4225. /* @r{Now @code{p} points at element 0. Save the value.} */
  4226. p0 = p;
  4227. printf ("%d, %d, %d, %d\n",
  4228. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4229. /* @r{Prints 4, 0, 3, -3.} */
  4230. @}
  4231. @end example
  4232. The addition operation does not know where arrays are. All it does is
  4233. add the integer (multiplied by object size) to the value of the
  4234. pointer. When the initial pointer and the result point into a single
  4235. array, the result is well-defined.
  4236. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4237. into different memory objects.
  4238. The difference between two pointers has type @code{int}, or
  4239. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4240. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4241. file @file{stddef.h}.
  4242. This definition of pointer subtraction is consistent with
  4243. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4244. @code{p3}, as in ordinary algebra.
  4245. In standard C, addition and subtraction are not allowed on @code{void
  4246. *}, since the target type's size is not defined in that case.
  4247. Likewise, they are not allowed on pointers to function types.
  4248. However, these operations work in GNU C, and the ``size of the target
  4249. type'' is taken as 1.
  4250. @node Pointers and Arrays
  4251. @section Pointers and Arrays
  4252. @cindex pointers and arrays
  4253. @cindex arrays and pointers
  4254. The clean way to refer to an array element is
  4255. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4256. same job is to get the address of that element as a pointer, then
  4257. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4258. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4259. pointer to element zero, then increments it with @code{+} to point to
  4260. the desired element, then gets the value from there.
  4261. That pointer-arithmetic construct is the @emph{definition} of square
  4262. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4263. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4264. symmetrically, so one must be a pointer and the other an integer; it
  4265. does not matter which comes first.
  4266. Since indexing with square brackets is defined in terms of addition
  4267. and dereference, that too is symmetrical. Thus, you can write
  4268. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4269. would be foolish to write @code{3[array]}, since it has no advantage
  4270. and could confuse people who read the code.
  4271. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4272. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4273. instead. Why is this valid? The name of the array, when used by
  4274. itself as an expression (other than in @code{sizeof}), stands for a
  4275. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4276. converts @code{array} implicitly to @code{&array[0]}, and the result
  4277. is a pointer to element 3, equivalent to @code{&array[3]}.
  4278. Since square brackets are defined in terms of such addition,
  4279. @code{array[3]} first converts @code{array} to a pointer. That's why
  4280. it works to use an array directly in that construct.
  4281. @node Pointer Arithmetic Low Level
  4282. @section Pointer Arithmetic at Low Level
  4283. @cindex pointer arithmetic, low level
  4284. @cindex low level pointer arithmetic
  4285. The behavior of pointer arithmetic is theoretically defined only when
  4286. the pointer values all point within one object allocated in memory.
  4287. But the addition and subtraction operators can't tell whether the
  4288. pointer values are all within one object. They don't know where
  4289. objects start and end. So what do they really do?
  4290. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4291. address, which is in fact an integer---call it @var{pint}. It treats
  4292. @var{i} as a number of elements of the type that @var{p} points to.
  4293. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4294. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4295. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4296. If the starting pointer value @var{p} and the result do not point at
  4297. parts of the same object, the operation is not officially legitimate,
  4298. and C code is not ``supposed'' to do it. But you can do it anyway,
  4299. and it gives precisely the results described by the procedure above.
  4300. In some special situations it can do something useful, but non-wizards
  4301. should avoid it.
  4302. Here's a function to offset a pointer value @emph{as if} it pointed to
  4303. an object of any given size, by explicitly performing that calculation:
  4304. @example
  4305. #include <stdint.h>
  4306. void *
  4307. ptr_add (void *p, int i, int objsize)
  4308. @{
  4309. intptr_t p_address = (long) p;
  4310. intptr_t totalsize = i * objsize;
  4311. intptr_t new_address = p_address + totalsize;
  4312. return (void *) new_address;
  4313. @}
  4314. @end example
  4315. @noindent
  4316. @cindex @code{intptr_t}
  4317. This does the same job as @code{@var{p} + @var{i}} with the proper
  4318. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4319. defined in the header file @file{stdint.h}. (In practice, @code{long
  4320. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4321. @node Pointer Increment/Decrement
  4322. @section Pointer Increment and Decrement
  4323. @cindex pointer increment and decrement
  4324. @cindex incrementing pointers
  4325. @cindex decrementing pointers
  4326. The @samp{++} operator adds 1 to a variable. We have seen it for
  4327. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4328. For instance, suppose we have a series of positive integers,
  4329. terminated by a zero, and we want to add them all up.
  4330. @example
  4331. int
  4332. sum_array_till_0 (int *p)
  4333. @{
  4334. int sum = 0;
  4335. for (;;)
  4336. @{
  4337. /* @r{Fetch the next integer.} */
  4338. int next = *p++;
  4339. /* @r{Exit the loop if it's 0.} */
  4340. if (next == 0)
  4341. break;
  4342. /* @r{Add it into running total.} */
  4343. sum += next;
  4344. @}
  4345. return sum;
  4346. @}
  4347. @end example
  4348. @noindent
  4349. The statement @samp{break;} will be explained further on (@pxref{break
  4350. Statement}). Used in this way, it immediately exits the surrounding
  4351. @code{for} statement.
  4352. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4353. takes precedence over a prefix operator. Therefore, it dereferences
  4354. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4355. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4356. pointer, adding 1 to it advances it by the width of the datum it
  4357. points to---in this case, one @code{int}. Therefore, each iteration
  4358. of the loop picks up the next integer from the series and puts it into
  4359. @code{next}.
  4360. This @code{for}-loop has no initialization expression since @code{p}
  4361. and @code{sum} are already initialized, it has no end-test since the
  4362. @samp{break;} statement will exit it, and needs no expression to
  4363. advance it since that's done within the loop by incrementing @code{p}
  4364. and @code{sum}. Thus, those three expressions after @code{for} are
  4365. left empty.
  4366. Another way to write this function is by keeping the parameter value unchanged
  4367. and using indexing to access the integers in the table.
  4368. @example
  4369. int
  4370. sum_array_till_0_indexing (int *p)
  4371. @{
  4372. int i;
  4373. int sum = 0;
  4374. for (i = 0; ; i++)
  4375. @{
  4376. /* @r{Fetch the next integer.} */
  4377. int next = p[i];
  4378. /* @r{Exit the loop if it's 0.} */
  4379. if (next == 0)
  4380. break;
  4381. /* @r{Add it into running total.} */
  4382. sum += next;
  4383. @}
  4384. return sum;
  4385. @}
  4386. @end example
  4387. In this program, instead of advancing @code{p}, we advance @code{i}
  4388. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4389. i)}.) Either way, it uses the same address to get the next integer.
  4390. It makes no difference in this program whether we write @code{i++} or
  4391. @code{++i}, because the value is not used. All that matters is the
  4392. effect, to increment @code{i}.
  4393. The @samp{--} operator also works on pointers; it can be used
  4394. to scan backwards through an array, like this:
  4395. @example
  4396. int
  4397. after_last_nonzero (int *p, int len)
  4398. @{
  4399. /* @r{Set up @code{q} to point just after the last array element.} */
  4400. int *q = p + len;
  4401. while (q != p)
  4402. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4403. if (*--q != 0)
  4404. /* @r{Return the index of the element after that nonzero.} */
  4405. return q - p + 1;
  4406. return 0;
  4407. @}
  4408. @end example
  4409. That function returns the length of the nonzero part of the
  4410. array specified by its arguments; that is, the index of the
  4411. first zero of the run of zeros at the end.
  4412. @node Pointer Arithmetic Drawbacks
  4413. @section Drawbacks of Pointer Arithmetic
  4414. @cindex drawbacks of pointer arithmetic
  4415. @cindex pointer arithmetic, drawbacks
  4416. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4417. major security flaw in the C language. Theoretically, it is only
  4418. valid to adjust a pointer within one object allocated as a unit in
  4419. memory. However, if you unintentionally adjust a pointer across the
  4420. bounds of the object and into some other object, the system has no way
  4421. to detect this error.
  4422. A bug which does that can easily result in clobbering part of another
  4423. object. For example, with @code{array[-1]} you can read or write the
  4424. nonexistent element before the beginning of an array---probably part
  4425. of some other data.
  4426. Combining pointer arithmetic with casts between pointer types, you can
  4427. create a pointer that fails to be properly aligned for its type. For
  4428. example,
  4429. @example
  4430. int a[2];
  4431. char *pa = (char *)a;
  4432. int *p = (int *)(pa + 1);
  4433. @end example
  4434. @noindent
  4435. gives @code{p} a value pointing to an ``integer'' that includes part
  4436. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4437. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4438. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4439. ``works,'' it may be quite slow. It can also cause aliasing
  4440. confusions (@pxref{Aliasing}).
  4441. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4442. unless it is really necessary.
  4443. @node Pointer-Integer Conversion
  4444. @section Pointer-Integer Conversion
  4445. @cindex pointer-integer conversion
  4446. @cindex conversion between pointers and integers
  4447. @cindex @code{uintptr_t}
  4448. On modern computers, an address is simply a number. It occupies the
  4449. same space as some size of integer. In C, you can convert a pointer
  4450. to the appropriate integer types and vice versa, without losing
  4451. information. The appropriate integer types are @code{uintptr_t} (an
  4452. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4453. in @file{stdint.h}.
  4454. For instance,
  4455. @example
  4456. #include <stdint.h>
  4457. #include <stdio.h>
  4458. void
  4459. print_pointer (void *ptr)
  4460. @{
  4461. uintptr_t converted = (uintptr_t) ptr;
  4462. printf ("Pointer value is 0x%x\n",
  4463. (unsigned int) converted);
  4464. @}
  4465. @end example
  4466. @noindent
  4467. The specification @samp{%x} in the template (the first argument) for
  4468. @code{printf} means to represent this argument using hexadecimal
  4469. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4470. printing treats the number as unsigned, but it won't actually matter:
  4471. all @code{printf} gets to see is the series of bits in the number.
  4472. @strong{Warning:} Converting pointers to integers is risky---don't do
  4473. it unless it is really necessary.
  4474. @node Printing Pointers
  4475. @section Printing Pointers
  4476. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4477. For example:
  4478. @example
  4479. void
  4480. print_pointer (void *ptr)
  4481. @{
  4482. printf ("Pointer value is %p\n", ptr);
  4483. @}
  4484. @end example
  4485. The specification @samp{%p} works with any pointer type. It prints
  4486. @samp{0x} followed by the address in hexadecimal, printed as the
  4487. appropriate unsigned integer type.
  4488. @node Structures
  4489. @chapter Structures
  4490. @cindex structures
  4491. @findex struct
  4492. @cindex fields in structures
  4493. A @dfn{structure} is a user-defined data type that holds various
  4494. @dfn{fields} of data. Each field has a name and a data type specified
  4495. in the structure's definition.
  4496. Here we define a structure suitable for storing a linked list of
  4497. integers. Each list item will hold one integer, plus a pointer
  4498. to the next item.
  4499. @example
  4500. struct intlistlink
  4501. @{
  4502. int datum;
  4503. struct intlistlink *next;
  4504. @};
  4505. @end example
  4506. The structure definition has a @dfn{type tag} so that the code can
  4507. refer to this structure. The type tag here is @code{intlistlink}.
  4508. The definition refers recursively to the same structure through that
  4509. tag.
  4510. You can define a structure without a type tag, but then you can't
  4511. refer to it again. That is useful only in some special contexts, such
  4512. as inside a @code{typedef} or a @code{union}.
  4513. The contents of the structure are specified by the @dfn{field
  4514. declarations} inside the braces. Each field in the structure needs a
  4515. declaration there. The fields in one structure definition must have
  4516. distinct names, but these names do not conflict with any other names
  4517. in the program.
  4518. A field declaration looks just like a variable declaration. You can
  4519. combine field declarations with the same beginning, just as you can
  4520. combine variable declarations.
  4521. This structure has two fields. One, named @code{datum}, has type
  4522. @code{int} and will hold one integer in the list. The other, named
  4523. @code{next}, is a pointer to another @code{struct intlistlink}
  4524. which would be the rest of the list. In the last list item, it would
  4525. be @code{NULL}.
  4526. This structure definition is recursive, since the type of the
  4527. @code{next} field refers to the structure type. Such recursion is not
  4528. a problem; in fact, you can use the type @code{struct intlistlink *}
  4529. before the definition of the type @code{struct intlistlink} itself.
  4530. That works because pointers to all kinds of structures really look the
  4531. same at the machine level.
  4532. After defining the structure, you can declare a variable of type
  4533. @code{struct intlistlink} like this:
  4534. @example
  4535. struct intlistlink foo;
  4536. @end example
  4537. The structure definition itself can serve as the beginning of a
  4538. variable declaration, so you can declare variables immediately after,
  4539. like this:
  4540. @example
  4541. struct intlistlink
  4542. @{
  4543. int datum;
  4544. struct intlistlink *next;
  4545. @} foo;
  4546. @end example
  4547. @noindent
  4548. But that is ugly. It is almost always clearer to separate the
  4549. definition of the structure from its uses.
  4550. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4551. the scope of the structure type name to that block. That means the
  4552. structure type is recognized only within that block. Declaring it in
  4553. a function parameter list, as here,
  4554. @example
  4555. int f (struct foo @{int a, b@} parm);
  4556. @end example
  4557. @noindent
  4558. (assuming that @code{struct foo} is not already defined) limits the
  4559. scope of the structure type @code{struct foo} to that parameter list;
  4560. that is basically useless, so it triggers a warning.
  4561. Standard C requires at least one field in a structure.
  4562. GNU C does not require this.
  4563. @menu
  4564. * Referencing Fields:: Accessing field values in a structure object.
  4565. * Dynamic Memory Allocation:: Allocating space for objects
  4566. while the program is running.
  4567. * Field Offset:: Memory layout of fields within a structure.
  4568. * Structure Layout:: Planning the memory layout of fields.
  4569. * Packed Structures:: Packing structure fields as close as possible.
  4570. * Bit Fields:: Dividing integer fields
  4571. into fields with fewer bits.
  4572. * Bit Field Packing:: How bit fields pack together in integers.
  4573. * const Fields:: Making structure fields immutable.
  4574. * Zero Length:: Zero-length array as a variable-length object.
  4575. * Flexible Array Fields:: Another approach to variable-length objects.
  4576. * Overlaying Structures:: Casting one structure type
  4577. over an object of another structure type.
  4578. * Structure Assignment:: Assigning values to structure objects.
  4579. * Unions:: Viewing the same object in different types.
  4580. * Packing With Unions:: Using a union type to pack various types into
  4581. the same memory space.
  4582. * Cast to Union:: Casting a value one of the union's alternative
  4583. types to the type of the union itself.
  4584. * Structure Constructors:: Building new structure objects.
  4585. * Unnamed Types as Fields:: Fields' types do not always need names.
  4586. * Incomplete Types:: Types which have not been fully defined.
  4587. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4588. * Type Tags:: Scope of structure and union type tags.
  4589. @end menu
  4590. @node Referencing Fields
  4591. @section Referencing Structure Fields
  4592. @cindex referencing structure fields
  4593. @cindex structure fields, referencing
  4594. To make a structure useful, there has to be a way to examine and store
  4595. its fields. The @samp{.} (period) operator does that; its use looks
  4596. like @code{@var{object}.@var{field}}.
  4597. Given this structure and variable,
  4598. @example
  4599. struct intlistlink
  4600. @{
  4601. int datum;
  4602. struct intlistlink *next;
  4603. @};
  4604. struct intlistlink foo;
  4605. @end example
  4606. @noindent
  4607. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4608. fields in the value of @code{foo}. These fields are lvalues, so you
  4609. can store values into them, and read the values out again.
  4610. Most often, structures are dynamically allocated (see the next
  4611. section), and we refer to the objects via pointers.
  4612. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4613. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4614. contains this declaration:
  4615. @example
  4616. struct intlistlink *ptr;
  4617. @end example
  4618. @noindent
  4619. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4620. to the two fields in the object that @code{ptr} points to.
  4621. If a unary operator precedes an expression using @samp{->},
  4622. the @samp{->} nests inside:
  4623. @example
  4624. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4625. @end example
  4626. You can intermix @samp{->} and @samp{.} without parentheses,
  4627. as shown here:
  4628. @example
  4629. struct @{ double d; struct intlistlink l; @} foo;
  4630. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4631. @end example
  4632. @node Dynamic Memory Allocation
  4633. @section Dynamic Memory Allocation
  4634. @cindex dynamic memory allocation
  4635. @cindex memory allocation, dynamic
  4636. @cindex allocating memory dynamically
  4637. To allocate an object dynamically, call the library function
  4638. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4639. Reference Manual}). Here is how to allocate an object of type
  4640. @code{struct intlistlink}. To make this code work, include the file
  4641. @file{stdlib.h}, like this:
  4642. @example
  4643. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4644. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4645. @dots{}
  4646. struct intlistlink *
  4647. alloc_intlistlink ()
  4648. @{
  4649. struct intlistlink *p;
  4650. p = malloc (sizeof (struct intlistlink));
  4651. if (p == NULL)
  4652. fatal ("Ran out of storage");
  4653. /* @r{Initialize the contents.} */
  4654. p->datum = 0;
  4655. p->next = NULL;
  4656. return p;
  4657. @}
  4658. @end example
  4659. @noindent
  4660. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4661. will automatically convert it to type @code{struct intlistlink *}.
  4662. The return value of @code{malloc} is always sufficiently aligned
  4663. (@pxref{Type Alignment}) that it is valid for any data type.
  4664. The test for @code{p == NULL} is necessary because @code{malloc}
  4665. returns a null pointer if it cannot get any storage. We assume that
  4666. the program defines the function @code{fatal} to report a fatal error
  4667. to the user.
  4668. Here's how to add one more integer to the front of such a list:
  4669. @example
  4670. struct intlistlink *my_list = NULL;
  4671. void
  4672. add_to_mylist (int my_int)
  4673. @{
  4674. struct intlistlink *p = alloc_intlistlink ();
  4675. p->datum = my_int;
  4676. p->next = mylist;
  4677. mylist = p;
  4678. @}
  4679. @end example
  4680. The way to free the objects is by calling @code{free}. Here's
  4681. a function to free all the links in one of these lists:
  4682. @example
  4683. void
  4684. free_intlist (struct intlistlink *p)
  4685. @{
  4686. while (p)
  4687. @{
  4688. struct intlistlink *q = p;
  4689. p = p->next;
  4690. free (q);
  4691. @}
  4692. @}
  4693. @end example
  4694. We must extract the @code{next} pointer from the object before freeing
  4695. it, because @code{free} can clobber the data that was in the object.
  4696. For the same reason, the program must not use the list any more after
  4697. freeing its elements. To make sure it won't, it is best to clear out
  4698. the variable where the list was stored, like this:
  4699. @example
  4700. free_intlist (mylist);
  4701. mylist = NULL;
  4702. @end example
  4703. @node Field Offset
  4704. @section Field Offset
  4705. @cindex field offset
  4706. @cindex structure field offset
  4707. @cindex offset of structure fields
  4708. To determine the offset of a given field @var{field} in a structure
  4709. type @var{type}, use the macro @code{offsetof}, which is defined in
  4710. the file @file{stddef.h}. It is used like this:
  4711. @example
  4712. offsetof (@var{type}, @var{field})
  4713. @end example
  4714. Here is an example:
  4715. @example
  4716. struct foo
  4717. @{
  4718. int element;
  4719. struct foo *next;
  4720. @};
  4721. offsetof (struct foo, next)
  4722. /* @r{On most machines that is 4. It may be 8.} */
  4723. @end example
  4724. @node Structure Layout
  4725. @section Structure Layout
  4726. @cindex structure layout
  4727. @cindex layout of structures
  4728. The rest of this chapter covers advanced topics about structures. If
  4729. you are just learning C, you can skip it.
  4730. The precise layout of a @code{struct} type is crucial when using it to
  4731. overlay hardware registers, to access data structures in shared
  4732. memory, or to assemble and disassemble packets for network
  4733. communication. It is also important for avoiding memory waste when
  4734. the program makes many objects of that type. However, the layout
  4735. depends on the target platform. Each platform has conventions for
  4736. structure layout, which compilers need to follow.
  4737. Here are the conventions used on most platforms.
  4738. The structure's fields appear in the structure layout in the order
  4739. they are declared. When possible, consecutive fields occupy
  4740. consecutive bytes within the structure. However, if a field's type
  4741. demands more alignment than it would get that way, C gives it the
  4742. alignment it requires by leaving a gap after the previous field.
  4743. Once all the fields have been laid out, it is possible to determine
  4744. the structure's alignment and size. The structure's alignment is the
  4745. maximum alignment of any of the fields in it. Then the structure's
  4746. size is rounded up to a multiple of its alignment. That may require
  4747. leaving a gap at the end of the structure.
  4748. Here are some examples, where we assume that @code{char} has size and
  4749. alignment 1 (always true), and @code{int} has size and alignment 4
  4750. (true on most kinds of computers):
  4751. @example
  4752. struct foo
  4753. @{
  4754. char a, b;
  4755. int c;
  4756. @};
  4757. @end example
  4758. @noindent
  4759. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4760. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4761. There is a gap of 2 bytes before @code{c}.
  4762. Contrast that with this structure:
  4763. @example
  4764. struct foo
  4765. @{
  4766. char a;
  4767. int c;
  4768. char b;
  4769. @};
  4770. @end example
  4771. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4772. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4773. gaps: three bytes before @code{c}, and three bytes at the end.
  4774. These two structures have the same contents at the C level, but one
  4775. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4776. fields. A reliable way to avoid this sort of wastage is to order the
  4777. fields by size, biggest fields first.
  4778. @node Packed Structures
  4779. @section Packed Structures
  4780. @cindex packed structures
  4781. @cindex @code{__attribute__((packed))}
  4782. In GNU C you can force a structure to be laid out with no gaps by
  4783. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4784. end of the structure type declaration). Here's an example:
  4785. @example
  4786. struct __attribute__((packed)) foo
  4787. @{
  4788. char a;
  4789. int c;
  4790. char b;
  4791. @};
  4792. @end example
  4793. Without @code{__attribute__((packed))}, this structure occupies 12
  4794. bytes (as described in the previous section), assuming 4-byte
  4795. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4796. only 6 bytes long---the sum of the lengths of its fields.
  4797. Use of @code{__attribute__((packed))} often results in fields that
  4798. don't have the normal alignment for their types. Taking the address
  4799. of such a field can result in an invalid pointer because of its
  4800. improper alignment. Dereferencing such a pointer can cause a
  4801. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4802. unaligned pointers.
  4803. @xref{Attributes}.
  4804. @node Bit Fields
  4805. @section Bit Fields
  4806. @cindex bit fields
  4807. A structure field declaration with an integer type can specify the
  4808. number of bits the field should occupy. We call that a @dfn{bit
  4809. field}. These are useful because consecutive bit fields are packed
  4810. into a larger storage unit. For instance,
  4811. @example
  4812. unsigned char opcode: 4;
  4813. @end example
  4814. @noindent
  4815. specifies that this field takes just 4 bits.
  4816. Since it is unsigned, its possible values range
  4817. from 0 to 15. A signed field with 4 bits, such as this,
  4818. @example
  4819. signed char small: 4;
  4820. @end example
  4821. @noindent
  4822. can hold values from -8 to 7.
  4823. You can subdivide a single byte into those two parts by writing
  4824. @example
  4825. unsigned char opcode: 4;
  4826. signed char small: 4;
  4827. @end example
  4828. @noindent
  4829. in the structure. With bit fields, these two numbers fit into
  4830. a single @code{char}.
  4831. Here's how to declare a one-bit field that can hold either 0 or 1:
  4832. @example
  4833. unsigned char special_flag: 1;
  4834. @end example
  4835. You can also use the @code{bool} type for bit fields:
  4836. @example
  4837. bool special_flag: 1;
  4838. @end example
  4839. Except when using @code{bool} (which is always unsigned,
  4840. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4841. for a bit field. There is a default, if that's not specified: the bit
  4842. field is signed if plain @code{char} is signed, except that the option
  4843. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4844. is cleaner not to depend on this default.
  4845. Bit fields are special in that you cannot take their address with
  4846. @samp{&}. They are not stored with the size and alignment appropriate
  4847. for the specified type, so they cannot be addressed through pointers
  4848. to that type.
  4849. @node Bit Field Packing
  4850. @section Bit Field Packing
  4851. Programs to communicate with low-level hardware interfaces need to
  4852. define bit fields laid out to match the hardware data. This section
  4853. explains how to do that.
  4854. Consecutive bit fields are packed together, but each bit field must
  4855. fit within a single object of its specified type. In this example,
  4856. @example
  4857. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4858. @end example
  4859. @noindent
  4860. all five fields fit consecutively into one two-byte @code{short}.
  4861. They need 15 bits, and one @code{short} provides 16. By contrast,
  4862. @example
  4863. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4864. @end example
  4865. @noindent
  4866. needs three bytes. It fits @code{a} and @code{b} into one
  4867. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4868. add up to 9 bits). So @code{c} and @code{d} go into a second
  4869. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4870. Then @code{e} needs a third @code{char}. By contrast,
  4871. @example
  4872. unsigned char a : 3, b : 3;
  4873. unsigned int c : 3;
  4874. unsigned char d : 3, e : 3;
  4875. @end example
  4876. @noindent
  4877. needs only two bytes: the type @code{unsigned int}
  4878. allows @code{c} to straddle bytes that are in the same word.
  4879. You can leave a gap of a specified number of bits by defining a
  4880. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4881. It is allocated space in the structure just as a named bit field would
  4882. be allocated.
  4883. You can force the following bit field to advance to the following
  4884. aligned memory object with @code{@var{type} : 0;}.
  4885. Both of these constructs can syntactically share @var{type} with
  4886. ordinary bit fields. This example illustrates both:
  4887. @example
  4888. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4889. @end example
  4890. @noindent
  4891. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4892. between them. Then @code{: 0} advances to the next @code{int},
  4893. so @code{c} and @code{d} fit into that one.
  4894. These rules for packing bit fields apply to most target platforms,
  4895. including all the usual real computers. A few embedded controllers
  4896. have special layout rules.
  4897. @node const Fields
  4898. @section @code{const} Fields
  4899. @cindex const fields
  4900. @cindex structure fields, constant
  4901. @c ??? Is this a C standard feature?
  4902. A structure field declared @code{const} cannot be assigned to
  4903. (@pxref{const}). For instance, let's define this modified version of
  4904. @code{struct intlistlink}:
  4905. @example
  4906. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4907. @{
  4908. const int datum;
  4909. struct intlistlink *next;
  4910. @};
  4911. @end example
  4912. This structure can be used to prevent part of the code from modifying
  4913. the @code{datum} field:
  4914. @example
  4915. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4916. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4917. struct intlistlink_ro *q
  4918. = (struct intlistlink_ro *) p;
  4919. q->datum = 5; /* @r{Error!} */
  4920. p->datum = 5; /* @r{Valid since @code{*p} is}
  4921. @r{not a @code{struct intlistlink_ro}.} */
  4922. @end example
  4923. A @code{const} field can get a value in two ways: by initialization of
  4924. the whole structure, and by making a pointer-to-structure point to an object
  4925. in which that field already has a value.
  4926. Any @code{const} field in a structure type makes assignment impossible
  4927. for structures of that type (@pxref{Structure Assignment}). That is
  4928. because structure assignment works by assigning the structure's
  4929. fields, one by one.
  4930. @node Zero Length
  4931. @section Arrays of Length Zero
  4932. @cindex array of length zero
  4933. @cindex zero-length arrays
  4934. @cindex length-zero arrays
  4935. GNU C allows zero-length arrays. They are useful as the last element
  4936. of a structure that is really a header for a variable-length object.
  4937. Here's an example, where we construct a variable-size structure
  4938. to hold a line which is @code{this_length} characters long:
  4939. @example
  4940. struct line @{
  4941. int length;
  4942. char contents[0];
  4943. @};
  4944. struct line *thisline
  4945. = ((struct line *)
  4946. malloc (sizeof (struct line)
  4947. + this_length));
  4948. thisline->length = this_length;
  4949. @end example
  4950. In ISO C90, we would have to give @code{contents} a length of 1, which
  4951. means either wasting space or complicating the argument to @code{malloc}.
  4952. @node Flexible Array Fields
  4953. @section Flexible Array Fields
  4954. @cindex flexible array fields
  4955. @cindex array fields, flexible
  4956. The C99 standard adopted a more complex equivalent of zero-length
  4957. array fields. It's called a @dfn{flexible array}, and it's indicated
  4958. by omitting the length, like this:
  4959. @example
  4960. struct line
  4961. @{
  4962. int length;
  4963. char contents[];
  4964. @};
  4965. @end example
  4966. The flexible array has to be the last field in the structure, and there
  4967. must be other fields before it.
  4968. Under the C standard, a structure with a flexible array can't be part
  4969. of another structure, and can't be an element of an array.
  4970. GNU C allows static initialization of flexible array fields. The effect
  4971. is to ``make the array long enough'' for the initializer.
  4972. @example
  4973. struct f1 @{ int x; int y[]; @} f1
  4974. = @{ 1, @{ 2, 3, 4 @} @};
  4975. @end example
  4976. @noindent
  4977. This defines a structure variable named @code{f1}
  4978. whose type is @code{struct f1}. In C, a variable name or function name
  4979. never conflicts with a structure type tag.
  4980. Omitting the flexible array field's size lets the initializer
  4981. determine it. This is allowed only when the flexible array is defined
  4982. in the outermost structure and you declare a variable of that
  4983. structure type. For example:
  4984. @example
  4985. struct foo @{ int x; int y[]; @};
  4986. struct bar @{ struct foo z; @};
  4987. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4988. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4989. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4990. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4991. @end example
  4992. @node Overlaying Structures
  4993. @section Overlaying Different Structures
  4994. @cindex overlaying structures
  4995. @cindex structures, overlaying
  4996. Be careful about using different structure types to refer to the same
  4997. memory within one function, because GNU C can optimize code assuming
  4998. it never does that. @xref{Aliasing}. Here's an example of the kind of
  4999. aliasing that can cause the problem:
  5000. @example
  5001. struct a @{ int size; char *data; @};
  5002. struct b @{ int size; char *data; @};
  5003. struct a foo;
  5004. struct b *q = (struct b *) &foo;
  5005. @end example
  5006. Here @code{q} points to the same memory that the variable @code{foo}
  5007. occupies, but they have two different types. The two types
  5008. @code{struct a} and @code{struct b} are defined alike, but they are
  5009. not the same type. Interspersing references using the two types,
  5010. like this,
  5011. @example
  5012. p->size = 0;
  5013. q->size = 1;
  5014. x = p->size;
  5015. @end example
  5016. @noindent
  5017. allows GNU C to assume that @code{p->size} is still zero when it is
  5018. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5019. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5020. Other compilers might also do this optimization. The ISO C standard
  5021. considers such code erroneous, precisely so that this optimization
  5022. will be valid.
  5023. @node Structure Assignment
  5024. @section Structure Assignment
  5025. @cindex structure assignment
  5026. @cindex assigning structures
  5027. Assignment operating on a structure type copies the structure. The
  5028. left and right operands must have the same type. Here is an example:
  5029. @example
  5030. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5031. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5032. @r{@dots{}}
  5033. struct point @{ double x, y; @};
  5034. struct point *
  5035. copy_point (struct point point)
  5036. @{
  5037. struct point *p
  5038. = (struct point *) malloc (sizeof (struct point));
  5039. if (p == NULL)
  5040. fatal ("Out of memory");
  5041. *p = point;
  5042. return p;
  5043. @}
  5044. @end example
  5045. Notionally, assignment on a structure type works by copying each of
  5046. the fields. Thus, if any of the fields has the @code{const}
  5047. qualifier, that structure type does not allow assignment:
  5048. @example
  5049. struct point @{ const double x, y; @};
  5050. struct point a, b;
  5051. a = b; /* @r{Error!} */
  5052. @end example
  5053. @xref{Assignment Expressions}.
  5054. @node Unions
  5055. @section Unions
  5056. @cindex unions
  5057. @findex union
  5058. A @dfn{union type} defines alternative ways of looking at the same
  5059. piece of memory. Each alternative view is defined with a data type,
  5060. and identified by a name. A union definition looks like this:
  5061. @example
  5062. union @var{name}
  5063. @{
  5064. @var{alternative declarations}@r{@dots{}}
  5065. @};
  5066. @end example
  5067. Each alternative declaration looks like a structure field declaration,
  5068. except that it can't be a bit field. For instance,
  5069. @example
  5070. union number
  5071. @{
  5072. long int integer;
  5073. double float;
  5074. @}
  5075. @end example
  5076. @noindent
  5077. lets you store either an integer (type @code{long int}) or a floating
  5078. point number (type @code{double}) in the same place in memory. The
  5079. length and alignment of the union type are the maximum of all the
  5080. alternatives---they do not have to be the same. In this union
  5081. example, @code{double} probably takes more space than @code{long int},
  5082. but that doesn't cause a problem in programs that use the union in the
  5083. normal way.
  5084. The members don't have to be different in data type. Sometimes
  5085. each member pertains to a way the data will be used. For instance,
  5086. @example
  5087. union datum
  5088. @{
  5089. double latitude;
  5090. double longitude;
  5091. double height;
  5092. double weight;
  5093. int continent;
  5094. @}
  5095. @end example
  5096. This union holds one of several kinds of data; most kinds are floating
  5097. points, but the value can also be a code for a continent which is an
  5098. integer. You @emph{could} use one member of type @code{double} to
  5099. access all the values which have that type, but the different member
  5100. names will make the program clearer.
  5101. The alignment of a union type is the maximum of the alignments of the
  5102. alternatives. The size of the union type is the maximum of the sizes
  5103. of the alternatives, rounded up to a multiple of the alignment
  5104. (because every type's size must be a multiple of its alignment).
  5105. All the union alternatives start at the address of the union itself.
  5106. If an alternative is shorter than the union as a whole, it occupies
  5107. the first part of the union's storage, leaving the last part unused
  5108. @emph{for that alternative}.
  5109. @strong{Warning:} if the code stores data using one union alternative
  5110. and accesses it with another, the results depend on the kind of
  5111. computer in use. Only wizards should try to do this. However, when
  5112. you need to do this, a union is a clean way to do it.
  5113. Assignment works on any union type by copying the entire value.
  5114. @node Packing With Unions
  5115. @section Packing With Unions
  5116. Sometimes we design a union with the intention of packing various
  5117. kinds of objects into a certain amount of memory space. For example.
  5118. @example
  5119. union bytes8
  5120. @{
  5121. long long big_int_elt;
  5122. double double_elt;
  5123. struct @{ int first, second; @} two_ints;
  5124. struct @{ void *first, *second; @} two_ptrs;
  5125. @};
  5126. union bytes8 *p;
  5127. @end example
  5128. This union makes it possible to look at 8 bytes of data that @code{p}
  5129. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5130. single floating-point number (@code{p->double_elt}), as a pair of
  5131. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5132. as a pair of pointers (@code{p->two_ptrs.first} and
  5133. @code{p->two_ptrs.second}).
  5134. To pack storage with such a union makes assumptions about the sizes of
  5135. all the types involved. This particular union was written expecting a
  5136. pointer to have the same size as @code{int}. On a machine where one
  5137. pointer takes 8 bytes, the code using this union probably won't work
  5138. as expected. The union, as such, will function correctly---if you
  5139. store two values through @code{two_ints} and extract them through
  5140. @code{two_ints}, you will get the same integers back---but the part of
  5141. the program that expects the union to be 8 bytes long could
  5142. malfunction, or at least use too much space.
  5143. The above example shows one case where a @code{struct} type with no
  5144. tag can be useful. Another way to get effectively the same result
  5145. is with arrays as members of the union:
  5146. @example
  5147. union eight_bytes
  5148. @{
  5149. long long big_int_elt;
  5150. double double_elt;
  5151. int two_ints[2];
  5152. void *two_ptrs[2];
  5153. @};
  5154. @end example
  5155. @node Cast to Union
  5156. @section Cast to a Union Type
  5157. @cindex cast to a union
  5158. @cindex union, casting to a
  5159. In GNU C, you can explicitly cast any of the alternative types to the
  5160. union type; for instance,
  5161. @example
  5162. (union eight_bytes) (long long) 5
  5163. @end example
  5164. @noindent
  5165. makes a value of type @code{union eight_bytes} which gets its contents
  5166. through the alternative named @code{big_int_elt}.
  5167. The value being cast must exactly match the type of the alternative,
  5168. so this is not valid:
  5169. @example
  5170. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5171. @end example
  5172. A cast to union type looks like any other cast, except that the type
  5173. specified is a union type. You can specify the type either with
  5174. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5175. Typedef Names}).
  5176. Using the cast as the right-hand side of an assignment to a variable of
  5177. union type is equivalent to storing in an alternative of the union:
  5178. @example
  5179. union foo u;
  5180. u = (union foo) x @r{means} u.i = x
  5181. u = (union foo) y @r{means} u.d = y
  5182. @end example
  5183. You can also use the union cast as a function argument:
  5184. @example
  5185. void hack (union foo);
  5186. @r{@dots{}}
  5187. hack ((union foo) x);
  5188. @end example
  5189. @node Structure Constructors
  5190. @section Structure Constructors
  5191. @cindex structure constructors
  5192. @cindex constructors, structure
  5193. You can construct a structure value by writing its type in
  5194. parentheses, followed by an initializer that would be valid in a
  5195. declaration for that type. For instance, given this declaration,
  5196. @example
  5197. struct foo @{int a; char b[2];@} structure;
  5198. @end example
  5199. @noindent
  5200. you can create a @code{struct foo} value as follows:
  5201. @example
  5202. ((struct foo) @{x + y, 'a', 0@})
  5203. @end example
  5204. @noindent
  5205. This specifies @code{x + y} for field @code{a},
  5206. the character @samp{a} for field @code{b}'s element 0,
  5207. and the null character for field @code{b}'s element 1.
  5208. The parentheses around that constructor are to necessary, but we
  5209. recommend writing them to make the nesting of the containing
  5210. expression clearer.
  5211. You can also show the nesting of the two by writing it like
  5212. this:
  5213. @example
  5214. ((struct foo) @{x + y, @{'a', 0@} @})
  5215. @end example
  5216. Each of those is equivalent to writing the following statement
  5217. expression (@pxref{Statement Exprs}):
  5218. @example
  5219. (@{
  5220. struct foo temp = @{x + y, 'a', 0@};
  5221. temp;
  5222. @})
  5223. @end example
  5224. You can also create a union value this way, but it is not especially
  5225. useful since that is equivalent to doing a cast:
  5226. @example
  5227. ((union whosis) @{@var{value}@})
  5228. @r{is equivalent to}
  5229. ((union whosis) (@var{value}))
  5230. @end example
  5231. @node Unnamed Types as Fields
  5232. @section Unnamed Types as Fields
  5233. @cindex unnamed structures
  5234. @cindex unnamed unions
  5235. @cindex structures, unnamed
  5236. @cindex unions, unnamed
  5237. A structure or a union can contain, as fields,
  5238. unnamed structures and unions. Here's an example:
  5239. @example
  5240. struct
  5241. @{
  5242. int a;
  5243. union
  5244. @{
  5245. int b;
  5246. float c;
  5247. @};
  5248. int d;
  5249. @} foo;
  5250. @end example
  5251. @noindent
  5252. You can access the fields of the unnamed union within @code{foo} as if they
  5253. were individual fields at the same level as the union definition:
  5254. @example
  5255. foo.a = 42;
  5256. foo.b = 47;
  5257. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5258. foo.d = 314;
  5259. @end example
  5260. Avoid using field names that could cause ambiguity. For example, with
  5261. this definition:
  5262. @example
  5263. struct
  5264. @{
  5265. int a;
  5266. struct
  5267. @{
  5268. int a;
  5269. float b;
  5270. @};
  5271. @} foo;
  5272. @end example
  5273. @noindent
  5274. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5275. an error when a definition is ambiguous in this way.
  5276. @node Incomplete Types
  5277. @section Incomplete Types
  5278. @cindex incomplete types
  5279. @cindex types, incomplete
  5280. A type that has not been fully defined is called an @dfn{incomplete
  5281. type}. Structure and union types are incomplete when the code makes a
  5282. forward reference, such as @code{struct foo}, before defining the
  5283. type. An array type is incomplete when its length is unspecified.
  5284. You can't use an incomplete type to declare a variable or field, or
  5285. use it for a function parameter or return type. The operators
  5286. @code{sizeof} and @code{_Alignof} give errors when used on an
  5287. incomplete type.
  5288. However, you can define a pointer to an incomplete type, and declare a
  5289. variable or field with such a pointer type. In general, you can do
  5290. everything with such pointers except dereference them. For example:
  5291. @example
  5292. extern void bar (struct mysterious_value *);
  5293. void
  5294. foo (struct mysterious_value *arg)
  5295. @{
  5296. bar (arg);
  5297. @}
  5298. @r{@dots{}}
  5299. @{
  5300. struct mysterious_value *p, **q;
  5301. p = *q;
  5302. foo (p);
  5303. @}
  5304. @end example
  5305. @noindent
  5306. These examples are valid because the code doesn't try to understand
  5307. what @code{p} points to; it just passes the pointer around.
  5308. (Presumably @code{bar} is defined in some other file that really does
  5309. have a definition for @code{struct mysterious_value}.) However,
  5310. dereferencing the pointer would get an error; that requires a
  5311. definition for the structure type.
  5312. @node Intertwined Incomplete Types
  5313. @section Intertwined Incomplete Types
  5314. When several structure types contain pointers to each other, you can
  5315. define the types in any order because pointers to types that come
  5316. later are incomplete types. Thus,
  5317. Here is an example.
  5318. @example
  5319. /* @r{An employee record points to a group.} */
  5320. struct employee
  5321. @{
  5322. char *name;
  5323. @r{@dots{}}
  5324. struct group *group; /* @r{incomplete type.} */
  5325. @r{@dots{}}
  5326. @};
  5327. /* @r{An employee list points to employees.} */
  5328. struct employee_list
  5329. @{
  5330. struct employee *this_one;
  5331. struct employee_list *next; /* @r{incomplete type.} */
  5332. @r{@dots{}}
  5333. @};
  5334. /* @r{A group points to one employee_list.} */
  5335. struct group
  5336. @{
  5337. char *name;
  5338. @r{@dots{}}
  5339. struct employee_list *employees;
  5340. @r{@dots{}}
  5341. @};
  5342. @end example
  5343. @node Type Tags
  5344. @section Type Tags
  5345. @cindex type tags
  5346. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5347. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5348. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5349. name or function name; the type tags have a separate @dfn{name space}.
  5350. Thus, there is no name conflict in this code:
  5351. @example
  5352. struct pair @{ int a, b; @};
  5353. int pair = 1;
  5354. @end example
  5355. @noindent
  5356. nor in this one:
  5357. @example
  5358. struct pair @{ int a, b; @} pair;
  5359. @end example
  5360. @noindent
  5361. where @code{pair} is both a structure type tag and a variable name.
  5362. However, @code{struct}, @code{union}, and @code{enum} share the same
  5363. name space of tags, so this is a conflict:
  5364. @example
  5365. struct pair @{ int a, b; @};
  5366. enum pair @{ c, d @};
  5367. @end example
  5368. @noindent
  5369. and so is this:
  5370. @example
  5371. struct pair @{ int a, b; @};
  5372. struct pair @{ int c, d; @};
  5373. @end example
  5374. When the code defines a type tag inside a block, the tag's scope is
  5375. limited to that block (as for local variables). Two definitions for
  5376. one type tag do not conflict if they are in different scopes; rather,
  5377. each is valid in its scope. For example,
  5378. @example
  5379. struct pair @{ int a, b; @};
  5380. void
  5381. pair_up_doubles (int len, double array[])
  5382. @{
  5383. struct pair @{ double a, b; @};
  5384. @r{@dots{}}
  5385. @}
  5386. @end example
  5387. @noindent
  5388. has two definitions for @code{struct pair} which do not conflict. The
  5389. one inside the function applies only within the definition of
  5390. @code{pair_up_doubles}. Within its scope, that definition
  5391. @dfn{shadows} the outer definition.
  5392. If @code{struct pair} appears inside the function body, before the
  5393. inner definition, it refers to the outer definition---the only one
  5394. that has been seen at that point. Thus, in this code,
  5395. @example
  5396. struct pair @{ int a, b; @};
  5397. void
  5398. pair_up_doubles (int len, double array[])
  5399. @{
  5400. struct two_pairs @{ struct pair *p, *q; @};
  5401. struct pair @{ double a, b; @};
  5402. @r{@dots{}}
  5403. @}
  5404. @end example
  5405. @noindent
  5406. the structure @code{two_pairs} has pointers to the outer definition of
  5407. @code{struct pair}, which is probably not desirable.
  5408. To prevent that, you can write @code{struct pair;} inside the function
  5409. body as a variable declaration with no variables. This is a
  5410. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5411. type tag local to the current block, with the details of the type to
  5412. come later. Here's an example:
  5413. @example
  5414. void
  5415. pair_up_doubles (int len, double array[])
  5416. @{
  5417. /* @r{Forward declaration for @code{pair}.} */
  5418. struct pair;
  5419. struct two_pairs @{ struct pair *p, *q; @};
  5420. /* @r{Give the details.} */
  5421. struct pair @{ double a, b; @};
  5422. @r{@dots{}}
  5423. @}
  5424. @end example
  5425. However, the cleanest practice is to avoid shadowing type tags.
  5426. @node Arrays
  5427. @chapter Arrays
  5428. @cindex array
  5429. @cindex elements of arrays
  5430. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5431. all of the same data type. Each element is identified by its numeric
  5432. @var{index} within the array.
  5433. We presented arrays of numbers in the sample programs early in this
  5434. manual (@pxref{Array Example}). However, arrays can have elements of
  5435. any data type, including pointers, structures, unions, and other
  5436. arrays.
  5437. If you know another programming language, you may suppose that you know all
  5438. about arrays, but C arrays have special quirks, so in this chapter we
  5439. collect all the information about arrays in C@.
  5440. The elements of a C array are allocated consecutively in memory,
  5441. with no gaps between them. Each element is aligned as required
  5442. for its data type (@pxref{Type Alignment}).
  5443. @menu
  5444. * Accessing Array Elements:: How to access individual elements of an array.
  5445. * Declaring an Array:: How to name and reserve space for a new array.
  5446. * Strings:: A string in C is a special case of array.
  5447. * Array Type Designators:: Referring to a specific array type.
  5448. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5449. * Limitations of C Arrays:: Arrays are not first-class objects.
  5450. * Multidimensional Arrays:: Arrays of arrays.
  5451. * Constructing Array Values:: Assigning values to an entire array at once.
  5452. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5453. @end menu
  5454. @node Accessing Array Elements
  5455. @section Accessing Array Elements
  5456. @cindex accessing array elements
  5457. @cindex array elements, accessing
  5458. If the variable @code{a} is an array, the @var{n}th element of
  5459. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5460. an element's value or to assign to it:
  5461. @example
  5462. x = a[5];
  5463. a[6] = 1;
  5464. @end example
  5465. @noindent
  5466. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5467. lvalue.
  5468. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5469. valid index is one less than the number of elements.
  5470. The C language does not check whether array indices are in bounds, so
  5471. if the code uses an out-of-range index, it will access memory outside the
  5472. array.
  5473. @strong{Warning:} Using only valid index values in C is the
  5474. programmer's responsibility.
  5475. Array indexing in C is not a primitive operation: it is defined in
  5476. terms of pointer arithmetic and dereferencing. Now that we know
  5477. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5478. its job.
  5479. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5480. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5481. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5482. When an expression with array type (such as @code{a}) appears as part
  5483. of a larger C expression, it is converted automatically to a pointer
  5484. to element zero of that array. For instance, @code{a} in an
  5485. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5486. computed as @code{*(&a[0]+i)}.
  5487. Now we can analyze how that expression gives us the desired element of
  5488. the array. It makes a pointer to element 0 of @code{a}, advances it
  5489. by the value of @code{i}, and dereferences that pointer.
  5490. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5491. @node Declaring an Array
  5492. @section Declaring an Array
  5493. @cindex declaring an array
  5494. @cindex array, declaring
  5495. To make an array declaration, write @code{[@var{length}]} after the
  5496. name being declared. This construct is valid in the declaration of a
  5497. variable, a function parameter, a function value type (the value can't
  5498. be an array, but it can be a pointer to one), a structure field, or a
  5499. union alternative.
  5500. The surrounding declaration specifies the element type of the array;
  5501. that can be any type of data, but not @code{void} or a function type.
  5502. For instance,
  5503. @example
  5504. double a[5];
  5505. @end example
  5506. @noindent
  5507. declares @code{a} as an array of 5 @code{double}s.
  5508. @example
  5509. struct foo bstruct[length];
  5510. @end example
  5511. @noindent
  5512. declares @code{bstruct} as an array of @code{length} objects of type
  5513. @code{struct foo}. A variable array size like this is allowed when
  5514. the array is not file-scope.
  5515. Other declaration constructs can nest within the array declaration
  5516. construct. For instance:
  5517. @example
  5518. struct foo *b[length];
  5519. @end example
  5520. @noindent
  5521. declares @code{b} as an array of @code{length} pointers to
  5522. @code{struct foo}. This shows that the length need not be a constant
  5523. (@pxref{Arrays of Variable Length}).
  5524. @example
  5525. double (*c)[5];
  5526. @end example
  5527. @noindent
  5528. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5529. @example
  5530. char *(*f (int))[5];
  5531. @end example
  5532. @noindent
  5533. declares @code{f} as a function taking an @code{int} argument and
  5534. returning a pointer to an array of 5 strings (pointers to
  5535. @code{char}s).
  5536. @example
  5537. double aa[5][10];
  5538. @end example
  5539. @noindent
  5540. declares @code{aa} as an array of 5 elements, each of which is an
  5541. array of 10 @code{double}s. This shows how to declare a
  5542. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5543. All these declarations specify the array's length, which is needed in
  5544. these cases in order to allocate storage for the array.
  5545. @node Strings
  5546. @section Strings
  5547. @cindex string
  5548. A string in C is a sequence of elements of type @code{char},
  5549. terminated with the null character, the character with code zero.
  5550. Programs often need to use strings with specific, fixed contents. To
  5551. write one in a C program, use a @dfn{string constant} such as
  5552. @code{"Take me to your leader!"}. The data type of a string constant
  5553. is @code{char *}. For the full syntactic details of writing string
  5554. constants, @ref{String Constants}.
  5555. To declare a place to store a non-constant string, declare an array of
  5556. @code{char}. Keep in mind that it must include one extra @code{char}
  5557. for the terminating null. For instance,
  5558. @example
  5559. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5560. @end example
  5561. @noindent
  5562. declares an array named @samp{text} with six elements---five letters
  5563. and the terminating null character. An equivalent way to get the same
  5564. result is this,
  5565. @example
  5566. char text[] = "Hello";
  5567. @end example
  5568. @noindent
  5569. which copies the elements of the string constant, including @emph{its}
  5570. terminating null character.
  5571. @example
  5572. char message[200];
  5573. @end example
  5574. @noindent
  5575. declares an array long enough to hold a string of 199 ASCII characters
  5576. plus the terminating null character.
  5577. When you store a string into @code{message} be sure to check or prove
  5578. that the length does not exceed its size. For example,
  5579. @example
  5580. void
  5581. set_message (char *text)
  5582. @{
  5583. int i;
  5584. for (i = 0; i < sizeof (message); i++)
  5585. @{
  5586. message[i] = text[i];
  5587. if (text[i] == 0)
  5588. return;
  5589. @}
  5590. fatal_error ("Message is too long for `message');
  5591. @}
  5592. @end example
  5593. It's easy to do this with the standard library function
  5594. @code{strncpy}, which fills out the whole destination array (up to a
  5595. specified length) with null characters. Thus, if the last character
  5596. of the destination is not null, the string did not fit. Many system
  5597. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5598. to run faster than an explicit @code{for}-loop.
  5599. Here's what the code looks like:
  5600. @example
  5601. void
  5602. set_message (char *text)
  5603. @{
  5604. strncpy (message, text, sizeof (message));
  5605. if (message[sizeof (message) - 1] != 0)
  5606. fatal_error ("Message is too long for `message');
  5607. @}
  5608. @end example
  5609. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5610. Library Reference Manual}, for more information about the standard
  5611. library functions for operating on strings.
  5612. You can avoid putting a fixed length limit on strings you construct or
  5613. operate on by allocating the space for them dynamically.
  5614. @xref{Dynamic Memory Allocation}.
  5615. @node Array Type Designators
  5616. @section Array Type Designators
  5617. Every C type has a type designator, which you make by deleting the
  5618. variable name and the semicolon from a declaration (@pxref{Type
  5619. Designators}). The designators for array types follow this rule, but
  5620. they may appear surprising.
  5621. @example
  5622. @r{type} int a[5]; @r{designator} int [5]
  5623. @r{type} double a[5][3]; @r{designator} double [5][3]
  5624. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5625. @end example
  5626. @node Incomplete Array Types
  5627. @section Incomplete Array Types
  5628. @cindex incomplete array types
  5629. @cindex array types, incomplete
  5630. An array is equivalent, for most purposes, to a pointer to its zeroth
  5631. element. When that is true, the length of the array is irrelevant.
  5632. The length needs to be known only for allocating space for the array, or
  5633. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5634. contexts C allows
  5635. @itemize @bullet
  5636. @item
  5637. An @code{extern} declaration says how to refer to a variable allocated
  5638. elsewhere. It does not need to allocate space for the variable,
  5639. so if it is an array, you can omit the length. For example,
  5640. @example
  5641. extern int foo[];
  5642. @end example
  5643. @item
  5644. When declaring a function parameter as an array, the argument value
  5645. passed to the function is really a pointer to the array's zeroth
  5646. element. This value does not say how long the array really is, there
  5647. is no need to declare it. For example,
  5648. @example
  5649. int
  5650. func (int foo[])
  5651. @end example
  5652. @end itemize
  5653. These declarations are examples of @dfn{incomplete} array types, types
  5654. that are not fully specified. The incompleteness makes no difference
  5655. for accessing elements of the array, but it matters for some other
  5656. things. For instance, @code{sizeof} is not allowed on an incomplete
  5657. type.
  5658. With multidimensional arrays, only the first dimension can be omitted:
  5659. @example
  5660. extern struct chesspiece *funnyboard foo[][8];
  5661. @end example
  5662. In other words, the code doesn't have to say how many rows there are,
  5663. but it must state how big each row is.
  5664. @node Limitations of C Arrays
  5665. @section Limitations of C Arrays
  5666. @cindex limitations of C arrays
  5667. @cindex first-class object
  5668. Arrays have quirks in C because they are not ``first-class objects'':
  5669. there is no way in C to operate on an array as a unit.
  5670. The other composite objects in C, structures and unions, are
  5671. first-class objects: a C program can copy a structure or union value
  5672. in an assignment, or pass one as an argument to a function, or make a
  5673. function return one. You can't do those things with an array in C@.
  5674. That is because a value you can operate on never has an array type.
  5675. An expression in C can have an array type, but that doesn't produce
  5676. the array as a value. Instead it is converted automatically to a
  5677. pointer to the array's element at index zero. The code can operate
  5678. on the pointer, and through that on individual elements of the array,
  5679. but it can't get and operate on the array as a unit.
  5680. There are three exceptions to this conversion rule, but none of them
  5681. offers a way to operate on the array as a whole.
  5682. First, @samp{&} applied to an expression with array type gives you the
  5683. address of the array, as an array type. However, you can't operate on the
  5684. whole array that way---if you apply @samp{*} to get the array back,
  5685. that expression converts, as usual, to a pointer to its zeroth
  5686. element.
  5687. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5688. @code{typeof} do not convert the array to a pointer; they leave it as
  5689. an array. But they don't operate on the array's data---they only give
  5690. information about its type.
  5691. Third, a string constant used as an initializer for an array is not
  5692. converted to a pointer---rather, the declaration copies the
  5693. @emph{contents} of that string in that one special case.
  5694. You @emph{can} copy the contents of an array, just not with an
  5695. assignment operator. You can do it by calling the library function
  5696. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5697. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5698. when a structure contains just an array, you can copy that structure.
  5699. An array itself is an lvalue if it is a declared variable, or part of
  5700. a structure or union that is an lvalue. When you construct an array
  5701. from elements (@pxref{Constructing Array Values}), that array is not
  5702. an lvalue.
  5703. @node Multidimensional Arrays
  5704. @section Multidimensional Arrays
  5705. @cindex multidimensional arrays
  5706. @cindex array, multidimensional
  5707. Strictly speaking, all arrays in C are unidimensional. However, you
  5708. can create an array of arrays, which is more or less equivalent to a
  5709. multidimensional array. For example,
  5710. @example
  5711. struct chesspiece *board[8][8];
  5712. @end example
  5713. @noindent
  5714. declares an array of 8 arrays of 8 pointers to @code{struct
  5715. chesspiece}. This data type could represent the state of a chess
  5716. game. To access one square's contents requires two array index
  5717. operations, one for each dimension. For instance, you can write
  5718. @code{board[row][column]}, assuming @code{row} and @code{column}
  5719. are variables with integer values in the proper range.
  5720. How does C understand @code{board[row][column]}? First of all,
  5721. @code{board} is converted automatically to a pointer to the zeroth
  5722. element (at index zero) of @code{board}. Adding @code{row} to that
  5723. makes it point to the desired element. Thus, @code{board[row]}'s
  5724. value is an element of @code{board}---an array of 8 pointers.
  5725. However, as an expression with array type, it is converted
  5726. automatically to a pointer to the array's zeroth element. The second
  5727. array index operation, @code{[column]}, accesses the chosen element
  5728. from that array.
  5729. As this shows, pointer-to-array types are meaningful in C@.
  5730. You can declare a variable that points to a row in a chess board
  5731. like this:
  5732. @example
  5733. struct chesspiece *(*rowptr)[8];
  5734. @end example
  5735. @noindent
  5736. This points to an array of 8 pointers to @code{struct chesspiece}.
  5737. You can assign to it as follows:
  5738. @example
  5739. rowptr = &board[5];
  5740. @end example
  5741. The dimensions don't have to be equal in length. Here we declare
  5742. @code{statepop} as an array to hold the population of each state in
  5743. the United States for each year since 1900:
  5744. @example
  5745. #define NSTATES 50
  5746. @{
  5747. int nyears = current_year - 1900 + 1;
  5748. int statepop[NSTATES][nyears];
  5749. @r{@dots{}}
  5750. @}
  5751. @end example
  5752. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5753. each indexed by the year (counting from 1900). Thus, to get the
  5754. element for a particular state and year, we must subscript it first
  5755. by the number that indicates the state, and second by the index for
  5756. the year:
  5757. @example
  5758. statepop[state][year - 1900]
  5759. @end example
  5760. @cindex array, layout in memory
  5761. The subarrays within the multidimensional array are allocated
  5762. consecutively in memory, and within each subarray, its elements are
  5763. allocated consecutively in memory. The most efficient way to process
  5764. all the elements in the array is to scan the last subscript in the
  5765. innermost loop. This means consecutive accesses go to consecutive
  5766. memory locations, which optimizes use of the processor's memory cache.
  5767. For example:
  5768. @example
  5769. int total = 0;
  5770. float average;
  5771. for (int state = 0; state < NSTATES, ++state)
  5772. @{
  5773. for (int year = 0; year < nyears; ++year)
  5774. @{
  5775. total += statepop[state][year];
  5776. @}
  5777. @}
  5778. average = total / nyears;
  5779. @end example
  5780. C's layout for multidimensional arrays is different from Fortran's
  5781. layout. In Fortran, a multidimensional array is not an array of
  5782. arrays; rather, multidimensional arrays are a primitive feature, and
  5783. it is the first index that varies most rapidly between consecutive
  5784. memory locations. Thus, the memory layout of a 50x114 array in C
  5785. matches that of a 114x50 array in Fortran.
  5786. @node Constructing Array Values
  5787. @section Constructing Array Values
  5788. @cindex constructing array values
  5789. @cindex array values, constructing
  5790. You can construct an array from elements by writing them inside
  5791. braces, and preceding all that with the array type's designator in
  5792. parentheses. There is no need to specify the array length, since the
  5793. number of elements determines that. The constructor looks like this:
  5794. @example
  5795. (@var{elttype}[]) @{ @var{elements} @};
  5796. @end example
  5797. Here is an example, which constructs an array of string pointers:
  5798. @example
  5799. (char *[]) @{ "x", "y", "z" @};
  5800. @end example
  5801. That's equivalent in effect to declaring an array with the same
  5802. initializer, like this:
  5803. @example
  5804. char *array[] = @{ "x", "y", "z" @};
  5805. @end example
  5806. and then using the array.
  5807. If all the elements are simple constant expressions, or made up of
  5808. such, then the compound literal can be coerced to a pointer to its
  5809. zeroth element and used to initialize a file-scope variable
  5810. (@pxref{File-Scope Variables}), as shown here:
  5811. @example
  5812. char **foo = (char *[]) @{ "x", "y", "z" @};
  5813. @end example
  5814. @noindent
  5815. The data type of @code{foo} is @code{char **}, which is a pointer
  5816. type, not an array type. The declaration is equivalent to defining
  5817. and then using an array-type variable:
  5818. @example
  5819. char *nameless_array[] = @{ "x", "y", "z" @};
  5820. char **foo = &nameless_array[0];
  5821. @end example
  5822. @node Arrays of Variable Length
  5823. @section Arrays of Variable Length
  5824. @cindex array of variable length
  5825. @cindex variable-length arrays
  5826. In GNU C, you can declare variable-length arrays like any other
  5827. arrays, but with a length that is not a constant expression. The
  5828. storage is allocated at the point of declaration and deallocated when
  5829. the block scope containing the declaration exits. For example:
  5830. @example
  5831. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5832. #include <string.h> /* @r{Declares @code{str}.} */
  5833. FILE *
  5834. concat_fopen (char *s1, char *s2, char *mode)
  5835. @{
  5836. char str[strlen (s1) + strlen (s2) + 1];
  5837. strcpy (str, s1);
  5838. strcat (str, s2);
  5839. return fopen (str, mode);
  5840. @}
  5841. @end example
  5842. @noindent
  5843. (This uses some standard library functions; see @ref{String and Array
  5844. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5845. The length of an array is computed once when the storage is allocated
  5846. and is remembered for the scope of the array in case it is used in
  5847. @code{sizeof}.
  5848. @strong{Warning:} don't allocate a variable-length array if the size
  5849. might be very large (more than 100,000), or in a recursive function,
  5850. because that is likely to cause stack overflow. Allocate the array
  5851. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5852. Jumping or breaking out of the scope of the array name deallocates the
  5853. storage. Jumping into the scope is not allowed; that gives an error
  5854. message.
  5855. You can also use variable-length arrays as arguments to functions:
  5856. @example
  5857. struct entry
  5858. tester (int len, char data[len][len])
  5859. @{
  5860. @r{@dots{}}
  5861. @}
  5862. @end example
  5863. As usual, a function argument declared with an array type
  5864. is really a pointer to an array that already exists.
  5865. Calling the function does not allocate the array, so there's no
  5866. particular danger of stack overflow in using this construct.
  5867. To pass the array first and the length afterward, use a forward
  5868. declaration in the function's parameter list (another GNU extension).
  5869. For example,
  5870. @example
  5871. struct entry
  5872. tester (int len; char data[len][len], int len)
  5873. @{
  5874. @r{@dots{}}
  5875. @}
  5876. @end example
  5877. The @code{int len} before the semicolon is a @dfn{parameter forward
  5878. declaration}, and it serves the purpose of making the name @code{len}
  5879. known when the declaration of @code{data} is parsed.
  5880. You can write any number of such parameter forward declarations in the
  5881. parameter list. They can be separated by commas or semicolons, but
  5882. the last one must end with a semicolon, which is followed by the
  5883. ``real'' parameter declarations. Each forward declaration must match
  5884. a ``real'' declaration in parameter name and data type. ISO C11 does
  5885. not support parameter forward declarations.
  5886. @node Enumeration Types
  5887. @chapter Enumeration Types
  5888. @cindex enumeration types
  5889. @cindex types, enumeration
  5890. @cindex enumerator
  5891. An @dfn{enumeration type} represents a limited set of integer values,
  5892. each with a name. It is effectively equivalent to a primitive integer
  5893. type.
  5894. Suppose we have a list of possible emotional states to store in an
  5895. integer variable. We can give names to these alternative values with
  5896. an enumeration:
  5897. @example
  5898. enum emotion_state @{ neutral, happy, sad, worried,
  5899. calm, nervous @};
  5900. @end example
  5901. @noindent
  5902. (Never mind that this is a simplistic way to classify emotional states;
  5903. it's just a code example.)
  5904. The names inside the enumeration are called @dfn{enumerators}. The
  5905. enumeration type defines them as constants, and their values are
  5906. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5907. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5908. the enumerators explicitly like this:
  5909. @example
  5910. enum emotion_state @{ neutral = 2, happy = 5,
  5911. sad = 20, worried = 10,
  5912. calm = -5, nervous = -300 @};
  5913. @end example
  5914. Each enumerator which does not specify a value gets value zero
  5915. (if it is at the beginning) or the next consecutive integer.
  5916. @example
  5917. /* @r{@code{neutral} is 0 by default,}
  5918. @r{and @code{worried} is 21 by default.} */
  5919. enum emotion_state @{ neutral,
  5920. happy = 5, sad = 20, worried,
  5921. calm = -5, nervous = -300 @};
  5922. @end example
  5923. If an enumerator is obsolete, you can specify that using it should
  5924. cause a warning, by including an attribute in the enumerator's
  5925. declaration. Here is how @code{happy} would look with this
  5926. attribute:
  5927. @example
  5928. happy __attribute__
  5929. ((deprecated
  5930. ("impossible under plutocratic rule")))
  5931. = 5,
  5932. @end example
  5933. @xref{Attributes}.
  5934. You can declare variables with the enumeration type:
  5935. @example
  5936. enum emotion_state feelings_now;
  5937. @end example
  5938. In the C code itself, this is equivalent to declaring the variable
  5939. @code{int}. (If all the enumeration values are positive, it is
  5940. equivalent to @code{unsigned int}.) However, declaring it with the
  5941. enumeration type has an advantage in debugging, because GDB knows it
  5942. should display the current value of the variable using the
  5943. corresponding name. If the variable's type is @code{int}, GDB can
  5944. only show the value as a number.
  5945. The identifier that follows @code{enum} is called a @dfn{type tag}
  5946. since it distinguishes different enumeration types. Type tags are in
  5947. a separate name space and belong to scopes like most other names in C@.
  5948. @xref{Type Tags}, for explanation.
  5949. You can predeclare an @code{enum} type tag like a structure or union
  5950. type tag, like this:
  5951. @example
  5952. enum foo;
  5953. @end example
  5954. @noindent
  5955. The @code{enum} type is incomplete until you finish defining it.
  5956. You can optionally include a trailing comma at the end of a list of
  5957. enumeration values:
  5958. @example
  5959. enum emotion_state @{ neutral, happy, sad, worried,
  5960. calm, nervous, @};
  5961. @end example
  5962. @noindent
  5963. This is useful in some macro definitions, since it enables you to
  5964. assemble the list of enumerators without knowing which one is last.
  5965. The extra comma does not change the meaning of the enumeration in any
  5966. way.
  5967. @node Defining Typedef Names
  5968. @chapter Defining Typedef Names
  5969. @cindex typedef names
  5970. @findex typedef
  5971. You can define a data type keyword as an alias for any type, and then
  5972. use the alias syntactically like a built-in type keyword such as
  5973. @code{int}. You do this using @code{typedef}, so these aliases are
  5974. also called @dfn{typedef names}.
  5975. @code{typedef} is followed by text that looks just like a variable
  5976. declaration, but instead of declaring variables it defines data type
  5977. keywords.
  5978. Here's how to define @code{fooptr} as a typedef alias for the type
  5979. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5980. with that type:
  5981. @example
  5982. typedef struct foo *fooptr;
  5983. fooptr x, y;
  5984. @end example
  5985. @noindent
  5986. That declaration is equivalent to the following one:
  5987. @example
  5988. struct foo *x, *y;
  5989. @end example
  5990. You can define a typedef alias for any type. For instance, this makes
  5991. @code{frobcount} an alias for type @code{int}:
  5992. @example
  5993. typedef int frobcount;
  5994. @end example
  5995. @noindent
  5996. This doesn't define a new type distinct from @code{int}. Rather,
  5997. @code{frobcount} is another name for the type @code{int}. Once the
  5998. variable is declared, it makes no difference which name the
  5999. declaration used.
  6000. There is a syntactic difference, however, between @code{frobcount} and
  6001. @code{int}: A typedef name cannot be used with
  6002. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6003. to specify the type all by itself. So you can't write this:
  6004. @example
  6005. unsigned frobcount f1; /* @r{Error!} */
  6006. @end example
  6007. But you can write this:
  6008. @example
  6009. typedef unsigned int unsigned_frobcount;
  6010. unsigned_frobcount f1;
  6011. @end example
  6012. In other words, a typedef name is not an alias for @emph{a keyword}
  6013. such as @code{int}. It stands for a @emph{type}, and that could be
  6014. the type @code{int}.
  6015. Typedef names are in the same namespace as functions and variables, so
  6016. you can't use the same name for a typedef and a function, or a typedef
  6017. and a variable. When a typedef is declared inside a code block, it is
  6018. in scope only in that block.
  6019. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6020. because many of these have standard meanings.
  6021. You can redefine a typedef name to the exact same type as its first
  6022. definition, but you cannot redefine a typedef name to a
  6023. different type, even if the two types are compatible. For example, this
  6024. is valid:
  6025. @example
  6026. typedef int frobcount;
  6027. typedef int frotzcount;
  6028. typedef frotzcount frobcount;
  6029. typedef frobcount frotzcount;
  6030. @end example
  6031. @noindent
  6032. because each typedef name is always defined with the same type
  6033. (@code{int}), but this is not valid:
  6034. @example
  6035. enum foo @{f1, f2, f3@};
  6036. typedef enum foo frobcount;
  6037. typedef int frobcount;
  6038. @end example
  6039. @noindent
  6040. Even though the type @code{enum foo} is compatible with @code{int},
  6041. they are not the @emph{same} type.
  6042. @node Statements
  6043. @chapter Statements
  6044. @cindex statements
  6045. A @dfn{statement} specifies computations to be done for effect; it
  6046. does not produce a value, as an expression would. In general a
  6047. statement ends with a semicolon (@samp{;}), but blocks (which are
  6048. statements, more or less) are an exception to that rule.
  6049. @ifnottex
  6050. @xref{Blocks}.
  6051. @end ifnottex
  6052. The places to use statements are inside a block, and inside a
  6053. complex statement. A @dfn{complex statement} contains one or two
  6054. components that are nested statements. Each such component must
  6055. consist of one and only one statement. The way to put multiple
  6056. statements in such a component is to group them into a @dfn{block}
  6057. (@pxref{Blocks}), which counts as one statement.
  6058. The following sections describe the various kinds of statement.
  6059. @menu
  6060. * Expression Statement:: Evaluate an expression, as a statement,
  6061. usually done for a side effect.
  6062. * if Statement:: Basic conditional execution.
  6063. * if-else Statement:: Multiple branches for conditional execution.
  6064. * Blocks:: Grouping multiple statements together.
  6065. * return Statement:: Return a value from a function.
  6066. * Loop Statements:: Repeatedly executing a statement or block.
  6067. * switch Statement:: Multi-way conditional choices.
  6068. * switch Example:: A plausible example of using @code{switch}.
  6069. * Duffs Device:: A special way to use @code{switch}.
  6070. * Case Ranges:: Ranges of values for @code{switch} cases.
  6071. * Null Statement:: A statement that does nothing.
  6072. * goto Statement:: Jump to another point in the source code,
  6073. identified by a label.
  6074. * Local Labels:: Labels with limited scope.
  6075. * Labels as Values:: Getting the address of a label.
  6076. * Statement Exprs:: A series of statements used as an expression.
  6077. @end menu
  6078. @node Expression Statement
  6079. @section Expression Statement
  6080. @cindex expression statement
  6081. @cindex statement, expression
  6082. The most common kind of statement in C is an @dfn{expression statement}.
  6083. It consists of an expression followed by a
  6084. semicolon. The expression's value is discarded, so the expressions
  6085. that are useful are those that have side effects: assignment
  6086. expressions, increment and decrement expressions, and function calls.
  6087. Here are examples of expression statements:
  6088. @smallexample
  6089. x = 5; /* @r{Assignment expression.} */
  6090. p++; /* @r{Increment expression.} */
  6091. printf ("Done\n"); /* @r{Function call expression.} */
  6092. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6093. x + y; /* @r{Useless statement without effect.} */
  6094. @end smallexample
  6095. In very unusual circumstances we use an expression statement
  6096. whose purpose is to get a fault if an address is invalid:
  6097. @smallexample
  6098. volatile char *p;
  6099. @r{@dots{}}
  6100. *p; /* @r{Cause signal if @code{p} is null.} */
  6101. @end smallexample
  6102. If the target of @code{p} is not declared @code{volatile}, the
  6103. compiler might optimize away the memory access, since it knows that
  6104. the value isn't really used. @xref{volatile}.
  6105. @node if Statement
  6106. @section @code{if} Statement
  6107. @cindex @code{if} statement
  6108. @cindex statement, @code{if}
  6109. @findex if
  6110. An @code{if} statement computes an expression to decide
  6111. whether to execute the following statement or not.
  6112. It looks like this:
  6113. @example
  6114. if (@var{condition})
  6115. @var{execute-if-true}
  6116. @end example
  6117. The first thing this does is compute the value of @var{condition}. If
  6118. that is true (nonzero), then it executes the statement
  6119. @var{execute-if-true}. If the value of @var{condition} is false
  6120. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6121. nothing.
  6122. This is a @dfn{complex statement} because it contains a component
  6123. @var{if-true-substatement} that is a nested statement. It must be one
  6124. and only one statement. The way to put multiple statements there is
  6125. to group them into a @dfn{block} (@pxref{Blocks}).
  6126. @node if-else Statement
  6127. @section @code{if-else} Statement
  6128. @cindex @code{if}@dots{}@code{else} statement
  6129. @cindex statement, @code{if}@dots{}@code{else}
  6130. @findex else
  6131. An @code{if}-@code{else} statement computes an expression to decide
  6132. which of two nested statements to execute.
  6133. It looks like this:
  6134. @example
  6135. if (@var{condition})
  6136. @var{if-true-substatement}
  6137. else
  6138. @var{if-false-substatement}
  6139. @end example
  6140. The first thing this does is compute the value of @var{condition}. If
  6141. that is true (nonzero), then it executes the statement
  6142. @var{if-true-substatement}. If the value of @var{condition} is false
  6143. (zero), then it executes the statement @var{if-false-substatement} instead.
  6144. This is a @dfn{complex statement} because it contains components
  6145. @var{if-true-substatement} and @var{if-else-substatement} that are
  6146. nested statements. Each must be one and only one statement. The way
  6147. to put multiple statements in such a component is to group them into a
  6148. @dfn{block} (@pxref{Blocks}).
  6149. @node Blocks
  6150. @section Blocks
  6151. @cindex block
  6152. @cindex compound statement
  6153. A @dfn{block} is a construct that contains multiple statements of any
  6154. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6155. series of statements and declarations in between. Another name for
  6156. blocks is @dfn{compound statements}.
  6157. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6158. normal statement---it does not end with a semicolon. But you can
  6159. @emph{use} it like a statement; anywhere that a statement is required
  6160. or allowed, you can write a block and consider that block a statement.
  6161. So far it seems that a block is a kind of statement with an unusual
  6162. syntax. But that is not entirely true: a function body is also a
  6163. block, and that block is definitely not a statement. The text after a
  6164. function header is not treated as a statement; only a function body is
  6165. allowed there, and nothing else would be meaningful there.
  6166. In a formal grammar we would have to choose---either a block is a kind
  6167. of statement or it is not. But this manual is meant for humans, not
  6168. for parser generators. The clearest answer for humans is, ``a block
  6169. is a statement, in some ways.''
  6170. @cindex nested block
  6171. @cindex internal block
  6172. A block that isn't a function body is called an @dfn{internal block}
  6173. or a @dfn{nested block}. You can put a nested block directly inside
  6174. another block, but more often the nested block is inside some complex
  6175. statement, such as a @code{for} statement or an @code{if} statement.
  6176. There are two uses for nested blocks in C:
  6177. @itemize @bullet
  6178. @item
  6179. To specify the scope for local declarations. For instance, a local
  6180. variable's scope is the rest of the innermost containing block.
  6181. @item
  6182. To write a series of statements where, syntactically, one statement is
  6183. called for. For instance, the @var{execute-if-true} of an @code{if}
  6184. statement is one statement. To put multiple statements there, they
  6185. have to be wrapped in a block, like this:
  6186. @example
  6187. if (x < 0)
  6188. @{
  6189. printf ("x was negative\n");
  6190. x = -x;
  6191. @}
  6192. @end example
  6193. @end itemize
  6194. This example (repeated from above) shows a nested block which serves
  6195. both purposes: it includes two statements (plus a declaration) in the
  6196. body of a @code{while} statement, and it provides the scope for the
  6197. declaration of @code{q}.
  6198. @example
  6199. void
  6200. free_intlist (struct intlistlink *p)
  6201. @{
  6202. while (p)
  6203. @{
  6204. struct intlistlink *q = p;
  6205. p = p->next;
  6206. free (q);
  6207. @}
  6208. @}
  6209. @end example
  6210. @node return Statement
  6211. @section @code{return} Statement
  6212. @cindex @code{return} statement
  6213. @cindex statement, @code{return}
  6214. @findex return
  6215. The @code{return} statement makes the containing function return
  6216. immediately. It has two forms. This one specifies no value to
  6217. return:
  6218. @example
  6219. return;
  6220. @end example
  6221. @noindent
  6222. That form is meant for functions whose return type is @code{void}
  6223. (@pxref{The Void Type}). You can also use it in a function that
  6224. returns nonvoid data, but that's a bad idea, since it makes the
  6225. function return garbage.
  6226. The form that specifies a value looks like this:
  6227. @example
  6228. return @var{value};
  6229. @end example
  6230. @noindent
  6231. which computes the expression @var{value} and makes the function
  6232. return that. If necessary, the value undergoes type conversion to
  6233. the function's declared return value type, which works like
  6234. assigning the value to a variable of that type.
  6235. @node Loop Statements
  6236. @section Loop Statements
  6237. @cindex loop statements
  6238. @cindex statements, loop
  6239. @cindex iteration
  6240. You can use a loop statement when you need to execute a series of
  6241. statements repeatedly, making an @dfn{iteration}. C provides several
  6242. different kinds of loop statements, described in the following
  6243. subsections.
  6244. Every kind of loop statement is a complex statement because contains a
  6245. component, here called @var{body}, which is a nested statement.
  6246. Most often the body is a block.
  6247. @menu
  6248. * while Statement:: Loop as long as a test expression is true.
  6249. * do-while Statement:: Execute a loop once, with further looping
  6250. as long as a test expression is true.
  6251. * break Statement:: End a loop immediately.
  6252. * for Statement:: Iterative looping.
  6253. * Example of for:: An example of iterative looping.
  6254. * Omitted for-Expressions:: for-loop expression options.
  6255. * for-Index Declarations:: for-loop declaration options.
  6256. * continue Statement:: Begin the next cycle of a loop.
  6257. @end menu
  6258. @node while Statement
  6259. @subsection @code{while} Statement
  6260. @cindex @code{while} statement
  6261. @cindex statement, @code{while}
  6262. @findex while
  6263. The @code{while} statement is the simplest loop construct.
  6264. It looks like this:
  6265. @example
  6266. while (@var{test})
  6267. @var{body}
  6268. @end example
  6269. Here, @var{body} is a statement (often a nested block) to repeat, and
  6270. @var{test} is the test expression that controls whether to repeat it again.
  6271. Each iteration of the loop starts by computing @var{test} and, if it
  6272. is true (nonzero), that means the loop should execute @var{body} again
  6273. and then start over.
  6274. Here's an example of advancing to the last structure in a chain of
  6275. structures chained through the @code{next} field:
  6276. @example
  6277. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6278. @r{@dots{}}
  6279. while (chain->next != NULL)
  6280. chain = chain->next;
  6281. @end example
  6282. @noindent
  6283. This code assumes the chain isn't empty to start with; if the chain is
  6284. empty (that is, if @code{chain} is a null pointer), the code gets a
  6285. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6286. @node do-while Statement
  6287. @subsection @code{do-while} Statement
  6288. @cindex @code{do}--@code{while} statement
  6289. @cindex statement, @code{do}--@code{while}
  6290. @findex do
  6291. The @code{do}--@code{while} statement is a simple loop construct that
  6292. performs the test at the end of the iteration.
  6293. @example
  6294. do
  6295. @var{body}
  6296. while (@var{test});
  6297. @end example
  6298. Here, @var{body} is a statement (possibly a block) to repeat, and
  6299. @var{test} is an expression that controls whether to repeat it again.
  6300. Each iteration of the loop starts by executing @var{body}. Then it
  6301. computes @var{test} and, if it is true (nonzero), that means to go
  6302. back and start over with @var{body}. If @var{test} is false (zero),
  6303. then the loop stops repeating and execution moves on past it.
  6304. @node break Statement
  6305. @subsection @code{break} Statement
  6306. @cindex @code{break} statement
  6307. @cindex statement, @code{break}
  6308. @findex break
  6309. The @code{break} statement looks like @samp{break;}. Its effect is to
  6310. exit immediately from the innermost loop construct or @code{switch}
  6311. statement (@pxref{switch Statement}).
  6312. For example, this loop advances @code{p} until the next null
  6313. character or newline.
  6314. @example
  6315. while (*p)
  6316. @{
  6317. /* @r{End loop if we have reached a newline.} */
  6318. if (*p == '\n')
  6319. break;
  6320. p++
  6321. @}
  6322. @end example
  6323. When there are nested loops, the @code{break} statement exits from the
  6324. innermost loop containing it.
  6325. @example
  6326. struct list_if_tuples
  6327. @{
  6328. struct list_if_tuples next;
  6329. int length;
  6330. data *contents;
  6331. @};
  6332. void
  6333. process_all_elements (struct list_if_tuples *list)
  6334. @{
  6335. while (list)
  6336. @{
  6337. /* @r{Process all the elements in this node's vector,}
  6338. @r{stopping when we reach one that is null.} */
  6339. for (i = 0; i < list->length; i++
  6340. @{
  6341. /* @r{Null element terminates this node's vector.} */
  6342. if (list->contents[i] == NULL)
  6343. /* @r{Exit the @code{for} loop.} */
  6344. break;
  6345. /* @r{Operate on the next element.} */
  6346. process_element (list->contents[i]);
  6347. @}
  6348. list = list->next;
  6349. @}
  6350. @}
  6351. @end example
  6352. The only way in C to exit from an outer loop is with
  6353. @code{goto} (@pxref{goto Statement}).
  6354. @node for Statement
  6355. @subsection @code{for} Statement
  6356. @cindex @code{for} statement
  6357. @cindex statement, @code{for}
  6358. @findex for
  6359. A @code{for} statement uses three expressions written inside a
  6360. parenthetical group to define the repetition of the loop. The first
  6361. expression says how to prepare to start the loop. The second says how
  6362. to test, before each iteration, whether to continue looping. The
  6363. third says how to advance, at the end of an iteration, for the next
  6364. iteration. All together, it looks like this:
  6365. @example
  6366. for (@var{start}; @var{continue-test}; @var{advance})
  6367. @var{body}
  6368. @end example
  6369. The first thing the @code{for} statement does is compute @var{start}.
  6370. The next thing it does is compute the expression @var{continue-test}.
  6371. If that expression is false (zero), the @code{for} statement finishes
  6372. immediately, so @var{body} is executed zero times.
  6373. However, if @var{continue-test} is true (nonzero), the @code{for}
  6374. statement executes @var{body}, then @var{advance}. Then it loops back
  6375. to the not-quite-top to test @var{continue-test} again. But it does
  6376. not compute @var{start} again.
  6377. @node Example of for
  6378. @subsection Example of @code{for}
  6379. Here is the @code{for} statement from the iterative Fibonacci
  6380. function:
  6381. @example
  6382. int i;
  6383. for (i = 1; i < n; ++i)
  6384. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6385. /* @r{since @code{i < n} is false the first time.} */
  6386. @{
  6387. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6388. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6389. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6390. int next = prev + last;
  6391. /* @r{Shift the values down.} */
  6392. prev = last;
  6393. last = next;
  6394. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6395. @r{and @var{prev} is @code{fib (@var{i})}.}
  6396. @r{But that won't stay true for long,}
  6397. @r{because we are about to increment @var{i}.} */
  6398. @}
  6399. @end example
  6400. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6401. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6402. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6403. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6404. that contains a declaration and two statements.
  6405. @node Omitted for-Expressions
  6406. @subsection Omitted @code{for}-Expressions
  6407. A fully-fleshed @code{for} statement contains all these parts,
  6408. @example
  6409. for (@var{start}; @var{continue-test}; @var{advance})
  6410. @var{body}
  6411. @end example
  6412. @noindent
  6413. but you can omit any of the three expressions inside the parentheses.
  6414. The parentheses and the two semicolons are required syntactically, but
  6415. the expressions between them may be missing. A missing expression
  6416. means this loop doesn't use that particular feature of the @code{for}
  6417. statement.
  6418. Instead of using @var{start}, you can do the loop preparation
  6419. before the @code{for} statement: the effect is the same. So we
  6420. could have written the beginning of the previous example this way:
  6421. @example
  6422. int i = 0;
  6423. for (; i < n; ++i)
  6424. @end example
  6425. @noindent
  6426. instead of this way:
  6427. @example
  6428. int i;
  6429. for (i = 0; i < n; ++i)
  6430. @end example
  6431. Omitting @var{continue-test} means the loop runs forever (or until
  6432. something else causes exit from it). Statements inside the loop can
  6433. test conditions for termination and use @samp{break;} to exit. This
  6434. is more flexible since you can put those tests anywhere in the loop,
  6435. not solely at the beginning.
  6436. Putting an expression in @var{advance} is almost equivalent to writing
  6437. it at the end of the loop body; it does almost the same thing. The
  6438. only difference is for the @code{continue} statement (@pxref{continue
  6439. Statement}). So we could have written this:
  6440. @example
  6441. for (i = 0; i < n;)
  6442. @{
  6443. @r{@dots{}}
  6444. ++i;
  6445. @}
  6446. @end example
  6447. @noindent
  6448. instead of this:
  6449. @example
  6450. for (i = 0; i < n; ++i)
  6451. @{
  6452. @r{@dots{}}
  6453. @}
  6454. @end example
  6455. The choice is mainly a matter of what is more readable for
  6456. programmers. However, there is also a syntactic difference:
  6457. @var{advance} is an expression, not a statement. It can't include
  6458. loops, blocks, declarations, etc.
  6459. @node for-Index Declarations
  6460. @subsection @code{for}-Index Declarations
  6461. You can declare loop-index variables directly in the @var{start}
  6462. portion of the @code{for}-loop, like this:
  6463. @example
  6464. for (int i = 0; i < n; ++i)
  6465. @{
  6466. @r{@dots{}}
  6467. @}
  6468. @end example
  6469. This kind of @var{start} is limited to a single declaration; it can
  6470. declare one or more variables, separated by commas, all of which are
  6471. the same @var{basetype} (@code{int}, in this example):
  6472. @example
  6473. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6474. @{
  6475. @r{@dots{}}
  6476. @}
  6477. @end example
  6478. @noindent
  6479. The scope of these variables is the @code{for} statement as a whole.
  6480. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6481. Variables declared in @code{for} statements should have initializers.
  6482. Omitting the initialization gives the variables unpredictable initial
  6483. values, so this code is erroneous.
  6484. @example
  6485. for (int i; i < n; ++i)
  6486. @{
  6487. @r{@dots{}}
  6488. @}
  6489. @end example
  6490. @node continue Statement
  6491. @subsection @code{continue} Statement
  6492. @cindex @code{continue} statement
  6493. @cindex statement, @code{continue}
  6494. @findex continue
  6495. The @code{continue} statement looks like @samp{continue;}, and its
  6496. effect is to jump immediately to the end of the innermost loop
  6497. construct. If it is a @code{for}-loop, the next thing that happens
  6498. is to execute the loop's @var{advance} expression.
  6499. For example, this loop increments @code{p} until the next null character
  6500. or newline, and operates (in some way not shown) on all the characters
  6501. in the line except for spaces. All it does with spaces is skip them.
  6502. @example
  6503. for (;*p; ++p)
  6504. @{
  6505. /* @r{End loop if we have reached a newline.} */
  6506. if (*p == '\n')
  6507. break;
  6508. /* @r{Pay no attention to spaces.} */
  6509. if (*p == ' ')
  6510. continue;
  6511. /* @r{Operate on the next character.} */
  6512. @r{@dots{}}
  6513. @}
  6514. @end example
  6515. @noindent
  6516. Executing @samp{continue;} skips the loop body but it does not
  6517. skip the @var{advance} expression, @code{p++}.
  6518. We could also write it like this:
  6519. @example
  6520. for (;*p; ++p)
  6521. @{
  6522. /* @r{Exit if we have reached a newline.} */
  6523. if (*p == '\n')
  6524. break;
  6525. /* @r{Pay no attention to spaces.} */
  6526. if (*p != ' ')
  6527. @{
  6528. /* @r{Operate on the next character.} */
  6529. @r{@dots{}}
  6530. @}
  6531. @}
  6532. @end example
  6533. The advantage of using @code{continue} is that it reduces the
  6534. depth of nesting.
  6535. Contrast @code{continue} with the @code{break} statement. @xref{break
  6536. Statement}.
  6537. @node switch Statement
  6538. @section @code{switch} Statement
  6539. @cindex @code{switch} statement
  6540. @cindex statement, @code{switch}
  6541. @findex switch
  6542. @findex case
  6543. @findex default
  6544. The @code{switch} statement selects code to run according to the value
  6545. of an expression. The expression, in parentheses, follows the keyword
  6546. @code{switch}. After that come all the cases to select among,
  6547. inside braces. It looks like this:
  6548. @example
  6549. switch (@var{selector})
  6550. @{
  6551. @var{cases}@r{@dots{}}
  6552. @}
  6553. @end example
  6554. A case can look like this:
  6555. @example
  6556. case @var{value}:
  6557. @var{statements}
  6558. break;
  6559. @end example
  6560. @noindent
  6561. which means ``come here if @var{selector} happens to have the value
  6562. @var{value},'' or like this (a GNU C extension):
  6563. @example
  6564. case @var{rangestart} ... @var{rangeend}:
  6565. @var{statements}
  6566. break;
  6567. @end example
  6568. @noindent
  6569. which means ``come here if @var{selector} happens to have a value
  6570. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6571. Ranges}.
  6572. The values in @code{case} labels must reduce to integer constants.
  6573. They can use arithmetic, and @code{enum} constants, but they cannot
  6574. refer to data in memory, because they have to be computed at compile
  6575. time. It is an error if two @code{case} labels specify the same
  6576. value, or ranges that overlap, or if one is a range and the other is a
  6577. value in that range.
  6578. You can also define a default case to handle ``any other value,'' like
  6579. this:
  6580. @example
  6581. default:
  6582. @var{statements}
  6583. break;
  6584. @end example
  6585. If the @code{switch} statement has no @code{default:} label, then it
  6586. does nothing when the value matches none of the cases.
  6587. The brace-group inside the @code{switch} statement is a block, and you
  6588. can declare variables with that scope just as in any other block
  6589. (@pxref{Blocks}). However, initializers in these declarations won't
  6590. necessarily be executed every time the @code{switch} statement runs,
  6591. so it is best to avoid giving them initializers.
  6592. @code{break;} inside a @code{switch} statement exits immediately from
  6593. the @code{switch} statement. @xref{break Statement}.
  6594. If there is no @code{break;} at the end of the code for a case,
  6595. execution continues into the code for the following case. This
  6596. happens more often by mistake than intentionally, but since this
  6597. feature is used in real code, we cannot eliminate it.
  6598. @strong{Warning:} When one case is intended to fall through to the
  6599. next, write a comment like @samp{falls through} to say it's
  6600. intentional. That way, other programmers won't assume it was an error
  6601. and ``fix'' it erroneously.
  6602. Consecutive @code{case} statements could, pedantically, be considered
  6603. an instance of falling through, but we don't consider or treat them that
  6604. way because they won't confuse anyone.
  6605. @node switch Example
  6606. @section Example of @code{switch}
  6607. Here's an example of using the @code{switch} statement
  6608. to distinguish among characters:
  6609. @cindex counting vowels and punctuation
  6610. @example
  6611. struct vp @{ int vowels, punct; @};
  6612. struct vp
  6613. count_vowels_and_punct (char *string)
  6614. @{
  6615. int c;
  6616. int vowels = 0;
  6617. int punct = 0;
  6618. /* @r{Don't change the parameter itself.} */
  6619. /* @r{That helps in debugging.} */
  6620. char *p = string;
  6621. struct vp value;
  6622. while (c = *p++)
  6623. switch (c)
  6624. @{
  6625. case 'y':
  6626. case 'Y':
  6627. /* @r{We assume @code{y_is_consonant} will check surrounding
  6628. letters to determine whether this y is a vowel.} */
  6629. if (y_is_consonant (p - 1))
  6630. break;
  6631. /* @r{Falls through} */
  6632. case 'a':
  6633. case 'e':
  6634. case 'i':
  6635. case 'o':
  6636. case 'u':
  6637. case 'A':
  6638. case 'E':
  6639. case 'I':
  6640. case 'O':
  6641. case 'U':
  6642. vowels++;
  6643. break;
  6644. case '.':
  6645. case ',':
  6646. case ':':
  6647. case ';':
  6648. case '?':
  6649. case '!':
  6650. case '\"':
  6651. case '\'':
  6652. punct++;
  6653. break;
  6654. @}
  6655. value.vowels = vowels;
  6656. value.punct = punct;
  6657. return value;
  6658. @}
  6659. @end example
  6660. @node Duffs Device
  6661. @section Duff's Device
  6662. @cindex Duff's device
  6663. The cases in a @code{switch} statement can be inside other control
  6664. constructs. For instance, we can use a technique known as @dfn{Duff's
  6665. device} to optimize this simple function,
  6666. @example
  6667. void
  6668. copy (char *to, char *from, int count)
  6669. @{
  6670. while (count > 0)
  6671. *to++ = *from++, count--;
  6672. @}
  6673. @end example
  6674. @noindent
  6675. which copies memory starting at @var{from} to memory starting at
  6676. @var{to}.
  6677. Duff's device involves unrolling the loop so that it copies
  6678. several characters each time around, and using a @code{switch} statement
  6679. to enter the loop body at the proper point:
  6680. @example
  6681. void
  6682. copy (char *to, char *from, int count)
  6683. @{
  6684. if (count <= 0)
  6685. return;
  6686. int n = (count + 7) / 8;
  6687. switch (count % 8)
  6688. @{
  6689. do @{
  6690. case 0: *to++ = *from++;
  6691. case 7: *to++ = *from++;
  6692. case 6: *to++ = *from++;
  6693. case 5: *to++ = *from++;
  6694. case 4: *to++ = *from++;
  6695. case 3: *to++ = *from++;
  6696. case 2: *to++ = *from++;
  6697. case 1: *to++ = *from++;
  6698. @} while (--n > 0);
  6699. @}
  6700. @}
  6701. @end example
  6702. @node Case Ranges
  6703. @section Case Ranges
  6704. @cindex case ranges
  6705. @cindex ranges in case statements
  6706. You can specify a range of consecutive values in a single @code{case} label,
  6707. like this:
  6708. @example
  6709. case @var{low} ... @var{high}:
  6710. @end example
  6711. @noindent
  6712. This has the same effect as the proper number of individual @code{case}
  6713. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6714. This feature is especially useful for ranges of ASCII character codes:
  6715. @example
  6716. case 'A' ... 'Z':
  6717. @end example
  6718. @strong{Be careful:} with integers, write spaces around the @code{...}
  6719. to prevent it from being parsed wrong. For example, write this:
  6720. @example
  6721. case 1 ... 5:
  6722. @end example
  6723. @noindent
  6724. rather than this:
  6725. @example
  6726. case 1...5:
  6727. @end example
  6728. @node Null Statement
  6729. @section Null Statement
  6730. @cindex null statement
  6731. @cindex statement, null
  6732. A @dfn{null statement} is just a semicolon. It does nothing.
  6733. A null statement is a placeholder for use where a statement is
  6734. grammatically required, but there is nothing to be done. For
  6735. instance, sometimes all the work of a @code{for}-loop is done in the
  6736. @code{for}-header itself, leaving no work for the body. Here is an
  6737. example that searches for the first newline in @code{array}:
  6738. @example
  6739. for (p = array; *p != '\n'; p++)
  6740. ;
  6741. @end example
  6742. @node goto Statement
  6743. @section @code{goto} Statement and Labels
  6744. @cindex @code{goto} statement
  6745. @cindex statement, @code{goto}
  6746. @cindex label
  6747. @findex goto
  6748. The @code{goto} statement looks like this:
  6749. @example
  6750. goto @var{label};
  6751. @end example
  6752. @noindent
  6753. Its effect is to transfer control immediately to another part of the
  6754. current function---where the label named @var{label} is defined.
  6755. An ordinary label definition looks like this:
  6756. @example
  6757. @var{label}:
  6758. @end example
  6759. @noindent
  6760. and it can appear before any statement. You can't use @code{default}
  6761. as a label, since that has a special meaning for @code{switch}
  6762. statements.
  6763. An ordinary label doesn't need a separate declaration; defining it is
  6764. enough.
  6765. Here's an example of using @code{goto} to implement a loop
  6766. equivalent to @code{do}--@code{while}:
  6767. @example
  6768. @{
  6769. loop_restart:
  6770. @var{body}
  6771. if (@var{condition})
  6772. goto loop_restart;
  6773. @}
  6774. @end example
  6775. The name space of labels is separate from that of variables and functions.
  6776. Thus, there is no error in using a single name in both ways:
  6777. @example
  6778. @{
  6779. int foo; // @r{Variable @code{foo}.}
  6780. foo: // @r{Label @code{foo}.}
  6781. @var{body}
  6782. if (foo > 0) // @r{Variable @code{foo}.}
  6783. goto foo; // @r{Label @code{foo}.}
  6784. @}
  6785. @end example
  6786. Blocks have no effect on ordinary labels; each label name is defined
  6787. throughout the whole of the function it appears in. It looks strange to
  6788. jump into a block with @code{goto}, but it works. For example,
  6789. @example
  6790. if (x < 0)
  6791. goto negative;
  6792. if (y < 0)
  6793. @{
  6794. negative:
  6795. printf ("Negative\n");
  6796. return;
  6797. @}
  6798. @end example
  6799. If the goto jumps into the scope of a variable, it does not
  6800. initialize the variable. For example, if @code{x} is negative,
  6801. @example
  6802. if (x < 0)
  6803. goto negative;
  6804. if (y < 0)
  6805. @{
  6806. int i = 5;
  6807. negative:
  6808. printf ("Negative, and i is %d\n", i);
  6809. return;
  6810. @}
  6811. @end example
  6812. @noindent
  6813. prints junk because @code{i} was not initialized.
  6814. If the block declares a variable-length automatic array, jumping into
  6815. it gives a compilation error. However, jumping out of the scope of a
  6816. variable-length array works fine, and deallocates its storage.
  6817. A label can't come directly before a declaration, so the code can't
  6818. jump directly to one. For example, this is not allowed:
  6819. @example
  6820. @{
  6821. goto foo;
  6822. foo:
  6823. int x = 5;
  6824. bar(&x);
  6825. @}
  6826. @end example
  6827. @noindent
  6828. The workaround is to add a statement, even an empty statement,
  6829. directly after the label. For example:
  6830. @example
  6831. @{
  6832. goto foo;
  6833. foo:
  6834. ;
  6835. int x = 5;
  6836. bar(&x);
  6837. @}
  6838. @end example
  6839. Likewise, a label can't be the last thing in a block. The workaround
  6840. solution is the same: add a semicolon after the label.
  6841. These unnecessary restrictions on labels make no sense, and ought in
  6842. principle to be removed; but they do only a little harm since labels
  6843. and @code{goto} are rarely the best way to write a program.
  6844. These examples are all artificial; it would be more natural to
  6845. write them in other ways, without @code{goto}. For instance,
  6846. the clean way to write the example that prints @samp{Negative} is this:
  6847. @example
  6848. if (x < 0 || y < 0)
  6849. @{
  6850. printf ("Negative\n");
  6851. return;
  6852. @}
  6853. @end example
  6854. @noindent
  6855. It is hard to construct simple examples where @code{goto} is actually
  6856. the best way to write a program. Its rare good uses tend to be in
  6857. complex code, thus not apt for the purpose of explaining the meaning
  6858. of @code{goto}.
  6859. The only good time to use @code{goto} is when it makes the code
  6860. simpler than any alternative. Jumping backward is rarely desirable,
  6861. because usually the other looping and control constructs give simpler
  6862. code. Using @code{goto} to jump forward is more often desirable, for
  6863. instance when a function needs to do some processing in an error case
  6864. and errors can occur at various different places within the function.
  6865. @node Local Labels
  6866. @section Locally Declared Labels
  6867. @cindex local labels
  6868. @cindex macros, local labels
  6869. @findex __label__
  6870. In GNU C you can declare @dfn{local labels} in any nested block
  6871. scope. A local label is used in a @code{goto} statement just like an
  6872. ordinary label, but you can only reference it within the block in
  6873. which it was declared.
  6874. A local label declaration looks like this:
  6875. @example
  6876. __label__ @var{label};
  6877. @end example
  6878. @noindent
  6879. or
  6880. @example
  6881. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6882. @end example
  6883. Local label declarations must come at the beginning of the block,
  6884. before any ordinary declarations or statements.
  6885. The label declaration declares the label @emph{name}, but does not define
  6886. the label itself. That's done in the usual way, with
  6887. @code{@var{label}:}, before one of the statements in the block.
  6888. The local label feature is useful for complex macros. If a macro
  6889. contains nested loops, a @code{goto} can be useful for breaking out of
  6890. them. However, an ordinary label whose scope is the whole function
  6891. cannot be used: if the macro can be expanded several times in one
  6892. function, the label will be multiply defined in that function. A
  6893. local label avoids this problem. For example:
  6894. @example
  6895. #define SEARCH(value, array, target) \
  6896. do @{ \
  6897. __label__ found; \
  6898. __auto_type _SEARCH_target = (target); \
  6899. __auto_type _SEARCH_array = (array); \
  6900. int i, j; \
  6901. int value; \
  6902. for (i = 0; i < max; i++) \
  6903. for (j = 0; j < max; j++) \
  6904. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6905. @{ (value) = i; goto found; @} \
  6906. (value) = -1; \
  6907. found:; \
  6908. @} while (0)
  6909. @end example
  6910. This could also be written using a statement expression
  6911. (@pxref{Statement Exprs}):
  6912. @example
  6913. #define SEARCH(array, target) \
  6914. (@{ \
  6915. __label__ found; \
  6916. __auto_type _SEARCH_target = (target); \
  6917. __auto_type _SEARCH_array = (array); \
  6918. int i, j; \
  6919. int value; \
  6920. for (i = 0; i < max; i++) \
  6921. for (j = 0; j < max; j++) \
  6922. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6923. @{ value = i; goto found; @} \
  6924. value = -1; \
  6925. found: \
  6926. value; \
  6927. @})
  6928. @end example
  6929. Ordinary labels are visible throughout the function where they are
  6930. defined, and only in that function. However, explicitly declared
  6931. local labels of a block are visible in nested functions declared
  6932. within that block. @xref{Nested Functions}, for details.
  6933. @xref{goto Statement}.
  6934. @node Labels as Values
  6935. @section Labels as Values
  6936. @cindex labels as values
  6937. @cindex computed gotos
  6938. @cindex goto with computed label
  6939. @cindex address of a label
  6940. In GNU C, you can get the address of a label defined in the current
  6941. function (or a local label defined in the containing function) with
  6942. the unary operator @samp{&&}. The value has type @code{void *}. This
  6943. value is a constant and can be used wherever a constant of that type
  6944. is valid. For example:
  6945. @example
  6946. void *ptr;
  6947. @r{@dots{}}
  6948. ptr = &&foo;
  6949. @end example
  6950. To use these values requires a way to jump to one. This is done
  6951. with the computed goto statement@footnote{The analogous feature in
  6952. Fortran is called an assigned goto, but that name seems inappropriate in
  6953. C, since you can do more with label addresses than store them in special label
  6954. variables.}, @code{goto *@var{exp};}. For example,
  6955. @example
  6956. goto *ptr;
  6957. @end example
  6958. @noindent
  6959. Any expression of type @code{void *} is allowed.
  6960. @xref{goto Statement}.
  6961. @menu
  6962. * Label Value Uses:: Examples of using label values.
  6963. * Label Value Caveats:: Limitations of label values.
  6964. @end menu
  6965. @node Label Value Uses
  6966. @subsection Label Value Uses
  6967. One use for label-valued constants is to initialize a static array to
  6968. serve as a jump table:
  6969. @example
  6970. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6971. @end example
  6972. Then you can select a label with indexing, like this:
  6973. @example
  6974. goto *array[i];
  6975. @end example
  6976. @noindent
  6977. Note that this does not check whether the subscript is in bounds---array
  6978. indexing in C never checks that.
  6979. You can make the table entries offsets instead of addresses
  6980. by subtracting one label from the others. Here is an example:
  6981. @example
  6982. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6983. &&hack - &&foo @};
  6984. goto *(&&foo + array[i]);
  6985. @end example
  6986. @noindent
  6987. Using offsets is preferable in shared libraries, as it avoids the need
  6988. for dynamic relocation of the array elements; therefore, the array can
  6989. be read-only.
  6990. An array of label values or offsets serves a purpose much like that of
  6991. the @code{switch} statement. The @code{switch} statement is cleaner,
  6992. so use @code{switch} by preference when feasible.
  6993. Another use of label values is in an interpreter for threaded code.
  6994. The labels within the interpreter function can be stored in the
  6995. threaded code for super-fast dispatching.
  6996. @node Label Value Caveats
  6997. @subsection Label Value Caveats
  6998. Jumping to a label defined in another function does not work.
  6999. It can cause unpredictable results.
  7000. The best way to avoid this is to store label values only in
  7001. automatic variables, or static variables whose names are declared
  7002. within the function. Never pass them as arguments.
  7003. @cindex cloning
  7004. An optimization known as @dfn{cloning} generates multiple simplified
  7005. variants of a function's code, for use with specific fixed arguments.
  7006. Using label values in certain ways, such as saving the address in one
  7007. call to the function and using it again in another call, would make cloning
  7008. give incorrect results. These functions must disable cloning.
  7009. Inlining calls to the function would also result in multiple copies of
  7010. the code, each with its own value of the same label. Using the label
  7011. in a computed goto is no problem, because the computed goto inhibits
  7012. inlining. However, using the label value in some other way, such as
  7013. an indication of where an error occurred, would be optimized wrong.
  7014. These functions must disable inlining.
  7015. To prevent inlining or cloning of a function, specify
  7016. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7017. @xref{Attributes}.
  7018. When a function uses a label value in a static variable initializer,
  7019. that automatically prevents inlining or cloning the function.
  7020. @node Statement Exprs
  7021. @section Statements and Declarations in Expressions
  7022. @cindex statements inside expressions
  7023. @cindex declarations inside expressions
  7024. @cindex expressions containing statements
  7025. @c the above section title wrapped and causes an underfull hbox.. i
  7026. @c changed it from "within" to "in". --mew 4feb93
  7027. A block enclosed in parentheses can be used as an expression in GNU
  7028. C@. This provides a way to use local variables, loops and switches within
  7029. an expression. We call it a @dfn{statement expression}.
  7030. Recall that a block is a sequence of statements
  7031. surrounded by braces. In this construct, parentheses go around the
  7032. braces. For example:
  7033. @example
  7034. (@{ int y = foo (); int z;
  7035. if (y > 0) z = y;
  7036. else z = - y;
  7037. z; @})
  7038. @end example
  7039. @noindent
  7040. is a valid (though slightly more complex than necessary) expression
  7041. for the absolute value of @code{foo ()}.
  7042. The last statement in the block should be an expression statement; an
  7043. expression followed by a semicolon, that is. The value of this
  7044. expression serves as the value of statement expression. If the last
  7045. statement is anything else, the statement expression's value is
  7046. @code{void}.
  7047. This feature is mainly useful in making macro definitions compute each
  7048. operand exactly once. @xref{Macros and Auto Type}.
  7049. Statement expressions are not allowed in expressions that must be
  7050. constant, such as the value for an enumerator, the width of a
  7051. bit-field, or the initial value of a static variable.
  7052. Jumping into a statement expression---with @code{goto}, or using a
  7053. @code{switch} statement outside the statement expression---is an
  7054. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7055. compiler can't detect the error, but it still won't work.
  7056. Jumping out of a statement expression is permitted, but since
  7057. subexpressions in C are not computed in a strict order, it is
  7058. unpredictable which other subexpressions will have been computed by
  7059. then. For example,
  7060. @example
  7061. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7062. @end example
  7063. @noindent
  7064. calls @code{foo} and @code{bar1} before it jumps, and never
  7065. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7066. does get called, that occurs after @code{foo} and before @code{bar1}.
  7067. @node Variables
  7068. @chapter Variables
  7069. @cindex variables
  7070. Every variable used in a C program needs to be made known by a
  7071. @dfn{declaration}. It can be used only after it has been declared.
  7072. It is an error to declare a variable name more than once in the same
  7073. scope; an exception is that @code{extern} declarations and tentative
  7074. definitions can coexist with another declaration of the same
  7075. variable.
  7076. Variables can be declared anywhere within a block or file. (Older
  7077. versions of C required that all variable declarations within a block
  7078. occur before any statements.)
  7079. Variables declared within a function or block are @dfn{local} to
  7080. it. This means that the variable name is visible only until the end
  7081. of that function or block, and the memory space is allocated only
  7082. while control is within it.
  7083. Variables declared at the top level in a file are called @dfn{file-scope}.
  7084. They are assigned fixed, distinct memory locations, so they retain
  7085. their values for the whole execution of the program.
  7086. @menu
  7087. * Variable Declarations:: Name a variable and and reserve space for it.
  7088. * Initializers:: Assigning inital values to variables.
  7089. * Designated Inits:: Assigning initial values to array elements
  7090. at particular array indices.
  7091. * Auto Type:: Obtaining the type of a variable.
  7092. * Local Variables:: Variables declared in function definitions.
  7093. * File-Scope Variables:: Variables declared outside of
  7094. function definitions.
  7095. * Static Local Variables:: Variables declared within functions,
  7096. but with permanent storage allocation.
  7097. * Extern Declarations:: Declaring a variable
  7098. which is allocated somewhere else.
  7099. * Allocating File-Scope:: When is space allocated
  7100. for file-scope variables?
  7101. * auto and register:: Historically used storage directions.
  7102. * Omitting Types:: The bad practice of declaring variables
  7103. with implicit type.
  7104. @end menu
  7105. @node Variable Declarations
  7106. @section Variable Declarations
  7107. @cindex variable declarations
  7108. @cindex declaration of variables
  7109. Here's what a variable declaration looks like:
  7110. @example
  7111. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7112. @end example
  7113. The @var{keywords} specify how to handle the scope of the variable
  7114. name and the allocation of its storage. Most declarations have
  7115. no keywords because the defaults are right for them.
  7116. C allows these keywords to come before or after @var{basetype}, or
  7117. even in the middle of it as in @code{unsigned static int}, but don't
  7118. do that---it would surprise other programmers. Always write the
  7119. keywords first.
  7120. The @var{basetype} can be any of the predefined types of C, or a type
  7121. keyword defined with @code{typedef}. It can also be @code{struct
  7122. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7123. addition, it can include type qualifiers such as @code{const} and
  7124. @code{volatile} (@pxref{Type Qualifiers}).
  7125. In the simplest case, @var{decorated-variable} is just the variable
  7126. name. That declares the variable with the type specified by
  7127. @var{basetype}. For instance,
  7128. @example
  7129. int foo;
  7130. @end example
  7131. @noindent
  7132. uses @code{int} as the @var{basetype} and @code{foo} as the
  7133. @var{decorated-variable}. It declares @code{foo} with type
  7134. @code{int}.
  7135. @example
  7136. struct tree_node foo;
  7137. @end example
  7138. @noindent
  7139. declares @code{foo} with type @code{struct tree_node}.
  7140. @menu
  7141. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7142. array and pointer types.
  7143. * Combining Variable Declarations:: More than one variable declaration
  7144. in a single statement.
  7145. @end menu
  7146. @node Declaring Arrays and Pointers
  7147. @subsection Declaring Arrays and Pointers
  7148. @cindex declaring arrays and pointers
  7149. @cindex array, declaring
  7150. @cindex pointers, declaring
  7151. To declare a variable that is an array, write
  7152. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7153. @example
  7154. int foo[5];
  7155. @end example
  7156. To declare a variable that has a pointer type, write
  7157. @code{*@var{variable}} for @var{decorated-variable}:
  7158. @example
  7159. struct list_elt *foo;
  7160. @end example
  7161. These constructs nest. For instance,
  7162. @example
  7163. int foo[3][5];
  7164. @end example
  7165. @noindent
  7166. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7167. @example
  7168. struct list_elt *foo[5];
  7169. @end example
  7170. @noindent
  7171. declares @code{foo} as an array of 5 pointers to structures, and
  7172. @example
  7173. struct list_elt **foo;
  7174. @end example
  7175. @noindent
  7176. declares @code{foo} as a pointer to a pointer to a structure.
  7177. @example
  7178. int **(*foo[30])(int, double);
  7179. @end example
  7180. @noindent
  7181. declares @code{foo} as an array of 30 pointers to functions
  7182. (@pxref{Function Pointers}), each of which must accept two arguments
  7183. (one @code{int} and one @code{double}) and return type @code{int **}.
  7184. @example
  7185. void
  7186. bar (int size)
  7187. @{
  7188. int foo[size];
  7189. @r{@dots{}}
  7190. @}
  7191. @end example
  7192. @noindent
  7193. declares @code{foo} as an array of integers with a size specified at
  7194. run time when the function @code{bar} is called.
  7195. @node Combining Variable Declarations
  7196. @subsection Combining Variable Declarations
  7197. @cindex combining variable declarations
  7198. @cindex variable declarations, combining
  7199. @cindex declarations, combining
  7200. When multiple declarations have the same @var{keywords} and
  7201. @var{basetype}, you can combine them using commas. Thus,
  7202. @example
  7203. @var{keywords} @var{basetype}
  7204. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7205. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7206. @end example
  7207. @noindent
  7208. is equivalent to
  7209. @example
  7210. @var{keywords} @var{basetype}
  7211. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7212. @var{keywords} @var{basetype}
  7213. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7214. @end example
  7215. Here are some simple examples:
  7216. @example
  7217. int a, b;
  7218. int a = 1, b = 2;
  7219. int a, *p, array[5];
  7220. int a = 0, *p = &a, array[5] = @{1, 2@};
  7221. @end example
  7222. @noindent
  7223. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7224. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7225. Since the initializer for @code{array} specifies only two elements,
  7226. the other three elements are initialized to zero.
  7227. @node Initializers
  7228. @section Initializers
  7229. @cindex initializers
  7230. A variable's declaration, unless it is @code{extern}, should also
  7231. specify its initial value. For numeric and pointer-type variables,
  7232. the initializer is an expression for the value. If necessary, it is
  7233. converted to the variable's type, just as in an assignment.
  7234. You can also initialize a local structure-type (@pxref{Structures}) or
  7235. local union-type (@pxref{Unions}) variable this way, from an
  7236. expression whose value has the same type. But you can't initialize an
  7237. array this way (@pxref{Arrays}), since arrays are not first-class
  7238. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7239. assignment.
  7240. You can initialize arrays and structures componentwise,
  7241. with a list of the elements or components. You can initialize
  7242. a union with any one of its alternatives.
  7243. @itemize @bullet
  7244. @item
  7245. A component-wise initializer for an array consists of element values
  7246. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7247. don't cover all the elements in the array, the remaining elements are
  7248. initialized to zero.
  7249. You can omit the size of the array when you declare it, and let
  7250. the initializer specify the size:
  7251. @example
  7252. int array[] = @{ 3, 9, 12 @};
  7253. @end example
  7254. @item
  7255. A component-wise initializer for a structure consists of field values
  7256. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7257. order as the fields are declared in the structure. If the values in
  7258. the initializer don't cover all the fields in the structure, the
  7259. remaining fields are initialized to zero.
  7260. @item
  7261. The initializer for a union-type variable has the form @code{@{
  7262. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7263. in the union definition.
  7264. @end itemize
  7265. For an array of arrays, a structure containing arrays, an array of
  7266. structures, etc., you can nest these constructs. For example,
  7267. @example
  7268. struct point @{ double x, y; @};
  7269. struct point series[]
  7270. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7271. @end example
  7272. You can omit a pair of inner braces if they contain the right
  7273. number of elements for the sub-value they initialize, so that
  7274. no elements or fields need to be filled in with zeros.
  7275. But don't do that very much, as it gets confusing.
  7276. An array of @code{char} can be initialized using a string constant.
  7277. Recall that the string constant includes an implicit null character at
  7278. the end (@pxref{String Constants}). Using a string constant as
  7279. initializer means to use its contents as the initial values of the
  7280. array elements. Here are examples:
  7281. @example
  7282. char text[6] = "text!"; /* @r{Includes the null.} */
  7283. char text[5] = "text!"; /* @r{Excludes the null.} */
  7284. char text[] = "text!"; /* @r{Gets length 6.} */
  7285. char text[]
  7286. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7287. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7288. @end example
  7289. @noindent
  7290. and this kind of initializer can be nested inside braces to initialize
  7291. structures or arrays that contain a @code{char}-array.
  7292. In like manner, you can use a wide string constant to initialize
  7293. an array of @code{wchar_t}.
  7294. @node Designated Inits
  7295. @section Designated Initializers
  7296. @cindex initializers with labeled elements
  7297. @cindex labeled elements in initializers
  7298. @cindex case labels in initializers
  7299. @cindex designated initializers
  7300. In a complex structure or long array, it's useful to indicate
  7301. which field or element we are initializing.
  7302. To designate specific array elements during initialization, include
  7303. the array index in brackets, and an assignment operator, for each
  7304. element:
  7305. @example
  7306. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7307. @end example
  7308. @noindent
  7309. This does the same thing as:
  7310. @example
  7311. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7312. @end example
  7313. The array initialization can include non-designated element values
  7314. alongside designated indices; these follow the expected ordering
  7315. of the array initialization, so that
  7316. @example
  7317. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7318. @end example
  7319. @noindent
  7320. does the same thing as:
  7321. @example
  7322. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7323. @end example
  7324. Note that you can only use constant expressions as array index values,
  7325. not variables.
  7326. If you need to initialize a subsequence of sequential array elements to
  7327. the same value, you can specify a range:
  7328. @example
  7329. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7330. @end example
  7331. @noindent
  7332. Using a range this way is a GNU C extension.
  7333. When subsequence ranges overlap, each element is initialized by the
  7334. last specification that applies to it. Thus, this initialization is
  7335. equivalent to the previous one.
  7336. @example
  7337. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7338. @end example
  7339. @noindent
  7340. as the second overrides the first for elements 0 through 19.
  7341. The value used to initialize a range of elements is evaluated only
  7342. once, for the first element in the range. So for example, this code
  7343. @example
  7344. int random_values[100]
  7345. = @{ [0 ... 99] = get_random_number() @};
  7346. @end example
  7347. @noindent
  7348. would initialize all 100 elements of the array @code{random_values} to
  7349. the same value---probably not what is intended.
  7350. Similarly, you can initialize specific fields of a structure variable
  7351. by specifying the field name prefixed with a dot:
  7352. @example
  7353. struct point @{ int x; int y; @};
  7354. struct point foo = @{ .y = 42; @};
  7355. @end example
  7356. @noindent
  7357. The same syntax works for union variables as well:
  7358. @example
  7359. union int_double @{ int i; double d; @};
  7360. union int_double foo = @{ .d = 34 @};
  7361. @end example
  7362. @noindent
  7363. This casts the integer value 34 to a double and stores it
  7364. in the union variable @code{foo}.
  7365. You can designate both array elements and structure elements in
  7366. the same initialization; for example, here's an array of point
  7367. structures:
  7368. @example
  7369. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7370. @end example
  7371. Along with the capability to specify particular array and structure
  7372. elements to initialize comes the possibility of initializing the same
  7373. element more than once:
  7374. @example
  7375. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7376. @end example
  7377. @noindent
  7378. In such a case, the last initialization value is retained.
  7379. @node Auto Type
  7380. @section Referring to a Type with @code{__auto_type}
  7381. @findex __auto_type
  7382. @findex typeof
  7383. @cindex macros, types of arguments
  7384. You can declare a variable copying the type from
  7385. the initializer by using @code{__auto_type} instead of a particular type.
  7386. Here's an example:
  7387. @example
  7388. #define max(a,b) \
  7389. (@{ __auto_type _a = (a); \
  7390. __auto_type _b = (b); \
  7391. _a > _b ? _a : _b @})
  7392. @end example
  7393. This defines @code{_a} to be of the same type as @code{a}, and
  7394. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7395. to do in a macro that ought to be able to handle any type of data
  7396. (@pxref{Macros and Auto Type}).
  7397. The original GNU C method for obtaining the type of a value is to use
  7398. @code{typeof}, which takes as an argument either a value or the name of
  7399. a type. The previous example could also be written as:
  7400. @example
  7401. #define max(a,b) \
  7402. (@{ typeof(a) _a = (a); \
  7403. typeof(b) _b = (b); \
  7404. _a > _b ? _a : _b @})
  7405. @end example
  7406. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7407. principal use case for @code{typeof} is in variable declarations with
  7408. initialization, which is exactly what @code{__auto_type} handles.
  7409. @node Local Variables
  7410. @section Local Variables
  7411. @cindex local variables
  7412. @cindex variables, local
  7413. Declaring a variable inside a function definition (@pxref{Function
  7414. Definitions}) makes the variable name @dfn{local} to the containing
  7415. block---that is, the containing pair of braces. More precisely, the
  7416. variable's name is visible starting just after where it appears in the
  7417. declaration, and its visibility continues until the end of the block.
  7418. Local variables in C are generally @dfn{automatic} variables: each
  7419. variable's storage exists only from the declaration to the end of the
  7420. block. Execution of the declaration allocates the storage, computes
  7421. the initial value, and stores it in the variable. The end of the
  7422. block deallocates the storage.@footnote{Due to compiler optimizations,
  7423. allocation and deallocation don't necessarily really happen at
  7424. those times.}
  7425. @strong{Warning:} Two declarations for the same local variable
  7426. in the same scope are an error.
  7427. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7428. The total space for the program's stack may be limited; therefore,
  7429. in using very large arrays, it may be necessary to allocate
  7430. them in some other way to stop the program from crashing.
  7431. @strong{Warning:} If the declaration of an automatic variable does not
  7432. specify an initial value, the variable starts out containing garbage.
  7433. In this example, the value printed could be anything at all:
  7434. @example
  7435. @{
  7436. int i;
  7437. printf ("Print junk %d\n", i);
  7438. @}
  7439. @end example
  7440. In a simple test program, that statement is likely to print 0, simply
  7441. because every process starts with memory zeroed. But don't rely on it
  7442. to be zero---that is erroneous.
  7443. @strong{Note:} Make sure to store a value into each local variable (by
  7444. assignment, or by initialization) before referring to its value.
  7445. @node File-Scope Variables
  7446. @section File-Scope Variables
  7447. @cindex file-scope variables
  7448. @cindex global variables
  7449. @cindex variables, file-scope
  7450. @cindex variables, global
  7451. A variable declaration at the top level in a file (not inside a
  7452. function definition) declares a @dfn{file-scope variable}. Loading a
  7453. program allocates the storage for all the file-scope variables in it,
  7454. and initializes them too.
  7455. Each file-scope variable is either @dfn{static} (limited to one
  7456. compilation module) or @dfn{global} (shared with all compilation
  7457. modules in the program). To make the variable static, write the
  7458. keyword @code{static} at the start of the declaration. Omitting
  7459. @code{static} makes the variable global.
  7460. The initial value for a file-scope variable can't depend on the
  7461. contents of storage, and can't call any functions.
  7462. @example
  7463. int foo = 5; /* @r{Valid.} */
  7464. int bar = foo; /* @r{Invalid!} */
  7465. int bar = sin (1.0); /* @r{Invalid!} */
  7466. @end example
  7467. But it can use the address of another file-scope variable:
  7468. @example
  7469. int foo;
  7470. int *bar = &foo; /* @r{Valid.} */
  7471. int arr[5];
  7472. int *bar3 = &arr[3]; /* @r{Valid.} */
  7473. int *bar4 = arr + 4; /* @r{Valid.} */
  7474. @end example
  7475. It is valid for a module to have multiple declarations for a
  7476. file-scope variable, as long as they are all global or all static, but
  7477. at most one declaration can specify an initial value for it.
  7478. @node Static Local Variables
  7479. @section Static Local Variables
  7480. @cindex static local variables
  7481. @cindex variables, static local
  7482. @findex static
  7483. The keyword @code{static} in a local variable declaration says to
  7484. allocate the storage for the variable permanently, just like a
  7485. file-scope variable, even if the declaration is within a function.
  7486. Here's an example:
  7487. @example
  7488. int
  7489. increment_counter ()
  7490. @{
  7491. static int counter = 0;
  7492. return ++counter;
  7493. @}
  7494. @end example
  7495. The scope of the name @code{counter} runs from the declaration to the
  7496. end of the containing block, just like an automatic local variable,
  7497. but its storage is permanent, so the value persists from one call to
  7498. the next. As a result, each call to @code{increment_counter}
  7499. returns a different, unique value.
  7500. The initial value of a static local variable has the same limitations
  7501. as for file-scope variables: it can't depend on the contents of
  7502. storage or call any functions. It can use the address of a file-scope
  7503. variable or a static local variable, because those addresses are
  7504. determined before the program runs.
  7505. @node Extern Declarations
  7506. @section @code{extern} Declarations
  7507. @cindex @code{extern} declarations
  7508. @cindex declarations, @code{extern}
  7509. @findex extern
  7510. An @code{extern} declaration is used to refer to a global variable
  7511. whose principal declaration comes elsewhere---in the same module, or in
  7512. another compilation module. It looks like this:
  7513. @example
  7514. extern @var{basetype} @var{decorated-variable};
  7515. @end example
  7516. Its meaning is that, in the current scope, the variable name refers to
  7517. the file-scope variable of that name---which needs to be declared in a
  7518. non-@code{extern}, non-@code{static} way somewhere else.
  7519. For instance, if one compilation module has this global variable
  7520. declaration
  7521. @example
  7522. int error_count = 0;
  7523. @end example
  7524. @noindent
  7525. then other compilation modules can specify this
  7526. @example
  7527. extern int error_count;
  7528. @end example
  7529. @noindent
  7530. to allow reference to the same variable.
  7531. The usual place to write an @code{extern} declaration is at top level
  7532. in a source file, but you can write an @code{extern} declaration
  7533. inside a block to make a global or static file-scope variable
  7534. accessible in that block.
  7535. Since an @code{extern} declaration does not allocate space for the
  7536. variable, it can omit the size of an array:
  7537. @example
  7538. extern int array[];
  7539. @end example
  7540. You can use @code{array} normally in all contexts where it is
  7541. converted automatically to a pointer. However, to use it as the
  7542. operand of @code{sizeof} is an error, since the size is unknown.
  7543. It is valid to have multiple @code{extern} declarations for the same
  7544. variable, even in the same scope, if they give the same type. They do
  7545. not conflict---they agree. For an array, it is legitimate for some
  7546. @code{extern} declarations can specify the size while others omit it.
  7547. However, if two declarations give different sizes, that is an error.
  7548. Likewise, you can use @code{extern} declarations at file scope
  7549. (@pxref{File-Scope Variables}) followed by an ordinary global
  7550. (non-static) declaration of the same variable. They do not conflict,
  7551. because they say compatible things about the same meaning of the variable.
  7552. @node Allocating File-Scope
  7553. @section Allocating File-Scope Variables
  7554. @cindex allocation file-scope variables
  7555. @cindex file-scope variables, allocating
  7556. Some file-scope declarations allocate space for the variable, and some
  7557. don't.
  7558. A file-scope declaration with an initial value @emph{must} allocate
  7559. space for the variable; if there are two of such declarations for the
  7560. same variable, even in different compilation modules, they conflict.
  7561. An @code{extern} declaration @emph{never} allocates space for the variable.
  7562. If all the top-level declarations of a certain variable are
  7563. @code{extern}, the variable never gets memory space. If that variable
  7564. is used anywhere in the program, the use will be reported as an error,
  7565. saying that the variable is not defined.
  7566. @cindex tentative definition
  7567. A file-scope declaration without an initial value is called a
  7568. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7569. allocate space for the variable, but does not insist. So it causes no
  7570. conflict, no error, if the variable has another declaration that
  7571. allocates space for it, perhaps in another compilation module. But if
  7572. nothing else allocates space for the variable, the tentative
  7573. definition will do it. Any number of compilation modules can declare
  7574. the same variable in this way, and that is sufficient for all of them
  7575. to use the variable.
  7576. @c @opindex -fno-common
  7577. @c @opindex --warn_common
  7578. In programs that are very large or have many contributors, it may be
  7579. wise to adopt the convention of never using tentative definitions.
  7580. You can use the compilation option @option{-fno-common} to make them
  7581. an error, or @option{--warn-common} to warn about them.
  7582. If a file-scope variable gets its space through a tentative
  7583. definition, it starts out containing all zeros.
  7584. @node auto and register
  7585. @section @code{auto} and @code{register}
  7586. @cindex @code{auto} declarations
  7587. @cindex @code{register} declarations
  7588. @findex auto
  7589. @findex register
  7590. For historical reasons, you can write @code{auto} or @code{register}
  7591. before a local variable declaration. @code{auto} merely emphasizes
  7592. that the variable isn't static; it changes nothing.
  7593. @code{register} suggests to the compiler storing this variable in a
  7594. register. However, GNU C ignores this suggestion, since it can
  7595. choose the best variables to store in registers without any hints.
  7596. It is an error to take the address of a variable declared
  7597. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7598. If the variable is an array, you can't use it at all (other than as
  7599. the operand of @code{sizeof}), which makes it rather useless.
  7600. @node Omitting Types
  7601. @section Omitting Types in Declarations
  7602. @cindex omitting types in declarations
  7603. The syntax of C traditionally allows omitting the data type in a
  7604. declaration if it specifies a storage class, a type qualifier (see the
  7605. next chapter), or @code{auto} or @code{register}. Then the type
  7606. defaults to @code{int}. For example:
  7607. @example
  7608. auto foo = 42;
  7609. @end example
  7610. This is bad practice; if you see it, fix it.
  7611. @node Type Qualifiers
  7612. @chapter Type Qualifiers
  7613. A declaration can include type qualifiers to advise the compiler
  7614. about how the variable will be used. There are three different
  7615. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7616. pertain to different issues, so you can use more than one together.
  7617. For instance, @code{const volatile} describes a value that the
  7618. program is not allowed to change, but might have a different value
  7619. each time the program examines it. (This might perhaps be a special
  7620. hardware register, or part of shared memory.)
  7621. If you are just learning C, you can skip this chapter.
  7622. @menu
  7623. * const:: Variables whose values don't change.
  7624. * volatile:: Variables whose values may be accessed
  7625. or changed outside of the control of
  7626. this program.
  7627. * restrict Pointers:: Restricted pointers for code optimization.
  7628. * restrict Pointer Example:: Example of how that works.
  7629. @end menu
  7630. @node const
  7631. @section @code{const} Variables and Fields
  7632. @cindex @code{const} variables and fields
  7633. @cindex variables, @code{const}
  7634. @findex const
  7635. You can mark a variable as ``constant'' by writing @code{const} in
  7636. front of the declaration. This says to treat any assignment to that
  7637. variable as an error. It may also permit some compiler
  7638. optimizations---for instance, to fetch the value only once to satisfy
  7639. multiple references to it. The construct looks like this:
  7640. @example
  7641. const double pi = 3.14159;
  7642. @end example
  7643. After this definition, the code can use the variable @code{pi}
  7644. but cannot assign a different value to it.
  7645. @example
  7646. pi = 3.0; /* @r{Error!} */
  7647. @end example
  7648. Simple variables that are constant can be used for the same purposes
  7649. as enumeration constants, and they are not limited to integers. The
  7650. constantness of the variable propagates into pointers, too.
  7651. A pointer type can specify that the @emph{target} is constant. For
  7652. example, the pointer type @code{const double *} stands for a pointer
  7653. to a constant @code{double}. That's the typethat results from taking
  7654. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7655. left side of an assignment.
  7656. @example
  7657. *(&pi) = 3.0; /* @r{Error!} */
  7658. @end example
  7659. Nonconstant pointers can be converted automatically to constant
  7660. pointers, but not vice versa. For instance,
  7661. @example
  7662. const double *cptr;
  7663. double *ptr;
  7664. cptr = &pi; /* @r{Valid.} */
  7665. cptr = ptr; /* @r{Valid.} */
  7666. ptr = cptr; /* @r{Error!} */
  7667. ptr = &pi; /* @r{Error!} */
  7668. @end example
  7669. This is not an ironclad protection against modifying the value. You
  7670. can always cast the constant pointer to a nonconstant pointer type:
  7671. @example
  7672. ptr = (double *)cptr; /* @r{Valid.} */
  7673. ptr = (double *)&pi; /* @r{Valid.} */
  7674. @end example
  7675. However, @code{const} provides a way to show that a certain function
  7676. won't modify the data structure whose address is passed to it. Here's
  7677. an example:
  7678. @example
  7679. int
  7680. string_length (const char *string)
  7681. @{
  7682. int count = 0;
  7683. while (*string++)
  7684. count++;
  7685. return count;
  7686. @}
  7687. @end example
  7688. @noindent
  7689. Using @code{const char *} for the parameter is a way of saying this
  7690. function never modifies the memory of the string itself.
  7691. In calling @code{string_length}, you can specify an ordinary
  7692. @code{char *} since that can be converted automatically to @code{const
  7693. char *}.
  7694. @node volatile
  7695. @section @code{volatile} Variables and Fields
  7696. @cindex @code{volatile} variables and fields
  7697. @cindex variables, @code{volatile}
  7698. @findex volatile
  7699. The GNU C compiler often performs optimizations that eliminate the
  7700. need to write or read a variable. For instance,
  7701. @example
  7702. int foo;
  7703. foo = 1;
  7704. foo++;
  7705. @end example
  7706. @noindent
  7707. might simply store the value 2 into @code{foo}, without ever storing 1.
  7708. These optimizations can also apply to structure fields in some cases.
  7709. If the memory containing @code{foo} is shared with another program,
  7710. or if it is examined asynchronously by hardware, such optimizations
  7711. could confuse the communication. Using @code{volatile} is one way
  7712. to prevent them.
  7713. Writing @code{volatile} with the type in a variable or field declaration
  7714. says that the value may be examined or changed for reasons outside the
  7715. control of the program at any moment. Therefore, the program must
  7716. execute in a careful way to assure correct interaction with those
  7717. accesses, whenever they may occur.
  7718. The simplest use looks like this:
  7719. @example
  7720. volatile int lock;
  7721. @end example
  7722. This directs the compiler not to do certain common optimizations on
  7723. use of the variable @code{lock}. All the reads and writes for a volatile
  7724. variable or field are really done, and done in the order specified
  7725. by the source code. Thus, this code:
  7726. @example
  7727. lock = 1;
  7728. list = list->next;
  7729. if (lock)
  7730. lock_broken (&lock);
  7731. lock = 0;
  7732. @end example
  7733. @noindent
  7734. really stores the value 1 in @code{lock}, even though there is no
  7735. sign it is really used, and the @code{if} statement reads and
  7736. checks the value of @code{lock}, rather than assuming it is still 1.
  7737. A limited amount of optimization can be done, in principle, on
  7738. @code{volatile} variables and fields: multiple references between two
  7739. sequence points (@pxref{Sequence Points}) can be simplified together.
  7740. Use of @code{volatile} does not eliminate the flexibility in ordering
  7741. the computation of the operands of most operators. For instance, in
  7742. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7743. @code{foo} is not specified, so they may be done in either order; the
  7744. fact that @code{lock} is @code{volatile} has no effect on that.
  7745. @node restrict Pointers
  7746. @section @code{restrict}-Qualified Pointers
  7747. @cindex @code{restrict} pointers
  7748. @cindex pointers, @code{restrict}-qualified
  7749. @findex restrict
  7750. You can declare a pointer as ``restricted'' using the @code{restrict}
  7751. type qualifier, like this:
  7752. @example
  7753. int *restrict p = x;
  7754. @end example
  7755. @noindent
  7756. This enables better optimization of code that uses the pointer.
  7757. If @code{p} is declared with @code{restrict}, and then the code
  7758. references the object that @code{p} points to (using @code{*p} or
  7759. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7760. code will not access that object in any other way---only through
  7761. @code{p}.
  7762. For instance, it means the code must not use another pointer
  7763. to access the same space, as shown here:
  7764. @example
  7765. int *restrict p = @var{whatever};
  7766. int *q = p;
  7767. foo (*p, *q);
  7768. @end example
  7769. @noindent
  7770. That contradicts the @code{restrict} promise by accessing the object
  7771. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7772. Likewise, it must not do this:
  7773. @example
  7774. int *restrict p = @var{whatever};
  7775. struct @{ int *a, *b; @} s;
  7776. s.a = p;
  7777. foo (*p, *s.a);
  7778. @end example
  7779. @noindent
  7780. This example uses a structure field instead of the variable @code{q}
  7781. to hold the other pointer, and that contradicts the promise just the
  7782. same.
  7783. The keyword @code{restrict} also promises that @code{p} won't point to
  7784. the allocated space of any automatic or static variable. So the code
  7785. must not do this:
  7786. @example
  7787. int a;
  7788. int *restrict p = &a;
  7789. foo (*p, a);
  7790. @end example
  7791. @noindent
  7792. because that does direct access to the object (@code{a}) that @code{p}
  7793. points to, which bypasses @code{p}.
  7794. If the code makes such promises with @code{restrict} then breaks them,
  7795. execution is unpredictable.
  7796. @node restrict Pointer Example
  7797. @section @code{restrict} Pointer Example
  7798. Here are examples where @code{restrict} enables real optimization.
  7799. In this example, @code{restrict} assures GCC that the array @code{out}
  7800. points to does not overlap with the array @code{in} points to.
  7801. @example
  7802. void
  7803. process_data (const char *in,
  7804. char * restrict out,
  7805. size_t size)
  7806. @{
  7807. for (i = 0; i < size; i++)
  7808. out[i] = in[i] + in[i + 1];
  7809. @}
  7810. @end example
  7811. Here's a simple tree structure, where each tree node holds data of
  7812. type @code{PAYLOAD} plus two subtrees.
  7813. @example
  7814. struct foo
  7815. @{
  7816. PAYLOAD payload;
  7817. struct foo *left;
  7818. struct foo *right;
  7819. @};
  7820. @end example
  7821. Now here's a function to null out both pointers in the @code{left}
  7822. subtree.
  7823. @example
  7824. void
  7825. null_left (struct foo *a)
  7826. @{
  7827. a->left->left = NULL;
  7828. a->left->right = NULL;
  7829. @}
  7830. @end example
  7831. Since @code{*a} and @code{*a->left} have the same data type,
  7832. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7833. the compiled code for @code{null_left} must read @code{a->left}
  7834. again from memory when executing the second assignment statement.
  7835. We can enable optimization, so that it does not need to read
  7836. @code{a->left} again, by writing @code{null_left} this in a less
  7837. obvious way.
  7838. @example
  7839. void
  7840. null_left (struct foo *a)
  7841. @{
  7842. struct foo *b = a->left;
  7843. b->left = NULL;
  7844. b->right = NULL;
  7845. @}
  7846. @end example
  7847. A more elegant way to fix this is with @code{restrict}.
  7848. @example
  7849. void
  7850. null_left (struct foo *restrict a)
  7851. @{
  7852. a->left->left = NULL;
  7853. a->left->right = NULL;
  7854. @}
  7855. @end example
  7856. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7857. as @code{a->left} will not point to the same memory space as @code{a}.
  7858. Therefore, the memory location @code{a->left->left} cannot be the same
  7859. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7860. reloading @code{a->left} for the second statement.
  7861. @node Functions
  7862. @chapter Functions
  7863. @cindex functions
  7864. We have already presented many examples of functions, so if you've
  7865. read this far, you basically understand the concept of a function. It
  7866. is vital, nonetheless, to have a chapter in the manual that collects
  7867. all the information about functions.
  7868. @menu
  7869. * Function Definitions:: Writing the body of a function.
  7870. * Function Declarations:: Declaring the interface of a function.
  7871. * Function Calls:: Using functions.
  7872. * Function Call Semantics:: Call-by-value argument passing.
  7873. * Function Pointers:: Using references to functions.
  7874. * The main Function:: Where execution of a GNU C program begins.
  7875. * Advanced Definitions:: Advanced features of function definitions.
  7876. * Obsolete Definitions:: Obsolete features still used
  7877. in function definitions in old code.
  7878. @end menu
  7879. @node Function Definitions
  7880. @section Function Definitions
  7881. @cindex function definitions
  7882. @cindex defining functions
  7883. We have already presented many examples of function definitions. To
  7884. summarize the rules, a function definition looks like this:
  7885. @example
  7886. @var{returntype}
  7887. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7888. @{
  7889. @var{body}
  7890. @}
  7891. @end example
  7892. The part before the open-brace is called the @dfn{function header}.
  7893. Write @code{void} as the @var{returntype} if the function does
  7894. not return a value.
  7895. @menu
  7896. * Function Parameter Variables:: Syntax and semantics
  7897. of function parameters.
  7898. * Forward Function Declarations:: Functions can only be called after
  7899. they have been defined or declared.
  7900. * Static Functions:: Limiting visibility of a function.
  7901. * Arrays as Parameters:: Functions that accept array arguments.
  7902. * Structs as Parameters:: Functions that accept structure arguments.
  7903. @end menu
  7904. @node Function Parameter Variables
  7905. @subsection Function Parameter Variables
  7906. @cindex function parameter variables
  7907. @cindex parameter variables in functions
  7908. @cindex parameter list
  7909. A function parameter variable is a local variable (@pxref{Local
  7910. Variables}) used within the function to store the value passed as an
  7911. argument in a call to the function. Usually we say ``function
  7912. parameter'' or ``parameter'' for short, not mentioning the fact that
  7913. it's a variable.
  7914. We declare these variables in the beginning of the function
  7915. definition, in the @dfn{parameter list}. For example,
  7916. @example
  7917. fib (int n)
  7918. @end example
  7919. @noindent
  7920. has a parameter list with one function parameter @code{n}, which has
  7921. type @code{int}.
  7922. Function parameter declarations differ from ordinary variable
  7923. declarations in several ways:
  7924. @itemize @bullet
  7925. @item
  7926. Inside the function definition header, commas separate parameter
  7927. declarations, and each parameter needs a complete declaration
  7928. including the type. For instance, if a function @code{foo} has two
  7929. @code{int} parameters, write this:
  7930. @example
  7931. foo (int a, int b)
  7932. @end example
  7933. You can't share the common @code{int} between the two declarations:
  7934. @example
  7935. foo (int a, b) /* @r{Invalid!} */
  7936. @end example
  7937. @item
  7938. A function parameter variable is initialized to whatever value is
  7939. passed in the function call, so its declaration cannot specify an
  7940. initial value.
  7941. @item
  7942. Writing an array type in a function parameter declaration has the
  7943. effect of declaring it as a pointer. The size specified for the array
  7944. has no effect at all, and we normally omit the size. Thus,
  7945. @example
  7946. foo (int a[5])
  7947. foo (int a[])
  7948. foo (int *a)
  7949. @end example
  7950. @noindent
  7951. are equivalent.
  7952. @item
  7953. The scope of the parameter variables is the entire function body,
  7954. notwithstanding the fact that they are written in the function header,
  7955. which is just outside the function body.
  7956. @end itemize
  7957. If a function has no parameters, it would be most natural for the
  7958. list of parameters in its definition to be empty. But that, in C, has
  7959. a special meaning for historical reasons: ``Do not check that calls to
  7960. this function have the right number of arguments.'' Thus,
  7961. @example
  7962. int
  7963. foo ()
  7964. @{
  7965. return 5;
  7966. @}
  7967. int
  7968. bar (int x)
  7969. @{
  7970. return foo (x);
  7971. @}
  7972. @end example
  7973. @noindent
  7974. would not report a compilation error in passing @code{x} as an
  7975. argument to @code{foo}. By contrast,
  7976. @example
  7977. int
  7978. foo (void)
  7979. @{
  7980. return 5;
  7981. @}
  7982. int
  7983. bar (int x)
  7984. @{
  7985. return foo (x);
  7986. @}
  7987. @end example
  7988. @noindent
  7989. would report an error because @code{foo} is supposed to receive
  7990. no arguments.
  7991. @node Forward Function Declarations
  7992. @subsection Forward Function Declarations
  7993. @cindex forward function declarations
  7994. @cindex function declarations, forward
  7995. The order of the function definitions in the source code makes no
  7996. difference, except that each function needs to be defined or declared
  7997. before code uses it.
  7998. The definition of a function also declares its name for the rest of
  7999. the containing scope. But what if you want to call the function
  8000. before its definition? To permit that, write a compatible declaration
  8001. of the same function, before the first call. A declaration that
  8002. prefigures a subsequent definition in this way is called a
  8003. @dfn{forward declaration}. The function declaration can be at top
  8004. @c ??? file scope
  8005. level or within a block, and it applies until the end of the containing
  8006. scope.
  8007. @xref{Function Declarations}, for more information about these
  8008. declarations.
  8009. @node Static Functions
  8010. @subsection Static Functions
  8011. @cindex static functions
  8012. @cindex functions, static
  8013. @findex static
  8014. The keyword @code{static} in a function definition limits the
  8015. visibility of the name to the current compilation module. (That's the
  8016. same thing @code{static} does in variable declarations;
  8017. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8018. contains this code:
  8019. @example
  8020. static int
  8021. foo (void)
  8022. @{
  8023. @r{@dots{}}
  8024. @}
  8025. @end example
  8026. @noindent
  8027. then the code of that compilation module can call @code{foo} anywhere
  8028. after the definition, but other compilation modules cannot refer to it
  8029. at all.
  8030. @cindex forward declaration
  8031. @cindex static function, declaration
  8032. To call @code{foo} before its definition, it needs a forward
  8033. declaration, which should use @code{static} since the function
  8034. definition does. For this function, it looks like this:
  8035. @example
  8036. static int foo (void);
  8037. @end example
  8038. It is generally wise to use @code{static} on the definitions of
  8039. functions that won't be called from outside the same compilation
  8040. module. This makes sure that calls are not added in other modules.
  8041. If programmers decide to change the function's calling convention, or
  8042. understand all the consequences of its use, they will only have to
  8043. check for calls in the same compilation module.
  8044. @node Arrays as Parameters
  8045. @subsection Arrays as Parameters
  8046. @cindex array as parameters
  8047. @cindex functions with array parameters
  8048. Arrays in C are not first-class objects: it is impossible to copy
  8049. them. So they cannot be passed as arguments like other values.
  8050. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8051. a special way.
  8052. @menu
  8053. * Array Parm Pointer::
  8054. * Passing Array Args::
  8055. * Array Parm Qualifiers::
  8056. @end menu
  8057. @node Array Parm Pointer
  8058. @subsubsection Array parameters are pointers
  8059. Declaring a function parameter variable as an array really gives it a
  8060. pointer type. C does this because an expression with array type, if
  8061. used as an argument in a function call, is converted automatically to
  8062. a pointer (to the zeroth element of the array). If you declare the
  8063. corresponding parameter as an ``array'', it will work correctly with
  8064. the pointer value that really gets passed.
  8065. This relates to the fact that C does not check array bounds in access
  8066. to elements of the array (@pxref{Accessing Array Elements}).
  8067. For example, in this function,
  8068. @example
  8069. void
  8070. clobber4 (int array[20])
  8071. @{
  8072. array[4] = 0;
  8073. @}
  8074. @end example
  8075. @noindent
  8076. the parameter @code{array}'s real type is @code{int *}; the specified
  8077. length, 20, has no effect on the program. You can leave out the length
  8078. and write this:
  8079. @example
  8080. void
  8081. clobber4 (int array[])
  8082. @{
  8083. array[4] = 0;
  8084. @}
  8085. @end example
  8086. @noindent
  8087. or write the parameter declaration explicitly as a pointer:
  8088. @example
  8089. void
  8090. clobber4 (int *array)
  8091. @{
  8092. array[4] = 0;
  8093. @}
  8094. @end example
  8095. They are all equivalent.
  8096. @node Passing Array Args
  8097. @subsubsection Passing array arguments
  8098. The function call passes this pointer by
  8099. value, like all argument values in C@. However, the result is
  8100. paradoxical in that the array itself is passed by reference: its
  8101. contents are treated as shared memory---shared between the caller and
  8102. the called function, that is. When @code{clobber4} assigns to element
  8103. 4 of @code{array}, the effect is to alter element 4 of the array
  8104. specified in the call.
  8105. @example
  8106. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8107. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8108. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8109. int
  8110. main (void)
  8111. @{
  8112. int data[] = @{1, 2, 3, 4, 5, 6@};
  8113. int i;
  8114. /* @r{Show the initial value of element 4.} */
  8115. for (i = 0; i < 6; i++)
  8116. printf ("data[%d] = %d\n", i, data[i]);
  8117. printf ("\n");
  8118. clobber4 (data);
  8119. /* @r{Show that element 4 has been changed.} */
  8120. for (i = 0; i < 6; i++)
  8121. printf ("data[%d] = %d\n", i, data[i]);
  8122. printf ("\n");
  8123. return EXIT_SUCCESS;
  8124. @}
  8125. @end example
  8126. @noindent
  8127. shows that @code{data[4]} has become zero after the call to
  8128. @code{clobber4}.
  8129. The array @code{data} has 6 elements, but passing it to a function
  8130. whose argument type is written as @code{int [20]} is not an error,
  8131. because that really stands for @code{int *}. The pointer that is the
  8132. real argument carries no indication of the length of the array it
  8133. points into. It is not required to point to the beginning of the
  8134. array, either. For instance,
  8135. @example
  8136. clobber4 (data+1);
  8137. @end example
  8138. @noindent
  8139. passes an ``array'' that starts at element 1 of @code{data}, and the
  8140. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8141. If all calls to the function will provide an array of a particular
  8142. size, you can specify the size of the array to be @code{static}:
  8143. @example
  8144. void
  8145. clobber4 (int array[static 20])
  8146. @r{@dots{}}
  8147. @end example
  8148. @noindent
  8149. This is a promise to the compiler that the function will always be
  8150. called with an array of 20 elements, so that the compiler can optimize
  8151. code accordingly. If the code breaks this promise and calls the
  8152. function with, for example, a shorter array, unpredictable things may
  8153. happen.
  8154. @node Array Parm Qualifiers
  8155. @subsubsection Type qualifiers on array parameters
  8156. You can use the type qualifiers @code{const}, @code{restrict}, and
  8157. @code{volatile} with array parameters; for example:
  8158. @example
  8159. void
  8160. clobber4 (volatile int array[20])
  8161. @r{@dots{}}
  8162. @end example
  8163. @noindent
  8164. denotes that @code{array} is equivalent to a pointer to a volatile
  8165. @code{int}. Alternatively:
  8166. @example
  8167. void
  8168. clobber4 (int array[const 20])
  8169. @r{@dots{}}
  8170. @end example
  8171. @noindent
  8172. makes the array parameter equivalent to a constant pointer to an
  8173. @code{int}. If we want the @code{clobber4} function to succeed, it
  8174. would not make sense to write
  8175. @example
  8176. void
  8177. clobber4 (const int array[20])
  8178. @r{@dots{}}
  8179. @end example
  8180. @noindent
  8181. as this would tell the compiler that the parameter should point to an
  8182. array of constant @code{int} values, and then we would not be able to
  8183. store zeros in them.
  8184. In a function with multiple array parameters, you can use @code{restrict}
  8185. to tell the compiler that each array parameter passed in will be distinct:
  8186. @example
  8187. void
  8188. foo (int array1[restrict 10], int array2[restrict 10])
  8189. @r{@dots{}}
  8190. @end example
  8191. @noindent
  8192. Using @code{restrict} promises the compiler that callers will
  8193. not pass in the same array for more than one @code{restrict} array
  8194. parameter. Knowing this enables the compiler to perform better code
  8195. optimization. This is the same effect as using @code{restrict}
  8196. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8197. the code that an array of a specific size is expected.
  8198. @node Structs as Parameters
  8199. @subsection Functions That Accept Structure Arguments
  8200. Structures in GNU C are first-class objects, so using them as function
  8201. parameters and arguments works in the natural way. This function
  8202. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8203. and returns a structure of the same type but with the fields
  8204. exchanged.
  8205. @example
  8206. struct foo @{ int a, b; @};
  8207. struct foo x;
  8208. struct foo
  8209. swapfoo (struct foo inval)
  8210. @{
  8211. struct foo outval;
  8212. outval.a = inval.b;
  8213. outval.b = inval.a;
  8214. return outval;
  8215. @}
  8216. @end example
  8217. This simpler definition of @code{swapfoo} avoids using a local
  8218. variable to hold the result about to be return, by using a structure
  8219. constructor (@pxref{Structure Constructors}), like this:
  8220. @example
  8221. struct foo
  8222. swapfoo (struct foo inval)
  8223. @{
  8224. return (struct foo) @{ inval.b, inval.a @};
  8225. @}
  8226. @end example
  8227. It is valid to define a structure type in a function's parameter list,
  8228. as in
  8229. @example
  8230. int
  8231. frob_bar (struct bar @{ int a, b; @} inval)
  8232. @{
  8233. @var{body}
  8234. @}
  8235. @end example
  8236. @noindent
  8237. and @var{body} can access the fields of @var{inval} since the
  8238. structure type @code{struct bar} is defined for the whole function
  8239. body. However, there is no way to create a @code{struct bar} argument
  8240. to pass to @code{frob_bar}, except with kludges. As a result,
  8241. defining a structure type in a parameter list is useless in practice.
  8242. @node Function Declarations
  8243. @section Function Declarations
  8244. @cindex function declarations
  8245. @cindex declararing functions
  8246. To call a function, or use its name as a pointer, a @dfn{function
  8247. declaration} for the function name must be in effect at that point in
  8248. the code. The function's definition serves as a declaration of that
  8249. function for the rest of the containing scope, but to use the function
  8250. in code before the definition, or from another compilation module, a
  8251. separate function declaration must precede the use.
  8252. A function declaration looks like the start of a function definition.
  8253. It begins with the return value type (@code{void} if none) and the
  8254. function name, followed by argument declarations in parentheses
  8255. (though these can sometimes be omitted). But that's as far as the
  8256. similarity goes: instead of the function body, the declaration uses a
  8257. semicolon.
  8258. @cindex function prototype
  8259. @cindex prototype of a function
  8260. A declaration that specifies argument types is called a @dfn{function
  8261. prototype}. You can include the argument names or omit them. The
  8262. names, if included in the declaration, have no effect, but they may
  8263. serve as documentation.
  8264. This form of prototype specifies fixed argument types:
  8265. @example
  8266. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8267. @end example
  8268. @noindent
  8269. This form says the function takes no arguments:
  8270. @example
  8271. @var{rettype} @var{function} (void);
  8272. @end example
  8273. @noindent
  8274. This form declares types for some arguments, and allows additional
  8275. arguments whose types are not specified:
  8276. @example
  8277. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8278. @end example
  8279. For a parameter that's an array of variable length, you can write
  8280. its declaration with @samp{*} where the ``length'' of the array would
  8281. normally go; for example, these are all equivalent.
  8282. @example
  8283. double maximum (int n, int m, double a[n][m]);
  8284. double maximum (int n, int m, double a[*][*]);
  8285. double maximum (int n, int m, double a[ ][*]);
  8286. double maximum (int n, int m, double a[ ][m]);
  8287. @end example
  8288. @noindent
  8289. The old-fashioned form of declaration, which is not a prototype, says
  8290. nothing about the types of arguments or how many they should be:
  8291. @example
  8292. @var{rettype} @var{function} ();
  8293. @end example
  8294. @strong{Warning:} Arguments passed to a function declared without a
  8295. prototype are converted with the default argument promotions
  8296. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8297. types are unspecified.
  8298. Function declarations are usually written at the top level in a source file,
  8299. but you can also put them inside code blocks. Then the function name
  8300. is visible for the rest of the containing scope. For example:
  8301. @example
  8302. void
  8303. foo (char *file_name)
  8304. @{
  8305. void save_file (char *);
  8306. save_file (file_name);
  8307. @}
  8308. @end example
  8309. If another part of the code tries to call the function
  8310. @code{save_file}, this declaration won't be in effect there. So the
  8311. function will get an implicit declaration of the form @code{extern int
  8312. save_file ();}. That conflicts with the explicit declaration
  8313. here, and the discrepancy generates a warning.
  8314. The syntax of C traditionally allows omitting the data type in a
  8315. function declaration if it specifies a storage class or a qualifier.
  8316. Then the type defaults to @code{int}. For example:
  8317. @example
  8318. static foo (double x);
  8319. @end example
  8320. @noindent
  8321. defaults the return type to @code{int}.
  8322. This is bad practice; if you see it, fix it.
  8323. Calling a function that is undeclared has the effect of an creating
  8324. @dfn{implicit} declaration in the innermost containing scope,
  8325. equivalent to this:
  8326. @example
  8327. extern int @dfn{function} ();
  8328. @end example
  8329. @noindent
  8330. This declaration says that the function returns @code{int} but leaves
  8331. its argument types unspecified. If that does not accurately fit the
  8332. function, then the program @strong{needs} an explicit declaration of
  8333. the function with argument types in order to call it correctly.
  8334. Implicit declarations are deprecated, and a function call that creates one
  8335. causes a warning.
  8336. @node Function Calls
  8337. @section Function Calls
  8338. @cindex function calls
  8339. @cindex calling functions
  8340. Starting a program automatically calls the function named @code{main}
  8341. (@pxref{The main Function}). Aside from that, a function does nothing
  8342. except when it is @dfn{called}. That occurs during the execution of a
  8343. function-call expression specifying that function.
  8344. A function-call expression looks like this:
  8345. @example
  8346. @var{function} (@var{arguments}@r{@dots{}})
  8347. @end example
  8348. Most of the time, @var{function} is a function name. However, it can
  8349. also be an expression with a function pointer value; that way, the
  8350. program can determine at run time which function to call.
  8351. The @var{arguments} are a series of expressions separated by commas.
  8352. Each expression specifies one argument to pass to the function.
  8353. The list of arguments in a function call looks just like use of the
  8354. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8355. the parentheses of a function call gives it a different meaning.
  8356. Here's an example of a function call, taken from an example near the
  8357. beginning (@pxref{Complete Program}).
  8358. @example
  8359. printf ("Fibonacci series item %d is %d\n",
  8360. 19, fib (19));
  8361. @end example
  8362. The three arguments given to @code{printf} are a constant string, the
  8363. integer 19, and the integer returned by @code{fib (19)}.
  8364. @node Function Call Semantics
  8365. @section Function Call Semantics
  8366. @cindex function call semantics
  8367. @cindex semantics of function calls
  8368. @cindex call-by-value
  8369. The meaning of a function call is to compute the specified argument
  8370. expressions, convert their values according to the function's
  8371. declaration, then run the function giving it copies of the converted
  8372. values. (This method of argument passing is known as
  8373. @dfn{call-by-value}.) When the function finishes, the value it
  8374. returns becomes the value of the function-call expression.
  8375. Call-by-value implies that an assignment to the function argument
  8376. variable has no direct effect on the caller. For instance,
  8377. @example
  8378. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8379. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8380. void
  8381. subroutine (int x)
  8382. @{
  8383. x = 5;
  8384. @}
  8385. void
  8386. main (void)
  8387. @{
  8388. int y = 20;
  8389. subroutine (y);
  8390. printf ("y is %d\n", y);
  8391. return EXIT_SUCCESS;
  8392. @}
  8393. @end example
  8394. @noindent
  8395. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8396. from the value of @code{y}, but this does not establish any other
  8397. relationship between the two variables. Thus, the assignment to
  8398. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8399. If an argument's type is specified by the function's declaration, the
  8400. function call converts the argument expression to that type if
  8401. possible. If the conversion is impossible, that is an error.
  8402. If the function's declaration doesn't specify the type of that
  8403. argument, then the @emph{default argument promotions} apply.
  8404. @xref{Argument Promotions}.
  8405. @node Function Pointers
  8406. @section Function Pointers
  8407. @cindex function pointers
  8408. @cindex pointers to functions
  8409. A function name refers to a fixed function. Sometimes it is useful to
  8410. call a function to be determined at run time; to do this, you can use
  8411. a @dfn{function pointer value} that points to the chosen function
  8412. (@pxref{Pointers}).
  8413. Pointer-to-function types can be used to declare variables and other
  8414. data, including array elements, structure fields, and union
  8415. alternatives. They can also be used for function arguments and return
  8416. values. These types have the peculiarity that they are never
  8417. converted automatically to @code{void *} or vice versa. However, you
  8418. can do that conversion with a cast.
  8419. @menu
  8420. * Declaring Function Pointers:: How to declare a pointer to a function.
  8421. * Assigning Function Pointers:: How to assign values to function pointers.
  8422. * Calling Function Pointers:: How to call functions through pointers.
  8423. @end menu
  8424. @node Declaring Function Pointers
  8425. @subsection Declaring Function Pointers
  8426. @cindex declaring function pointers
  8427. @cindex function pointers, declaring
  8428. The declaration of a function pointer variable (or structure field)
  8429. looks almost like a function declaration, except it has an additional
  8430. @samp{*} just before the variable name. Proper nesting requires a
  8431. pair of parentheses around the two of them. For instance, @code{int
  8432. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8433. an @code{int}-returning function.''
  8434. Contrast these three declarations:
  8435. @example
  8436. /* @r{Declare a function returning @code{char *}.} */
  8437. char *a (char *);
  8438. /* @r{Declare a pointer to a function returning @code{char}.} */
  8439. char (*a) (char *);
  8440. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8441. char *(*a) (char *);
  8442. @end example
  8443. The possible argument types of the function pointed to are the same
  8444. as in a function declaration. You can write a prototype
  8445. that specifies all the argument types:
  8446. @example
  8447. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8448. @end example
  8449. @noindent
  8450. or one that specifies some and leaves the rest unspecified:
  8451. @example
  8452. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8453. @end example
  8454. @noindent
  8455. or one that says there are no arguments:
  8456. @example
  8457. @var{rettype} (*@var{function}) (void);
  8458. @end example
  8459. You can also write a non-prototype declaration that says
  8460. nothing about the argument types:
  8461. @example
  8462. @var{rettype} (*@var{function}) ();
  8463. @end example
  8464. For example, here's a declaration for a variable that should
  8465. point to some arithmetic function that operates on two @code{double}s:
  8466. @example
  8467. double (*binary_op) (double, double);
  8468. @end example
  8469. Structure fields, union alternatives, and array elements can be
  8470. function pointers; so can parameter variables. The function pointer
  8471. declaration construct can also be combined with other operators
  8472. allowed in declarations. For instance,
  8473. @example
  8474. int **(*foo)();
  8475. @end example
  8476. @noindent
  8477. declares @code{foo} as a pointer to a function that returns
  8478. type @code{int **}, and
  8479. @example
  8480. int **(*foo[30])();
  8481. @end example
  8482. @noindent
  8483. declares @code{foo} as an array of 30 pointers to functions that
  8484. return type @code{int **}.
  8485. @example
  8486. int **(**foo)();
  8487. @end example
  8488. @noindent
  8489. declares @code{foo} as a pointer to a pointer to a function that
  8490. returns type @code{int **}.
  8491. @node Assigning Function Pointers
  8492. @subsection Assigning Function Pointers
  8493. @cindex assigning function pointers
  8494. @cindex function pointers, assigning
  8495. Assuming we have declared the variable @code{binary_op} as in the
  8496. previous section, giving it a value requires a suitable function to
  8497. use. So let's define a function suitable for the variable to point
  8498. to. Here's one:
  8499. @example
  8500. double
  8501. double_add (double a, double b)
  8502. @{
  8503. return a+b;
  8504. @}
  8505. @end example
  8506. Now we can give it a value:
  8507. @example
  8508. binary_op = double_add;
  8509. @end example
  8510. The target type of the function pointer must be upward compatible with
  8511. the type of the function (@pxref{Compatible Types}).
  8512. There is no need for @samp{&} in front of @code{double_add}.
  8513. Using a function name such as @code{double_add} as an expression
  8514. automatically converts it to the function's address, with the
  8515. appropriate function pointer type. However, it is ok to use
  8516. @samp{&} if you feel that is clearer:
  8517. @example
  8518. binary_op = &double_add;
  8519. @end example
  8520. @node Calling Function Pointers
  8521. @subsection Calling Function Pointers
  8522. @cindex calling function pointers
  8523. @cindex function pointers, calling
  8524. To call the function specified by a function pointer, just write the
  8525. function pointer value in a function call. For instance, here's a
  8526. call to the function @code{binary_op} points to:
  8527. @example
  8528. binary_op (x, 5)
  8529. @end example
  8530. Since the data type of @code{binary_op} explicitly specifies type
  8531. @code{double} for the arguments, the call converts @code{x} and 5 to
  8532. @code{double}.
  8533. The call conceptually dereferences the pointer @code{binary_op} to
  8534. ``get'' the function it points to, and calls that function. If you
  8535. wish, you can explicitly represent the derefence by writing the
  8536. @code{*} operator:
  8537. @example
  8538. (*binary_op) (x, 5)
  8539. @end example
  8540. The @samp{*} reminds people reading the code that @code{binary_op} is
  8541. a function pointer rather than the name of a specific function.
  8542. @node The main Function
  8543. @section The @code{main} Function
  8544. @cindex @code{main} function
  8545. @findex main
  8546. Every complete executable program requires at least one function,
  8547. called @code{main}, which is where execution begins. You do not have
  8548. to explicitly declare @code{main}, though GNU C permits you to do so.
  8549. Conventionally, @code{main} should be defined to follow one of these
  8550. calling conventions:
  8551. @example
  8552. int main (void) @{@r{@dots{}}@}
  8553. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8554. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8555. @end example
  8556. @noindent
  8557. Using @code{void} as the parameter list means that @code{main} does
  8558. not use the arguments. You can write @code{char **argv} instead of
  8559. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8560. constructs are equivalent.
  8561. @ignore @c Not so at present
  8562. Defining @code{main} in any other way generates a warning. Your
  8563. program will still compile, but you may get unexpected results when
  8564. executing it.
  8565. @end ignore
  8566. You can call @code{main} from C code, as you can call any other
  8567. function, though that is an unusual thing to do. When you do that,
  8568. you must write the call to pass arguments that match the parameters in
  8569. the definition of @code{main}.
  8570. The @code{main} function is not actually the first code that runs when
  8571. a program starts. In fact, the first code that runs is system code
  8572. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8573. code, but in GNU we replaced it with C code. Its job is to find
  8574. the arguments for @code{main} and call that.
  8575. @menu
  8576. * Values from main:: Returning values from the main function.
  8577. * Command-line Parameters:: Accessing command-line parameters
  8578. provided to the program.
  8579. * Environment Variables:: Accessing system environment variables.
  8580. @end menu
  8581. @node Values from main
  8582. @subsection Returning Values from @code{main}
  8583. @cindex returning values from @code{main}
  8584. @cindex success
  8585. @cindex failure
  8586. @cindex exit status
  8587. When @code{main} returns, the process terminates. Whatever value
  8588. @code{main} returns becomes the exit status which is reported to the
  8589. parent process. While nominally the return value is of type
  8590. @code{int}, in fact the exit status gets truncated to eight bits; if
  8591. @code{main} returns the value 256, the exit status is 0.
  8592. Normally, programs return only one of two values: 0 for success,
  8593. and 1 for failure. For maximum portability, use the macro
  8594. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8595. @code{stdlib.h}. Here's an example:
  8596. @cindex @code{EXIT_FAILURE}
  8597. @cindex @code{EXIT_SUCCESS}
  8598. @example
  8599. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8600. /* @r{and @code{EXIT_FAILURE}.} */
  8601. int
  8602. main (void)
  8603. @{
  8604. @r{@dots{}}
  8605. if (foo)
  8606. return EXIT_SUCCESS;
  8607. else
  8608. return EXIT_FAILURE;
  8609. @}
  8610. @end example
  8611. Some types of programs maintain special conventions for various return
  8612. values; for example, comparison programs including @code{cmp} and
  8613. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8614. the comparison couldn't be performed.
  8615. @node Command-line Parameters
  8616. @subsection Accessing Command-line Parameters
  8617. @cindex command-line parameters
  8618. @cindex parameters, command-line
  8619. If the program was invoked with any command-line arguments, it can
  8620. access them through the arguments of @code{main}, @code{argc} and
  8621. @code{argv}. (You can give these arguments any names, but the names
  8622. @code{argc} and @code{argv} are customary.)
  8623. The value of @code{argv} is an array containing all of the
  8624. command-line arguments as strings, with the name of the command
  8625. invoked as the first string. @code{argc} is an integer that says how
  8626. many strings @code{argv} contains. Here is an example of accessing
  8627. the command-line parameters, retrieving the program's name and
  8628. checking for the standard @option{--version} and @option{--help} options:
  8629. @example
  8630. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8631. int
  8632. main (int argc, char *argv[])
  8633. @{
  8634. char *program_name = argv[0];
  8635. for (int i = 1; i < argc; i++)
  8636. @{
  8637. if (!strcmp (argv[i], "--version"))
  8638. @{
  8639. /* @r{Print version information and exit.} */
  8640. @r{@dots{}}
  8641. @}
  8642. else if (!strcmp (argv[i], "--help"))
  8643. @{
  8644. /* @r{Print help information and exit.} */
  8645. @r{@dots{}}
  8646. @}
  8647. @}
  8648. @r{@dots{}}
  8649. @}
  8650. @end example
  8651. @node Environment Variables
  8652. @subsection Accessing Environment Variables
  8653. @cindex environment variables
  8654. You can optionally include a third parameter to @code{main}, another
  8655. array of strings, to capture the environment variables available to
  8656. the program. Unlike what happens with @code{argv}, there is no
  8657. additional parameter for the count of environment variables; rather,
  8658. the array of environment variables concludes with a null pointer.
  8659. @example
  8660. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8661. int
  8662. main (int argc, char *argv[], char *envp[])
  8663. @{
  8664. /* @r{Print out all environment variables.} */
  8665. int i = 0;
  8666. while (envp[i])
  8667. @{
  8668. printf ("%s\n", envp[i]);
  8669. i++;
  8670. @}
  8671. @}
  8672. @end example
  8673. Another method of retrieving environment variables is to use the
  8674. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8675. Using @code{getenv} does not require defining @code{main} to accept the
  8676. @code{envp} pointer. For example, here is a program that fetches and prints
  8677. the user's home directory (if defined):
  8678. @example
  8679. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8680. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8681. int
  8682. main (void)
  8683. @{
  8684. char *home_directory = getenv ("HOME");
  8685. if (home_directory)
  8686. printf ("My home directory is: %s\n", home_directory);
  8687. else
  8688. printf ("My home directory is not defined!\n");
  8689. @}
  8690. @end example
  8691. @node Advanced Definitions
  8692. @section Advanced Function Features
  8693. This section describes some advanced or obscure features for GNU C
  8694. function definitions. If you are just learning C, you can skip the
  8695. rest of this chapter.
  8696. @menu
  8697. * Variable-Length Array Parameters:: Functions that accept arrays
  8698. of variable length.
  8699. * Variable Number of Arguments:: Variadic functions.
  8700. * Nested Functions:: Defining functions within functions.
  8701. * Inline Function Definitions:: A function call optimization technique.
  8702. @end menu
  8703. @node Variable-Length Array Parameters
  8704. @subsection Variable-Length Array Parameters
  8705. @cindex variable-length array parameters
  8706. @cindex array parameters, variable-length
  8707. @cindex functions that accept variable-length arrays
  8708. An array parameter can have variable length: simply declare the array
  8709. type with a size that isn't constant. In a nested function, the
  8710. length can refer to a variable defined in a containing scope. In any
  8711. function, it can refer to a previous parameter, like this:
  8712. @example
  8713. struct entry
  8714. tester (int len, char data[len][len])
  8715. @{
  8716. @r{@dots{}}
  8717. @}
  8718. @end example
  8719. Alternatively, in function declarations (but not in function
  8720. definitions), you can use @code{[*]} to denote that the array
  8721. parameter is of a variable length, such that these two declarations
  8722. mean the same thing:
  8723. @example
  8724. struct entry
  8725. tester (int len, char data[len][len]);
  8726. @end example
  8727. @example
  8728. struct entry
  8729. tester (int len, char data[*][*]);
  8730. @end example
  8731. @noindent
  8732. The two forms of input are equivalent in GNU C, but emphasizing that
  8733. the array parameter is variable-length may be helpful to those
  8734. studying the code.
  8735. You can also omit the length parameter, and instead use some other
  8736. in-scope variable for the length in the function definition:
  8737. @example
  8738. struct entry
  8739. tester (char data[*][*]);
  8740. @r{@dots{}}
  8741. int dataLength = 20;
  8742. @r{@dots{}}
  8743. struct entry
  8744. tester (char data[dataLength][dataLength])
  8745. @{
  8746. @r{@dots{}}
  8747. @}
  8748. @end example
  8749. @c ??? check text above
  8750. @cindex parameter forward declaration
  8751. In GNU C, to pass the array first and the length afterward, you can
  8752. use a @dfn{parameter forward declaration}, like this:
  8753. @example
  8754. struct entry
  8755. tester (int len; char data[len][len], int len)
  8756. @{
  8757. @r{@dots{}}
  8758. @}
  8759. @end example
  8760. The @samp{int len} before the semicolon is the parameter forward
  8761. declaration; it serves the purpose of making the name @code{len} known
  8762. when the declaration of @code{data} is parsed.
  8763. You can write any number of such parameter forward declarations in the
  8764. parameter list. They can be separated by commas or semicolons, but
  8765. the last one must end with a semicolon, which is followed by the
  8766. ``real'' parameter declarations. Each forward declaration must match
  8767. a subsequent ``real'' declaration in parameter name and data type.
  8768. Standard C does not support parameter forward declarations.
  8769. @node Variable Number of Arguments
  8770. @subsection Variable-Length Parameter Lists
  8771. @cindex variable-length parameter lists
  8772. @cindex parameters lists, variable length
  8773. @cindex function parameter lists, variable length
  8774. @cindex variadic function
  8775. A function that takes a variable number of arguments is called a
  8776. @dfn{variadic function}. In C, a variadic function must specify at
  8777. least one fixed argument with an explicitly declared data type.
  8778. Additional arguments can follow, and can vary in both quantity and
  8779. data type.
  8780. In the function header, declare the fixed parameters in the normal
  8781. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8782. example of a variadic function header:
  8783. @example
  8784. int add_multiple_values (int number, ...)
  8785. @end example
  8786. @cindex @code{va_list}
  8787. @cindex @code{va_start}
  8788. @cindex @code{va_end}
  8789. The function body can refer to fixed arguments by their parameter
  8790. names, but the additional arguments have no names. Accessing them in
  8791. the function body uses certain standard macros. They are defined in
  8792. the library header file @file{stdarg.h}, so the code must
  8793. @code{#include} that file.
  8794. In the body, write
  8795. @example
  8796. va_list ap;
  8797. va_start (ap, @var{last_fixed_parameter});
  8798. @end example
  8799. @noindent
  8800. This declares the variable @code{ap} (you can use any name for it)
  8801. and then sets it up to point before the first additional argument.
  8802. Then, to fetch the next consecutive additional argument, write this:
  8803. @example
  8804. va_arg (ap, @var{type})
  8805. @end example
  8806. After fetching all the additional arguments (or as many as need to be
  8807. used), write this:
  8808. @example
  8809. va_end (ap);
  8810. @end example
  8811. Here's an example of a variadic function definition that adds any
  8812. number of @code{int} arguments. The first (fixed) argument says how
  8813. many more arguments follow.
  8814. @example
  8815. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8816. @r{@dots{}}
  8817. int
  8818. add_multiple_values (int argcount, ...)
  8819. @{
  8820. int counter, total = 0;
  8821. /* @r{Declare a variable of type @code{va_list}.} */
  8822. va_list argptr;
  8823. /* @r{Initialize that variable..} */
  8824. va_start (argptr, argcount);
  8825. for (counter = 0; counter < argcount; counter++)
  8826. @{
  8827. /* @r{Get the next additional argument.} */
  8828. total += va_arg (argptr, int);
  8829. @}
  8830. /* @r{End use of the @code{argptr} variable.} */
  8831. va_end (argptr);
  8832. return total;
  8833. @}
  8834. @end example
  8835. With GNU C, @code{va_end} is superfluous, but some other compilers
  8836. might make @code{va_start} allocate memory so that calling
  8837. @code{va_end} is necessary to avoid a memory leak. Before doing
  8838. @code{va_start} again with the same variable, do @code{va_end}
  8839. first.
  8840. @cindex @code{va_copy}
  8841. Because of this possible memory allocation, it is risky (in principle)
  8842. to copy one @code{va_list} variable to another with assignment.
  8843. Instead, use @code{va_copy}, which copies the substance but allocates
  8844. separate memory in the variable you copy to. The call looks like
  8845. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8846. @var{from} should be variables of type @code{va_list}. In principle,
  8847. do @code{va_end} on each of these variables before its scope ends.
  8848. Since the additional arguments' types are not specified in the
  8849. function's definition, the default argument promotions
  8850. (@pxref{Argument Promotions}) apply to them in function calls. The
  8851. function definition must take account of this; thus, if an argument
  8852. was passed as @code{short}, the function should get it as @code{int}.
  8853. If an argument was passed as @code{float}, the function should get it
  8854. as @code{double}.
  8855. C has no mechanism to tell the variadic function how many arguments
  8856. were passed to it, so its calling convention must give it a way to
  8857. determine this. That's why @code{add_multiple_values} takes a fixed
  8858. argument that says how many more arguments follow. Thus, you can
  8859. call the function like this:
  8860. @example
  8861. sum = add_multiple_values (3, 12, 34, 190);
  8862. /* @r{Value is 12+34+190.} */
  8863. @end example
  8864. In GNU C, there is no actual need to use the @code{va_end} function.
  8865. In fact, it does nothing. It's used for compatibility with other
  8866. compilers, when that matters.
  8867. It is a mistake to access variables declared as @code{va_list} except
  8868. in the specific ways described here. Just what that type consists of
  8869. is an implementation detail, which could vary from one platform to
  8870. another.
  8871. @node Nested Functions
  8872. @subsection Nested Functions
  8873. @cindex nested functions
  8874. @cindex functions, nested
  8875. @cindex downward funargs
  8876. @cindex thunks
  8877. A @dfn{nested function} is a function defined inside another function.
  8878. The nested function's name is local to the block where it is defined.
  8879. For example, here we define a nested function named @code{square}, and
  8880. call it twice:
  8881. @example
  8882. @group
  8883. foo (double a, double b)
  8884. @{
  8885. double square (double z) @{ return z * z; @}
  8886. return square (a) + square (b);
  8887. @}
  8888. @end group
  8889. @end example
  8890. The nested function can access all the variables of the containing
  8891. function that are visible at the point of its definition. This is
  8892. called @dfn{lexical scoping}. For example, here we show a nested
  8893. function that uses an inherited variable named @code{offset}:
  8894. @example
  8895. @group
  8896. bar (int *array, int offset, int size)
  8897. @{
  8898. int access (int *array, int index)
  8899. @{ return array[index + offset]; @}
  8900. int i;
  8901. @r{@dots{}}
  8902. for (i = 0; i < size; i++)
  8903. @r{@dots{}} access (array, i) @r{@dots{}}
  8904. @}
  8905. @end group
  8906. @end example
  8907. Nested function definitions can appear wherever automatic variable
  8908. declarations are allowed; that is, in any block, interspersed with the
  8909. other declarations and statements in the block.
  8910. The nested function's name is visible only within the parent block;
  8911. the name's scope starts from its definition and continues to the end
  8912. of the containing block. If the nested function's name
  8913. is the same as the parent function's name, there wil be
  8914. no way to refer to the parent function inside the scope of the
  8915. name of the nested function.
  8916. Using @code{extern} or @code{static} on a nested function definition
  8917. is an error.
  8918. It is possible to call the nested function from outside the scope of its
  8919. name by storing its address or passing the address to another function.
  8920. You can do this safely, but you must be careful:
  8921. @example
  8922. @group
  8923. hack (int *array, int size, int addition)
  8924. @{
  8925. void store (int index, int value)
  8926. @{ array[index] = value + addition; @}
  8927. intermediate (store, size);
  8928. @}
  8929. @end group
  8930. @end example
  8931. Here, the function @code{intermediate} receives the address of
  8932. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8933. the arguments given to @code{store} are used to store into @code{array}.
  8934. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8935. It is safe for @code{intermediate} to call @code{store} because
  8936. @code{hack}'s stack frame, with its arguments and local variables,
  8937. continues to exist during the call to @code{intermediate}.
  8938. Calling the nested function through its address after the containing
  8939. function has exited is asking for trouble. If it is called after a
  8940. containing scope level has exited, and if it refers to some of the
  8941. variables that are no longer in scope, it will refer to memory
  8942. containing junk or other data. It's not wise to take the risk.
  8943. The GNU C Compiler implements taking the address of a nested function
  8944. using a technique called @dfn{trampolines}. This technique was
  8945. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8946. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8947. A nested function can jump to a label inherited from a containing
  8948. function, provided the label was explicitly declared in the containing
  8949. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8950. containing function, exiting the nested function that did the
  8951. @code{goto} and any intermediate function invocations as well. Here
  8952. is an example:
  8953. @example
  8954. @group
  8955. bar (int *array, int offset, int size)
  8956. @{
  8957. /* @r{Explicitly declare the label @code{failure}.} */
  8958. __label__ failure;
  8959. int access (int *array, int index)
  8960. @{
  8961. if (index > size)
  8962. /* @r{Exit this function,}
  8963. @r{and return to @code{bar}.} */
  8964. goto failure;
  8965. return array[index + offset];
  8966. @}
  8967. @end group
  8968. @group
  8969. int i;
  8970. @r{@dots{}}
  8971. for (i = 0; i < size; i++)
  8972. @r{@dots{}} access (array, i) @r{@dots{}}
  8973. @r{@dots{}}
  8974. return 0;
  8975. /* @r{Control comes here from @code{access}
  8976. if it does the @code{goto}.} */
  8977. failure:
  8978. return -1;
  8979. @}
  8980. @end group
  8981. @end example
  8982. To declare the nested function before its definition, use
  8983. @code{auto} (which is otherwise meaningless for function declarations;
  8984. @pxref{auto and register}). For example,
  8985. @example
  8986. bar (int *array, int offset, int size)
  8987. @{
  8988. auto int access (int *, int);
  8989. @r{@dots{}}
  8990. @r{@dots{}} access (array, i) @r{@dots{}}
  8991. @r{@dots{}}
  8992. int access (int *array, int index)
  8993. @{
  8994. @r{@dots{}}
  8995. @}
  8996. @r{@dots{}}
  8997. @}
  8998. @end example
  8999. @node Inline Function Definitions
  9000. @subsection Inline Function Definitions
  9001. @cindex inline function definitions
  9002. @cindex function definitions, inline
  9003. @findex inline
  9004. To declare a function inline, use the @code{inline} keyword in its
  9005. definition. Here's a simple function that takes a pointer-to-@code{int}
  9006. and increments the integer stored there---declared inline.
  9007. @example
  9008. struct list
  9009. @{
  9010. struct list *first, *second;
  9011. @};
  9012. inline struct list *
  9013. list_first (struct list *p)
  9014. @{
  9015. return p->first;
  9016. @}
  9017. inline struct list *
  9018. list_second (struct list *p)
  9019. @{
  9020. return p->second;
  9021. @}
  9022. @end example
  9023. optimized compilation can substitute the inline function's body for
  9024. any call to it. This is called @emph{inlining} the function. It
  9025. makes the code that contains the call run faster, significantly so if
  9026. the inline function is small.
  9027. Here's a function that uses @code{pair_second}:
  9028. @example
  9029. int
  9030. pairlist_length (struct list *l)
  9031. @{
  9032. int length = 0;
  9033. while (l)
  9034. @{
  9035. length++;
  9036. l = pair_second (l);
  9037. @}
  9038. return length;
  9039. @}
  9040. @end example
  9041. Substituting the code of @code{pair_second} into the definition of
  9042. @code{pairlist_length} results in this code, in effect:
  9043. @example
  9044. int
  9045. pairlist_length (struct list *l)
  9046. @{
  9047. int length = 0;
  9048. while (l)
  9049. @{
  9050. length++;
  9051. l = l->second;
  9052. @}
  9053. return length;
  9054. @}
  9055. @end example
  9056. Since the definition of @code{pair_second} does not say @code{extern}
  9057. or @code{static}, that definition is used only for inlining. It
  9058. doesn't generate code that can be called at run time. If not all the
  9059. calls to the function are inlined, there must be a definition of the
  9060. same function name in another module for them to call.
  9061. @cindex inline functions, omission of
  9062. @c @opindex fkeep-inline-functions
  9063. Adding @code{static} to an inline function definition means the
  9064. function definition is limited to this compilation module. Also, it
  9065. generates run-time code if necessary for the sake of any calls that
  9066. were not inlined. If all calls are inlined then the function
  9067. definition does not generate run-time code, but you can force
  9068. generation of run-time code with the option
  9069. @option{-fkeep-inline-functions}.
  9070. @cindex extern inline function
  9071. Specifying @code{extern} along with @code{inline} means the function is
  9072. external and generates run-time code to be called from other
  9073. separately compiled modules, as well as inlined. You can define the
  9074. function as @code{inline} without @code{extern} in other modules so as
  9075. to inline calls to the same function in those modules.
  9076. Why are some calls not inlined? First of all, inlining is an
  9077. optimization, so non-optimized compilation does not inline.
  9078. Some calls cannot be inlined for technical reasons. Also, certain
  9079. usages in a function definition can make it unsuitable for inline
  9080. substitution. Among these usages are: variadic functions, use of
  9081. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9082. use of nonlocal goto. The option @option{-Winline} requests a warning
  9083. when a function marked @code{inline} is unsuitable to be inlined. The
  9084. warning explains what obstacle makes it unsuitable.
  9085. Just because a call @emph{can} be inlined does not mean it
  9086. @emph{should} be inlined. The GNU C compiler weighs costs and
  9087. benefits to decide whether inlining a particular call is advantageous.
  9088. You can force inlining of all calls to a given function that can be
  9089. inlined, even in a non-optimized compilation. by specifying the
  9090. @samp{always_inline} attribute for the function, like this:
  9091. @example
  9092. /* @r{Prototype.} */
  9093. inline void foo (const char) __attribute__((always_inline));
  9094. @end example
  9095. @noindent
  9096. This is a GNU C extension. @xref{Attributes}.
  9097. A function call may be inlined even if not declared @code{inline} in
  9098. special cases where the compiler can determine this is correct and
  9099. desirable. For instance, when a static function is called only once,
  9100. it will very likely be inlined. With @option{-flto}, link-time
  9101. optimization, any function might be inlined. To absolutely prevent
  9102. inlining of a specific function, specify
  9103. @code{__attribute__((__noinline__))} in the function's definition.
  9104. @node Obsolete Definitions
  9105. @section Obsolete Function Features
  9106. These features of function definitions are still used in old
  9107. programs, but you shouldn't write code this way today.
  9108. If you are just learning C, you can skip this section.
  9109. @menu
  9110. * Old GNU Inlining:: An older inlining technique.
  9111. * Old-Style Function Definitions:: Original K&R style functions.
  9112. @end menu
  9113. @node Old GNU Inlining
  9114. @subsection Older GNU C Inlining
  9115. The GNU C spec for inline functions, before GCC version 5, defined
  9116. @code{extern inline} on a function definition to mean to inline calls
  9117. to it but @emph{not} generate code for the function that could be
  9118. called at run time. By contrast, @code{inline} without @code{extern}
  9119. specified to generate run-time code for the function. In effect, ISO
  9120. incompatibly flipped the meanings of these two cases. We changed GCC
  9121. in version 5 to adopt the ISO specification.
  9122. Many programs still use these cases with the previous GNU C meanings.
  9123. You can specify use of those meanings with the option
  9124. @option{-fgnu89-inline}. You can also specify this for a single
  9125. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9126. @example
  9127. inline __attribute__ ((gnu_inline))
  9128. int
  9129. inc (int *a)
  9130. @{
  9131. (*a)++;
  9132. @}
  9133. @end example
  9134. @node Old-Style Function Definitions
  9135. @subsection Old-Style Function Definitions
  9136. @cindex old-style function definitions
  9137. @cindex function definitions, old-style
  9138. @cindex K&R-style function definitions
  9139. The syntax of C traditionally allows omitting the data type in a
  9140. function declaration if it specifies a storage class or a qualifier.
  9141. Then the type defaults to @code{int}. For example:
  9142. @example
  9143. static foo (double x);
  9144. @end example
  9145. @noindent
  9146. defaults the return type to @code{int}. This is bad practice; if you
  9147. see it, fix it.
  9148. An @dfn{old-style} (or ``K&R'') function definition is the way
  9149. function definitions were written in the 1980s. It looks like this:
  9150. @example
  9151. @var{rettype}
  9152. @var{function} (@var{parmnames})
  9153. @var{parm_declarations}
  9154. @{
  9155. @var{body}
  9156. @}
  9157. @end example
  9158. In @var{parmnames}, only the parameter names are listed, separated by
  9159. commas. Then @var{parm_declarations} declares their data types; these
  9160. declarations look just like variable declarations. If a parameter is
  9161. listed in @var{parmnames} but has no declaration, it is implicitly
  9162. declared @code{int}.
  9163. There is no reason to write a definition this way nowadays, but they
  9164. can still be seen in older GNU programs.
  9165. An old-style variadic function definition looks like this:
  9166. @example
  9167. #include <varargs.h>
  9168. int
  9169. add_multiple_values (va_alist)
  9170. va_dcl
  9171. @{
  9172. int argcount;
  9173. int counter, total = 0;
  9174. /* @r{Declare a variable of type @code{va_list}.} */
  9175. va_list argptr;
  9176. /* @r{Initialize that variable.} */
  9177. va_start (argptr);
  9178. /* @r{Get the first argument (fixed).} */
  9179. argcount = va_arg (int);
  9180. for (counter = 0; counter < argcount; counter++)
  9181. @{
  9182. /* @r{Get the next additional argument.} */
  9183. total += va_arg (argptr, int);
  9184. @}
  9185. /* @r{End use of the @code{argptr} variable.} */
  9186. va_end (argptr);
  9187. return total;
  9188. @}
  9189. @end example
  9190. Note that the old-style variadic function definition has no fixed
  9191. parameter variables; all arguments must be obtained with
  9192. @code{va_arg}.
  9193. @node Compatible Types
  9194. @chapter Compatible Types
  9195. @cindex compatible types
  9196. @cindex types, compatible
  9197. Declaring a function or variable twice is valid in C only if the two
  9198. declarations specify @dfn{compatible} types. In addition, some
  9199. operations on pointers require operands to have compatible target
  9200. types.
  9201. In C, two different primitive types are never compatible. Likewise for
  9202. the defined types @code{struct}, @code{union} and @code{enum}: two
  9203. separately defined types are incompatible unless they are defined
  9204. exactly the same way.
  9205. However, there are a few cases where different types can be
  9206. compatible:
  9207. @itemize @bullet
  9208. @item
  9209. Every enumeration type is compatible with some integer type. In GNU
  9210. C, the choice of integer type depends on the largest enumeration
  9211. value.
  9212. @c ??? Which one, in GCC?
  9213. @c ??? ... it varies, depending on the enum values. Testing on
  9214. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9215. @c ??? then moves on to an 8-byte signed integer. These details
  9216. @c ??? might be platform-dependent, as the C standard says that even
  9217. @c ??? char could be used as an enum type, but it's at least true
  9218. @c ??? that GCC chooses a type that is at least large enough to
  9219. @c ??? hold the largest enum value.
  9220. @item
  9221. Array types are compatible if the element types are compatible
  9222. and the sizes (when specified) match.
  9223. @item
  9224. Pointer types are compatible if the pointer target types are
  9225. compatible.
  9226. @item
  9227. Function types that specify argument types are compatible if the
  9228. return types are compatible and the argument types are compatible,
  9229. argument by argument. In addition, they must all agree in whether
  9230. they use @code{...} to allow additional arguments.
  9231. @item
  9232. Function types that don't specify argument types are compatible if the
  9233. return types are.
  9234. @item
  9235. Function types that specify the argument types are compatible with
  9236. function types that omit them, if the return types are compatible and
  9237. the specified argument types are unaltered by the argument promotions
  9238. (@pxref{Argument Promotions}).
  9239. @end itemize
  9240. In order for types to be compatible, they must agree in their type
  9241. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9242. It follows that @code{const int *} and @code{int *} are incompatible
  9243. too (they are pointers to types that are not compatible).
  9244. If two types are compatible ignoring the qualifiers, we call them
  9245. @dfn{nearly compatible}. (If they are array types, we ignore
  9246. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9247. Comparison of pointers is valid if the pointers' target types are
  9248. nearly compatible. Likewise, the two branches of a conditional
  9249. expression may be pointers to nearly compatible target types.
  9250. If two types are compatible ignoring the qualifiers, and the first
  9251. type has all the qualifiers of the second type, we say the first is
  9252. @dfn{upward compatible} with the second. Assignment of pointers
  9253. requires the assigned pointer's target type to be upward compatible
  9254. with the right operand (the new value)'s target type.
  9255. @node Type Conversions
  9256. @chapter Type Conversions
  9257. @cindex type conversions
  9258. @cindex conversions, type
  9259. C converts between data types automatically when that seems clearly
  9260. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9261. @menu
  9262. * Explicit Type Conversion:: Casting a value from one type to another.
  9263. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9264. * Argument Promotions:: Automatic conversion of function parameters.
  9265. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9266. * Common Type:: When operand types differ, which one is used?
  9267. @end menu
  9268. @node Explicit Type Conversion
  9269. @section Explicit Type Conversion
  9270. @cindex cast
  9271. @cindex explicit type conversion
  9272. You can do explicit conversions using the unary @dfn{cast} operator,
  9273. which is written as a type designator (@pxref{Type Designators}) in
  9274. parentheses. For example, @code{(int)} is the operator to cast to
  9275. type @code{int}. Here's an example of using it:
  9276. @example
  9277. @{
  9278. double d = 5.5;
  9279. printf ("Floating point value: %f\n", d);
  9280. printf ("Rounded to integer: %d\n", (int) d);
  9281. @}
  9282. @end example
  9283. Using @code{(int) d} passes an @code{int} value as argument to
  9284. @code{printf}, so you can print it with @samp{%d}. Using just
  9285. @code{d} without the cast would pass the value as @code{double}.
  9286. That won't work at all with @samp{%d}; the results would be gibberish.
  9287. To divide one integer by another without rounding,
  9288. cast either of the integers to @code{double} first:
  9289. @example
  9290. (double) @var{dividend} / @var{divisor}
  9291. @var{dividend} / (double) @var{divisor}
  9292. @end example
  9293. It is enough to cast one of them, because that forces the common type
  9294. to @code{double} so the other will be converted automatically.
  9295. The valid cast conversions are:
  9296. @itemize @bullet
  9297. @item
  9298. One numerical type to another.
  9299. @item
  9300. One pointer type to another.
  9301. (Converting between pointers that point to functions
  9302. and pointers that point to data is not standard C.)
  9303. @item
  9304. A pointer type to an integer type.
  9305. @item
  9306. An integer type to a pointer type.
  9307. @item
  9308. To a union type, from the type of any alternative in the union
  9309. (@pxref{Unions}). (This is a GNU extension.)
  9310. @item
  9311. Anything, to @code{void}.
  9312. @end itemize
  9313. @node Assignment Type Conversions
  9314. @section Assignment Type Conversions
  9315. @cindex assignment type conversions
  9316. Certain type conversions occur automatically in assignments
  9317. and certain other contexts. These are the conversions
  9318. assignments can do:
  9319. @itemize @bullet
  9320. @item
  9321. Converting any numeric type to any other numeric type.
  9322. @item
  9323. Converting @code{void *} to any other pointer type
  9324. (except pointer-to-function types).
  9325. @item
  9326. Converting any other pointer type to @code{void *}.
  9327. (except pointer-to-function types).
  9328. @item
  9329. Converting 0 (a null pointer constant) to any pointer type.
  9330. @item
  9331. Converting any pointer type to @code{bool}. (The result is
  9332. 1 if the pointer is not null.)
  9333. @item
  9334. Converting between pointer types when the left-hand target type is
  9335. upward compatible with the right-hand target type. @xref{Compatible
  9336. Types}.
  9337. @end itemize
  9338. These type conversions occur automatically in certain contexts,
  9339. which are:
  9340. @itemize @bullet
  9341. @item
  9342. An assignment converts the type of the right-hand expression
  9343. to the type wanted by the left-hand expression. For example,
  9344. @example
  9345. double i;
  9346. i = 5;
  9347. @end example
  9348. @noindent
  9349. converts 5 to @code{double}.
  9350. @item
  9351. A function call, when the function specifies the type for that
  9352. argument, converts the argument value to that type. For example,
  9353. @example
  9354. void foo (double);
  9355. foo (5);
  9356. @end example
  9357. @noindent
  9358. converts 5 to @code{double}.
  9359. @item
  9360. A @code{return} statement converts the specified value to the type
  9361. that the function is declared to return. For example,
  9362. @example
  9363. double
  9364. foo ()
  9365. @{
  9366. return 5;
  9367. @}
  9368. @end example
  9369. @noindent
  9370. also converts 5 to @code{double}.
  9371. @end itemize
  9372. In all three contexts, if the conversion is impossible, that
  9373. constitutes an error.
  9374. @node Argument Promotions
  9375. @section Argument Promotions
  9376. @cindex argument promotions
  9377. @cindex promotion of arguments
  9378. When a function's definition or declaration does not specify the type
  9379. of an argument, that argument is passed without conversion in whatever
  9380. type it has, with these exceptions:
  9381. @itemize @bullet
  9382. @item
  9383. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9384. expression is a narrow integer, such as @code{char} or @code{short},
  9385. the call converts it automatically to @code{int} (@pxref{Integer
  9386. Types}).@footnote{On an embedded controller where @code{char}
  9387. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9388. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9389. never occurs in GNU C on real computers.}
  9390. In this example, the expression @code{c} is passed as an @code{int}:
  9391. @example
  9392. char c = '$';
  9393. printf ("Character c is '%c'\n", c);
  9394. @end example
  9395. @item
  9396. If the expression
  9397. has type @code{float}, the call converts it automatically to
  9398. @code{double}.
  9399. @item
  9400. An array as argument is converted to a pointer to its zeroth element.
  9401. @item
  9402. A function name as argument is converted to a pointer to that function.
  9403. @end itemize
  9404. @node Operand Promotions
  9405. @section Operand Promotions
  9406. @cindex operand promotions
  9407. The operands in arithmetic operations undergo type conversion automatically.
  9408. These @dfn{operand promotions} are the same as the argument promotions
  9409. except without converting @code{float} to @code{double}. In other words,
  9410. the operand promotions convert
  9411. @itemize @bullet
  9412. @item
  9413. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9414. @item
  9415. an array to a pointer to its zeroth element, and
  9416. @item
  9417. a function name to a pointer to that function.
  9418. @end itemize
  9419. @node Common Type
  9420. @section Common Type
  9421. @cindex common type
  9422. Arithmetic binary operators (except the shift operators) convert their
  9423. operands to the @dfn{common type} before operating on them.
  9424. Conditional expressions also convert the two possible results to their
  9425. common type. Here are the rules for determining the common type.
  9426. If one of the numbers has a floating-point type and the other is an
  9427. integer, the common type is that floating-point type. For instance,
  9428. @example
  9429. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9430. @end example
  9431. If both are floating point, the type with the larger range is the
  9432. common type.
  9433. If both are integers but of different widths, the common type
  9434. is the wider of the two.
  9435. If they are integer types of the same width, the common type is
  9436. unsigned if either operand is unsigned, and it's @code{long} if either
  9437. operand is @code{long}. It's @code{long long} if either operand is
  9438. @code{long long}.
  9439. These rules apply to addition, subtraction, multiplication, division,
  9440. remainder, comparisons, and bitwise operations. They also apply to
  9441. the two branches of a conditional expression, and to the arithmetic
  9442. done in a modifying assignment operation.
  9443. @node Scope
  9444. @chapter Scope
  9445. @cindex scope
  9446. @cindex block scope
  9447. @cindex function scope
  9448. @cindex function prototype scope
  9449. Each definition or declaration of an identifier is visible
  9450. in certain parts of the program, which is typically less than the whole
  9451. of the program. The parts where it is visible are called its @dfn{scope}.
  9452. Normally, declarations made at the top-level in the source -- that is,
  9453. not within any blocks and function definitions -- are visible for the
  9454. entire contents of the source file after that point. This is called
  9455. @dfn{file scope} (@pxref{File-Scope Variables}).
  9456. Declarations made within blocks of code, including within function
  9457. definitions, are visible only within those blocks. This is called
  9458. @dfn{block scope}. Here is an example:
  9459. @example
  9460. @group
  9461. void
  9462. foo (void)
  9463. @{
  9464. int x = 42;
  9465. @}
  9466. @end group
  9467. @end example
  9468. @noindent
  9469. In this example, the variable @code{x} has block scope; it is visible
  9470. only within the @code{foo} function definition block. Thus, other
  9471. blocks could have their own variables, also named @code{x}, without
  9472. any conflict between those variables.
  9473. A variable declared inside a subblock has a scope limited to
  9474. that subblock,
  9475. @example
  9476. @group
  9477. void
  9478. foo (void)
  9479. @{
  9480. @{
  9481. int x = 42;
  9482. @}
  9483. // @r{@code{x} is out of scope here.}
  9484. @}
  9485. @end group
  9486. @end example
  9487. If a variable declared within a block has the same name as a variable
  9488. declared outside of that block, the definition within the block
  9489. takes precedence during its scope:
  9490. @example
  9491. @group
  9492. int x = 42;
  9493. void
  9494. foo (void)
  9495. @{
  9496. int x = 17;
  9497. printf ("%d\n", x);
  9498. @}
  9499. @end group
  9500. @end example
  9501. @noindent
  9502. This prints 17, the value of the variable @code{x} declared in the
  9503. function body block, rather than the value of the variable @code{x} at
  9504. file scope. We say that the inner declaration of @code{x}
  9505. @dfn{shadows} the outer declaration, for the extent of the inner
  9506. declaration's scope.
  9507. A declaration with block scope can be shadowed by another declaration
  9508. with the same name in a subblock.
  9509. @example
  9510. @group
  9511. void
  9512. foo (void)
  9513. @{
  9514. char *x = "foo";
  9515. @{
  9516. int x = 42;
  9517. @r{@dots{}}
  9518. exit (x / 6);
  9519. @}
  9520. @}
  9521. @end group
  9522. @end example
  9523. A function parameter's scope is the entire function body, but it can
  9524. be shadowed. For example:
  9525. @example
  9526. @group
  9527. int x = 42;
  9528. void
  9529. foo (int x)
  9530. @{
  9531. printf ("%d\n", x);
  9532. @}
  9533. @end group
  9534. @end example
  9535. @noindent
  9536. This prints the value of @code{x} the function parameter, rather than
  9537. the value of the file-scope variable @code{x}. However,
  9538. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9539. is visible for the whole of the containing function body, both before
  9540. and after the label declaration:
  9541. @example
  9542. @group
  9543. void
  9544. foo (void)
  9545. @{
  9546. @r{@dots{}}
  9547. goto bar;
  9548. @r{@dots{}}
  9549. @{ // @r{Subblock does not affect labels.}
  9550. bar:
  9551. @r{@dots{}}
  9552. @}
  9553. goto bar;
  9554. @}
  9555. @end group
  9556. @end example
  9557. Except for labels, a declared identifier is not
  9558. visible to code before its declaration. For example:
  9559. @example
  9560. @group
  9561. int x = 5;
  9562. int y = x + 10;
  9563. @end group
  9564. @end example
  9565. @noindent
  9566. will work, but:
  9567. @example
  9568. @group
  9569. int x = y + 10;
  9570. int y = 5;
  9571. @end group
  9572. @end example
  9573. @noindent
  9574. cannot refer to the variable @code{y} before its declaration.
  9575. @include cpp.texi
  9576. @node Integers in Depth
  9577. @chapter Integers in Depth
  9578. This chapter explains the machine-level details of integer types: how
  9579. they are represented as bits in memory, and the range of possible
  9580. values for each integer type.
  9581. @menu
  9582. * Integer Representations:: How integer values appear in memory.
  9583. * Maximum and Minimum Values:: Value ranges of integer types.
  9584. @end menu
  9585. @node Integer Representations
  9586. @section Integer Representations
  9587. @cindex integer representations
  9588. @cindex representation of integers
  9589. Modern computers store integer values as binary (base-2) numbers that
  9590. occupy a single unit of storage, typically either as an 8-bit
  9591. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9592. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9593. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9594. any of these types could have some other size, bit it's not worth even
  9595. a minute to cater to that possibility. It never happens on
  9596. GNU/Linux.}
  9597. @cindex @code{CHAR_BIT}
  9598. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9599. of bits in type @code{char}. On any real operating system, the value
  9600. is 8.
  9601. The fixed sizes of numeric types necessarily limits their @dfn{range
  9602. of values}, and the particular encoding of integers decides what that
  9603. range is.
  9604. @cindex two's-complement representation
  9605. For unsigned integers, the entire space is used to represent a
  9606. nonnegative value. Signed integers are stored using
  9607. @dfn{two's-complement representation}: a signed integer with @var{n}
  9608. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9609. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9610. high-order, bit is called the @dfn{sign bit}.
  9611. @c ??? Needs correcting
  9612. There is only one value that means zero, and the most negative number
  9613. lacks a positive counterpart. As a result, negating that number
  9614. causes overflow; in practice, its result is that number back again.
  9615. For example, a two's-complement signed 8-bit integer can represent all
  9616. decimal numbers from @minus{}128 to +127. We will revisit that
  9617. peculiarity shortly.
  9618. Decades ago, there were computers that didn't use two's-complement
  9619. representation for integers (@pxref{Integers in Depth}), but they are
  9620. long gone and not worth any effort to support.
  9621. @c ??? Is this duplicate?
  9622. When an arithmetic operation produces a value that is too big to
  9623. represent, the operation is said to @dfn{overflow}. In C, integer
  9624. overflow does not interrupt the control flow or signal an error.
  9625. What it does depends on signedness.
  9626. For unsigned arithmetic, the result of an operation that overflows is
  9627. the @var{n} low-order bits of the correct value. If the correct value
  9628. is representable in @var{n} bits, that is always the result;
  9629. thus we often say that ``integer arithmetic is exact,'' omitting the
  9630. crucial qualifying phrase ``as long as the exact result is
  9631. representable.''
  9632. In principle, a C program should be written so that overflow never
  9633. occurs for signed integers, but in GNU C you can specify various ways
  9634. of handling such overflow (@pxref{Integer Overflow}).
  9635. Integer representations are best understood by looking at a table for
  9636. a tiny integer size; here are the possible values for an integer with
  9637. three bits:
  9638. @multitable @columnfractions .25 .25 .25 .25
  9639. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9640. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9641. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9642. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9643. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9644. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9645. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9646. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9647. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9648. @end multitable
  9649. The parenthesized decimal numbers in the last column represent the
  9650. signed meanings of the two's-complement of the line's value. Recall
  9651. that, in two's-complement encoding, the high-order bit is 0 when
  9652. the number is nonnegative.
  9653. We can now understand the peculiar behavior of negation of the
  9654. most negative two's-complement integer: start with 0b100,
  9655. invert the bits to get 0b011, and add 1: we get
  9656. 0b100, the value we started with.
  9657. We can also see overflow behavior in two's-complement:
  9658. @example
  9659. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9660. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9661. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9662. @end example
  9663. @noindent
  9664. A sum of two nonnegative signed values that overflows has a 1 in the
  9665. sign bit, so the exact positive result is truncated to a negative
  9666. value.
  9667. @c =====================================================================
  9668. @node Maximum and Minimum Values
  9669. @section Maximum and Minimum Values
  9670. @cindex maximum integer values
  9671. @cindex minimum integer values
  9672. @cindex integer ranges
  9673. @cindex ranges of integer types
  9674. @findex INT_MAX
  9675. @findex UINT_MAX
  9676. @findex SHRT_MAX
  9677. @findex LONG_MAX
  9678. @findex LLONG_MAX
  9679. @findex USHRT_MAX
  9680. @findex ULONG_MAX
  9681. @findex ULLONG_MAX
  9682. @findex CHAR_MAX
  9683. @findex SCHAR_MAX
  9684. @findex UCHAR_MAX
  9685. For each primitive integer type, there is a standard macro defined in
  9686. @file{limits.h} that gives the largest value that type can hold. For
  9687. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9688. On a 32-bit computer, that is equal to 2,147,483,647. The
  9689. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9690. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9691. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9692. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9693. @code{ULLONG_MAX}.
  9694. Since there are three ways to specify a @code{char} type, there are
  9695. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9696. @code{UCHAR_MAX}.
  9697. For each type that is or might be signed, there is another symbol that
  9698. gives the minimum value it can hold. (Just replace @code{MAX} with
  9699. @code{MIN} in the names listed above.) There is no minimum limit
  9700. symbol for types specified with @code{unsigned} because the
  9701. minimum for them is universally zero.
  9702. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9703. two's-complement representation, the most negative number is 1 less
  9704. than the negative of the most positive number. Thus, @code{INT_MIN}
  9705. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9706. actually write the value that way in C, since it would overflow.
  9707. That's a good reason to use @code{INT_MIN} to specify
  9708. that value. Its definition is written to avoid overflow.
  9709. @include fp.texi
  9710. @node Compilation
  9711. @chapter Compilation
  9712. @cindex object file
  9713. @cindex compilation module
  9714. @cindex make rules
  9715. Early in the manual we explained how to compile a simple C program
  9716. that consists of a single source file (@pxref{Compile Example}).
  9717. However, we handle only short programs that way. A typical C program
  9718. consists of many source files, each of which is a separate
  9719. @dfn{compilation module}---meaning that it has to be compiled
  9720. separately.
  9721. The full details of how to compile with GCC are documented in xxxx.
  9722. @c ??? ref
  9723. Here we give only a simple introduction.
  9724. These are the commands to compile two compilation modules,
  9725. @file{foo.c} and @file{bar.c}, with a command for each module:
  9726. @example
  9727. gcc -c -O -g foo.c
  9728. gcc -c -O -g bar.c
  9729. @end example
  9730. @noindent
  9731. In these commands, @option{-g} says to generate debugging information,
  9732. @option{-O} says to do some optimization, and @option{-c} says to put
  9733. the compiled code for that module into a corresponding @dfn{object
  9734. file} and go no further. The object file for @file{foo.c} is called
  9735. @file{foo.o}, and so on.
  9736. If you wish, you can specify the additional options @option{-Wformat
  9737. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9738. One reason to divide a large program into multiple compilation modules
  9739. is to control how each module can access the internals of the others.
  9740. When a module declares a function or variable @code{extern}, other
  9741. modules can access it. The other functions and variables in
  9742. a module can't be accessed from outside that module.
  9743. The other reason for using multiple modules is so that changing
  9744. one source file does not require recompiling all of them in order
  9745. to try the modified program. Dividing a large program into many
  9746. substantial modules in this way typically makes recompilation much faster.
  9747. @cindex linking object files
  9748. After you compile all the program's modules, in order to run the
  9749. program you must @dfn{link} the object files into a combined
  9750. executable, like this:
  9751. @example
  9752. gcc -o foo foo.o bar.o
  9753. @end example
  9754. @noindent
  9755. In this command, @option{-o foo} species the file name for the
  9756. executable file, and the other arguments are the object files to link.
  9757. Always specify the executable file name in a command that generates
  9758. one.
  9759. Normally we don't run any of these commands directly. Instead we
  9760. write a set of @dfn{make rules} for the program, then use the
  9761. @command{make} program to recompile only the source files that need to
  9762. be recompiled.
  9763. @c ??? ref to make manual
  9764. @node Directing Compilation
  9765. @chapter Directing Compilation
  9766. This chapter describes C constructs that don't alter the program's
  9767. meaning @emph{as such}, but rather direct the compiler how to treat
  9768. some aspects of the program.
  9769. @menu
  9770. * Pragmas:: Controling compilation of some constructs.
  9771. * Static Assertions:: Compile-time tests for conditions.
  9772. @end menu
  9773. @node Pragmas
  9774. @section Pragmas
  9775. A @dfn{pragma} is an annotation in a program that gives direction to
  9776. the compiler.
  9777. @menu
  9778. * Pragma Basics:: Pragma syntax and usage.
  9779. * Severity Pragmas:: Settings for compile-time pragma output.
  9780. * Optimization Pragmas:: Controlling optimizations.
  9781. @end menu
  9782. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9783. @node Pragma Basics
  9784. @subsection Pragma Basics
  9785. C defines two syntactical forms for pragmas, the line form and the
  9786. token form. You can write any pragma in either form, with the same
  9787. meaning.
  9788. The line form is a line in the source code, like this:
  9789. @example
  9790. #pragma @var{line}
  9791. @end example
  9792. @noindent
  9793. The line pragma has no effect on the parsing of the lines around it.
  9794. This form has the drawback that it can't be generated by a macro expansion.
  9795. The token form is a series of tokens; it can appear anywhere in the
  9796. program between the other tokens.
  9797. @example
  9798. _Pragma (@var{stringconstant})
  9799. @end example
  9800. @noindent
  9801. The pragma has no effect on the syntax of the tokens that surround it;
  9802. thus, here's a pragma in the middle of an @code{if} statement:
  9803. @example
  9804. if _Pragma ("hello") (x > 1)
  9805. @end example
  9806. @noindent
  9807. However, that's an unclear thing to do; for the sake of
  9808. understandability, it is better to put a pragma on a line by itself
  9809. and not embedded in the middle of another construct.
  9810. Both forms of pragma have a textual argument. In a line pragma, the
  9811. text is the rest of the line. The textual argument to @code{_Pragma}
  9812. uses the same syntax as a C string constant: surround the text with
  9813. two @samp{"} characters, and add a backslash before each @samp{"} or
  9814. @samp{\} character in it.
  9815. With either syntax, the textual argument specifies what to do.
  9816. It begins with one or several words that specify the operation.
  9817. If the compiler does not recognize them, it ignores the pragma.
  9818. Here are the pragma operations supported in GNU C@.
  9819. @c ??? Verify font for []
  9820. @table @code
  9821. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9822. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9823. Declares that the current source file depends on @var{file}, so GNU C
  9824. compares the file times and gives a warning if @var{file} is newer
  9825. than the current source file.
  9826. This directive searches for @var{file} the way @code{#include}
  9827. searches for a non-system header file.
  9828. If @var{message} is given, the warning message includes that text.
  9829. Examples:
  9830. @example
  9831. #pragma GCC dependency "parse.y"
  9832. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9833. rerun fixincludes")
  9834. @end example
  9835. @item #pragma GCC poison @var{identifiers}
  9836. @itemx _Pragma ("GCC poison @var{identifiers}")
  9837. Poisons the identifiers listed in @var{identifiers}.
  9838. This is useful to make sure all mention of @var{identifiers} has been
  9839. deleted from the program and that no reference to them creeps back in.
  9840. If any of those identifiers appears anywhere in the source after the
  9841. directive, it causes a compilation error. For example,
  9842. @example
  9843. #pragma GCC poison printf sprintf fprintf
  9844. sprintf(some_string, "hello");
  9845. @end example
  9846. @noindent
  9847. generates an error.
  9848. If a poisoned identifier appears as part of the expansion of a macro
  9849. that was defined before the identifier was poisoned, it will @emph{not}
  9850. cause an error. Thus, system headers that define macros that use
  9851. the identifier will not cause errors.
  9852. For example,
  9853. @example
  9854. #define strrchr rindex
  9855. _Pragma ("GCC poison rindex")
  9856. strrchr(some_string, 'h');
  9857. @end example
  9858. @noindent
  9859. does not cause a compilation error.
  9860. @item #pragma GCC system_header
  9861. @itemx _Pragma ("GCC system_header")
  9862. Specify treating the rest of the current source file as if it came
  9863. from a system header file. @xref{System Headers, System Headers,
  9864. System Headers, gcc, Using the GNU Compiler Collection}.
  9865. @item #pragma GCC warning @var{message}
  9866. @itemx _Pragma ("GCC warning @var{message}")
  9867. Equivalent to @code{#warning}. Its advantage is that the
  9868. @code{_Pragma} form can be included in a macro definition.
  9869. @item #pragma GCC error @var{message}
  9870. @itemx _Pragma ("GCC error @var{message}")
  9871. Equivalent to @code{#error}. Its advantage is that the
  9872. @code{_Pragma} form can be included in a macro definition.
  9873. @item #pragma GCC message @var{message}
  9874. @itemx _Pragma ("GCC message @var{message}")
  9875. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9876. informational message, and could be used to include additional warning
  9877. or error text without triggering more warnings or errors. (Note that
  9878. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9879. @samp{GCC} as part of the pragma.)
  9880. @end table
  9881. @node Severity Pragmas
  9882. @subsection Severity Pragmas
  9883. These pragmas control the severity of classes of diagnostics.
  9884. You can specify the class of diagnostic with the GCC option that causes
  9885. those diagnostics to be generated.
  9886. @table @code
  9887. @item #pragma GCC diagnostic error @var{option}
  9888. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9889. For code following this pragma, treat diagnostics of the variety
  9890. specified by @var{option} as errors. For example:
  9891. @example
  9892. _Pragma ("GCC diagnostic error -Wformat")
  9893. @end example
  9894. @noindent
  9895. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9896. as errors rather than warnings.
  9897. @item #pragma GCC diagnostic warning @var{option}
  9898. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9899. For code following this pragma, treat diagnostics of the variety
  9900. specified by @var{option} as warnings. This overrides the
  9901. @var{-Werror} option which says to treat warnings as errors.
  9902. @item #pragma GCC diagnostic ignore @var{option}
  9903. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9904. For code following this pragma, refrain from reporting any diagnostics
  9905. of the variety specified by @var{option}.
  9906. @item #pragma GCC diagnostic push
  9907. @itemx _Pragma ("GCC diagnostic push")
  9908. @itemx #pragma GCC diagnostic pop
  9909. @itemx _Pragma ("GCC diagnostic pop")
  9910. These pragmas maintain a stack of states for severity settings.
  9911. @samp{GCC diagnostic push} saves the current settings on the stack,
  9912. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9913. the current settings from that.
  9914. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9915. restores the settings to what they were at the start of compilation.
  9916. Here is an example:
  9917. @example
  9918. _Pragma ("GCC diagnostic error -Wformat")
  9919. /* @r{@option{-Wformat} messages treated as errors. } */
  9920. _Pragma ("GCC diagnostic push")
  9921. _Pragma ("GCC diagnostic warning -Wformat")
  9922. /* @r{@option{-Wformat} messages treated as warnings. } */
  9923. _Pragma ("GCC diagnostic push")
  9924. _Pragma ("GCC diagnostic ignored -Wformat")
  9925. /* @r{@option{-Wformat} messages suppressed. } */
  9926. _Pragma ("GCC diagnostic pop")
  9927. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9928. _Pragma ("GCC diagnostic pop")
  9929. /* @r{@option{-Wformat} messages treated as errors again. } */
  9930. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9931. _Pragma ("GCC diagnostic pop")
  9932. /* @r{@option{-Wformat} messages treated once again}
  9933. @r{as specified by the GCC command-line options.} */
  9934. @end example
  9935. @end table
  9936. @node Optimization Pragmas
  9937. @subsection Optimization Pragmas
  9938. These pragmas enable a particular optimization for specific function
  9939. definitions. The settings take effect at the end of a function
  9940. definition, so the clean place to use these pragmas is between
  9941. function definitions.
  9942. @table @code
  9943. @item #pragma GCC optimize @var{optimization}
  9944. @itemx _Pragma ("GCC optimize @var{optimization}")
  9945. These pragmas enable the optimization @var{optimization} for the
  9946. following functions. For example,
  9947. @example
  9948. _Pragma ("GCC optimize -fforward-propagate")
  9949. @end example
  9950. @noindent
  9951. says to apply the @samp{forward-propagate} optimization to all
  9952. following function definitions. Specifying optimizations for
  9953. individual functions, rather than for the entire program, is rare but
  9954. can be useful for getting around a bug in the compiler.
  9955. If @var{optimization} does not correspond to a defined optimization
  9956. option, the pragma is erroneous. To turn off an optimization, use the
  9957. corresponding @samp{-fno-} option, such as
  9958. @samp{-fno-forward-propagate}.
  9959. @item #pragma GCC target @var{optimizations}
  9960. @itemx _Pragma ("GCC target @var{optimizations}")
  9961. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9962. used for platform-specific optimizations. Thus,
  9963. @example
  9964. _Pragma ("GCC target popcnt")
  9965. @end example
  9966. @noindent
  9967. activates the optimization @samp{popcnt} for all
  9968. following function definitions. This optimization is supported
  9969. on a few common targets but not on others.
  9970. @item #pragma GCC push_options
  9971. @itemx _Pragma ("GCC push_options")
  9972. The @samp{push_options} pragma saves on a stack the current settings
  9973. specified with the @samp{target} and @samp{optimize} pragmas.
  9974. @item #pragma GCC pop_options
  9975. @itemx _Pragma ("GCC pop_options")
  9976. The @samp{pop_options} pragma pops saved settings from that stack.
  9977. Here's an example of using this stack.
  9978. @example
  9979. _Pragma ("GCC push_options")
  9980. _Pragma ("GCC optimize forward-propagate")
  9981. /* @r{Functions to compile}
  9982. @r{with the @code{forward-propagate} optimization.} */
  9983. _Pragma ("GCC pop_options")
  9984. /* @r{Ends enablement of @code{forward-propagate}.} */
  9985. @end example
  9986. @item #pragma GCC reset_options
  9987. @itemx _Pragma ("GCC reset_options")
  9988. Clears all pragma-defined @samp{target} and @samp{optimize}
  9989. optimization settings.
  9990. @end table
  9991. @node Static Assertions
  9992. @section Static Assertions
  9993. @cindex static assertions
  9994. @findex _Static_assert
  9995. You can add compiler-time tests for necessary conditions into your
  9996. code using @code{_Static_assert}. This can be useful, for example, to
  9997. check that the compilation target platform supports the type sizes
  9998. that the code expects. For example,
  9999. @example
  10000. _Static_assert ((sizeof (long int) >= 8),
  10001. "long int needs to be at least 8 bytes");
  10002. @end example
  10003. @noindent
  10004. reports a compile-time error if compiled on a system with long
  10005. integers smaller than 8 bytes, with @samp{long int needs to be at
  10006. least 8 bytes} as the error message.
  10007. Since calls @code{_Static_assert} are processed at compile time, the
  10008. expression must be computable at compile time and the error message
  10009. must be a literal string. The expression can refer to the sizes of
  10010. variables, but can't refer to their values. For example, the
  10011. following static assertion is invalid for two reasons:
  10012. @example
  10013. char *error_message
  10014. = "long int needs to be at least 8 bytes";
  10015. int size_of_long_int = sizeof (long int);
  10016. _Static_assert (size_of_long_int == 8, error_message);
  10017. @end example
  10018. @noindent
  10019. The expression @code{size_of_long_int == 8} isn't computable at
  10020. compile time, and the error message isn't a literal string.
  10021. You can, though, use preprocessor definition values with
  10022. @code{_Static_assert}:
  10023. @example
  10024. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10025. at least 8 bytes"
  10026. _Static_assert ((sizeof (long int) == 8),
  10027. LONG_INT_ERROR_MESSAGE);
  10028. @end example
  10029. Static assertions are permitted wherever a statement or declaration is
  10030. permitted, including at top level in the file, and also inside the
  10031. definition of a type.
  10032. @example
  10033. union y
  10034. @{
  10035. int i;
  10036. int *ptr;
  10037. _Static_assert (sizeof (int *) == sizeof (int),
  10038. "Pointer and int not same size");
  10039. @};
  10040. @end example
  10041. @node Type Alignment
  10042. @appendix Type Alignment
  10043. @cindex type alignment
  10044. @cindex alignment of type
  10045. @findex _Alignof
  10046. @findex __alignof__
  10047. Code for device drivers and other communication with low-level
  10048. hardware sometimes needs to be concerned with the alignment of
  10049. data objects in memory.
  10050. Each data type has a required @dfn{alignment}, always a power of 2,
  10051. that says at which memory addresses an object of that type can validly
  10052. start. A valid address for the type must be a multiple of its
  10053. alignment. If a type's alignment is 1, that means it can validly
  10054. start at any address. If a type's alignment is 2, that means it can
  10055. only start at an even address. If a type's alignment is 4, that means
  10056. it can only start at an address that is a multiple of 4.
  10057. The alignment of a type (except @code{char}) can vary depending on the
  10058. kind of computer in use. To refer to the alignment of a type in a C
  10059. program, use @code{_Alignof}, whose syntax parallels that of
  10060. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10061. operation, and it doesn't compute the value of the expression used
  10062. as its argument.
  10063. Nominally, each integer and floating-point type has an alignment equal to
  10064. the largest power of 2 that divides its size. Thus, @code{int} with
  10065. size 4 has a nominal alignment of 4, and @code{long long int} with
  10066. size 8 has a nominal alignment of 8.
  10067. However, each kind of computer generally has a maximum alignment, and
  10068. no type needs more alignment than that. If the computer's maximum
  10069. alignment is 4 (which is common), then no type's alignment is more
  10070. than 4.
  10071. The size of any type is always a multiple of its alignment; that way,
  10072. in an array whose elements have that type, all the elements are
  10073. properly aligned if the first one is.
  10074. These rules apply to all real computers today, but some embedded
  10075. controllers have odd exceptions. We don't have references to cite for
  10076. them.
  10077. @c We can't cite a nonfree manual as documentation.
  10078. Ordinary C code guarantees that every object of a given type is in
  10079. fact aligned as that type requires.
  10080. If the operand of @code{_Alignof} is a structure field, the value
  10081. is the alignment it requires. It may have a greater alignment by
  10082. coincidence, due to the other fields, but @code{_Alignof} is not
  10083. concerned about that. @xref{Structures}.
  10084. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10085. but now that the feature has been standardized, it is better
  10086. to use the standard keyword @code{_Alignof}.
  10087. @findex _Alignas
  10088. @findex __aligned__
  10089. You can explicitly specify an alignment requirement for a particular
  10090. variable or structure field by adding @code{_Alignas
  10091. (@var{alignment})} to the declaration, where @var{alignment} is a
  10092. power of 2 or a type name. For instance:
  10093. @example
  10094. char _Alignas (8) x;
  10095. @end example
  10096. @noindent
  10097. or
  10098. @example
  10099. char _Alignas (double) x;
  10100. @end example
  10101. @noindent
  10102. specifies that @code{x} must start on an address that is a multiple of
  10103. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10104. machine, that maximum is how much alignment @code{x} will get.
  10105. The older GNU C syntax for this feature looked like
  10106. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10107. declaration, and was added after the variable. For instance:
  10108. @example
  10109. char x __attribute__ ((__aligned__ 8));
  10110. @end example
  10111. @xref{Attributes}.
  10112. @node Aliasing
  10113. @appendix Aliasing
  10114. @cindex aliasing (of storage)
  10115. @cindex pointer type conversion
  10116. @cindex type conversion, pointer
  10117. We have already presented examples of casting a @code{void *} pointer
  10118. to another pointer type, and casting another pointer type to
  10119. @code{void *}.
  10120. One common kind of pointer cast is guaranteed safe: casting the value
  10121. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10122. Allocation}). It is safe because these functions do not save the
  10123. pointer anywhere else; the only way the program will access the newly
  10124. allocated memory is via the pointer just returned.
  10125. In fact, C allows casting any pointer type to any other pointer type.
  10126. Using this to access the same place in memory using two
  10127. different data types is called @dfn{aliasing}.
  10128. Aliasing is necessary in some programs that do sophisticated memory
  10129. management, such as GNU Emacs, but most C programs don't need to do
  10130. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10131. aliasing correctly requires following the rules stated below.
  10132. Otherwise, the aliasing may result in malfunctions when the program
  10133. runs.
  10134. The rest of this appendix explains the pitfalls and rules of aliasing.
  10135. @menu
  10136. * Aliasing Alignment:: Memory alignment considerations for
  10137. casting between pointer types.
  10138. * Aliasing Length:: Type size considerations for
  10139. casting between pointer types.
  10140. * Aliasing Type Rules:: Even when type alignment and size matches,
  10141. aliasing can still have surprising results.
  10142. @end menu
  10143. @node Aliasing Alignment
  10144. @appendixsection Aliasing and Alignment
  10145. In order for a type-converted pointer to be valid, it must have the
  10146. alignment that the new pointer type requires. For instance, on most
  10147. computers, @code{int} has alignment 4; the address of an @code{int}
  10148. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10149. address of a @code{char} is usually not a multiple of 4. Taking the
  10150. address of such a @code{char} and casting it to @code{int *} probably
  10151. results in an invalid pointer. Trying to dereference it may cause a
  10152. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10153. @example
  10154. foo ()
  10155. @{
  10156. char i[4];
  10157. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10158. return *p; /* @r{Crash!} */
  10159. @}
  10160. @end example
  10161. This requirement is never a problem when casting the return value
  10162. of @code{malloc} because that function always returns a pointer
  10163. with as much alignment as any type can require.
  10164. @node Aliasing Length
  10165. @appendixsection Aliasing and Length
  10166. When converting a pointer to a different pointer type, make sure the
  10167. object it really points to is at least as long as the target of the
  10168. converted pointer. For instance, suppose @code{p} has type @code{int
  10169. *} and it's cast as follows:
  10170. @example
  10171. int *p;
  10172. struct
  10173. @{
  10174. double d, e, f;
  10175. @} foo;
  10176. struct foo *q = (struct foo *)p;
  10177. q->f = 5.14159;
  10178. @end example
  10179. @noindent
  10180. the value @code{q->f} will run past the end of the @code{int} that
  10181. @code{p} points to. If @code{p} was initialized to the start of an
  10182. array of type @code{int[6]}, the object is long enough for three
  10183. @code{double}s. But if @code{p} points to something shorter,
  10184. @code{q->f} will run on beyond the end of that, overlaying some other
  10185. data. Storing that will garble that other data. Or it could extend
  10186. past the end of memory space and cause a @code{SIGSEGV} signal
  10187. (@pxref{Signals}).
  10188. @node Aliasing Type Rules
  10189. @appendixsection Type Rules for Aliasing
  10190. C code that converts a pointer to a different pointer type can use the
  10191. pointers to access the same memory locations with two different data
  10192. types. If the same address is accessed with different types in a
  10193. single control thread, optimization can make the code do surprising
  10194. things (in effect, make it malfunction).
  10195. Here's a concrete example where aliasing that can change the code's
  10196. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10197. long, like @code{int}, and so is every pointer. Thus, the structures
  10198. @code{struct a} and @code{struct b} are both 8 bytes.
  10199. @example
  10200. #include <stdio.h>
  10201. struct a @{ int size; char *data; @};
  10202. struct b @{ float size; char *data; @};
  10203. void sub (struct a *p, struct b *q)
  10204. @{
  10205.   int x;
  10206.   p->size = 0;
  10207.   q->size = 1;
  10208.   x = p->size;
  10209.   printf("x       =%d\n", x);
  10210.   printf("p->size =%d\n", (int)p->size);
  10211.   printf("q->size =%d\n", (int)q->size);
  10212. @}
  10213. int main(void)
  10214. @{
  10215.   struct a foo;
  10216.   struct a *p = &foo;
  10217.   struct b *q = (struct b *) &foo;
  10218.   sub (p, q);
  10219. @}
  10220. @end example
  10221. This code works as intended when compiled without optimization. All
  10222. the operations are carried out sequentially as written. The code
  10223. sets @code{x} to @code{p->size}, but what it actually gets is the
  10224. bits of the floating point number 1, as type @code{int}.
  10225. However, when optimizing, the compiler is allowed to assume
  10226. (mistakenly, here) that @code{q} does not point to the same storage as
  10227. @code{p}, because their data types are not allowed to alias.
  10228. From this assumption, the compiler can deduce (falsely, here) that the
  10229. assignment into @code{q->size} has no effect on the value of
  10230. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10231. be set to 0.
  10232. GNU C, following the C standard, @emph{defines} this optimization as
  10233. legitimate. Code that misbehaves when optimized following these rules
  10234. is, by definition, incorrect C code.
  10235. The rules for storage aliasing in C are based on the two data types:
  10236. the type of the object, and the type it is accessed through. The
  10237. rules permit accessing part of a storage object of type @var{t} using
  10238. only these types:
  10239. @itemize @bullet
  10240. @item
  10241. @var{t}.
  10242. @item
  10243. A type compatible with @var{t}. @xref{Compatible Types}.
  10244. @item
  10245. A signed or unsigned version of one of the above.
  10246. @item
  10247. A qualifed version of one of the above.
  10248. @xref{Type Qualifiers}.
  10249. @item
  10250. An array, structure (@pxref{Structures}), or union type
  10251. (@code{Unions}) that contains one of the above, either directly as a
  10252. field or through multiple levels of fields. If @var{t} is
  10253. @code{double}, this would include @code{struct s @{ union @{ double
  10254. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10255. inside it somewhere.
  10256. @item
  10257. A character type.
  10258. @end itemize
  10259. What do these rules say about the example in this subsection?
  10260. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10261. @code{int}. The type @code{float} is not allowed as an aliasing type
  10262. by those rules, so @code{b->size} is not supposed to alias with
  10263. elements of @code{j}. Based on that assumption, GNU C makes a
  10264. permitted optimization that was not, in this case, consistent with
  10265. what the programmer intended the program to do.
  10266. Whether GCC actually performs type-based aliasing analysis depends on
  10267. the details of the code. GCC has other ways to determine (in some cases)
  10268. whether objects alias, and if it gets a reliable answer that way, it won't
  10269. fall back on type-based heuristics.
  10270. @c @opindex -fno-strict-aliasing
  10271. The importance of knowing the type-based aliasing rules is not so as
  10272. to ensure that the optimization is done where it would be safe, but so
  10273. as to ensure it is @emph{not} done in a way that would break the
  10274. program. You can turn off type-based aliasing analysis by giving GCC
  10275. the option @option{-fno-strict-aliasing}.
  10276. @node Digraphs
  10277. @appendix Digraphs
  10278. @cindex digraphs
  10279. C accepts aliases for certain characters. Apparently in the 1990s
  10280. some computer systems had trouble inputting these characters, or
  10281. trouble displaying them. These digraphs almost never appear in C
  10282. programs nowadays, but we mention them for completeness.
  10283. @table @samp
  10284. @item <:
  10285. An alias for @samp{[}.
  10286. @item :>
  10287. An alias for @samp{]}.
  10288. @item <%
  10289. An alias for @samp{@{}.
  10290. @item %>
  10291. An alias for @samp{@}}.
  10292. @item %:
  10293. An alias for @samp{#},
  10294. used for preprocessing directives (@pxref{Directives}) and
  10295. macros (@pxref{Macros}).
  10296. @end table
  10297. @node Attributes
  10298. @appendix Attributes in Declarations
  10299. @cindex attributes
  10300. @findex __attribute__
  10301. You can specify certain additional requirements in a declaration, to
  10302. get fine-grained control over code generation, and helpful
  10303. informational messages during compilation. We use a few attributes in
  10304. code examples throughout this manual, including
  10305. @table @code
  10306. @item aligned
  10307. The @code{aligned} attribute specifies a minimum alignment for a
  10308. variable or structure field, measured in bytes:
  10309. @example
  10310. int foo __attribute__ ((aligned (8))) = 0;
  10311. @end example
  10312. @noindent
  10313. This directs GNU C to allocate @code{foo} at an address that is a
  10314. multiple of 8 bytes. However, you can't force an alignment bigger
  10315. than the computer's maximum meaningful alignment.
  10316. @item packed
  10317. The @code{packed} attribute specifies to compact the fields of a
  10318. structure by not leaving gaps between fields. For example,
  10319. @example
  10320. struct __attribute__ ((packed)) bar
  10321. @{
  10322. char a;
  10323. int b;
  10324. @};
  10325. @end example
  10326. @noindent
  10327. allocates the integer field @code{b} at byte 1 in the structure,
  10328. immediately after the character field @code{a}. The packed structure
  10329. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10330. alignment is 1, that of @code{char}.
  10331. @item deprecated
  10332. Applicable to both variables and functions, the @code{deprecated}
  10333. attribute tells the compiler to issue a warning if the variable or
  10334. function is ever used in the source file.
  10335. @example
  10336. int old_foo __attribute__ ((deprecated));
  10337. int old_quux () __attribute__ ((deprecated));
  10338. @end example
  10339. @item __noinline__
  10340. The @code{__noinline__} attribute, in a function's declaration or
  10341. definition, specifies never to inline calls to that function. All
  10342. calls to that function, in a compilation unit where it has this
  10343. attribute, will be compiled to invoke the separately compiled
  10344. function. @xref{Inline Function Definitions}.
  10345. @item __noclone__
  10346. The @code{__noclone__} attribute, in a function's declaration or
  10347. definition, specifies never to clone that function. Thus, there will
  10348. be only one compiled version of the function. @xref{Label Value
  10349. Caveats}, for more information about cloning.
  10350. @item always_inline
  10351. The @code{always_inline} attribute, in a function's declaration or
  10352. definition, specifies to inline all calls to that function (unless
  10353. something about the function makes inlining impossible). This applies
  10354. to all calls to that function in a compilation unit where it has this
  10355. attribute. @xref{Inline Function Definitions}.
  10356. @item gnu_inline
  10357. The @code{gnu_inline} attribute, in a function's declaration or
  10358. definition, specifies to handle the @code{inline} keywprd the way GNU
  10359. C originally implemented it, many years before ISO C said anything
  10360. about inlining. @xref{Inline Function Definitions}.
  10361. @end table
  10362. For full documentation of attributes, see the GCC manual.
  10363. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10364. the GNU Compiler Collection}.
  10365. @node Signals
  10366. @appendix Signals
  10367. @cindex signal
  10368. @cindex handler (for signal)
  10369. @cindex @code{SIGSEGV}
  10370. @cindex @code{SIGFPE}
  10371. @cindex @code{SIGBUS}
  10372. Some program operations bring about an error condition called a
  10373. @dfn{signal}. These signals terminate the program, by default.
  10374. There are various different kinds of signals, each with a name. We
  10375. have seen several such error conditions through this manual:
  10376. @table @code
  10377. @item SIGSEGV
  10378. This signal is generated when a program tries to read or write outside
  10379. the memory that is allocated for it, or to write memory that can only
  10380. be read. The name is an abbreviation for ``segmentation violation''.
  10381. @item SIGFPE
  10382. This signal indicates a fatal arithmetic error. The name is an
  10383. abbreviation for ``floating-point exception'', but covers all types of
  10384. arithmetic errors, including division by zero and overflow.
  10385. @item SIGBUS
  10386. This signal is generated when an invalid pointer is dereferenced,
  10387. typically the result of dereferencing an uninintalized pointer. It is
  10388. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10389. invalid access to valid memory, while @code{SIGBUS} indicates an
  10390. attempt to access an invalid address.
  10391. @end table
  10392. These kinds of signal allow the program to specify a function as a
  10393. @dfn{signal handler}. When a signal has a handler, it doesn't
  10394. terminate the program; instead it calls the handler.
  10395. There are many other kinds of signal; here we list only those that
  10396. come from run-time errors in C operations. The rest have to do with
  10397. the functioning of the operating system. The GNU C Library Reference
  10398. Manual gives more explanation about signals (@pxref{Program Signal
  10399. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10400. Manual}).
  10401. @node GNU Free Documentation License
  10402. @appendix GNU Free Documentation License
  10403. @include fdl.texi
  10404. @node Symbol Index
  10405. @unnumbered Index of Symbols and Keywords
  10406. @printindex fn
  10407. @node Concept Index
  10408. @unnumbered Concept Index
  10409. @printindex cp
  10410. @bye