c.texi 420 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029
  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 describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are defined in
  112. a standard library, which is automatically available in every C
  113. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  114. Reference Manual}.
  115. This manual incorporates the former GNU C Preprocessor Manual, which
  116. was among the earliest GNU Manuals. It also uses some text from the
  117. earlier GNU C Manual that was written by Trevis Rothwell and James
  118. Youngman.
  119. GNU C has many obscure features, each one either for historical
  120. compatibility or meant for very special situations. We have left them
  121. to a companion manual, the GNU C Obscurities Manual, which will be
  122. published digitally later.
  123. Please report errors and suggestions to c-manual@@gnu.org.
  124. @menu
  125. * The First Example:: Getting started with basic C code.
  126. * Complete Program:: A whole example program
  127. that can be compiled and run.
  128. * Storage:: Basic layout of storage; bytes.
  129. * Beyond Integers:: Exploring different numeric types.
  130. * Lexical Syntax:: The various lexical components of C programs.
  131. * Arithmetic:: Numeric computations.
  132. * Assignment Expressions:: Storing values in variables.
  133. * Execution Control Expressions:: Expressions combining values in various ways.
  134. * Binary Operator Grammar:: An overview of operator precedence.
  135. * Order of Execution:: The order of program execution.
  136. * Primitive Types:: More details about primitive data types.
  137. * Constants:: Explicit constant values:
  138. details and examples.
  139. * Type Size:: The memory space occupied by a type.
  140. * Pointers:: Creating and manipulating memory pointers.
  141. * Structures:: Compound data types built
  142. by grouping other types.
  143. * Arrays:: Creating and manipulating arrays.
  144. * Enumeration Types:: Sets of integers with named values.
  145. * Defining Typedef Names:: Using @code{typedef} to define type names.
  146. * Statements:: Controling program flow.
  147. * Variables:: Details about declaring, initializing,
  148. and using variables.
  149. * Type Qualifiers:: Mark variables for certain intended uses.
  150. * Functions:: Declaring, defining, and calling functions.
  151. * Compatible Types:: How to tell if two types are compatible
  152. with each other.
  153. * Type Conversions:: Converting between types.
  154. * Scope:: Different categories of identifier scope.
  155. * Preprocessing:: Using the GNU C preprocessor.
  156. * Integers in Depth:: How integer numbers are represented.
  157. * Floating Point in Depth:: How floating-point numbers are represented.
  158. * Compilation:: How to compile multi-file programs.
  159. * Directing Compilation:: Operations that affect compilation
  160. but don't change the program.
  161. Appendices
  162. * Type Alignment:: Where in memory a type can validly start.
  163. * Aliasing:: Accessing the same data in two types.
  164. * Digraphs:: Two-character aliases for some characters.
  165. * Attributes:: Specifying additional information
  166. in a declaration.
  167. * Signals:: Fatal errors triggered in various scenarios.
  168. * GNU Free Documentation License:: The license for this manual.
  169. * Symbol Index:: Keyword and symbol index.
  170. * Concept Index:: Detailed topical index.
  171. @detailmenu
  172. --- The Detailed Node Listing ---
  173. * Recursive Fibonacci:: Writing a simple function recursively.
  174. * Stack:: Each function call uses space in the stack.
  175. * Iterative Fibonacci:: Writing the same function iteratively.
  176. * Complete Example:: Turn the simple function into a full program.
  177. * Complete Explanation:: Explanation of each part of the example.
  178. * Complete Line-by-Line:: Explaining each line of the example.
  179. * Compile Example:: Using GCC to compile the example.
  180. * Float Example:: A function that uses floating-point numbers.
  181. * Array Example:: A function that works with arrays.
  182. * Array Example Call:: How to call that function.
  183. * Array Example Variations:: Different ways to write the call example.
  184. Lexical Syntax
  185. * English:: Write programs in English!
  186. * Characters:: The characters allowed in C programs.
  187. * Whitespace:: The particulars of whitespace characters.
  188. * Comments:: How to include comments in C code.
  189. * Identifiers:: How to form identifiers (names).
  190. * Operators/Punctuation:: Characters used as operators or punctuation.
  191. * Line Continuation:: Splitting one line into multiple lines.
  192. * Digraphs:: Two-character substitutes for some characters.
  193. Arithmetic
  194. * Basic Arithmetic:: Addition, subtraction, multiplication,
  195. and division.
  196. * Integer Arithmetic:: How C performs arithmetic with integer values.
  197. * Integer Overflow:: When an integer value exceeds the range
  198. of its type.
  199. * Mixed Mode:: Calculating with both integer values
  200. and floating-point values.
  201. * Division and Remainder:: How integer division works.
  202. * Numeric Comparisons:: Comparing numeric values for
  203. equality or order.
  204. * Shift Operations:: Shift integer bits left or right.
  205. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  206. Assignment Expressions
  207. * Simple Assignment:: The basics of storing a value.
  208. * Lvalues:: Expressions into which a value can be stored.
  209. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  210. * Increment/Decrement:: Shorthand for incrementing and decrementing
  211. an lvalue's contents.
  212. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  213. * Assignment in Subexpressions:: How to avoid ambiguity.
  214. * Write Assignments Separately:: Write assignments as separate statements.
  215. Execution Control Expressions
  216. * Logical Operators:: Logical conjunction, disjunction, negation.
  217. * Logicals and Comparison:: Logical operators with comparison operators.
  218. * Logicals and Assignments:: Assignments with logical operators.
  219. * Conditional Expression:: An if/else construct inside expressions.
  220. * Comma Operator:: Build a sequence of subexpressions.
  221. Order of Execution
  222. * Reordering of Operands:: Operations in C are not necessarily computed
  223. in the order they are written.
  224. * Associativity and Ordering:: Some associative operations are performed
  225. in a particular order; others are not.
  226. * Sequence Points:: Some guarantees about the order of operations.
  227. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  228. * Ordering of Operands:: Evaluation order of operands
  229. and function arguments.
  230. * Optimization and Ordering:: Compiler optimizations can reorder operations
  231. only if it has no impact on program results.
  232. Primitive Data Types
  233. * Integer Types:: Description of integer types.
  234. * Floating-Point Data Types:: Description of floating-point types.
  235. * Complex Data Types:: Description of complex number types.
  236. * The Void Type:: A type indicating no value at all.
  237. * Other Data Types:: A brief summary of other types.
  238. Constants
  239. * Integer Constants:: Literal integer values.
  240. * Integer Const Type:: Types of literal integer values.
  241. * Floating Constants:: Literal floating-point values.
  242. * Imaginary Constants:: Literal imaginary number values.
  243. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  244. * Character Constants:: Literal character values.
  245. * Unicode Character Codes:: Unicode characters represented
  246. in either UTF-16 or UTF-32.
  247. * Wide Character Constants:: Literal characters values larger than 8 bits.
  248. * String Constants:: Literal string values.
  249. * UTF-8 String Constants:: Literal UTF-8 string values.
  250. * Wide String Constants:: Literal string values made up of
  251. 16- or 32-bit characters.
  252. Pointers
  253. * Address of Data:: Using the ``address-of'' operator.
  254. * Pointer Types:: For each type, there is a pointer type.
  255. * Pointer Declarations:: Declaring variables with pointer types.
  256. * Pointer Type Designators:: Designators for pointer types.
  257. * Pointer Dereference:: Accessing what a pointer points at.
  258. * Null Pointers:: Pointers which do not point to any object.
  259. * Invalid Dereference:: Dereferencing null or invalid pointers.
  260. * Void Pointers:: Totally generic pointers, can cast to any.
  261. * Pointer Comparison:: Comparing memory address values.
  262. * Pointer Arithmetic:: Computing memory address values.
  263. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  264. * Pointer Arithmetic Low Level:: More about computing memory address values.
  265. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  266. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  267. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  268. * Printing Pointers:: Using @code{printf} for a pointer's value.
  269. Structures
  270. * Referencing Fields:: Accessing field values in a structure object.
  271. * Dynamic Memory Allocation:: Allocating space for objects
  272. while the program is running.
  273. * Field Offset:: Memory layout of fields within a structure.
  274. * Structure Layout:: Planning the memory layout of fields.
  275. * Packed Structures:: Packing structure fields as close as possible.
  276. * Bit Fields:: Dividing integer fields
  277. into fields with fewer bits.
  278. * Bit Field Packing:: How bit fields pack together in integers.
  279. * const Fields:: Making structure fields immutable.
  280. * Zero Length:: Zero-length array as a variable-length object.
  281. * Flexible Array Fields:: Another approach to variable-length objects.
  282. * Overlaying Structures:: Casting one structure type
  283. over an object of another structure type.
  284. * Structure Assignment:: Assigning values to structure objects.
  285. * Unions:: Viewing the same object in different types.
  286. * Packing With Unions:: Using a union type to pack various types into
  287. the same memory space.
  288. * Cast to Union:: Casting a value one of the union's alternative
  289. types to the type of the union itself.
  290. * Structure Constructors:: Building new structure objects.
  291. * Unnamed Types as Fields:: Fields' types do not always need names.
  292. * Incomplete Types:: Types which have not been fully defined.
  293. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  294. * Type Tags:: Scope of structure and union type tags.
  295. Arrays
  296. * Accessing Array Elements:: How to access individual elements of an array.
  297. * Declaring an Array:: How to name and reserve space for a new array.
  298. * Strings:: A string in C is a special case of array.
  299. * Incomplete Array Types:: Naming, but not allocating, a new array.
  300. * Limitations of C Arrays:: Arrays are not first-class objects.
  301. * Multidimensional Arrays:: Arrays of arrays.
  302. * Constructing Array Values:: Assigning values to an entire array at once.
  303. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  304. Statements
  305. * Expression Statement:: Evaluate an expression, as a statement,
  306. usually done for a side effect.
  307. * if Statement:: Basic conditional execution.
  308. * if-else Statement:: Multiple branches for conditional execution.
  309. * Blocks:: Grouping multiple statements together.
  310. * return Statement:: Return a value from a function.
  311. * Loop Statements:: Repeatedly executing a statement or block.
  312. * switch Statement:: Multi-way conditional choices.
  313. * switch Example:: A plausible example of using @code{switch}.
  314. * Duffs Device:: A special way to use @code{switch}.
  315. * Case Ranges:: Ranges of values for @code{switch} cases.
  316. * Null Statement:: A statement that does nothing.
  317. * goto Statement:: Jump to another point in the source code,
  318. identified by a label.
  319. * Local Labels:: Labels with limited scope.
  320. * Labels as Values:: Getting the address of a label.
  321. * Statement Exprs:: A series of statements used as an expression.
  322. Variables
  323. * Variable Declarations:: Name a variable and and reserve space for it.
  324. * Initializers:: Assigning inital values to variables.
  325. * Designated Inits:: Assigning initial values to array elements
  326. at particular array indices.
  327. * Auto Type:: Obtaining the type of a variable.
  328. * Local Variables:: Variables declared in function definitions.
  329. * File-Scope Variables:: Variables declared outside of
  330. function definitions.
  331. * Static Local Variables:: Variables declared within functions,
  332. but with permanent storage allocation.
  333. * Extern Declarations:: Declaring a variable
  334. which is allocated somewhere else.
  335. * Allocating File-Scope:: When is space allocated
  336. for file-scope variables?
  337. * auto and register:: Historically used storage directions.
  338. * Omitting Types:: The bad practice of declaring variables
  339. with implicit type.
  340. Type Qualifiers
  341. * const:: Variables whose values don't change.
  342. * volatile:: Variables whose values may be accessed
  343. or changed outside of the control of
  344. this program.
  345. * restrict Pointers:: Restricted pointers for code optimization.
  346. * restrict Pointer Example:: Example of how that works.
  347. Functions
  348. * Function Definitions:: Writing the body of a function.
  349. * Function Declarations:: Declaring the interface of a function.
  350. * Function Calls:: Using functions.
  351. * Function Call Semantics:: Call-by-value argument passing.
  352. * Function Pointers:: Using references to functions.
  353. * The main Function:: Where execution of a GNU C program begins.
  354. Type Conversions
  355. * Explicit Type Conversion:: Casting a value from one type to another.
  356. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  357. * Argument Promotions:: Automatic conversion of function parameters.
  358. * Operand Promotions:: Automatic conversion of arithmetic operands.
  359. * Common Type:: When operand types differ, which one is used?
  360. Scope
  361. * Scope:: Different categories of identifier scope.
  362. Preprocessing
  363. * Preproc Overview:: Introduction to the C preprocessor.
  364. * Directives:: The form of preprocessor directives.
  365. * Preprocessing Tokens:: The lexical elements of preprocessing.
  366. * Header Files:: Including one source file in another.
  367. * Macros:: Macro expansion by the preprocessor.
  368. * Conditionals:: Controling whether to compile some lines
  369. or ignore them.
  370. * Diagnostics:: Reporting warnings and errors.
  371. * Line Control:: Reporting source line numbers.
  372. * Null Directive:: A preprocessing no-op.
  373. Integers in Depth
  374. * Integer Representations:: How integer values appear in memory.
  375. * Maximum and Minimum Values:: Value ranges of integer types.
  376. Floating Point in Depth
  377. * Floating Representations:: How floating-point values appear in memory.
  378. * Floating Type Specs:: Precise details of memory representations.
  379. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  380. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  381. * Exception Flags:: Handling certain conditions in floating point.
  382. * Exact Floating-Point:: Not all floating calculations lose precision.
  383. * Rounding:: When a floating result can't be represented
  384. exactly in the floating-point type in use.
  385. * Rounding Issues:: Avoid magnifying rounding errors.
  386. * Significance Loss:: Subtracting numbers that are almost equal.
  387. * Fused Multiply-Add:: Taking advantage of a special floating-point
  388. instruction for faster execution.
  389. * Error Recovery:: Determining rounding errors.
  390. * Exact Floating Constants:: Precisely specified floating-point numbers.
  391. * Handling Infinity:: When floating calculation is out of range.
  392. * Handling NaN:: What floating calculation is undefined.
  393. * Signed Zeros:: Positive zero vs. negative zero.
  394. * Scaling by the Base:: A useful exact floating-point operation.
  395. * Rounding Control:: Specifying some rounding behaviors.
  396. * Machine Epsilon:: The smallest number you can add to 1.0
  397. and get a sum which is larger than 1.0.
  398. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  399. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  400. * Further Reading:: References for floating-point numbers.
  401. Directing Compilation
  402. * Pragmas:: Controling compilation of some constructs.
  403. * Static Assertions:: Compile-time tests for conditions.
  404. @end detailmenu
  405. @end menu
  406. @node The First Example
  407. @chapter The First Example
  408. This chapter presents the source code for a very simple C program and
  409. uses it to explain a few features of the language. If you already
  410. know the basic points of C presented in this chapter, you can skim it
  411. or skip it.
  412. @menu
  413. * Recursive Fibonacci:: Writing a simple function recursively.
  414. * Stack:: Each function call uses space in the stack.
  415. * Iterative Fibonacci:: Writing the same function iteratively.
  416. @end menu
  417. @node Recursive Fibonacci
  418. @section Example: Recursive Fibonacci
  419. @cindex recursive Fibonacci function
  420. @cindex Fibonacci function, recursive
  421. To introduce the most basic features of C, let's look at code for a
  422. simple mathematical function that does calculations on integers. This
  423. function calculates the @var{n}th number in the Fibonacci series, in
  424. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  425. 13, 21, 34, 55, @dots{}.
  426. @example
  427. int
  428. fib (int n)
  429. @{
  430. if (n <= 2) /* @r{This avoids infinite recursion.} */
  431. return 1;
  432. else
  433. return fib (n - 1) + fib (n - 2);
  434. @}
  435. @end example
  436. This very simple program illustrates several features of C:
  437. @itemize @bullet
  438. @item
  439. A function definition, whose first two lines constitute the function
  440. header. @xref{Function Definitions}.
  441. @item
  442. A function parameter @code{n}, referred to as the variable @code{n}
  443. inside the function body. @xref{Function Parameter Variables}.
  444. A function definition uses parameters to refer to the argument
  445. values provided in a call to that function.
  446. @item
  447. Arithmetic. C programs add with @samp{+} and subtract with
  448. @samp{-}. @xref{Arithmetic}.
  449. @item
  450. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  451. equal.'' @xref{Numeric Comparisons}.
  452. @item
  453. Integer constants written in base 10.
  454. @xref{Integer Constants}.
  455. @item
  456. A function call. The function call @code{fib (n - 1)} calls the
  457. function @code{fib}, passing as its argument the value @code{n - 1}.
  458. @xref{Function Calls}.
  459. @item
  460. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  461. comment has no effect on the execution of the program. Its purpose is
  462. to provide explanations to people reading the source code. Including
  463. comments in the code is tremendously important---they provide
  464. background information so others can understand the code more quickly.
  465. @xref{Comments}.
  466. @item
  467. Two kinds of statements, the @code{return} statement and the
  468. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  469. @item
  470. Recursion. The function @code{fib} calls itself; that is called a
  471. @dfn{recursive call}. These are valid in C, and quite common.
  472. The @code{fib} function would not be useful if it didn't return.
  473. Thus, recursive definitions, to be of any use, must avoid infinite
  474. recursion.
  475. This function definition prevents infinite recursion by specially
  476. handling the case where @code{n} is two or less. Thus the maximum
  477. depth of recursive calls is less than @code{n}.
  478. @end itemize
  479. @menu
  480. * Function Header:: The function's name and how it is called.
  481. * Function Body:: Declarations and statements that implement the function.
  482. @end menu
  483. @node Function Header
  484. @subsection Function Header
  485. @cindex function header
  486. In our example, the first two lines of the function definition are the
  487. @dfn{header}. Its purpose is to state the function's name and say how
  488. it is called:
  489. @example
  490. int
  491. fib (int n)
  492. @end example
  493. @noindent
  494. says that the function returns an integer (type @code{int}), its name is
  495. @code{fib}, and it takes one argument named @code{n} which is also an
  496. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  497. @node Function Body
  498. @subsection Function Body
  499. @cindex function body
  500. @cindex recursion
  501. The rest of the function definition is called the @dfn{function body}.
  502. Like every function body, this one starts with @samp{@{}, ends with
  503. @samp{@}}, and contains zero or more @dfn{statements} and
  504. @dfn{declarations}. Statements specify actions to take, whereas
  505. declarations define names of variables, functions, and so on. Each
  506. statement and each declaration ends with a semicolon (@samp{;}).
  507. Statements and declarations often contain @dfn{expressions}; an
  508. expression is a construct whose execution produces a @dfn{value} of
  509. some data type, but may also take actions through ``side effects''
  510. that alter subsequent execution. A statement, by contrast, does not
  511. have a value; it affects further execution of the program only through
  512. the actions it takes.
  513. This function body contains no declarations, and just one statement,
  514. but that one is a complex statement in that it contains nested
  515. statements. This function uses two kinds of statements:
  516. @table @code
  517. @item return
  518. The @code{return} statement makes the function return immediately.
  519. It looks like this:
  520. @example
  521. return @var{value};
  522. @end example
  523. Its meaning is to compute the expression @var{value} and exit the
  524. function, making it return whatever value that expression produced.
  525. For instance,
  526. @example
  527. return 1;
  528. @end example
  529. @noindent
  530. returns the integer 1 from the function, and
  531. @example
  532. return fib (n - 1) + fib (n - 2);
  533. @end example
  534. @noindent
  535. returns a value computed by performing two function calls
  536. as specified and adding their results.
  537. @item @code{if}@dots{}@code{else}
  538. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  539. Each time it executes, it chooses one of its two substatements to execute
  540. and ignores the other. It looks like this:
  541. @example
  542. if (@var{condition})
  543. @var{if-true-statement}
  544. else
  545. @var{if-false-statement}
  546. @end example
  547. Its meaning is to compute the expression @var{condition} and, if it's
  548. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  549. @var{if-false-statement}. @xref{if-else Statement}.
  550. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  551. simply an expression. It's considered ``true'' if its value is
  552. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  553. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  554. Comparisons}.) Thus,
  555. @example
  556. if (n <= 2)
  557. return 1;
  558. else
  559. return fib (n - 1) + fib (n - 2);
  560. @end example
  561. @noindent
  562. first tests whether the value of @code{n} is less than or equal to 2.
  563. If so, the expression @code{n <= 2} has the value 1. So execution
  564. continues with the statement
  565. @example
  566. return 1;
  567. @end example
  568. @noindent
  569. Otherwise, execution continues with this statement:
  570. @example
  571. return fib (n - 1) + fib (n - 2);
  572. @end example
  573. Each of these statements ends the execution of the function and
  574. provides a value for it to return. @xref{return Statement}.
  575. @end table
  576. Calculating @code{fib} using ordinary integers in C works only for
  577. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  578. in type @code{int}. The addition operation that tries to add
  579. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  580. This occurrence is called @dfn{integer overflow}.
  581. Overflow can manifest itself in various ways, but one thing that can't
  582. possibly happen is to produce the correct value, since that can't fit
  583. in the space for the value. @xref{Integer Overflow}.
  584. @xref{Functions}, for a full explanation about functions.
  585. @node Stack
  586. @section The Stack, And Stack Overflow
  587. @cindex stack
  588. @cindex stack frame
  589. @cindex stack overflow
  590. @cindex recursion, drawbacks of
  591. @cindex stack frame
  592. Recursion has a drawback: there are limits to how many nested function
  593. calls a program can make. In C, each function call allocates a block
  594. of memory which it uses until the call returns. C allocates these
  595. blocks consecutively within a large area of memory known as the
  596. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  597. The size of the stack is limited; if the program tries to use too
  598. much, that causes the program to fail because the stack is full. This
  599. is called @dfn{stack overflow}.
  600. @cindex crash
  601. @cindex segmentation fault
  602. Stack overflow on GNU/Linux typically manifests itself as the
  603. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  604. fault.'' By default, this signal terminates the program immediately,
  605. rather than letting the program try to recover, or reach an expected
  606. ending point. (We commonly say in this case that the program
  607. ``crashes''). @xref{Signals}.
  608. It is inconvenient to observe a crash by passing too large
  609. an argument to recursive Fibonacci, because the program would run a
  610. long time before it crashes. This algorithm is simple but
  611. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  612. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  613. the final result.
  614. However, you can observe stack overflow very quickly if you use
  615. this function instead:
  616. @example
  617. int
  618. fill_stack (int n)
  619. @{
  620. if (n <= 1) /* @r{This limits the depth of recursion.} */
  621. return 1;
  622. else
  623. return fill_stack (n - 1);
  624. @}
  625. @end example
  626. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  627. and using the default configuration, an experiment showed there is
  628. enough stack space to do 261906 nested calls to that function. One
  629. more, and the stack overflows and the program crashes. On another
  630. platform, with a different configuration, or with a different
  631. function, the limit might be bigger or smaller.
  632. @node Iterative Fibonacci
  633. @section Example: Iterative Fibonacci
  634. @cindex iterative Fibonacci function
  635. @cindex Fibonacci function, iterative
  636. Here's a much faster algorithm for computing the same Fibonacci
  637. series. It is faster for two reasons. First, it uses @dfn{iteration}
  638. (that is, repetition or looping) rather than recursion, so it doesn't
  639. take time for a large number of function calls. But mainly, it is
  640. faster because the number of repetitions is small---only @code{@var{n}}.
  641. @c If you change this, change the duplicate in node Example of for.
  642. @example
  643. int
  644. fib (int n)
  645. @{
  646. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  647. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  648. int i;
  649. for (i = 1; i < n; ++i)
  650. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  651. /* @r{since @code{i < n} is false the first time.} */
  652. @{
  653. /* @r{Now @code{last} is @code{fib (@code{i})}}
  654. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  655. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  656. int next = prev + last;
  657. /* @r{Shift the values down.} */
  658. prev = last;
  659. last = next;
  660. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  661. @r{and @code{prev} is @code{fib (@code{i})}.}
  662. @r{But that won't stay true for long,}
  663. @r{because we are about to increment @code{i}.} */
  664. @}
  665. return last;
  666. @}
  667. @end example
  668. This definition computes @code{fib (@var{n})} in a time proportional
  669. to @code{@var{n}}. The comments in the definition explain how it works: it
  670. advances through the series, always keeps the last two values in
  671. @code{last} and @code{prev}, and adds them to get the next value.
  672. Here are the additional C features that this definition uses:
  673. @table @asis
  674. @item Internal blocks
  675. Within a function, wherever a statement is called for, you can write a
  676. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  677. more statements and declarations. (You can also use additional
  678. blocks as statements in a block.)
  679. The function body also counts as a block, which is why it can contain
  680. statements and declarations.
  681. @xref{Blocks}.
  682. @item Declarations of local variables
  683. This function body contains declarations as well as statements. There
  684. are three declarations directly in the function body, as well as a
  685. fourth declaration in an internal block. Each starts with @code{int}
  686. because it declares a variable whose type is integer. One declaration
  687. can declare several variables, but each of these declarations is
  688. simple and declares just one variable.
  689. Variables declared inside a block (either a function body or an
  690. internal block) are @dfn{local variables}. These variables exist only
  691. within that block; their names are not defined outside the block, and
  692. exiting the block deallocates their storage. This example declares
  693. four local variables: @code{last}, @code{prev}, @code{i}, and
  694. @code{next}.
  695. The most basic local variable declaration looks like this:
  696. @example
  697. @var{type} @var{variablename};
  698. @end example
  699. For instance,
  700. @example
  701. int i;
  702. @end example
  703. @noindent
  704. declares the local variable @code{i} as an integer.
  705. @xref{Variable Declarations}.
  706. @item Initializers
  707. When you declare a variable, you can also specify its initial value,
  708. like this:
  709. @example
  710. @var{type} @var{variablename} = @var{value};
  711. @end example
  712. For instance,
  713. @example
  714. int last = 1;
  715. @end example
  716. @noindent
  717. declares the local variable @code{last} as an integer (type
  718. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  719. @item Assignment
  720. Assignment: a specific kind of expression, written with the @samp{=}
  721. operator, that stores a new value in a variable or other place. Thus,
  722. @example
  723. @var{variable} = @var{value}
  724. @end example
  725. @noindent
  726. is an expression that computes @code{@var{value}} and stores the value in
  727. @code{@var{variable}}. @xref{Assignment Expressions}.
  728. @item Expression statements
  729. An expression statement is an expression followed by a semicolon.
  730. That computes the value of the expression, then ignores the value.
  731. An expression statement is useful when the expression changes some
  732. data or has other side effects---for instance, with function calls, or
  733. with assignments as in this example. @xref{Expression Statement}.
  734. Using an expression with no side effects in an expression statement is
  735. pointless except in very special cases. For instance, the expression
  736. statement @code{x;} would examine the value of @code{x} and ignore it.
  737. That is not useful.
  738. @item Increment operator
  739. The increment operator is @samp{++}. @code{++i} is an
  740. expression that is short for @code{i = i + 1}.
  741. @xref{Increment/Decrement}.
  742. @item @code{for} statements
  743. A @code{for} statement is a clean way of executing a statement
  744. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  745. @example
  746. for (i = 1; i < n; ++i)
  747. @var{body}
  748. @end example
  749. @noindent
  750. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  751. for the loop. The loop itself consists of
  752. @itemize @bullet
  753. @item
  754. Testing @code{i < n} and exiting the loop if that's false.
  755. @item
  756. Executing @var{body}.
  757. @item
  758. Advancing the loop (executing @code{++i}, which increments @code{i}).
  759. @end itemize
  760. The net result is to execute @var{body} with 1 in @code{i},
  761. then with 2 in @code{i}, and so on, stopping just before the repetition
  762. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  763. the loop will execute the body zero times.
  764. The body of the @code{for} statement must be one and only one
  765. statement. You can't write two statements in a row there; if you try
  766. to, only the first of them will be treated as part of the loop.
  767. The way to put multiple statements in such a place is to group them
  768. with a block, and that's what we do in this example.
  769. @end table
  770. @node Complete Program
  771. @chapter A Complete Program
  772. @cindex complete example program
  773. @cindex example program, complete
  774. It's all very well to write a Fibonacci function, but you cannot run
  775. it by itself. It is a useful program, but it is not a complete
  776. program.
  777. In this chapter we present a complete program that contains the
  778. @code{fib} function. This example shows how to make the program
  779. start, how to make it finish, how to do computation, and how to print
  780. a result.
  781. @menu
  782. * Complete Example:: Turn the simple function into a full program.
  783. * Complete Explanation:: Explanation of each part of the example.
  784. * Complete Line-by-Line:: Explaining each line of the example.
  785. * Compile Example:: Using GCC to compile the example.
  786. @end menu
  787. @node Complete Example
  788. @section Complete Program Example
  789. Here is the complete program that uses the simple, recursive version
  790. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  791. @example
  792. #include <stdio.h>
  793. int
  794. fib (int n)
  795. @{
  796. if (n <= 2) /* @r{This avoids infinite recursion.} */
  797. return 1;
  798. else
  799. return fib (n - 1) + fib (n - 2);
  800. @}
  801. int
  802. main (void)
  803. @{
  804. printf ("Fibonacci series item %d is %d\n",
  805. 20, fib (20));
  806. return 0;
  807. @}
  808. @end example
  809. @noindent
  810. This program prints a message that shows the value of @code{fib (20)}.
  811. Now for an explanation of what that code means.
  812. @node Complete Explanation
  813. @section Complete Program Explanation
  814. @ifnottex
  815. Here's the explanation of the code of the example in the
  816. previous section.
  817. @end ifnottex
  818. This sample program prints a message that shows the value of @code{fib
  819. (20)}, and exits with code 0 (which stands for successful execution).
  820. Every C program is started by running the function named @code{main}.
  821. Therefore, the example program defines a function named @code{main} to
  822. provide a way to start it. Whatever that function does is what the
  823. program does. @xref{The main Function}.
  824. The @code{main} function is the first one called when the program
  825. runs, but it doesn't come first in the example code. The order of the
  826. function definitions in the source code makes no difference to the
  827. program's meaning.
  828. The initial call to @code{main} always passes certain arguments, but
  829. @code{main} does not have to pay attention to them. To ignore those
  830. arguments, define @code{main} with @code{void} as the parameter list.
  831. (@code{void} as a function's parameter list normally means ``call with
  832. no arguments,'' but @code{main} is a special case.)
  833. The function @code{main} returns 0 because that is
  834. the conventional way for @code{main} to indicate successful execution.
  835. It could instead return a positive integer to indicate failure, and
  836. some utility programs have specific conventions for the meaning of
  837. certain numeric @dfn{failure codes}. @xref{Values from main}.
  838. @cindex @code{printf}
  839. The simplest way to print text in C is by calling the @code{printf}
  840. function, so here we explain what that does.
  841. @cindex standard output
  842. The first argument to @code{printf} is a @dfn{string constant}
  843. (@pxref{String Constants}) that is a template for output. The
  844. function @code{printf} copies most of that string directly as output,
  845. including the newline character at the end of the string, which is
  846. written as @samp{\n}. The output goes to the program's @dfn{standard
  847. output} destination, which in the usual case is the terminal.
  848. @samp{%} in the template introduces a code that substitutes other text
  849. into the output. Specifically, @samp{%d} means to take the next
  850. argument to @code{printf} and substitute it into the text as a decimal
  851. number. (The argument for @samp{%d} must be of type @code{int}; if it
  852. isn't, @code{printf} will malfunction.) So the output is a line that
  853. looks like this:
  854. @example
  855. Fibonacci series item 20 is 6765
  856. @end example
  857. This program does not contain a definition for @code{printf} because
  858. it is defined by the C library, which makes it available in all C
  859. programs. However, each program does need to @dfn{declare}
  860. @code{printf} so it will be called correctly. The @code{#include}
  861. line takes care of that; it includes a @dfn{header file} called
  862. @file{stdio.h} into the program's code. That file is provided by the
  863. operating system and it contains declarations for the many standard
  864. input/output functions in the C library, one of which is
  865. @code{printf}.
  866. Don't worry about header files for now; we'll explain them later in
  867. @ref{Header Files}.
  868. The first argument of @code{printf} does not have to be a string
  869. constant; it can be any string (@pxref{Strings}). However, using a
  870. constant is the most common case.
  871. To learn more about @code{printf} and other facilities of the C
  872. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  873. Reference Manual}.
  874. @node Complete Line-by-Line
  875. @section Complete Program, Line by Line
  876. Here's the same example, explained line by line.
  877. @strong{Beginners, do you find this helpful or not?
  878. Would you prefer a different layout for the example?
  879. Please tell rms@@gnu.org.}
  880. @example
  881. #include <stdio.h> /* @r{Include declaration of usual} */
  882. /* @r{I/O functions such as @code{printf}.} */
  883. /* @r{Most programs need these.} */
  884. int /* @r{This function returns an @code{int}.} */
  885. fib (int n) /* @r{Its name is @code{fib};} */
  886. /* @r{its argument is called @code{n}.} */
  887. @{ /* @r{Start of function body.} */
  888. /* @r{This stops the recursion from being infinite.} */
  889. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  890. return 1; /* @r{make @code{fib} return 1.} */
  891. else /* @r{otherwise, add the two previous} */
  892. /* @r{fibonacci numbers.} */
  893. return fib (n - 1) + fib (n - 2);
  894. @}
  895. int /* @r{This function returns an @code{int}.} */
  896. main (void) /* @r{Start here; ignore arguments.} */
  897. @{ /* @r{Print message with numbers in it.} */
  898. printf ("Fibonacci series item %d is %d\n",
  899. 20, fib (20));
  900. return 0; /* @r{Terminate program, report success.} */
  901. @}
  902. @end example
  903. @node Compile Example
  904. @section Compiling the Example Program
  905. @cindex compiling
  906. @cindex executable file
  907. To run a C program requires converting the source code into an
  908. @dfn{executable file}. This is called @dfn{compiling} the program,
  909. and the command to do that using GNU C is @command{gcc}.
  910. This example program consists of a single source file. If we
  911. call that file @file{fib1.c}, the complete command to compile it is
  912. this:
  913. @example
  914. gcc -g -O -o fib1 fib1.c
  915. @end example
  916. @noindent
  917. Here, @option{-g} says to generate debugging information, @option{-O}
  918. says to optimize at the basic level, and @option{-o fib1} says to put
  919. the executable program in the file @file{fib1}.
  920. To run the program, use its file name as a shell command.
  921. For instance,
  922. @example
  923. ./fib1
  924. @end example
  925. @noindent
  926. However, unless you are sure the program is correct, you should
  927. expect to need to debug it. So use this command,
  928. @example
  929. gdb fib1
  930. @end example
  931. @noindent
  932. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  933. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  934. debug the executable program @code{fib1}.
  935. @xref{Compilation}, for an introduction to compiling more complex
  936. programs which consist of more than one source file.
  937. @node Storage
  938. @chapter Storage and Data
  939. @cindex bytes
  940. @cindex storage organization
  941. @cindex memory organization
  942. Storage in C programs is made up of units called @dfn{bytes}. On
  943. nearly all computers, a byte consists of 8 bits, but there are a few
  944. peculiar computers (mostly ``embedded controllers'' for very small
  945. systems) where a byte is longer than that. This manual does not try
  946. to explain the peculiarity of those computers; we assume that a byte
  947. is 8 bits.
  948. Every C data type is made up of a certain number of bytes; that number
  949. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  950. types @code{signed char} and @code{unsigned char} are one byte long;
  951. use those types to operate on data byte by byte. @xref{Signed and
  952. Unsigned Types}. You can refer to a series of consecutive bytes as an
  953. array of @code{char} elements; that's what an ASCII string looks like
  954. in memory. @xref{String Constants}.
  955. @node Beyond Integers
  956. @chapter Beyond Integers
  957. So far we've presented programs that operate on integers. In this
  958. chapter we'll present examples of handling non-integral numbers and
  959. arrays of numbers.
  960. @menu
  961. * Float Example:: A function that uses floating-point numbers.
  962. * Array Example:: A function that works with arrays.
  963. * Array Example Call:: How to call that function.
  964. * Array Example Variations:: Different ways to write the call example.
  965. @end menu
  966. @node Float Example
  967. @section An Example with Non-Integer Numbers
  968. @cindex floating point example
  969. Here's a function that operates on and returns @dfn{floating point}
  970. numbers that don't have to be integers. Floating point represents a
  971. number as a fraction together with a power of 2. (For more detail,
  972. @pxref{Floating-Point Data Types}.) This example calculates the
  973. average of three floating point numbers that are passed to it as
  974. arguments:
  975. @example
  976. double
  977. average_of_three (double a, double b, double c)
  978. @{
  979. return (a + b + c) / 3;
  980. @}
  981. @end example
  982. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  983. integers, and even when they happen to be integers, most likely their
  984. average is not an integer.
  985. @code{double} is the usual data type in C for calculations on
  986. floating-point numbers.
  987. To print a @code{double} with @code{printf}, we must use @samp{%f}
  988. instead of @samp{%d}:
  989. @example
  990. printf ("Average is %f\n",
  991. average_of_three (1.1, 9.8, 3.62));
  992. @end example
  993. The code that calls @code{printf} must pass a @code{double} for
  994. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  995. If the argument has the wrong type, @code{printf} will produce garbage
  996. output.
  997. Here's a complete program that computes the average of three
  998. specific numbers and prints the result:
  999. @example
  1000. double
  1001. average_of_three (double a, double b, double c)
  1002. @{
  1003. return (a + b + c) / 3;
  1004. @}
  1005. int
  1006. main (void)
  1007. @{
  1008. printf ("Average is %f\n",
  1009. average_of_three (1.1, 9.8, 3.62));
  1010. return 0;
  1011. @}
  1012. @end example
  1013. From now on we will not present examples of calls to @code{main}.
  1014. Instead we encourage you to write them for yourself when you want
  1015. to test executing some code.
  1016. @node Array Example
  1017. @section An Example with Arrays
  1018. @cindex array example
  1019. A function to take the average of three numbers is very specific and
  1020. limited. A more general function would take the average of any number
  1021. of numbers. That requires passing the numbers in an array. An array
  1022. is an object in memory that contains a series of values of the same
  1023. data type. This chapter presents the basic concepts and use of arrays
  1024. through an example; for the full explanation, see @ref{Arrays}.
  1025. Here's a function definition to take the average of several
  1026. floating-point numbers, passed as type @code{double}. The first
  1027. parameter, @code{length}, specifies how many numbers are passed. The
  1028. second parameter, @code{input_data}, is an array that holds those
  1029. numbers.
  1030. @example
  1031. double
  1032. avg_of_double (int length, double input_data[])
  1033. @{
  1034. double sum = 0;
  1035. int i;
  1036. for (i = 0; i < length; i++)
  1037. sum = sum + input_data[i];
  1038. return sum / length;
  1039. @}
  1040. @end example
  1041. This introduces the expression to refer to an element of an array:
  1042. @code{input_data[i]} means the element at index @code{i} in
  1043. @code{input_data}. The index of the element can be any expression
  1044. with an integer value; in this case, the expression is @code{i}.
  1045. @xref{Accessing Array Elements}.
  1046. @cindex zero-origin indexing
  1047. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1048. valid index is one less than the number of elements. (This is known
  1049. as @dfn{zero-origin indexing}.)
  1050. This example also introduces the way to declare that a function
  1051. parameter is an array. Such declarations are modeled after the syntax
  1052. for an element of the array. Just as @code{double foo} declares that
  1053. @code{foo} is of type @code{double}, @code{double input_data[]}
  1054. declares that each element of @code{input_data} is of type
  1055. @code{double}. Therefore, @code{input_data} itself has type ``array
  1056. of @code{double}.''
  1057. When declaring an array parameter, it's not necessary to say how long
  1058. the array is. In this case, the parameter @code{input_data} has no
  1059. length information. That's why the function needs another parameter,
  1060. @code{length}, for the caller to provide that information to the
  1061. function @code{avg_of_double}.
  1062. @node Array Example Call
  1063. @section Calling the Array Example
  1064. To call the function @code{avg_of_double} requires making an
  1065. array and then passing it as an argument. Here is an example.
  1066. @example
  1067. @{
  1068. /* @r{The array of values to average.} */
  1069. double nums_to_average[5];
  1070. /* @r{The average, once we compute it.} */
  1071. double average;
  1072. /* @r{Fill in elements of @code{nums_to_average}.} */
  1073. nums_to_average[0] = 58.7;
  1074. nums_to_average[1] = 5.1;
  1075. nums_to_average[2] = 7.7;
  1076. nums_to_average[3] = 105.2;
  1077. nums_to_average[4] = -3.14159;
  1078. average = avg_of_double (5, nums_to_average);
  1079. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1080. @}
  1081. @end example
  1082. This shows an array subscripting expression again, this time
  1083. on the left side of an assignment, storing a value into an
  1084. element of an array.
  1085. It also shows how to declare a local variable that is an array:
  1086. @code{double nums_to_average[5];}. Since this declaration allocates the
  1087. space for the array, it needs to know the array's length. You can
  1088. specify the length with any expression whose value is an integer, but
  1089. in this declaration the length is a constant, the integer 5.
  1090. The name of the array, when used by itself as an expression, stands
  1091. for the address of the array's data, and that's what gets passed to
  1092. the function @code{avg_of_double} in @code{avg_of_double (5,
  1093. nums_to_average)}.
  1094. We can make the code easier to maintain by avoiding the need to write
  1095. 5, the array length, when calling @code{avg_of_double}. That way, if
  1096. we change the array to include more elements, we won't have to change
  1097. that call. One way to do this is with the @code{sizeof} operator:
  1098. @example
  1099. average = avg_of_double ((sizeof (nums_to_average)
  1100. / sizeof (nums_to_average[0])),
  1101. nums_to_average);
  1102. @end example
  1103. This computes the number of elements in @code{nums_to_average} by dividing
  1104. its total size by the size of one element. @xref{Type Size}, for more
  1105. details of using @code{sizeof}.
  1106. We don't show in this example what happens after storing the result of
  1107. @code{avg_of_double} in the variable @code{average}. Presumably
  1108. more code would follow that uses that result somehow. (Why compute
  1109. the average and not use it?) But that isn't part of this topic.
  1110. @node Array Example Variations
  1111. @section Variations for Array Example
  1112. The code to call @code{avg_of_double} has two declarations that
  1113. start with the same data type:
  1114. @example
  1115. /* @r{The array of values to average.} */
  1116. double nums_to_average[5];
  1117. /* @r{The average, once we compute it.} */
  1118. double average;
  1119. @end example
  1120. In C, you can combine the two, like this:
  1121. @example
  1122. double nums_to_average[5], average;
  1123. @end example
  1124. This declares @code{nums_to_average} so each of its elements is a
  1125. @code{double}, and @code{average} so that it simply is a
  1126. @code{double}.
  1127. However, while you @emph{can} combine them, that doesn't mean you
  1128. @emph{should}. If it is useful to write comments about the variables,
  1129. and usually it is, then it's clearer to keep the declarations separate
  1130. so you can put a comment on each one.
  1131. We set all of the elements of the array @code{nums_to_average} with
  1132. assignments, but it is more convenient to use an initializer in the
  1133. declaration:
  1134. @example
  1135. @{
  1136. /* @r{The array of values to average.} */
  1137. double nums_to_average[]
  1138. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1139. /* @r{The average, once we compute it.} */
  1140. average = avg_of_double ((sizeof (nums_to_average)
  1141. / sizeof (nums_to_average[0])),
  1142. nums_to_average);
  1143. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1144. @}
  1145. @end example
  1146. The array initializer is a comma-separated list of values, delimited
  1147. by braces. @xref{Initializers}.
  1148. Note that the declaration does not specify a size for
  1149. @code{nums_to_average}, so the size is determined from the
  1150. initializer. There are five values in the initializer, so
  1151. @code{nums_to_average} gets length 5. If we add another element to
  1152. the initializer, @code{nums_to_average} will have six elements.
  1153. Because the code computes the number of elements from the size of
  1154. the array, using @code{sizeof}, the program will operate on all the
  1155. elements in the initializer, regardless of how many those are.
  1156. @node Lexical Syntax
  1157. @chapter Lexical Syntax
  1158. @cindex lexical syntax
  1159. @cindex token
  1160. To start the full description of the C language, we explain the
  1161. lexical syntax and lexical units of C code. The lexical units of a
  1162. programming language are known as @dfn{tokens}. This chapter covers
  1163. all the tokens of C except for constants, which are covered in a later
  1164. chapter (@pxref{Constants}). One vital kind of token is the
  1165. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1166. kind.
  1167. @menu
  1168. * English:: Write programs in English!
  1169. * Characters:: The characters allowed in C programs.
  1170. * Whitespace:: The particulars of whitespace characters.
  1171. * Comments:: How to include comments in C code.
  1172. * Identifiers:: How to form identifiers (names).
  1173. * Operators/Punctuation:: Characters used as operators or punctuation.
  1174. * Line Continuation:: Splitting one line into multiple lines.
  1175. @end menu
  1176. @node English
  1177. @section Write Programs in English!
  1178. In principle, you can write the function and variable names in a
  1179. program, and the comments, in any human language. C allows any kinds
  1180. of characters in comments, and you can put non-ASCII characters into
  1181. identifiers with a special prefix. However, to enable programmers in
  1182. all countries to understand and develop the program, it is best given
  1183. today's circumstances to write identifiers and comments in
  1184. English.
  1185. English is the one language that programmers in all countries
  1186. generally study. If a program's names are in English, most
  1187. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1188. understand them. Most programmers in those countries can speak
  1189. English, or at least read it, but they do not read each other's
  1190. languages at all. In India, with so many languages, two programmers
  1191. may have no common language other than English.
  1192. If you don't feel confident in writing English, do the best you can,
  1193. and follow each English comment with a version in a language you
  1194. write better; add a note asking others to translate that to English.
  1195. Someone will eventually do that.
  1196. The program's user interface is a different matter. We don't need to
  1197. choose one language for that; it is easy to support multiple languages
  1198. and let each user choose the language to use. This requires writing
  1199. the program to support localization of its interface. (The
  1200. @code{gettext} package exists to support this; @pxref{Message
  1201. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1202. Manual}.) Then a community-based translation effort can provide
  1203. support for all the languages users want to use.
  1204. @node Characters
  1205. @section Characters
  1206. @cindex character set
  1207. @cindex Unicode
  1208. @c ??? How to express ¶?
  1209. GNU C source files are usually written in the
  1210. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1211. was defined in the 1960s for English. However, they can also include
  1212. Unicode characters represented in the
  1213. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1214. This makes it possible to represent accented letters such as @samp{á},
  1215. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1216. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1217. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1218. manual.}
  1219. In C source code, non-ASCII characters are valid in comments, in wide
  1220. character constants (@pxref{Wide Character Constants}), and in string
  1221. constants (@pxref{String Constants}).
  1222. @c ??? valid in identifiers?
  1223. Another way to specify non-ASCII characters in constants (character or
  1224. string) and identifiers is with an escape sequence starting with
  1225. backslash, specifying the intended Unicode character. (@xref{Unicode
  1226. Character Codes}.) This specifies non-ASCII characters without
  1227. putting a real non-ASCII character in the source file itself.
  1228. C accepts two-character aliases called @dfn{digraphs} for certain
  1229. characters. @xref{Digraphs}.
  1230. @node Whitespace
  1231. @section Whitespace
  1232. @cindex whitespace characters in source files
  1233. @cindex space character in source
  1234. @cindex tab character in source
  1235. @cindex formfeed in source
  1236. @cindex linefeed in source
  1237. @cindex newline in source
  1238. @cindex carriage return in source
  1239. @cindex vertical tab in source
  1240. Whitespace means characters that exist in a file but appear blank in a
  1241. printed listing of a file (or traditionally did appear blank, several
  1242. decades ago). The C language requires whitespace in order to separate
  1243. two consecutive identifiers, or to separate an identifier from a
  1244. numeric constant. Other than that, and a few special situations
  1245. described later, whitespace is optional; you can put it in when you
  1246. wish, to make the code easier to read.
  1247. Space and tab in C code are treated as whitespace characters. So are
  1248. line breaks. You can represent a line break with the newline
  1249. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1250. the CRLF sequence (two characters: carriage return followed by a
  1251. newline character).
  1252. The @dfn{formfeed} character, Control-L, was traditionally used to
  1253. divide a file into pages. It is still used this way in source code,
  1254. and the tools that generate nice printouts of source code still start
  1255. a new page after each ``formfeed'' character. Dividing code into
  1256. pages separated by formfeed characters is a good way to break it up
  1257. into comprehensible pieces and show other programmers where they start
  1258. and end.
  1259. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1260. make printing advance down to the next section of a page. We know of
  1261. no particular reason to use it in source code, but it is still
  1262. accepted as whitespace in C.
  1263. Comments are also syntactically equivalent to whitespace.
  1264. @ifinfo
  1265. @xref{Comments}.
  1266. @end ifinfo
  1267. @node Comments
  1268. @section Comments
  1269. @cindex comments
  1270. A comment encapsulates text that has no effect on the program's
  1271. execution or meaning.
  1272. The purpose of comments is to explain the code to people that read it.
  1273. Writing good comments for your code is tremendously important---they
  1274. should provide background information that helps programmers
  1275. understand the reasons why the code is written the way it is. You,
  1276. returning to the code six months from now, will need the help of these
  1277. comments to remember why you wrote it this way.
  1278. Outdated comments that become incorrect are counterproductive, so part
  1279. of the software developer's responsibility is to update comments as
  1280. needed to correspond with changes to the program code.
  1281. C allows two kinds of comment syntax, the traditional style and the
  1282. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1283. with @samp{*/}. For instance,
  1284. @example
  1285. /* @r{This is a comment in traditional C syntax.} */
  1286. @end example
  1287. A traditional comment can contain @samp{/*}, but these delimiters do
  1288. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1289. whether it contains @samp{/*} sequences.
  1290. @example
  1291. /* @r{This} /* @r{is a comment} */ But this is not! */
  1292. @end example
  1293. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1294. For instance,
  1295. @example
  1296. // @r{This is a comment in C@t{++} style.}
  1297. @end example
  1298. Line comments do nest, in effect, because @samp{//} inside a line
  1299. comment is part of that comment:
  1300. @example
  1301. // @r{this whole line is} // @r{one comment}
  1302. This is code, not comment.
  1303. @end example
  1304. It is safe to put line comments inside block comments, or vice versa.
  1305. @example
  1306. @group
  1307. /* @r{traditional comment}
  1308. // @r{contains line comment}
  1309. @r{more traditional comment}
  1310. */ text here is not a comment
  1311. // @r{line comment} /* @r{contains traditional comment} */
  1312. @end group
  1313. @end example
  1314. But beware of commenting out one end of a traditional comment with a line
  1315. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1316. inside an already-started comment.
  1317. @example
  1318. @group
  1319. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1320. Oops! The line comment has ended;
  1321. this isn't a comment any more. */
  1322. @end group
  1323. @end example
  1324. Comments are not recognized within string constants. @t{@w{"/* blah
  1325. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1326. string.
  1327. In this manual we show the text in comments in a variable-width font,
  1328. for readability, but this font distinction does not exist in source
  1329. files.
  1330. A comment is syntactically equivalent to whitespace, so it always
  1331. separates tokens. Thus,
  1332. @example
  1333. @group
  1334. int/* @r{comment} */foo;
  1335. @r{is equivalent to}
  1336. int foo;
  1337. @end group
  1338. @end example
  1339. @noindent
  1340. but clean code always uses real whitespace to separate the comment
  1341. visually from surrounding code.
  1342. @node Identifiers
  1343. @section Identifiers
  1344. @cindex identifiers
  1345. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1346. as well as @samp{_}, that does not start with a digit. Most compilers
  1347. also allow @samp{$}. An identifier can be as long as you like; for
  1348. example,
  1349. @example
  1350. int anti_dis_establishment_arian_ism;
  1351. @end example
  1352. @cindex case of letters in identifiers
  1353. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1354. and @code{A} are two different identifiers.
  1355. @cindex keyword
  1356. @cindex reserved words
  1357. Identifiers in C are used as variable names, function names, typedef
  1358. names, enumeration constants, type tags, field names, and labels.
  1359. Certain identifiers in C are @dfn{keywords}, which means they have
  1360. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1361. meaning you cannot use them in any other way. For instance, you can't
  1362. define a variable or function named @code{return} or @code{if}.
  1363. You can also include other characters, even non-ASCII characters, in
  1364. identifiers by writing their Unicode character names, which start with
  1365. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1366. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1367. characters in identifiers, and when they are written in English, they
  1368. never need non-ASCII characters. @xref{English}.
  1369. Whitespace is required to separate two consecutive identifiers, or to
  1370. separate an identifier from a preceding or following numeric
  1371. constant.
  1372. @node Operators/Punctuation
  1373. @section Operators and Punctuation
  1374. @cindex operators
  1375. @cindex punctuation
  1376. Here we describe the lexical syntax of operators and punctuation in C.
  1377. The specific operators of C and their meanings are presented in
  1378. subsequent chapters.
  1379. Most operators in C consist of one or two characters that can't be
  1380. used in identifiers. The characters used for operators in C are
  1381. @samp{!~^&|*/%+-=<>,.?:}.
  1382. Some operators are a single character. For instance, @samp{-} is the
  1383. operator for negation (with one operand) and the operator for
  1384. subtraction (with two operands).
  1385. Some operators are two characters. For example, @samp{++} is the
  1386. increment operator. Recognition of multicharacter operators works by
  1387. grouping together as many consecutive characters as can constitute one
  1388. operator.
  1389. For instance, the character sequence @samp{++} is always interpreted
  1390. as the increment operator; therefore, if we want to write two
  1391. consecutive instances of the operator @samp{+}, we must separate them
  1392. with a space so that they do not combine as one token. Applying the
  1393. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1394. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1395. of a valid C program and the former could not (since @code{a++}
  1396. is not an lvalue and thus can't be the operand of @code{++}).
  1397. A few C operators are keywords rather than special characters. They
  1398. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1399. (@pxref{Type Alignment}).
  1400. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1401. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1402. @samp{@}}) begin and end a block at the statement level
  1403. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1404. for a variable with multiple elements or components (such as arrays or
  1405. structures).
  1406. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1407. @code{array[5]}.
  1408. Parentheses are used in expressions for explicit nesting of
  1409. expressions (@pxref{Basic Arithmetic}), around the parameter
  1410. declarations in a function declaration or definition, and around the
  1411. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1412. (@pxref{Function Calls}). Several kinds of statements also use
  1413. parentheses as part of their syntax---for instance, @code{if}
  1414. statements, @code{for} statements, @code{while} statements, and
  1415. @code{switch} statements. @xref{if Statement}, and following
  1416. sections.
  1417. Parentheses are also required around the operand of the operator
  1418. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1419. type rather than a value. @xref{Type Size}.
  1420. @node Line Continuation
  1421. @section Line Continuation
  1422. @cindex line continuation
  1423. @cindex continuation of lines
  1424. The sequence of a backslash and a newline is ignored absolutely
  1425. anywhere in a C program. This makes it possible to split a single
  1426. source line into multiple lines in the source file. GNU C tolerates
  1427. and ignores other whitespace between the backslash and the newline.
  1428. In particular, it always ignores a CR (carriage return) character
  1429. there, in case some text editor decided to end the line with the CRLF
  1430. sequence.
  1431. The main use of line continuation in C is for macro definitions that
  1432. would be inconveniently long for a single line (@pxref{Macros}).
  1433. It is possible to continue a line comment onto another line with
  1434. backslash-newline. You can put backslash-newline in the middle of an
  1435. identifier, even a keyword, or an operator. You can even split
  1436. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1437. backslash-newline. Here's an ugly example:
  1438. @example
  1439. @group
  1440. /\
  1441. *
  1442. */ fo\
  1443. o +\
  1444. = 1\
  1445. 0;
  1446. @end group
  1447. @end example
  1448. @noindent
  1449. That's equivalent to @samp{/* */ foo += 10;}.
  1450. Don't do those things in real programs, since they make code hard to
  1451. read.
  1452. @strong{Note:} For the sake of using certain tools on the source code, it is
  1453. wise to end every source file with a newline character which is not
  1454. preceded by a backslash, so that it really ends the last line.
  1455. @node Arithmetic
  1456. @chapter Arithmetic
  1457. @cindex arithmetic operators
  1458. @cindex operators, arithmetic
  1459. @c ??? Duplication with other sections -- get rid of that?
  1460. Arithmetic operators in C attempt to be as similar as possible to the
  1461. abstract arithmetic operations, but it is impossible to do this
  1462. perfectly. Numbers in a computer have a finite range of possible
  1463. values, and non-integer values have a limit on their possible
  1464. accuracy. Nonetheless, in most cases you will encounter no surprises
  1465. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1466. for multiplication.
  1467. Each C operator has a @dfn{precedence}, which is its rank in the
  1468. grammatical order of the various operators. The operators with the
  1469. highest precedence grab adjoining operands first; these expressions
  1470. then become operands for operators of lower precedence. We give some
  1471. information about precedence of operators in this chapter where we
  1472. describe the operators; for the full explanation, see @ref{Binary
  1473. Operator Grammar}.
  1474. The arithmetic operators always @dfn{promote} their operands before
  1475. operating on them. This means converting narrow integer data types to
  1476. a wider data type (@pxref{Operand Promotions}). If you are just
  1477. learning C, don't worry about this yet.
  1478. Given two operands that have different types, most arithmetic
  1479. operations convert them both to their @dfn{common type}. For
  1480. instance, if one is @code{int} and the other is @code{double}, the
  1481. common type is @code{double}. (That's because @code{double} can
  1482. represent all the values that an @code{int} can hold, but not vice
  1483. versa.) For the full details, see @ref{Common Type}.
  1484. @menu
  1485. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1486. and division.
  1487. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1488. * Integer Overflow:: When an integer value exceeds the range
  1489. of its type.
  1490. * Mixed Mode:: Calculating with both integer values
  1491. and floating-point values.
  1492. * Division and Remainder:: How integer division works.
  1493. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1494. * Shift Operations:: Shift integer bits left or right.
  1495. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1496. @end menu
  1497. @node Basic Arithmetic
  1498. @section Basic Arithmetic
  1499. @cindex addition operator
  1500. @cindex subtraction operator
  1501. @cindex multiplication operator
  1502. @cindex division operator
  1503. @cindex negation operator
  1504. @cindex operator, addition
  1505. @cindex operator, subtraction
  1506. @cindex operator, multiplication
  1507. @cindex operator, division
  1508. @cindex operator, negation
  1509. Basic arithmetic in C is done with the usual binary operators of
  1510. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1511. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1512. used to change the sign of a number. The unary @code{+} operator also
  1513. exists; it yields its operand unaltered.
  1514. @samp{/} is the division operator, but dividing integers may not give
  1515. the result you expect. Its value is an integer, which is not equal to
  1516. the mathematical quotient when that is a fraction. Use @samp{%} to
  1517. get the corresponding integer remainder when necessary.
  1518. @xref{Division and Remainder}. Floating point division yields value
  1519. as close as possible to the mathematical quotient.
  1520. These operators use algebraic syntax with the usual algebraic
  1521. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1522. and division are done before addition and subtraction, but you can use
  1523. parentheses to explicitly specify how the operators nest. They are
  1524. left-associative (@pxref{Associativity and Ordering}). Thus,
  1525. @example
  1526. -a + b - c + d * e / f
  1527. @end example
  1528. @noindent
  1529. is equivalent to
  1530. @example
  1531. (((-a) + b) - c) + ((d * e) / f)
  1532. @end example
  1533. @node Integer Arithmetic
  1534. @section Integer Arithmetic
  1535. @cindex integer arithmetic
  1536. Each of the basic arithmetic operations in C has two variants for
  1537. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1538. by the data types of their operands.
  1539. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1540. A signed type can hold a range of positive and negative numbers, with
  1541. zero near the middle of the range. An unsigned type can hold only
  1542. nonnegative numbers; its range starts with zero and runs upward.
  1543. The most basic integer types are @code{int}, which normally can hold
  1544. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1545. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1546. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1547. computers but not always on embedded controllers.) @xref{Integer
  1548. Types}, for full information about integer types.
  1549. When a basic arithmetic operation is given two signed operands, it
  1550. does signed arithmetic. Given two unsigned operands, it does
  1551. unsigned arithmetic.
  1552. If one operand is @code{unsigned int} and the other is @code{int}, the
  1553. operator treats them both as unsigned. More generally, the common
  1554. type of the operands determines whether the operation is signed or
  1555. not. @xref{Common Type}.
  1556. Printing the results of unsigned arithmetic with @code{printf} using
  1557. @samp{%d} can produce surprising results for values far away from
  1558. zero. Even though the rules above say that the computation was done
  1559. with unsigned arithmetic, the printed result may appear to be signed!
  1560. The explanation is that the bit pattern resulting from addition,
  1561. subtraction or multiplication is actually the same for signed and
  1562. unsigned operations. The difference is only in the data type of the
  1563. result, which affects the @emph{interpretation} of the result bit pattern,
  1564. and whether the arithmetic operation can overflow (see the next section).
  1565. But @samp{%d} doesn't know its argument's data type. It sees only the
  1566. value's bit pattern, and it is defined to interpret that as
  1567. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1568. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1569. libc, The GNU C Library Reference Manual}.
  1570. Arithmetic in C never operates directly on narrow integer types (those
  1571. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1572. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1573. @node Integer Overflow
  1574. @section Integer Overflow
  1575. @cindex integer overflow
  1576. @cindex overflow, integer
  1577. When the mathematical value of an arithmetic operation doesn't fit in
  1578. the range of the data type in use, that's called @dfn{overflow}.
  1579. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1580. Integer overflow happens only in arithmetic operations. Type conversion
  1581. operations, by definition, do not cause overflow, not even when the
  1582. result can't fit in its new type. @xref{Integer Conversion}.
  1583. Signed numbers use two's-complement representation, in which the most
  1584. negative number lacks a positive counterpart (@pxref{Integers in
  1585. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1586. overflow.
  1587. @menu
  1588. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1589. * Signed Overflow:: Overlow in signed integer arithmetic.
  1590. @end menu
  1591. @node Unsigned Overflow
  1592. @subsection Overflow with Unsigned Integers
  1593. Unsigned arithmetic in C ignores overflow; it produces the true result
  1594. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1595. in the data type. We say it ``truncates'' the true result to the
  1596. lowest @var{n} bits.
  1597. A true result that is negative, when taken modulo the @var{n}th power
  1598. of 2, yields a positive number. For instance,
  1599. @example
  1600. unsigned int x = 1;
  1601. unsigned int y;
  1602. y = -x;
  1603. @end example
  1604. @noindent
  1605. causes overflow because the negative number @minus{}1 can't be stored
  1606. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1607. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1608. is the largest value that the unsigned data type can store. For a
  1609. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1610. and Minimum Values}.
  1611. Adding that number to itself, as here,
  1612. @example
  1613. unsigned int z;
  1614. z = y + y;
  1615. @end example
  1616. @noindent
  1617. ought to yield 8,489,934,590; however, that is again too large to fit,
  1618. so overflow truncates the value to 4,294,967,294. If that were a
  1619. signed integer, it would mean @minus{}2, which (not by coincidence)
  1620. equals @minus{}1 + @minus{}1.
  1621. @node Signed Overflow
  1622. @subsection Overflow with Signed Integers
  1623. @cindex compiler options for integer overflow
  1624. @cindex integer overflow, compiler options
  1625. @cindex overflow, compiler options
  1626. For signed integers, the result of overflow in C is @emph{in
  1627. principle} undefined, meaning that anything whatsoever could happen.
  1628. Therefore, C compilers can do optimizations that treat the overflow
  1629. case with total unconcern. (Since the result of overflow is undefined
  1630. in principle, one cannot claim that these optimizations are
  1631. erroneous.)
  1632. @strong{Watch out:} These optimizations can do surprising things. For
  1633. instance,
  1634. @example
  1635. int i;
  1636. @r{@dots{}}
  1637. if (i < i + 1)
  1638. x = 5;
  1639. @end example
  1640. @noindent
  1641. could be optimized to do the assignment unconditionally, because the
  1642. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1643. GCC offers compiler options to control handling signed integer
  1644. overflow. These options operate per module; that is, each module
  1645. behaves according to the options it was compiled with.
  1646. These two options specify particular ways to handle signed integer
  1647. overflow, other than the default way:
  1648. @table @option
  1649. @item -fwrapv
  1650. Make signed integer operations well-defined, like unsigned integer
  1651. operations: they produce the @var{n} low-order bits of the true
  1652. result. The highest of those @var{n} bits is the sign bit of the
  1653. result. With @option{-fwrapv}, these out-of-range operations are not
  1654. considered overflow, so (strictly speaking) integer overflow never
  1655. happens.
  1656. The option @option{-fwrapv} enables some optimizations based on the
  1657. defined values of out-of-range results. In GCC 8, it disables
  1658. optimizations that are based on assuming signed integer operations
  1659. will not overflow.
  1660. @item -ftrapv
  1661. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1662. This terminates the program unless the program handles the signal.
  1663. @xref{Signals}.
  1664. @end table
  1665. One other option is useful for finding where overflow occurs:
  1666. @ignore
  1667. @item -fno-strict-overflow
  1668. Disable optimizations that are based on assuming signed integer
  1669. operations will not overflow.
  1670. @end ignore
  1671. @table @option
  1672. @item -fsanitize=signed-integer-overflow
  1673. Output a warning message at run time when signed integer overflow
  1674. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1675. This takes priority over @option{-ftrapv}.
  1676. @end table
  1677. @node Mixed Mode
  1678. @section Mixed-Mode Arithmetic
  1679. Mixing integers and floating-point numbers in a basic arithmetic
  1680. operation converts the integers automatically to floating point.
  1681. In most cases, this gives exactly the desired results.
  1682. But sometimes it matters precisely where the conversion occurs.
  1683. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1684. as an integer, then converts the sum to floating point for the
  1685. multiplication. If the addition gets an overflow, that is not
  1686. equivalent to converting both integers to floating point and then
  1687. adding them. You can get the latter result by explicitly converting
  1688. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1689. @xref{Explicit Type Conversion}.
  1690. @c Eggert's report
  1691. Adding or multiplying several values, including some integers and some
  1692. floating point, does the operations left to right. Thus, @code{3.0 +
  1693. i + j} converts @code{i} to floating point, then adds 3.0, then
  1694. converts @code{j} to floating point and adds that. You can specify a
  1695. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1696. and @code{j} first and then adds that result (converting to floating
  1697. point) to 3.0. In this respect, C differs from other languages, such
  1698. as Fortran.
  1699. @node Division and Remainder
  1700. @section Division and Remainder
  1701. @cindex remainder operator
  1702. @cindex modulus
  1703. @cindex operator, remainder
  1704. Division of integers in C rounds the result to an integer. The result
  1705. is always rounded towards zero.
  1706. @example
  1707. 16 / 3 @result{} 5
  1708. -16 / 3 @result{} -5
  1709. 16 / -3 @result{} -5
  1710. -16 / -3 @result{} 5
  1711. @end example
  1712. @noindent
  1713. To get the corresponding remainder, use the @samp{%} operator:
  1714. @example
  1715. 16 % 3 @result{} 1
  1716. -16 % 3 @result{} -1
  1717. 16 % -3 @result{} 1
  1718. -16 % -3 @result{} -1
  1719. @end example
  1720. @noindent
  1721. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1722. From the rounded quotient and the remainder, you can reconstruct
  1723. the dividend, like this:
  1724. @example
  1725. int
  1726. original_dividend (int divisor, int quotient, int remainder)
  1727. @{
  1728. return divisor * quotient + remainder;
  1729. @}
  1730. @end example
  1731. To do unrounded division, use floating point. If only one operand is
  1732. floating point, @samp{/} converts the other operand to floating
  1733. point.
  1734. @example
  1735. 16.0 / 3 @result{} 5.333333333333333
  1736. 16 / 3.0 @result{} 5.333333333333333
  1737. 16.0 / 3.0 @result{} 5.333333333333333
  1738. 16 / 3 @result{} 5
  1739. @end example
  1740. The remainder operator @samp{%} is not allowed for floating-point
  1741. operands, because it is not needed. The concept of remainder makes
  1742. sense for integers because the result of division of integers has to
  1743. be an integer. For floating point, the result of division is a
  1744. floating-point number, in other words a fraction, which will differ
  1745. from the exact result only by a very small amount.
  1746. There are functions in the standard C library to calculate remainders
  1747. from integral-values division of floating-point numbers.
  1748. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1749. Reference Manual}.
  1750. Integer division overflows in one specific case: dividing the smallest
  1751. negative value for the data type (@pxref{Maximum and Minimum Values})
  1752. by @minus{}1. That's because the correct result, which is the
  1753. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1754. in the same number of bits. On some computers now in use, this always
  1755. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1756. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1757. Division by zero leads to unpredictable results---depending on the
  1758. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1759. produce a numeric result.
  1760. @cindex division by zero
  1761. @cindex zero, division by
  1762. @strong{Watch out:} Make sure the program does not divide by zero. If
  1763. you can't prove that the divisor is not zero, test whether it is zero,
  1764. and skip the division if so.
  1765. @node Numeric Comparisons
  1766. @section Numeric Comparisons
  1767. @cindex numeric comparisons
  1768. @cindex comparisons
  1769. @cindex operators, comparison
  1770. @cindex equal operator
  1771. @cindex not-equal operator
  1772. @cindex less-than operator
  1773. @cindex greater-than operator
  1774. @cindex less-or-equal operator
  1775. @cindex greater-or-equal operator
  1776. @cindex operator, equal
  1777. @cindex operator, not-equal
  1778. @cindex operator, less-than
  1779. @cindex operator, greater-than
  1780. @cindex operator, less-or-equal
  1781. @cindex operator, greater-or-equal
  1782. @cindex truth value
  1783. There are two kinds of comparison operators: @dfn{equality} and
  1784. @dfn{ordering}. Equality comparisons test whether two expressions
  1785. have the same value. The result is a @dfn{truth value}: a number that
  1786. is 1 for ``true'' and 0 for ``false.''
  1787. @example
  1788. a == b /* @r{Test for equal.} */
  1789. a != b /* @r{Test for not equal.} */
  1790. @end example
  1791. The equality comparison is written @code{==} because plain @code{=}
  1792. is the assignment operator.
  1793. Ordering comparisons test which operand is greater or less. Their
  1794. results are truth values. These are the ordering comparisons of C:
  1795. @example
  1796. a < b /* @r{Test for less-than.} */
  1797. a > b /* @r{Test for greater-than.} */
  1798. a <= b /* @r{Test for less-than-or-equal.} */
  1799. a >= b /* @r{Test for greater-than-or-equal.} */
  1800. @end example
  1801. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1802. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1803. mathematics. However, if @code{a} and @code{b} are special floating
  1804. point values (not ordinary numbers), all three can be false.
  1805. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1806. @node Shift Operations
  1807. @section Shift Operations
  1808. @cindex shift operators
  1809. @cindex operators, shift
  1810. @cindex operators, shift
  1811. @cindex shift count
  1812. @dfn{Shifting} an integer means moving the bit values to the left or
  1813. right within the bits of the data type. Shifting is defined only for
  1814. integers. Here's the way to write it:
  1815. @example
  1816. /* @r{Left shift.} */
  1817. 5 << 2 @result{} 20
  1818. /* @r{Right shift.} */
  1819. 5 >> 2 @result{} 1
  1820. @end example
  1821. @noindent
  1822. The left operand is the value to be shifted, and the right operand
  1823. says how many bits to shift it (the @dfn{shift count}). The left
  1824. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1825. operates on a narrow integer type; it's always either @code{int} or
  1826. wider. The value of the shift operator has the same type as the
  1827. promoted left operand.
  1828. @menu
  1829. * Bits Shifted In:: How shifting makes new bits to shift in.
  1830. * Shift Caveats:: Caveats of shift operations.
  1831. * Shift Hacks:: Clever tricks with shift operations.
  1832. @end menu
  1833. @node Bits Shifted In
  1834. @subsection Shifting Makes New Bits
  1835. A shift operation shifts towards one end of the number and has to
  1836. generate new bits at the other end.
  1837. Shifting left one bit must generate a new least significant bit. It
  1838. always brings in zero there. It is equivalent to multiplying by the
  1839. appropriate power of 2. For example,
  1840. @example
  1841. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1842. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1843. @end example
  1844. The meaning of shifting right depends on whether the data type is
  1845. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1846. data type, it performs ``arithmetic shift,'' which keeps the number's
  1847. sign unchanged by duplicating the sign bit. For an unsigned data
  1848. type, it performs ``logical shift,'' which always shifts in zeros at
  1849. the most significant bit.
  1850. In both cases, shifting right one bit is division by two, rounding
  1851. towards negative infinity. For example,
  1852. @example
  1853. (unsigned) 19 >> 2 @result{} 4
  1854. (unsigned) 20 >> 2 @result{} 5
  1855. (unsigned) 21 >> 2 @result{} 5
  1856. @end example
  1857. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1858. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1859. zero.
  1860. The shift count must be zero or greater. Shifting by a negative
  1861. number of bits gives machine-dependent results.
  1862. @node Shift Caveats
  1863. @subsection Caveats for Shift Operations
  1864. @strong{Warning:} If the shift count is greater than or equal to the
  1865. width in bits of the first operand, the results are machine-dependent.
  1866. Logically speaking, the ``correct'' value would be either -1 (for
  1867. right shift of a negative number) or 0 (in all other cases), but what
  1868. it really generates is whatever the machine's shift instruction does in
  1869. that case. So unless you can prove that the second operand is not too
  1870. large, write code to check it at run time.
  1871. @strong{Warning:} Never rely on how the shift operators relate in
  1872. precedence to other arithmetic binary operators. Programmers don't
  1873. remember these precedences, and won't understand the code. Always use
  1874. parentheses to explicitly specify the nesting, like this:
  1875. @example
  1876. a + (b << 5) /* @r{Shift first, then add.} */
  1877. (a + b) << 5 /* @r{Add first, then shift.} */
  1878. @end example
  1879. Note: according to the C standard, shifting of signed values isn't
  1880. guaranteed to work properly when the value shifted is negative, or
  1881. becomes negative during the operation of shifting left. However, only
  1882. pedants have a reason to be concerned about this; only computers with
  1883. strange shift instructions could plausibly do this wrong. In GNU C,
  1884. the operation always works as expected,
  1885. @node Shift Hacks
  1886. @subsection Shift Hacks
  1887. You can use the shift operators for various useful hacks. For
  1888. example, given a date specified by day of the month @code{d}, month
  1889. @code{m}, and year @code{y}, you can store the entire date in a single
  1890. integer @code{date}:
  1891. @example
  1892. unsigned int d = 12;
  1893. unsigned int m = 6;
  1894. unsigned int y = 1983;
  1895. unsigned int date = ((y << 4) + m) << 5) + d;
  1896. @end example
  1897. @noindent
  1898. To extract the original day, month, and year out of
  1899. @code{date}, use a combination of shift and remainder.
  1900. @example
  1901. d = date % 32;
  1902. m = (date >> 5) % 16;
  1903. y = date >> 9;
  1904. @end example
  1905. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1906. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1907. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1908. multiplication, since negating a value is equivalent to multiplying it
  1909. by @minus{}1.
  1910. @node Bitwise Operations
  1911. @section Bitwise Operations
  1912. @cindex bitwise operators
  1913. @cindex operators, bitwise
  1914. @cindex negation, bitwise
  1915. @cindex conjunction, bitwise
  1916. @cindex disjunction, bitwise
  1917. Bitwise operators operate on integers, treating each bit independently.
  1918. They are not allowed for floating-point types.
  1919. The examples in this section use binary constants, starting with
  1920. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1921. of type @code{int}.
  1922. @table @code
  1923. @item ~@code{a}
  1924. Unary operator for bitwise negation; this changes each bit of
  1925. @code{a} from 1 to 0 or from 0 to 1.
  1926. @example
  1927. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1928. ~0 @result{} 0b11111111111111111111111111111111
  1929. ~0b11111111111111111111111111111111 @result{} 0
  1930. ~ (-1) @result{} 0
  1931. @end example
  1932. It is useful to remember that @code{~@var{x} + 1} equals
  1933. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1934. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1935. as @var{x}.
  1936. @item @code{a} & @code{b}
  1937. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1938. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1939. @example
  1940. 0b10101010 & 0b11001100 @result{} 0b10001000
  1941. @end example
  1942. @item @code{a} | @code{b}
  1943. Binary operator for bitwise ``or'' (``inclusive or'' or
  1944. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1945. either @code{a} or @code{b}.
  1946. @example
  1947. 0b10101010 | 0b11001100 @result{} 0b11101110
  1948. @end example
  1949. @item @code{a} ^ @code{b}
  1950. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1951. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1952. @example
  1953. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1954. @end example
  1955. @end table
  1956. To understand the effect of these operators on signed integers, keep
  1957. in mind that all modern computers use two's-complement representation
  1958. (@pxref{Integer Representations}) for negative integers. This means
  1959. that the highest bit of the number indicates the sign; it is 1 for a
  1960. negative number and 0 for a positive number. In a negative number,
  1961. the value in the other bits @emph{increases} as the number gets closer
  1962. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1963. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1964. @strong{Warning:} C defines a precedence ordering for the bitwise
  1965. binary operators, but you should never rely on it. You should
  1966. never rely on how bitwise binary operators relate in precedence to the
  1967. arithmetic and shift binary operators. Other programmers don't
  1968. remember this precedence ordering, so always use parentheses to
  1969. explicitly specify the nesting.
  1970. For example, suppose @code{offset} is an integer that specifies
  1971. the offset within shared memory of a table, except that its bottom few
  1972. bits (@code{LOWBITS} says how many) are special flags. Here's
  1973. how to get just that offset and add it to the base address.
  1974. @example
  1975. shared_mem_base + (offset & (-1 << LOWBITS))
  1976. @end example
  1977. Thanks to the outer set of parentheses, we don't need to know whether
  1978. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1979. set, we don't need to know whether @samp{&} has higher precedence than
  1980. @samp{<<}. But we can rely on all unary operators to have higher
  1981. precedence than any binary operator, so we don't need parentheses
  1982. around the left operand of @samp{<<}.
  1983. @node Assignment Expressions
  1984. @chapter Assignment Expressions
  1985. @cindex assignment expressions
  1986. @cindex operators, assignment
  1987. As a general concept in programming, an @dfn{assignment} is a
  1988. construct that stores a new value into a place where values can be
  1989. stored---for instance, in a variable. Such places are called
  1990. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1991. An assignment in C is an expression because it has a value; we call
  1992. it an @dfn{assignment expression}. A simple assignment looks like
  1993. @example
  1994. @var{lvalue} = @var{value-to-store}
  1995. @end example
  1996. @noindent
  1997. We say it assigns the value of the expression @var{value-to-store} to
  1998. the location @var{lvalue}, or that it stores @var{value-to-store}
  1999. there. You can think of the ``l'' in ``lvalue'' as standing for
  2000. ``left,'' since that's what you put on the left side of the assignment
  2001. operator.
  2002. However, that's not the only way to use an lvalue, and not all lvalues
  2003. can be assigned to. To use the lvalue in the left side of an
  2004. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2005. not declared with the type qualifier @code{const} (@pxref{const}).
  2006. The value of the assignment expression is that of @var{lvalue} after
  2007. the new value is stored in it. This means you can use an assignment
  2008. inside other expressions. Assignment operators are right-associative
  2009. so that
  2010. @example
  2011. x = y = z = 0;
  2012. @end example
  2013. @noindent
  2014. is equivalent to
  2015. @example
  2016. x = (y = (z = 0));
  2017. @end example
  2018. This is the only useful way for them to associate;
  2019. the other way,
  2020. @example
  2021. ((x = y) = z) = 0;
  2022. @end example
  2023. @noindent
  2024. would be invalid since an assignment expression such as @code{x = y}
  2025. is not valid as an lvalue.
  2026. @strong{Warning:} Write parentheses around an assignment if you nest
  2027. it inside another expression, unless that is a conditional expression,
  2028. or comma-separated series, or another assignment.
  2029. @menu
  2030. * Simple Assignment:: The basics of storing a value.
  2031. * Lvalues:: Expressions into which a value can be stored.
  2032. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2033. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2034. an lvalue's contents.
  2035. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2036. * Assignment in Subexpressions:: How to avoid ambiguity.
  2037. * Write Assignments Separately:: Write assignments as separate statements.
  2038. @end menu
  2039. @node Simple Assignment
  2040. @section Simple Assignment
  2041. @cindex simple assignment
  2042. @cindex assignment, simple
  2043. A @dfn{simple assignment expression} computes the value of the right
  2044. operand and stores it into the lvalue on the left. Here is a simple
  2045. assignment expression that stores 5 in @code{i}:
  2046. @example
  2047. i = 5
  2048. @end example
  2049. @noindent
  2050. We say that this is an @dfn{assignment to} the variable @code{i} and
  2051. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2052. because it is an expression (so it has a value). Adding a semicolon
  2053. at the end would make it a statement (@pxref{Expression Statement}).
  2054. Here is another example of a simple assignment expression. Its
  2055. operands are not simple, but the kind of assignment done here is
  2056. simple assignment.
  2057. @example
  2058. x[foo ()] = y + 6
  2059. @end example
  2060. A simple assignment with two different numeric data types converts the
  2061. right operand value to the lvalue's type, if possible. It can convert
  2062. any numeric type to any other numeric type.
  2063. Simple assignment is also allowed on some non-numeric types: pointers
  2064. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2065. unions (@pxref{Unions}).
  2066. @strong{Warning:} Assignment is not allowed on arrays because
  2067. there are no array values in C; C variables can be arrays, but these
  2068. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2069. Arrays}.
  2070. @xref{Assignment Type Conversions}, for the complete rules about data
  2071. types used in assignments.
  2072. @node Lvalues
  2073. @section Lvalues
  2074. @cindex lvalues
  2075. An expression that identifies a memory space that holds a value is
  2076. called an @dfn{lvalue}, because it is a location that can hold a value.
  2077. The standard kinds of lvalues are:
  2078. @itemize @bullet
  2079. @item
  2080. A variable.
  2081. @item
  2082. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2083. unary @samp{*}.
  2084. @item
  2085. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2086. the structure value is an lvalue.
  2087. @item
  2088. A structure field reference using @samp{->}. This is always an lvalue
  2089. since @samp{->} implies pointer dereference.
  2090. @item
  2091. A union alternative reference (@pxref{Unions}), on the same conditions
  2092. as for structure fields.
  2093. @item
  2094. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2095. is an lvalue.
  2096. @end itemize
  2097. If an expression's outermost operation is any other operator, that
  2098. expression is not an lvalue. Thus, the variable @code{x} is an
  2099. lvalue, but @code{x + 0} is not, even though these two expressions
  2100. compute the same value (assuming @code{x} is a number).
  2101. An array can be an lvalue (the rules above determine whether it is
  2102. one), but using the array in an expression converts it automatically
  2103. to a pointer to the first element. The result of this conversion is
  2104. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2105. use @code{a} by itself as the left operand of an assignment. But you
  2106. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2107. lvalue since @code{a} is an lvalue.
  2108. @node Modifying Assignment
  2109. @section Modifying Assignment
  2110. @cindex modifying assignment
  2111. @cindex assignment, modifying
  2112. You can abbreviate the common construct
  2113. @example
  2114. @var{lvalue} = @var{lvalue} + @var{expression}
  2115. @end example
  2116. @noindent
  2117. as
  2118. @example
  2119. @var{lvalue} += @var{expression}
  2120. @end example
  2121. This is known as a @dfn{modifying assignment}. For instance,
  2122. @example
  2123. i = i + 5;
  2124. i += 5;
  2125. @end example
  2126. @noindent
  2127. shows two statements that are equivalent. The first uses
  2128. simple assignment; the second uses modifying assignment.
  2129. Modifying assignment works with any binary arithmetic operator. For
  2130. instance, you can subtract something from an lvalue like this,
  2131. @example
  2132. @var{lvalue} -= @var{expression}
  2133. @end example
  2134. @noindent
  2135. or multiply it by a certain amount like this,
  2136. @example
  2137. @var{lvalue} *= @var{expression}
  2138. @end example
  2139. @noindent
  2140. or shift it by a certain amount like this.
  2141. @example
  2142. @var{lvalue} <<= @var{expression}
  2143. @var{lvalue} >>= @var{expression}
  2144. @end example
  2145. In most cases, this feature adds no power to the language, but it
  2146. provides substantial convenience. Also, when @var{lvalue} contains
  2147. code that has side effects, the simple assignment performs those side
  2148. effects twice, while the modifying assignment performs them once. For
  2149. instance,
  2150. @example
  2151. x[foo ()] = x[foo ()] + 5;
  2152. @end example
  2153. @noindent
  2154. calls @code{foo} twice, and it could return different values each
  2155. time. If @code{foo ()} returns 1 the first time and 3 the second
  2156. time, then the effect could be to add @code{x[3]} and 5 and store the
  2157. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2158. result in @code{x[3]}. We don't know which of the two it will do,
  2159. because C does not specify which call to @code{foo} is computed first.
  2160. Such a statement is not well defined, and shouldn't be used.
  2161. By contrast,
  2162. @example
  2163. x[foo ()] += 5;
  2164. @end example
  2165. @noindent
  2166. is well defined: it calls @code{foo} only once to determine which
  2167. element of @code{x} to adjust, and it adjusts that element by adding 5
  2168. to it.
  2169. @node Increment/Decrement
  2170. @section Increment and Decrement Operators
  2171. @cindex increment operator
  2172. @cindex decrement operator
  2173. @cindex operator, increment
  2174. @cindex operator, decrement
  2175. @cindex preincrement expression
  2176. @cindex predecrement expression
  2177. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2178. @dfn{decrement} operators. When used on a numeric value, they add or
  2179. subtract 1. We don't consider them assignments, but they are
  2180. equivalent to assignments.
  2181. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2182. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2183. and the result becomes the expression's value. For instance,
  2184. @example
  2185. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2186. int
  2187. main (void)
  2188. @{
  2189. int i = 5;
  2190. printf ("%d\n", i);
  2191. printf ("%d\n", ++i);
  2192. printf ("%d\n", i);
  2193. return 0;
  2194. @}
  2195. @end example
  2196. @noindent
  2197. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2198. increments @code{i} from 5 to 6, and has the value 6, so the output
  2199. from @code{printf} on that line says @samp{6}.
  2200. Using @samp{--} instead, for predecrement,
  2201. @example
  2202. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2203. int
  2204. main (void)
  2205. @{
  2206. int i = 5;
  2207. printf ("%d\n", i);
  2208. printf ("%d\n", --i);
  2209. printf ("%d\n", i);
  2210. return 0;
  2211. @}
  2212. @end example
  2213. @noindent
  2214. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2215. again @samp{4}.
  2216. @node Postincrement/Postdecrement
  2217. @section Postincrement and Postdecrement
  2218. @cindex postincrement expression
  2219. @cindex postdecrement expression
  2220. @cindex operator, postincrement
  2221. @cindex operator, postdecrement
  2222. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2223. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2224. increments or decrement it. Thus, the value of @code{i++} is the same
  2225. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2226. little later.'' This is called @dfn{postincrement} or
  2227. @dfn{postdecrement}.
  2228. For example,
  2229. @example
  2230. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2231. int
  2232. main (void)
  2233. @{
  2234. int i = 5;
  2235. printf ("%d\n", i);
  2236. printf ("%d\n", i++);
  2237. printf ("%d\n", i);
  2238. return 0;
  2239. @}
  2240. @end example
  2241. @noindent
  2242. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2243. has the value 5, which is the value of @code{i} at the time,
  2244. but it increments @code{i} from 5 to 6 just a little later.
  2245. How much later is ``just a little later''? That is flexible. The
  2246. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2247. that means by the end of the statement. @xref{Sequence Points}.
  2248. If a unary operator precedes a postincrement or postincrement expression,
  2249. the increment nests inside:
  2250. @example
  2251. -a++ @r{is equivalent to} -(a++)
  2252. @end example
  2253. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2254. it can't be incremented.
  2255. @node Assignment in Subexpressions
  2256. @section Pitfall: Assignment in Subexpressions
  2257. @cindex assignment in subexpressions
  2258. @cindex subexpressions, assignment in
  2259. In C, the order of computing parts of an expression is not fixed.
  2260. Aside from a few special cases, the operations can be computed in any
  2261. order. If one part of the expression has an assignment to @code{x}
  2262. and another part of the expression uses @code{x}, the result is
  2263. unpredictable because that use might be computed before or after the
  2264. assignment.
  2265. Here's an example of ambiguous code:
  2266. @example
  2267. x = 20;
  2268. printf ("%d %d\n", x, x = 4);
  2269. @end example
  2270. @noindent
  2271. If the second argument, @code{x}, is computed before the third argument,
  2272. @code{x = 4}, the second argument's value will be 20. If they are
  2273. computed in the other order, the second argument's value will be 4.
  2274. Here's one way to make that code unambiguous:
  2275. @example
  2276. y = 20;
  2277. printf ("%d %d\n", y, x = 4);
  2278. @end example
  2279. Here's another way, with the other meaning:
  2280. @example
  2281. x = 4;
  2282. printf ("%d %d\n", x, x);
  2283. @end example
  2284. This issue applies to all kinds of assignments, and to the increment
  2285. and decrement operators, which are equivalent to assignments.
  2286. @xref{Order of Execution}, for more information about this.
  2287. However, it can be useful to write assignments inside an
  2288. @code{if}-condition or @code{while}-test along with logical operators.
  2289. @xref{Logicals and Assignments}.
  2290. @node Write Assignments Separately
  2291. @section Write Assignments in Separate Statements
  2292. It is often convenient to write an assignment inside an
  2293. @code{if}-condition, but that can reduce the readability of the
  2294. program. Here's an example of what to avoid:
  2295. @example
  2296. if (x = advance (x))
  2297. @r{@dots{}}
  2298. @end example
  2299. The idea here is to advance @code{x} and test if the value is nonzero.
  2300. However, readers might miss the fact that it uses @samp{=} and not
  2301. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2302. inside a condition is a common error, so GNU C can give warnings when
  2303. @samp{=} appears in a way that suggests it's an error.
  2304. It is much clearer to write the assignment as a separate statement, like this:
  2305. @example
  2306. x = advance (x);
  2307. if (x != 0)
  2308. @r{@dots{}}
  2309. @end example
  2310. @noindent
  2311. This makes it unmistakably clear that @code{x} is assigned a new value.
  2312. Another method is to use the comma operator (@pxref{Comma Operator}),
  2313. like this:
  2314. @example
  2315. if (x = advance (x), x != 0)
  2316. @r{@dots{}}
  2317. @end example
  2318. @noindent
  2319. However, putting the assignment in a separate statement is usually clearer
  2320. unless the assignment is very short, because it reduces nesting.
  2321. @node Execution Control Expressions
  2322. @chapter Execution Control Expressions
  2323. @cindex execution control expressions
  2324. @cindex expressions, execution control
  2325. This chapter describes the C operators that combine expressions to
  2326. control which of those expressions execute, or in which order.
  2327. @menu
  2328. * Logical Operators:: Logical conjunction, disjunction, negation.
  2329. * Logicals and Comparison:: Logical operators with comparison operators.
  2330. * Logicals and Assignments:: Assignments with logical operators.
  2331. * Conditional Expression:: An if/else construct inside expressions.
  2332. * Comma Operator:: Build a sequence of subexpressions.
  2333. @end menu
  2334. @node Logical Operators
  2335. @section Logical Operators
  2336. @cindex logical operators
  2337. @cindex operators, logical
  2338. @cindex conjunction operator
  2339. @cindex disjunction operator
  2340. @cindex negation operator, logical
  2341. The @dfn{logical operators} combine truth values, which are normally
  2342. represented in C as numbers. Any expression with a numeric value is a
  2343. valid truth value: zero means false, and any other value means true.
  2344. A pointer type is also meaningful as a truth value; a null pointer
  2345. (which is zero) means false, and a non-null pointer means true
  2346. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2347. or 0 and has type @code{int} (@pxref{Integer Types}).
  2348. The logical operators are used mainly in the condition of an @code{if}
  2349. statement, or in the end test in a @code{for} statement or
  2350. @code{while} statement (@pxref{Statements}). However, they are valid
  2351. in any context where an integer-valued expression is allowed.
  2352. @table @samp
  2353. @item ! @var{exp}
  2354. Unary operator for logical ``not.'' The value is 1 (true) if
  2355. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2356. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2357. function call, you should write parentheses around it.
  2358. @item @var{left} && @var{right}
  2359. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2360. @var{right}. If both of the operands are 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 false value,
  2363. that determines the overall result, so @var{right} is not computed.
  2364. @item @var{left} || @var{right}
  2365. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2366. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2367. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2368. gives the value 0 (false). If @var{left} yields a true value,
  2369. that determines the overall result, so @var{right} is not computed.
  2370. @end table
  2371. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2372. and @samp{||}. When you use them together, always use parentheses to
  2373. specify explicitly how they nest, as shown here:
  2374. @example
  2375. if ((r != 0 && x % r == 0)
  2376. ||
  2377. (s != 0 && x % s == 0))
  2378. @end example
  2379. @node Logicals and Comparison
  2380. @section Logical Operators and Comparisons
  2381. The most common thing to use inside the logical operators is a
  2382. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2383. precedence than comparison operators and arithmetic operators, so we
  2384. can write expressions like this without parentheses and get the
  2385. nesting that is natural: two comparison operations that must both be
  2386. true.
  2387. @example
  2388. if (r != 0 && x % r == 0)
  2389. @end example
  2390. @noindent
  2391. This example also shows how it is useful that @samp{&&} guarantees to
  2392. skip the right operand if the left one turns out false. Because of
  2393. that, this code never tries to divide by zero.
  2394. This is equivalent:
  2395. @example
  2396. if (r && x % r == 0)
  2397. @end example
  2398. @noindent
  2399. A truth value is simply a number, so @code{r}
  2400. as a truth value tests whether it is nonzero.
  2401. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2402. So it is better style to write the explicit @code{!= 0}.
  2403. Here's another equivalent way to write it:
  2404. @example
  2405. if (!(r == 0) && x % r == 0)
  2406. @end example
  2407. @noindent
  2408. This illustrates the unary @samp{!} operator, and the need to
  2409. write parentheses around its operand.
  2410. @node Logicals and Assignments
  2411. @section Logical Operators and Assignments
  2412. There are cases where assignments nested inside the condition can
  2413. actually make a program @emph{easier} to read. Here is an example
  2414. using a hypothetical type @code{list} which represents a list; it
  2415. tests whether the list has at least two links, using hypothetical
  2416. functions, @code{nonempty} which is true of the argument is a nonempty
  2417. list, and @code{list_next} which advances from one list link to the
  2418. next. We assume that a list is never a null pointer, so that the
  2419. assignment expressions are always ``true.''
  2420. @example
  2421. if (nonempty (list)
  2422. && (temp1 = list_next (list))
  2423. && nonempty (temp1)
  2424. && (temp2 = list_next (temp1)))
  2425. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2426. @end example
  2427. @noindent
  2428. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2429. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2430. only natural place to put the assignments is among those calls.
  2431. It would be possible to rewrite this as several statements, but that
  2432. could make it much more cumbersome. On the other hand, when the test
  2433. is even more complex than this one, splitting it into multiple
  2434. statements might be necessary for clarity.
  2435. If an empty list is a null pointer, we can dispense with calling
  2436. @code{nonempty}:
  2437. @example
  2438. if ((temp1 = list_next (list))
  2439. && (temp2 = list_next (temp1)))
  2440. @r{@dots{}}
  2441. @end example
  2442. @node Conditional Expression
  2443. @section Conditional Expression
  2444. @cindex conditional expression
  2445. @cindex expression, conditional
  2446. C has a conditional expression that selects one of two expressions
  2447. to compute and get the value from. It looks like this:
  2448. @example
  2449. @var{condition} ? @var{iftrue} : @var{iffalse}
  2450. @end example
  2451. @menu
  2452. * Conditional Rules:: Rules for the conditional operator.
  2453. * Conditional Branches:: About the two branches in a conditional.
  2454. @end menu
  2455. @node Conditional Rules
  2456. @subsection Rules for Conditional Operator
  2457. The first operand, @var{condition}, should be a value that can be
  2458. compared with zero---a number or a pointer. If it is true (nonzero),
  2459. then the conditional expression computes @var{iftrue} and its value
  2460. becomes the value of the conditional expression. Otherwise the
  2461. conditional expression computes @var{iffalse} and its value becomes
  2462. the value of the conditional expression. The conditional expression
  2463. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2464. of them.
  2465. Here's an example: the absolute value of a number @code{x}
  2466. can be written as @code{(x >= 0 ? x : -x)}.
  2467. @strong{Warning:} The conditional expression operators have rather low
  2468. syntactic precedence. Except when the conditional expression is used
  2469. as an argument in a function call, write parentheses around it. For
  2470. clarity, always write parentheses around it if it extends across more
  2471. than one line.
  2472. Assignment operators and the comma operator (@pxref{Comma Operator})
  2473. have lower precedence than conditional expression operators, so write
  2474. parentheses around those when they appear inside a conditional
  2475. expression. @xref{Order of Execution}.
  2476. @node Conditional Branches
  2477. @subsection Conditional Operator Branches
  2478. @cindex branches of conditional expression
  2479. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2480. conditional.
  2481. The two branches should normally have the same type, but a few
  2482. exceptions are allowed. If they are both numeric types, the
  2483. conditional converts both to their common type (@pxref{Common Type}).
  2484. With pointers (@pxref{Pointers}), the two values can be pointers to
  2485. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2486. result type is a similar pointer whose target type combines all the
  2487. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2488. If one branch has type @code{void *} and the other is a pointer to an
  2489. object (not to a function), the conditional converts the @code{void *}
  2490. branch to the type of the other.
  2491. If one branch is an integer constant with value zero and the other is
  2492. a pointer, the conditional converts zero to the pointer's type.
  2493. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2494. that case, if @var{condition} is nonzero, its value becomes the value of
  2495. the conditional expression, after conversion to the common type.
  2496. Thus,
  2497. @example
  2498. x ? : y
  2499. @end example
  2500. @noindent
  2501. has the value of @code{x} if that is nonzero; otherwise, the value of
  2502. @code{y}.
  2503. @cindex side effect in ?:
  2504. @cindex ?: side effect
  2505. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2506. In that case, writing that expression twice would carry out the side
  2507. effects twice, but writing it once does them just once. For example,
  2508. if we suppose that the function @code{next_element} advances a pointer
  2509. variable to point to the next element in a list and returns the new
  2510. pointer,
  2511. @example
  2512. next_element () ? : default_pointer
  2513. @end example
  2514. @noindent
  2515. is a way to advance the pointer and use its new value if it isn't
  2516. null, but use @code{default_pointer} if that is null. We must not do
  2517. it this way,
  2518. @example
  2519. next_element () ? next_element () : default_pointer
  2520. @end example
  2521. @noindent
  2522. because it would advance the pointer a second time.
  2523. @node Comma Operator
  2524. @section Comma Operator
  2525. @cindex comma operator
  2526. @cindex operator, comma
  2527. The comma operator stands for sequential execution of expressions.
  2528. The value of the comma expression comes from the last expression in
  2529. the sequence; the previous expressions are computed only for their
  2530. side effects. It looks like this:
  2531. @example
  2532. @var{exp1}, @var{exp2} @r{@dots{}}
  2533. @end example
  2534. @noindent
  2535. You can bundle any number of expressions together this way, by putting
  2536. commas between them.
  2537. @menu
  2538. * Uses of Comma:: When to use the comma operator.
  2539. * Clean Comma:: Clean use of the comma operator.
  2540. * Avoid Comma:: When to not use the comma operator.
  2541. @end menu
  2542. @node Uses of Comma
  2543. @subsection The Uses of the Comma Operator
  2544. With commas, you can put several expressions into a place that
  2545. requires just one expression---for example, in the header of a
  2546. @code{for} statement. This statement
  2547. @example
  2548. for (i = 0, j = 10, k = 20; i < n; i++)
  2549. @end example
  2550. @noindent
  2551. contains three assignment expressions, to initialize @code{i}, @code{j}
  2552. and @code{k}. The syntax of @code{for} requires just one expression
  2553. for initialization; to include three assignments, we use commas to
  2554. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2555. 20}. This technique is also useful in the loop-advance expression,
  2556. the last of the three inside the @code{for} parentheses.
  2557. In the @code{for} statement and the @code{while} statement
  2558. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2559. effect before the loop-exit test. For example,
  2560. @example
  2561. while (printf ("At the test, x = %d\n", x), x != 0)
  2562. @end example
  2563. @node Clean Comma
  2564. @subsection Clean Use of the Comma Operator
  2565. Always write parentheses around a series of comma operators, except
  2566. when it is at top level in an expression statement, or within the
  2567. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2568. statement (@pxref{Statements}). For instance, in
  2569. @example
  2570. for (i = 0, j = 10, k = 20; i < n; i++)
  2571. @end example
  2572. @noindent
  2573. the commas between the assignments are clear because they are between
  2574. a parenthesis and a semicolon.
  2575. The arguments in a function call are also separated by commas, but that is
  2576. not an instance of the comma operator. Note the difference between
  2577. @example
  2578. foo (4, 5, 6)
  2579. @end example
  2580. @noindent
  2581. which passes three arguments to @code{foo} and
  2582. @example
  2583. foo ((4, 5, 6))
  2584. @end example
  2585. @noindent
  2586. which uses the comma operator and passes just one argument
  2587. (with value 6).
  2588. @strong{Warning:} don't use the comma operator around an argument
  2589. of a function unless it helps understand the code. When you do so,
  2590. don't put part of another argument on the same line. Instead, add a
  2591. line break to make the parentheses around the comma operator easier to
  2592. see, like this.
  2593. @example
  2594. foo ((mumble (x, y), frob (z)),
  2595. *p)
  2596. @end example
  2597. @node Avoid Comma
  2598. @subsection When Not to Use the Comma Operator
  2599. You can use a comma in any subexpression, but in most cases it only
  2600. makes the code confusing, and it is clearer to raise all but the last
  2601. of the comma-separated expressions to a higher level. Thus, instead
  2602. of this:
  2603. @example
  2604. x = (y += 4, 8);
  2605. @end example
  2606. @noindent
  2607. it is much clearer to write this:
  2608. @example
  2609. y += 4, x = 8;
  2610. @end example
  2611. @noindent
  2612. or this:
  2613. @example
  2614. y += 4;
  2615. x = 8;
  2616. @end example
  2617. Use commas only in the cases where there is no clearer alternative
  2618. involving multiple statements.
  2619. By contrast, don't hesitate to use commas in the expansion in a macro
  2620. definition. The trade-offs of code clarity are different in that
  2621. case, because the @emph{use} of the macro may improve overall clarity
  2622. so much that the ugliness of the macro's @emph{definition} is a small
  2623. price to pay. @xref{Macros}.
  2624. @node Binary Operator Grammar
  2625. @chapter Binary Operator Grammar
  2626. @cindex binary operator grammar
  2627. @cindex grammar, binary operator
  2628. @cindex operator precedence
  2629. @cindex precedence, operator
  2630. @cindex left-associative
  2631. @dfn{Binary operators} are those that take two operands, one
  2632. on the left and one on the right.
  2633. All the binary operators in C are syntactically left-associative.
  2634. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2635. @var{op} b) @var{op} c}}. However, you should only write repeated
  2636. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2637. @samp{/}, because those cases are clear from algebra. So it is ok to
  2638. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2639. c} or @code{a % b % c}.
  2640. Each C operator has a @dfn{precedence}, which is its rank in the
  2641. grammatical order of the various operators. The operators with the
  2642. highest precedence grab adjoining operands first; these expressions
  2643. then become operands for operators of lower precedence.
  2644. The precedence order of operators in C is fully specified, so any
  2645. combination of operations leads to a well-defined nesting. We state
  2646. only part of the full precedence ordering here because it is bad
  2647. practice for C code to depend on the other cases. For cases not
  2648. specified in this chapter, always use parentheses to make the nesting
  2649. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2650. remembering anything about the C precedence order beyond what's stated
  2651. here. I studied the full precedence table to write the parser, and
  2652. promptly forgot it again. If you need to look up the full precedence order
  2653. to understand some C code, fix the code with parentheses so nobody else
  2654. needs to do that.}
  2655. You can depend on this subsequence of the precedence ordering
  2656. (stated from highest precedence to lowest):
  2657. @enumerate
  2658. @item
  2659. Component access (@samp{.} and @samp{->}).
  2660. @item
  2661. Unary prefix operators.
  2662. @item
  2663. Unary postfix operators.
  2664. @item
  2665. Multiplication, division, and remainder (they have the same precedence).
  2666. @item
  2667. Addition and subtraction (they have the same precedence).
  2668. @item
  2669. Comparisons---but watch out!
  2670. @item
  2671. Logical operators @samp{&&} and @samp{||}---but watch out!
  2672. @item
  2673. Conditional expression with @samp{?} and @samp{:}.
  2674. @item
  2675. Assignments.
  2676. @item
  2677. Sequential execution (the comma operator, @samp{,}).
  2678. @end enumerate
  2679. Two of the lines in the above list say ``but watch out!'' That means
  2680. that the line covers operators with subtly different precedence.
  2681. Never depend on the grammar of C to decide how two comparisons nest;
  2682. instead, always use parentheses to specify their nesting.
  2683. You can let several @samp{&&} operators associate, or several
  2684. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2685. and @samp{||} nest with each other. @xref{Logical Operators}.
  2686. There is one other precedence ordering that code can depend on:
  2687. @enumerate
  2688. @item
  2689. Unary postfix operators.
  2690. @item
  2691. Bitwise and shift operators---but watch out!
  2692. @item
  2693. Conditional expression with @samp{?} and @samp{:}.
  2694. @end enumerate
  2695. The caveat for bitwise and shift operators is like that for logical
  2696. operators: you can let multiple uses of one bitwise operator
  2697. associate, but always use parentheses to control nesting of dissimilar
  2698. operators.
  2699. These lists do not specify any precedence ordering between the bitwise
  2700. and shift operators of the second list and the binary operators above
  2701. conditional expressions in the first list. When they come together,
  2702. parenthesize them. @xref{Bitwise Operations}.
  2703. @node Order of Execution
  2704. @chapter Order of Execution
  2705. @cindex order of execution
  2706. The order of execution of a C program is not always obvious, and not
  2707. necessarily predictable. This chapter describes what you can count on.
  2708. @menu
  2709. * Reordering of Operands:: Operations in C are not necessarily computed
  2710. in the order they are written.
  2711. * Associativity and Ordering:: Some associative operations are performed
  2712. in a particular order; others are not.
  2713. * Sequence Points:: Some guarantees about the order of operations.
  2714. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2715. * Ordering of Operands:: Evaluation order of operands
  2716. and function arguments.
  2717. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2718. only if it has no impact on program results.
  2719. @end menu
  2720. @node Reordering of Operands
  2721. @section Reordering of Operands
  2722. @cindex ordering of operands
  2723. @cindex reordering of operands
  2724. @cindex operand execution ordering
  2725. The C language does not necessarily carry out operations within an
  2726. expression in the order they appear in the code. For instance, in
  2727. this expression,
  2728. @example
  2729. foo () + bar ()
  2730. @end example
  2731. @noindent
  2732. @code{foo} might be called first or @code{bar} might be called first.
  2733. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2734. results can be unpredictable.
  2735. The unpredictable order of computation of subexpressions also makes a
  2736. difference when one of them contains an assignment. We already saw
  2737. this example of bad code,
  2738. @example
  2739. x = 20;
  2740. printf ("%d %d\n", x, x = 4);
  2741. @end example
  2742. @noindent
  2743. in which the second argument, @code{x}, has a different value
  2744. depending on whether it is computed before or after the assignment in
  2745. the third argument.
  2746. @node Associativity and Ordering
  2747. @section Associativity and Ordering
  2748. @cindex associativity and ordering
  2749. An associative binary operator, such as @code{+}, when used repeatedly
  2750. can combine any number of operands. The operands' values may be
  2751. computed in any order.
  2752. If the values are integers and overflow can be ignored, they may be
  2753. combined in any order. Thus, given four functions that return
  2754. @code{unsigned int}, calling them and adding their results as here
  2755. @example
  2756. (foo () + bar ()) + (baz () + quux ())
  2757. @end example
  2758. @noindent
  2759. may add up the results in any order.
  2760. By contrast, arithmetic on signed integers, with overflow significant,
  2761. is not really associative (@pxref{Integer Overflow}). Thus, the
  2762. additions must be done in the order specified, obeying parentheses and
  2763. left-association. That means computing @code{(foo () + bar ())} and
  2764. @code{(baz () + quux ())} first (in either order), then adding the
  2765. two.
  2766. The same applies to arithmetic on floating-point values, since that
  2767. too is not really associative. However, the GCC option
  2768. @option{-funsafe-math-optimizations} allows the compiler to change the
  2769. order of calculation when an associative operation (associative in
  2770. exact mathematics) combines several operands. The option takes effect
  2771. when compiling a module (@pxref{Compilation}). Changing the order
  2772. of association can enable the program to pipeline the floating point
  2773. operations.
  2774. In all these cases, the four function calls can be done in any order.
  2775. There is no right or wrong about that.
  2776. @node Sequence Points
  2777. @section Sequence Points
  2778. @cindex sequence points
  2779. @cindex full expression
  2780. There are some points in the code where C makes limited guarantees
  2781. about the order of operations. These are called @dfn{sequence
  2782. points}. Here is where they occur:
  2783. @itemize @bullet
  2784. @item
  2785. At the end of a @dfn{full expression}; that is to say, an expression
  2786. that is not part of a larger expression. All side effects specified
  2787. by that expression are carried out before execution moves
  2788. on to subsequent code.
  2789. @item
  2790. At the end of the first operand of certain operators: @samp{,},
  2791. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2792. that expression are carried out before any execution of the
  2793. next operand.
  2794. The commas that separate arguments in a function call are @emph{not}
  2795. comma operators, and they do not create sequence points. The rule
  2796. for function arguments and the rule for operands are different
  2797. (@pxref{Ordering of Operands}).
  2798. @item
  2799. Just before calling a function. All side effects specified by the
  2800. argument expressions are carried out before calling the function.
  2801. If the function to be called is not constant---that is, if it is
  2802. computed by an expression---all side effects in that expression are
  2803. carried out before calling the function.
  2804. @end itemize
  2805. The ordering imposed by a sequence point applies locally to a limited
  2806. range of code, as stated above in each case. For instance, the
  2807. ordering imposed by the comma operator does not apply to code outside
  2808. that comma operator. Thus, in this code,
  2809. @example
  2810. (x = 5, foo (x)) + x * x
  2811. @end example
  2812. @noindent
  2813. the sequence point of the comma operator orders @code{x = 5} before
  2814. @code{foo (x)}, but @code{x * x} could be computed before or after
  2815. them.
  2816. @node Postincrement and Ordering
  2817. @section Postincrement and Ordering
  2818. @cindex postincrement and ordering
  2819. @cindex ordering and postincrement
  2820. Ordering requirements are loose with the postincrement and
  2821. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2822. specify side effects to happen ``a little later.'' They must happen
  2823. before the next sequence point, but that still leaves room for various
  2824. meanings. In this expression,
  2825. @example
  2826. z = x++ - foo ()
  2827. @end example
  2828. @noindent
  2829. it's unpredictable whether @code{x} gets incremented before or after
  2830. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2831. it might see the old value or it might see the incremented value.
  2832. In this perverse expression,
  2833. @example
  2834. x = x++
  2835. @end example
  2836. @noindent
  2837. @code{x} will certainly be incremented but the incremented value may
  2838. not stick. If the incrementation of @code{x} happens after the
  2839. assignment to @code{x}, the incremented value will remain in place.
  2840. But if the incrementation happens first, the assignment will overwrite
  2841. that with the not-yet-incremented value, so the expression as a whole
  2842. will leave @code{x} unchanged.
  2843. @node Ordering of Operands
  2844. @section Ordering of Operands
  2845. @cindex ordering of operands
  2846. @cindex operand ordering
  2847. Operands and arguments can be computed in any order, but there are limits to
  2848. this intermixing in GNU C:
  2849. @itemize @bullet
  2850. @item
  2851. The operands of a binary arithmetic operator can be computed in either
  2852. order, but they can't be intermixed: one of them has to come first,
  2853. followed by the other. Any side effects in the operand that's computed
  2854. first are executed before the other operand is computed.
  2855. @item
  2856. That applies to assignment operators too, except that in simple assignment
  2857. the previous value of the left operand is unused.
  2858. @item
  2859. The arguments in a function call can be computed in any order, but
  2860. they can't be intermixed. Thus, one argument is fully computed, then
  2861. another, and so on until they are all done. Any side effects in one argument
  2862. are executed before computation of another argument begins.
  2863. @end itemize
  2864. These rules don't cover side effects caused by postincrement and
  2865. postdecrement operators---those can be deferred up to the next
  2866. sequence point.
  2867. If you want to get pedantic, the fact is that GCC can reorder the
  2868. computations in many other ways provided that doesn't alter the result
  2869. of running the program. However, because they don't alter the result
  2870. of running the program, they are negligible, unless you are concerned
  2871. with the values in certain variables at various times as seen by other
  2872. processes. In those cases, you can use @code{volatile} to prevent
  2873. optimizations that would make them behave strangely. @xref{volatile}.
  2874. @node Optimization and Ordering
  2875. @section Optimization and Ordering
  2876. @cindex optimization and ordering
  2877. @cindex ordering and optimization
  2878. Sequence points limit the compiler's freedom to reorder operations
  2879. arbitrarily, but optimizations can still reorder them if the compiler
  2880. concludes that this won't alter the results. Thus, in this code,
  2881. @example
  2882. x++;
  2883. y = z;
  2884. x++;
  2885. @end example
  2886. @noindent
  2887. there is a sequence point after each statement, so the code is
  2888. supposed to increment @code{x} once before the assignment to @code{y}
  2889. and once after. However, incrementing @code{x} has no effect on
  2890. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2891. the code could be optimized into this:
  2892. @example
  2893. y = z;
  2894. x += 2;
  2895. @end example
  2896. Normally that has no effect except to make the program faster. But
  2897. there are special situations where it can cause trouble due to things
  2898. that the compiler cannot know about, such as shared memory. To limit
  2899. optimization in those places, use the @code{volatile} type qualifier
  2900. (@pxref{volatile}).
  2901. @node Primitive Types
  2902. @chapter Primitive Data Types
  2903. @cindex primitive types
  2904. @cindex types, primitive
  2905. This chapter describes all the primitive data types of C---that is,
  2906. all the data types that aren't built up from other types. They
  2907. include the types @code{int} and @code{double} that we've already covered.
  2908. @menu
  2909. * Integer Types:: Description of integer types.
  2910. * Floating-Point Data Types:: Description of floating-point types.
  2911. * Complex Data Types:: Description of complex number types.
  2912. * The Void Type:: A type indicating no value at all.
  2913. * Other Data Types:: A brief summary of other types.
  2914. * Type Designators:: Referring to a data type abstractly.
  2915. @end menu
  2916. These types are all made up of bytes (@pxref{Storage}).
  2917. @node Integer Types
  2918. @section Integer Data Types
  2919. @cindex integer types
  2920. @cindex types, integer
  2921. Here we describe all the integer types and their basic
  2922. characteristics. @xref{Integers in Depth}, for more information about
  2923. the bit-level integer data representations and arithmetic.
  2924. @menu
  2925. * Basic Integers:: Overview of the various kinds of integers.
  2926. * Signed and Unsigned Types:: Integers can either hold both negative and
  2927. non-negative values, or only non-negative.
  2928. * Narrow Integers:: When to use smaller integer types.
  2929. * Integer Conversion:: Casting a value from one integer type
  2930. to another.
  2931. * Boolean Type:: An integer type for boolean values.
  2932. * Integer Variations:: Sizes of integer types can vary
  2933. across platforms.
  2934. @end menu
  2935. @node Basic Integers
  2936. @subsection Basic Integers
  2937. @findex char
  2938. @findex int
  2939. @findex short int
  2940. @findex long int
  2941. @findex long long int
  2942. Integer data types in C can be signed or unsigned. An unsigned type
  2943. can represent only positive numbers and zero. A signed type can
  2944. represent both positive and negative numbers, in a range spread almost
  2945. equally on both sides of zero.
  2946. Aside from signedness, the integer data types vary in size: how many
  2947. bytes long they are. The size determines how many different integer
  2948. values the type can hold.
  2949. Here's a list of the signed integer data types, with the sizes they
  2950. have on most computers. Each has a corresponding unsigned type; see
  2951. @ref{Signed and Unsigned Types}.
  2952. @table @code
  2953. @item signed char
  2954. One byte (8 bits). This integer type is used mainly for integers that
  2955. represent characters, as part of arrays or other data structures.
  2956. @item short
  2957. @itemx short int
  2958. Two bytes (16 bits).
  2959. @item int
  2960. Four bytes (32 bits).
  2961. @item long
  2962. @itemx long int
  2963. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2964. platform. Typically it is 32 bits on 32-bit computers
  2965. and 64 bits on 64-bit computers, but there are exceptions.
  2966. @item long long
  2967. @itemx long long int
  2968. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2969. incorporated into standard C as of ISO C99.
  2970. @end table
  2971. You can omit @code{int} when you use @code{long} or @code{short}.
  2972. This is harmless and customary.
  2973. @node Signed and Unsigned Types
  2974. @subsection Signed and Unsigned Types
  2975. @cindex signed types
  2976. @cindex unsigned types
  2977. @cindex types, signed
  2978. @cindex types, unsigned
  2979. @findex signed
  2980. @findex unsigned
  2981. An unsigned integer type can represent only positive numbers and zero.
  2982. A signed type can represent both positive and negative number, in a
  2983. range spread almost equally on both sides of zero. For instance,
  2984. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2985. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2986. these types holds 256 different possible values, since they are both 8
  2987. bits wide.
  2988. Write @code{signed} or @code{unsigned} before the type keyword to
  2989. specify a signed or an unsigned type. However, the integer types
  2990. other than @code{char} are signed by default; with them, @code{signed}
  2991. is a no-op.
  2992. Plain @code{char} may be signed or unsigned; this depends on the
  2993. compiler, the machine in use, and its operating system.
  2994. In many programs, it makes no difference whether @code{char} is
  2995. signed. When it does matter, don't leave it to chance; write
  2996. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2997. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2998. Arctic Char. When my meal arrived, I noted that the chef had not
  2999. signed it. So I complained, ``This char is unsigned---I wanted a
  3000. signed char!'' Or rather, I would have said this if I had thought of
  3001. it fast enough.}
  3002. @node Narrow Integers
  3003. @subsection Narrow Integers
  3004. The types that are narrower than @code{int} are rarely used for
  3005. ordinary variables---we declare them @code{int} instead. This is
  3006. because C converts those narrower types to @code{int} for any
  3007. arithmetic. There is literally no reason to declare a local variable
  3008. @code{char}, for instance.
  3009. In particular, if the value is really a character, you should declare
  3010. the variable @code{int}. Not @code{char}! Using that narrow type can
  3011. force the compiler to truncate values for conversion, which is a
  3012. waste. Furthermore, some functions return either a character value,
  3013. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3014. values distinct.
  3015. The narrow integer types are useful as parts of other objects, such as
  3016. arrays and structures. Compare these array declarations, whose sizes
  3017. on 32-bit processors are shown:
  3018. @example
  3019. signed char ac[1000]; /* @r{1000 bytes} */
  3020. short as[1000]; /* @r{2000 bytes} */
  3021. int ai[1000]; /* @r{4000 bytes} */
  3022. long long all[1000]; /* @r{8000 bytes} */
  3023. @end example
  3024. In addition, character strings must be made up of @code{char}s,
  3025. because that's what all the standard library string functions expect.
  3026. Thus, array @code{ac} could be used as a character string, but the
  3027. others could not be.
  3028. @node Integer Conversion
  3029. @subsection Conversion among Integer Types
  3030. C converts between integer types implicitly in many situations. It
  3031. converts the narrow integer types, @code{char} and @code{short}, to
  3032. @code{int} whenever they are used in arithmetic. Assigning a new
  3033. value to an integer variable (or other lvalue) converts the value to
  3034. the variable's type.
  3035. You can also convert one integer type to another explicitly with a
  3036. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3037. The process of conversion to a wider type is straightforward: the
  3038. value is unchanged. The only exception is when converting a negative
  3039. value (in a signed type, obviously) to a wider unsigned type. In that
  3040. case, the result is a positive value with the same bits
  3041. (@pxref{Integers in Depth}).
  3042. @cindex truncation
  3043. Converting to a narrower type, also called @dfn{truncation}, involves
  3044. discarding some of the value's bits. This is not considered overflow
  3045. (@pxref{Integer Overflow}) because loss of significant bits is a
  3046. normal consequence of truncation. Likewise for conversion between
  3047. signed and unsigned types of the same width.
  3048. More information about conversion for assignment is in
  3049. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3050. see @ref{Argument Promotions}.
  3051. @node Boolean Type
  3052. @subsection Boolean Type
  3053. @cindex boolean type
  3054. @cindex type, boolean
  3055. @findex bool
  3056. The unsigned integer type @code{bool} holds truth values: its possible
  3057. values are 0 and 1. Converting any nonzero value to @code{bool}
  3058. results in 1. For example:
  3059. @example
  3060. bool a = 0;
  3061. bool b = 1;
  3062. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3063. @end example
  3064. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3065. the header file @file{stdbool.h}.
  3066. @node Integer Variations
  3067. @subsection Integer Variations
  3068. The integer types of C have standard @emph{names}, but what they
  3069. @emph{mean} varies depending on the kind of platform in use:
  3070. which kind of computer, which operating system, and which compiler.
  3071. It may even depend on the compiler options used.
  3072. Plain @code{char} may be signed or unsigned; this depends on the
  3073. platform, too. Even for GNU C, there is no general rule.
  3074. In theory, all of the integer types' sizes can vary. @code{char} is
  3075. always considered one ``byte'' for C, but it is not necessarily an
  3076. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3077. specifies only that none of these types is narrower than the ones
  3078. above it in the list in @ref{Basic Integers}, and that @code{short}
  3079. has at least 16 bits.
  3080. It is possible that in the future GNU C will support platforms where
  3081. @code{int} is 64 bits long. In practice, however, on today's real
  3082. computers, there is little variation; you can rely on the table
  3083. given previously (@pxref{Basic Integers}).
  3084. To be completely sure of the size of an integer type,
  3085. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3086. Their corresponding unsigned types add @samp{u} at the front.
  3087. To define these, include the header file @file{stdint.h}.
  3088. The GNU C Compiler compiles for some embedded controllers that use two
  3089. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3090. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3091. 32 bits. These processors can't support an ordinary operating system
  3092. (they may have their own specialized operating systems), and most C
  3093. programs do not try to support them.
  3094. @node Floating-Point Data Types
  3095. @section Floating-Point Data Types
  3096. @cindex floating-point types
  3097. @cindex types, floating-point
  3098. @findex double
  3099. @findex float
  3100. @findex long double
  3101. @dfn{Floating point} is the binary analogue of scientific notation:
  3102. internally it represents a number as a fraction and a binary exponent; the
  3103. value is that fraction multiplied by the specified power of 2.
  3104. For instance, to represent 6, the fraction would be 0.75 and the
  3105. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3106. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3107. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3108. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3109. -1 as the exponent.
  3110. These binary exponents are used by machine instructions. You can
  3111. write a floating-point constant this way if you wish, using
  3112. hexadecimal; but normally we write floating-point numbers in decimal.
  3113. @xref{Floating Constants}.
  3114. C has three floating-point data types:
  3115. @table @code
  3116. @item double
  3117. ``Double-precision'' floating point, which uses 64 bits. This is the
  3118. normal floating-point type, and modern computers normally do
  3119. their floating-point computations in this type, or some wider type.
  3120. Except when there is a special reason to do otherwise, this is the
  3121. type to use for floating-point values.
  3122. @item float
  3123. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3124. for floating-point values stored in structures and arrays, to save
  3125. space when the full precision of @code{double} is not needed. In
  3126. addition, single-precision arithmetic is faster on some computers, and
  3127. occasionally that is useful. But not often---most programs don't use
  3128. the type @code{float}.
  3129. C would be cleaner if @code{float} were the name of the type we
  3130. use for most floating-point values; however, for historical reasons,
  3131. that's not so.
  3132. @item long double
  3133. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3134. precision, depending on the machine in use. On some machines, which
  3135. have no floating-point format wider than @code{double}, this is
  3136. equivalent to @code{double}.
  3137. @end table
  3138. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3139. Point in Depth}, for more information.
  3140. @node Complex Data Types
  3141. @section Complex Data Types
  3142. @cindex complex numbers
  3143. @cindex types, complex
  3144. @cindex @code{_Complex} keyword
  3145. @cindex @code{__complex__} keyword
  3146. @findex _Complex
  3147. @findex __complex__
  3148. Complex numbers can include both a real part and an imaginary part.
  3149. The numeric constants covered above have real-numbered values. An
  3150. imaginary-valued constant is an ordinary real-valued constant followed
  3151. by @samp{i}.
  3152. To declare numeric variables as complex, use the @code{_Complex}
  3153. keyword.@footnote{For compatibility with older versions of GNU C, the
  3154. keyword @code{__complex__} is also allowed. Going forward, however,
  3155. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3156. standard C complex data types are floating point,
  3157. @example
  3158. _Complex float foo;
  3159. _Complex double bar;
  3160. _Complex long double quux;
  3161. @end example
  3162. @noindent
  3163. but GNU C supports integer complex types as well.
  3164. Since @code{_Complex} is a keyword just like @code{float} and
  3165. @code{double} and @code{long}, the keywords can appear in any order,
  3166. but the order shown above seems most logical.
  3167. GNU C supports constants for complex values; for instance, @code{4.0 +
  3168. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3169. @xref{Imaginary Constants}.
  3170. To pull the real and imaginary parts of the number back out, GNU C
  3171. provides the keywords @code{__real__} and @code{__imag__}:
  3172. @example
  3173. _Complex double foo = 4.0 + 3.0i;
  3174. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3175. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3176. @end example
  3177. @noindent
  3178. Standard C does not include these keywords, and instead relies on
  3179. functions defined in @code{complex.h} for accessing the real and
  3180. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3181. @code{creall} extract the real part of a float, double, or long double
  3182. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3183. @code{cimagl} extract the imaginary part.
  3184. @cindex complex conjugation
  3185. GNU C also defines @samp{~} as an operator for complex conjugation,
  3186. which means negating the imaginary part of a complex number:
  3187. @example
  3188. _Complex double foo = 4.0 + 3.0i;
  3189. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3190. @end example
  3191. @noindent
  3192. For standard C compatibility, you can use the appropriate library
  3193. function: @code{conjf}, @code{conj}, or @code{confl}.
  3194. @node The Void Type
  3195. @section The Void Type
  3196. @cindex void type
  3197. @cindex type, void
  3198. @findex void
  3199. The data type @code{void} is a dummy---it allows no operations. It
  3200. really means ``no value at all.'' When a function is meant to return
  3201. no value, we write @code{void} for its return type. Then
  3202. @code{return} statements in that function should not specify a value
  3203. (@pxref{return Statement}). Here's an example:
  3204. @example
  3205. void
  3206. print_if_positive (double x, double y)
  3207. @{
  3208. if (x <= 0)
  3209. return;
  3210. if (y <= 0)
  3211. return;
  3212. printf ("Next point is (%f,%f)\n", x, y);
  3213. @}
  3214. @end example
  3215. A @code{void}-returning function is comparable to what some other languages
  3216. call a ``procedure'' instead of a ``function.''
  3217. @c ??? Already presented
  3218. @c @samp{%f} in an output template specifies to format a @code{double} value
  3219. @c as a decimal number, using a decimal point if needed.
  3220. @node Other Data Types
  3221. @section Other Data Types
  3222. Beyond the primitive types, C provides several ways to construct new
  3223. data types. For instance, you can define @dfn{pointers}, values that
  3224. represent the addresses of other data (@pxref{Pointers}). You can
  3225. define @dfn{structures}, as in many other languages
  3226. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3227. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3228. are collections of named integer codes (@pxref{Enumeration Types}).
  3229. @dfn{Array types} in C are used for allocating space for objects,
  3230. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3231. @node Type Designators
  3232. @section Type Designators
  3233. @cindex type designator
  3234. Some C constructs require a way to designate a specific data type
  3235. independent of any particular variable or expression which has that
  3236. type. The way to do this is with a @dfn{type designator}. The
  3237. constucts that need one include casts (@pxref{Explicit Type
  3238. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3239. We also use type designators to talk about the type of a value in C,
  3240. so you will see many type designators in this manual. When we say,
  3241. ``The value has type @code{int},'' @code{int} is a type designator.
  3242. To make the designator for any type, imagine a variable declaration
  3243. for a variable of that type and delete the variable name and the final
  3244. semicolon.
  3245. For example, to designate the type of full-word integers, we start
  3246. with the declaration for a variable @code{foo} with that type,
  3247. which is this:
  3248. @example
  3249. int foo;
  3250. @end example
  3251. @noindent
  3252. Then we delete the variable name @code{foo} and the semicolon, leaving
  3253. @code{int}---exactly the keyword used in such a declaration.
  3254. Therefore, the type designator for this type is @code{int}.
  3255. What about long unsigned integers? From the declaration
  3256. @example
  3257. unsigned long int foo;
  3258. @end example
  3259. @noindent
  3260. we determine that the designator is @code{unsigned long int}.
  3261. Following this procedure, the designator for any primitive type is
  3262. simply the set of keywords which specifies that type in a declaration.
  3263. The same is true for compound types such as structures, unions, and
  3264. enumerations.
  3265. Designators for pointer types do follow the rule of deleting the
  3266. variable name and semicolon, but the result is not so simple.
  3267. @xref{Pointer Type Designators}, as part of the chapter about
  3268. pointers. @xref{Array Type Designators}), for designators for array
  3269. types.
  3270. To understand what type a designator stands for, imagine a variable
  3271. name inserted into the right place in the designator to make a valid
  3272. declaration. What type would that variable be declared as? That is the
  3273. type the designator designates.
  3274. @node Constants
  3275. @chapter Constants
  3276. @cindex constants
  3277. A @dfn{constant} is an expression that stands for a specific value by
  3278. explicitly representing the desired value. C allows constants for
  3279. numbers, characters, and strings. We have already seen numeric and
  3280. string constants in the examples.
  3281. @menu
  3282. * Integer Constants:: Literal integer values.
  3283. * Integer Const Type:: Types of literal integer values.
  3284. * Floating Constants:: Literal floating-point values.
  3285. * Imaginary Constants:: Literal imaginary number values.
  3286. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3287. * Character Constants:: Literal character values.
  3288. * String Constants:: Literal string values.
  3289. * UTF-8 String Constants:: Literal UTF-8 string values.
  3290. * Unicode Character Codes:: Unicode characters represented
  3291. in either UTF-16 or UTF-32.
  3292. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3293. * Wide String Constants:: Literal string values made up of
  3294. 16- or 32-bit characters.
  3295. @end menu
  3296. @node Integer Constants
  3297. @section Integer Constants
  3298. @cindex integer constants
  3299. @cindex constants, integer
  3300. An integer constant consists of a number to specify the value,
  3301. followed optionally by suffix letters to specify the data type.
  3302. The simplest integer constants are numbers written in base 10
  3303. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3304. constant cannot start with the character @samp{0} (zero) because
  3305. that makes the constant octal.
  3306. You can get the effect of a negative integer constant by putting a
  3307. minus sign at the beginning. Grammatically speaking, that is an
  3308. arithmetic expression rather than a constant, but it behaves just like
  3309. a true constant.
  3310. Integer constants can also be written in octal (base 8), hexadecimal
  3311. (base 16), or binary (base 2). An octal constant starts with the
  3312. character @samp{0} (zero), followed by any number of octal digits
  3313. (@samp{0} to @samp{7}):
  3314. @example
  3315. 0 // @r{zero}
  3316. 077 // @r{63}
  3317. 0403 // @r{259}
  3318. @end example
  3319. @noindent
  3320. Pedantically speaking, the constant @code{0} is an octal constant, but
  3321. we can think of it as decimal; it has the same value either way.
  3322. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3323. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3324. through @samp{f} in upper or lower case):
  3325. @example
  3326. 0xff // @r{255}
  3327. 0XA0 // @r{160}
  3328. 0xffFF // @r{65535}
  3329. @end example
  3330. @cindex binary integer constants
  3331. A binary constant starts with @samp{0b} (upper or lower case) followed
  3332. by bits (each represented by the characters @samp{0} or @samp{1}):
  3333. @example
  3334. 0b101 // @r{5}
  3335. @end example
  3336. Binary constants are a GNU C extension, not part of the C standard.
  3337. Sometimes a space is needed after an integer constant to avoid
  3338. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3339. @node Integer Const Type
  3340. @section Integer Constant Data Types
  3341. @cindex integer constant data types
  3342. @cindex constant data types, integer
  3343. @cindex types of integer constants
  3344. The type of an integer constant is normally @code{int}, if the value
  3345. fits in that type, but here are the complete rules. The type
  3346. of an integer constant is the first one in this sequence that can
  3347. properly represent the value,
  3348. @enumerate
  3349. @item
  3350. @code{int}
  3351. @item
  3352. @code{unsigned int}
  3353. @item
  3354. @code{long int}
  3355. @item
  3356. @code{unsigned long int}
  3357. @item
  3358. @code{long long int}
  3359. @item
  3360. @code{unsigned long long int}
  3361. @end enumerate
  3362. @noindent
  3363. and that isn't excluded by the following rules.
  3364. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3365. first two types (non-@code{long}).
  3366. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3367. first four types (non-@code{long long}).
  3368. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3369. the signed types.
  3370. Otherwise, if the constant is decimal, that excludes the unsigned
  3371. types.
  3372. @c ### This said @code{unsigned int} is excluded.
  3373. @c ### See 17 April 2016
  3374. Here are some examples of the suffixes.
  3375. @example
  3376. 3000000000u // @r{three billion as @code{unsigned int}.}
  3377. 0LL // @r{zero as a @code{long long int}.}
  3378. 0403l // @r{259 as a @code{long int}.}
  3379. @end example
  3380. Suffixes in integer constants are rarely used. When the precise type
  3381. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3382. Type Conversion}).
  3383. @xref{Integer Types}.
  3384. @node Floating Constants
  3385. @section Floating-Point Constants
  3386. @cindex floating-point constants
  3387. @cindex constants, floating-point
  3388. A floating-point constant must have either a decimal point, an
  3389. exponent-of-ten, or both; they distinguish it from an integer
  3390. constant.
  3391. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3392. value follows. It is always written as a decimal number; it can
  3393. optionally start with a sign. The exponent @var{n} means to multiply
  3394. the constant's value by ten to the @var{n}th power.
  3395. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3396. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3397. writing a floating-point number whose value is 1500. They are all
  3398. equivalent.
  3399. Here are more examples with decimal points:
  3400. @example
  3401. 1.0
  3402. 1000.
  3403. 3.14159
  3404. .05
  3405. .0005
  3406. @end example
  3407. For each of them, here are some equivalent constants written with
  3408. exponents:
  3409. @example
  3410. 1e0, 1.0000e0
  3411. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3412. 3.14159e0
  3413. 5e-2, .0005e+2, 5E-2, .0005E2
  3414. .05e-2
  3415. @end example
  3416. A floating-point constant normally has type @code{double}. You can
  3417. force it to type @code{float} by adding @samp{f} or @samp{F}
  3418. at the end. For example,
  3419. @example
  3420. 3.14159f
  3421. 3.14159e0f
  3422. 1000.f
  3423. 100E1F
  3424. .0005f
  3425. .05e-2f
  3426. @end example
  3427. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3428. to type @code{long double}.
  3429. You can use exponents in hexadecimal floating constants, but since
  3430. @samp{e} would be interpreted as a hexadecimal digit, the character
  3431. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3432. The exponent in a hexadecimal floating constant is a possibly-signed
  3433. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3434. multiply into the number.
  3435. Here are some examples:
  3436. @example
  3437. @group
  3438. 0xAp2 // @r{40 in decimal}
  3439. 0xAp-1 // @r{5 in decimal}
  3440. 0x2.0Bp4 // @r{16.75 decimal}
  3441. 0xE.2p3 // @r{121 decimal}
  3442. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3443. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3444. 0x100p-8 // @r{1}
  3445. 0x10p-4 // @r{1}
  3446. 0x1p+4 // @r{16}
  3447. 0x1p+8 // @r{256}
  3448. @end group
  3449. @end example
  3450. @xref{Floating-Point Data Types}.
  3451. @node Imaginary Constants
  3452. @section Imaginary Constants
  3453. @cindex imaginary constants
  3454. @cindex complex constants
  3455. @cindex constants, imaginary
  3456. A complex number consists of a real part plus an imaginary part.
  3457. (Either or both parts may be zero.) This section explains how to
  3458. write numeric constants with imaginary values. By adding these to
  3459. ordinary real-valued numeric constants, we can make constants with
  3460. complex values.
  3461. The simple way to write an imaginary-number constant is to attach the
  3462. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3463. floating-point constant. For example, @code{2.5fi} has type
  3464. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3465. The four alternative suffix letters are all equivalent.
  3466. @cindex _Complex_I
  3467. The other way to write an imaginary constant is to multiply a real
  3468. constant by @code{_Complex_I}, which represents the imaginary number
  3469. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3470. this clunky way is needed.
  3471. To write a complex constant with a nonzero real part and a nonzero
  3472. imaginary part, write the two separately and add them, like this:
  3473. @example
  3474. 4.0 + 3.0i
  3475. @end example
  3476. @noindent
  3477. That gives the value 4 + 3i, with type @code{_Complex double}.
  3478. Such a sum can include multiple real constants, or none. Likewise, it
  3479. can include multiple imaginary constants, or none. For example:
  3480. @example
  3481. _Complex double foo, bar, quux;
  3482. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3483. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3484. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3485. @end example
  3486. @xref{Complex Data Types}.
  3487. @node Invalid Numbers
  3488. @section Invalid Numbers
  3489. Some number-like constructs which are not really valid as numeric
  3490. constants are treated as numbers in preprocessing directives. If
  3491. these constructs appear outside of preprocessing, they are erroneous.
  3492. @xref{Preprocessing Tokens}.
  3493. Sometimes we need to insert spaces to separate tokens so that they
  3494. won't be combined into a single number-like construct. For example,
  3495. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3496. constant, so it is a syntax error. If what we want is the three
  3497. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3498. @node Character Constants
  3499. @section Character Constants
  3500. @cindex character constants
  3501. @cindex constants, character
  3502. @cindex escape sequence
  3503. A @dfn{character constant} is written with single quotes, as in
  3504. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3505. character that the constant should represent. The constant has type
  3506. @code{int}, and its value is the character code of that character.
  3507. For instance, @code{'a'} represents the character code for the letter
  3508. @samp{a}: 97, that is.
  3509. To put the @samp{'} character (single quote) in the character
  3510. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3511. constant looks like @code{'\''}. This sort of sequence, starting with
  3512. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3513. here functions as a kind of @dfn{escape character}.
  3514. To put the @samp{\} character (backslash) in the character constant,
  3515. quote it likewise with @samp{\} (another backslash). This character
  3516. constant looks like @code{'\\'}.
  3517. @cindex bell character
  3518. @cindex @samp{\a}
  3519. @cindex backspace
  3520. @cindex @samp{\b}
  3521. @cindex tab (ASCII character)
  3522. @cindex @samp{\t}
  3523. @cindex vertical tab
  3524. @cindex @samp{\v}
  3525. @cindex formfeed
  3526. @cindex @samp{\f}
  3527. @cindex newline
  3528. @cindex @samp{\n}
  3529. @cindex return (ASCII character)
  3530. @cindex @samp{\r}
  3531. @cindex escape (ASCII character)
  3532. @cindex @samp{\e}
  3533. Here are all the escape sequences that represent specific
  3534. characters in a character constant. The numeric values shown are
  3535. the corresponding ASCII character codes, as decimal numbers.
  3536. @example
  3537. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3538. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3539. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3540. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3541. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3542. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3543. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3544. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3545. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3546. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3547. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3548. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3549. @end example
  3550. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3551. You can also write octal and hex character codes as
  3552. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3553. option here, so octal codes do not need to start with @samp{0}.
  3554. The character constant's value has type @code{int}. However, the
  3555. character code is treated initially as a @code{char} value, which is
  3556. then converted to @code{int}. If the character code is greater than
  3557. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3558. on a platform where the type @code{char} is 8 bits long and signed.
  3559. @node String Constants
  3560. @section String Constants
  3561. @cindex string constants
  3562. @cindex constants, string
  3563. A @dfn{string constant} represents a series of characters. It starts
  3564. with @samp{"} and ends with @samp{"}; in between are the contents of
  3565. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3566. newline in the contents works in string constants as in character
  3567. constants. In a string constant, @samp{'} does not need to be quoted.
  3568. A string constant defines an array of characters which contains the
  3569. specified characters followed by the null character (code 0). Using
  3570. the string constant is equivalent to using the name of an array with
  3571. those contents. In simple cases, the length in bytes of the string
  3572. constant is one greater than the number of characters written in it.
  3573. As with any array in C, using the string constant in an expression
  3574. converts the array to a pointer (@pxref{Pointers}) to the array's
  3575. first element (@pxref{Accessing Array Elements}). This pointer will
  3576. have type @code{char *} because it points to an element of type
  3577. @code{char}. @code{char *} is an example of a type designator for a
  3578. pointer type (@pxref{Pointer Type Designators}). That type is used
  3579. for strings generally, not just the strings expressed as constants
  3580. in a program.
  3581. Thus, the string constant @code{"Foo!"} is almost
  3582. equivalent to declaring an array like this
  3583. @example
  3584. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3585. @end example
  3586. @noindent
  3587. and then using @code{string_array_1} in the program. There
  3588. are two differences, however:
  3589. @itemize @bullet
  3590. @item
  3591. The string constant doesn't define a name for the array.
  3592. @item
  3593. The string constant is probably stored in a read-only area of memory.
  3594. @end itemize
  3595. Newlines are not allowed in the text of a string constant. The motive
  3596. for this prohibition is to catch the error of omitting the closing
  3597. @samp{"}. To put a newline in a constant string, write it as
  3598. @samp{\n} in the string constant.
  3599. A real null character in the source code inside a string constant
  3600. causes a warning. To put a null character in the middle of a string
  3601. constant, write @samp{\0} or @samp{\000}.
  3602. Consecutive string constants are effectively concatenated. Thus,
  3603. @example
  3604. "Fo" "o!" @r{is equivalent to} "Foo!"
  3605. @end example
  3606. This is useful for writing a string containing multiple lines,
  3607. like this:
  3608. @example
  3609. "This message is so long that it needs more than\n"
  3610. "a single line of text. C does not allow a newline\n"
  3611. "to represent itself in a string constant, so we have to\n"
  3612. "write \\n to put it in the string. For readability of\n"
  3613. "the source code, it is advisable to put line breaks in\n"
  3614. "the source where they occur in the contents of the\n"
  3615. "constant.\n"
  3616. @end example
  3617. The sequence of a backslash and a newline is ignored anywhere
  3618. in a C program, and that includes inside a string constant.
  3619. Thus, you can write multi-line string constants this way:
  3620. @example
  3621. "This is another way to put newlines in a string constant\n\
  3622. and break the line after them in the source code."
  3623. @end example
  3624. @noindent
  3625. However, concatenation is the recommended way to do this.
  3626. You can also write perverse string constants like this,
  3627. @example
  3628. "Fo\
  3629. o!"
  3630. @end example
  3631. @noindent
  3632. but don't do that---write it like this instead:
  3633. @example
  3634. "Foo!"
  3635. @end example
  3636. Be careful to avoid passing a string constant to a function that
  3637. modifies the string it receives. The memory where the string constant
  3638. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3639. signal that normally terminates the function (@pxref{Signals}. Even
  3640. worse, the memory may not be read-only. Then the function might
  3641. modify the string constant, thus spoiling the contents of other string
  3642. constants that are supposed to contain the same value and are unified
  3643. by the compiler.
  3644. @node UTF-8 String Constants
  3645. @section UTF-8 String Constants
  3646. @cindex UTF-8 String Constants
  3647. Writing @samp{u8} immediately before a string constant, with no
  3648. intervening space, means to represent that string in UTF-8 encoding as
  3649. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3650. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3651. as multibyte sequences. Here is an example of a UTF-8 constant:
  3652. @example
  3653. u8"A cónstàñt"
  3654. @end example
  3655. This constant occupies 13 bytes plus the terminating null,
  3656. because each of the accented letters is a two-byte sequence.
  3657. Concatenating an ordinary string with a UTF-8 string conceptually
  3658. produces another UTF-8 string. However, if the ordinary string
  3659. contains character codes 128 and up, the results cannot be relied on.
  3660. @node Unicode Character Codes
  3661. @section Unicode Character Codes
  3662. @cindex Unicode character codes
  3663. @cindex universal character names
  3664. You can specify Unicode characters, for individual character constants
  3665. or as part of string constants (@pxref{String Constants}), using
  3666. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3667. hexadecimal Unicode character code. If the code value is too big for
  3668. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3669. Unicode character code. (These codes are called @dfn{universal
  3670. character names}.) For example,
  3671. @example
  3672. \u6C34 /* @r{16-bit code (UTF-16)} */
  3673. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3674. @end example
  3675. @noindent
  3676. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3677. Constants}). For instance,
  3678. @example
  3679. u8"fóó \u6C34 \U0010ABCD"
  3680. @end example
  3681. You can also use them in wide character constants (@pxref{Wide
  3682. Character Constants}), like this:
  3683. @example
  3684. u'\u6C34' /* @r{16-bit code} */
  3685. U'\U0010ABCD' /* @r{32-bit code} */
  3686. @end example
  3687. @noindent
  3688. and in wide string constants (@pxref{Wide String Constants}), like
  3689. this:
  3690. @example
  3691. u"\u6C34\u6C33" /* @r{16-bit code} */
  3692. U"\U0010ABCD" /* @r{32-bit code} */
  3693. @end example
  3694. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3695. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3696. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3697. actually ASCII control characters, and you can specify them with other
  3698. escape sequences (@pxref{Character Constants}).
  3699. @node Wide Character Constants
  3700. @section Wide Character Constants
  3701. @cindex wide character constants
  3702. @cindex constants, wide character
  3703. A @dfn{wide character constant} represents characters with more than 8
  3704. bits of character code. This is an obscure feature that we need to
  3705. document but that you probably won't ever use. If you're just
  3706. learning C, you may as well skip this section.
  3707. The original C wide character constant looks like @samp{L} (upper
  3708. case!) followed immediately by an ordinary character constant (with no
  3709. intervening space). Its data type is @code{wchar_t}, which is an
  3710. alias defined in @file{stddef.h} for one of the standard integer
  3711. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3712. it is 16 bits, these character constants use the UTF-16 form of
  3713. Unicode; if 32 bits, UTF-32.
  3714. There are also Unicode wide character constants which explicitly
  3715. specify the width. These constants start with @samp{u} or @samp{U}
  3716. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3717. character constant, and @samp{U} a 32-bit Unicode wide character
  3718. constant. Their types are, respectively, @code{char16_t} and
  3719. @w{@code{char32_t}}; they are declared in the header file
  3720. @file{uchar.h}. These character constants are valid even if
  3721. @file{uchar.h} is not included, but some uses of them may be
  3722. inconvenient without including it to declare those type names.
  3723. The character represented in a wide character constant can be an
  3724. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3725. are all valid, and they are all equal to @code{'a'}.
  3726. In all three kinds of wide character constants, you can write a
  3727. non-ASCII Unicode character in the constant itself; the constant's
  3728. value is the character's Unicode character code. Or you can specify
  3729. the Unicode character with an escape sequence (@pxref{Unicode
  3730. Character Codes}).
  3731. @node Wide String Constants
  3732. @section Wide String Constants
  3733. @cindex wide string constants
  3734. @cindex constants, wide string
  3735. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3736. characters. They are rarely used; if you're just
  3737. learning C, you may as well skip this section.
  3738. There are three kinds of wide string constants, which differ in the
  3739. data type used for each character in the string. Each wide string
  3740. constant is equivalent to an array of integers, but the data type of
  3741. those integers depends on the kind of wide string. Using the constant
  3742. in an expression will convert the array to a pointer to its first
  3743. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3744. For each kind of wide string constant, we state here what type that
  3745. pointer will be.
  3746. @table @code
  3747. @item char16_t
  3748. This is a 16-bit Unicode wide string constant: each element is a
  3749. 16-bit Unicode character code with type @code{char16_t}, so the string
  3750. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3751. @pxref{Pointer Type Designators}.) The constant is written as
  3752. @samp{u} (which must be lower case) followed (with no intervening
  3753. space) by a string constant with the usual syntax.
  3754. @item char32_t
  3755. This is a 32-bit Unicode wide string constant: each element is a
  3756. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3757. It's written as @samp{U} (which must be upper case) followed (with no
  3758. intervening space) by a string constant with the usual syntax.
  3759. @item wchar_t
  3760. This is the original kind of wide string constant. It's written as
  3761. @samp{L} (which must be upper case) followed (with no intervening
  3762. space) by a string constant with the usual syntax, and the string has
  3763. type @code{wchar_t@ *}.
  3764. The width of the data type @code{wchar_t} depends on the target
  3765. platform, which makes this kind of wide string somewhat less useful
  3766. than the newer kinds.
  3767. @end table
  3768. @code{char16_t} and @code{char32_t} are declared in the header file
  3769. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3770. Consecutive wide string constants of the same kind concatenate, just
  3771. like ordinary string constants. A wide string constant concatenated
  3772. with an ordinary string constant results in a wide string constant.
  3773. You can't concatenate two wide string constants of different kinds.
  3774. You also can't concatenate a wide string constant (of any kind) with a
  3775. UTF-8 string constant.
  3776. @node Type Size
  3777. @chapter Type Size
  3778. @cindex type size
  3779. @cindex size of type
  3780. @findex sizeof
  3781. Each data type has a @dfn{size}, which is the number of bytes
  3782. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3783. a C program, use @code{sizeof}. There are two ways to use it:
  3784. @table @code
  3785. @item sizeof @var{expression}
  3786. This gives the size of @var{expression}, based on its data type. It
  3787. does not calculate the value of @var{expression}, only its size, so if
  3788. @var{expression} includes side effects or function calls, they do not
  3789. happen. Therefore, @code{sizeof} is always a compile-time operation
  3790. that has zero run-time cost.
  3791. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3792. operand of @code{sizeof}.
  3793. For example,
  3794. @example
  3795. double a;
  3796. i = sizeof a + 10;
  3797. @end example
  3798. @noindent
  3799. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3800. Here's how to determine the number of elements in an array
  3801. @code{array}:
  3802. @example
  3803. (sizeof array / sizeof array[0])
  3804. @end example
  3805. @noindent
  3806. The expression @code{sizeof array} gives the size of the array, not
  3807. the size of a pointer to an element. However, if @var{expression} is
  3808. a function parameter that was declared as an array, that
  3809. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3810. the result is the size of that pointer.
  3811. @item sizeof (@var{type})
  3812. This gives the size of @var{type}.
  3813. For example,
  3814. @example
  3815. i = sizeof (double) + 10;
  3816. @end example
  3817. @noindent
  3818. is equivalent to the previous example.
  3819. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3820. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3821. C, which makes adding an integer to a function pointer work as desired
  3822. (@pxref{Pointer Arithmetic}).
  3823. @end table
  3824. @strong{Warning}: When you use @code{sizeof} with a type
  3825. instead of an expression, you must write parentheses around the type.
  3826. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3827. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3828. the cast expression to avoid an ambiguity in the grammar of C@.
  3829. Specifically,
  3830. @example
  3831. sizeof (int) -x
  3832. @end example
  3833. @noindent
  3834. parses as
  3835. @example
  3836. (sizeof (int)) - x
  3837. @end example
  3838. @noindent
  3839. If what you want is
  3840. @example
  3841. sizeof ((int) -x)
  3842. @end example
  3843. @noindent
  3844. you must write it that way, with parentheses.
  3845. The data type of the value of the @code{sizeof} operator is always one
  3846. of the unsigned integer types; which one of those types depends on the
  3847. machine. The header file @code{stddef.h} defines the typedef name
  3848. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3849. Names}.
  3850. @node Pointers
  3851. @chapter Pointers
  3852. @cindex pointers
  3853. Among high-level languages, C is rather low level, close to the
  3854. machine. This is mainly because it has explicit @dfn{pointers}. A
  3855. pointer value is the numeric address of data in memory. The type of
  3856. data to be found at that address is specified by the data type of the
  3857. pointer itself. The unary operator @samp{*} gets the data that a
  3858. pointer points to---this is called @dfn{dereferencing the pointer}.
  3859. C also allows pointers to functions, but since there are some
  3860. differences in how they work, we treat them later. @xref{Function
  3861. Pointers}.
  3862. @menu
  3863. * Address of Data:: Using the ``address-of'' operator.
  3864. * Pointer Types:: For each type, there is a pointer type.
  3865. * Pointer Declarations:: Declaring variables with pointer types.
  3866. * Pointer Type Designators:: Designators for pointer types.
  3867. * Pointer Dereference:: Accessing what a pointer points at.
  3868. * Null Pointers:: Pointers which do not point to any object.
  3869. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3870. * Void Pointers:: Totally generic pointers, can cast to any.
  3871. * Pointer Comparison:: Comparing memory address values.
  3872. * Pointer Arithmetic:: Computing memory address values.
  3873. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3874. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3875. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3876. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3877. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3878. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3879. @end menu
  3880. @node Address of Data
  3881. @section Address of Data
  3882. @cindex address-of operator
  3883. The most basic way to make a pointer is with the ``address-of''
  3884. operator, @samp{&}. Let's suppose we have these variables available:
  3885. @example
  3886. int i;
  3887. double a[5];
  3888. @end example
  3889. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3890. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3891. address of the element 3 of @code{a}. (It is actually the fourth
  3892. element in the array, since the first element has index 0.)
  3893. The address-of operator is unusual because it operates on a place to
  3894. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3895. stored there. (The left argument of a simple assignment is unusual in
  3896. the same way.) You can use it on any lvalue except a bit field
  3897. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3898. Constructors}).
  3899. @node Pointer Types
  3900. @section Pointer Types
  3901. For each data type @var{t}, there is a type for pointers to type
  3902. @var{t}. For these variables,
  3903. @example
  3904. int i;
  3905. double a[5];
  3906. @end example
  3907. @itemize @bullet
  3908. @item
  3909. @code{i} has type @code{int}; we say
  3910. @code{&i} is a ``pointer to @code{int}.''
  3911. @item
  3912. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3913. arrays of five @code{double}s.''
  3914. @item
  3915. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3916. to @code{double}.''
  3917. @end itemize
  3918. @node Pointer Declarations
  3919. @section Pointer-Variable Declarations
  3920. The way to declare that a variable @code{foo} points to type @var{t} is
  3921. @example
  3922. @var{t} *foo;
  3923. @end example
  3924. To remember this syntax, think ``if you dereference @code{foo}, using
  3925. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3926. points to type @var{t}.''
  3927. Thus, we can declare variables that hold pointers to these three
  3928. types, like this:
  3929. @example
  3930. int *ptri; /* @r{Pointer to @code{int}.} */
  3931. double *ptrd; /* @r{Pointer to @code{double}.} */
  3932. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3933. @end example
  3934. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3935. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3936. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3937. @code{double}.'' The parentheses express the point that you would
  3938. dereference it first, then subscript it.
  3939. Contrast the last one with this:
  3940. @example
  3941. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3942. @end example
  3943. @noindent
  3944. Because @samp{*} has higher syntactic precedence than subscripting,
  3945. you would subscript @code{aptrd} then dereference it. Therefore, it
  3946. declares an array of pointers, not a pointer.
  3947. @node Pointer Type Designators
  3948. @section Pointer-Type Designators
  3949. Every type in C has a designator; you make it by deleting the variable
  3950. name and the semicolon from a declaration (@pxref{Type
  3951. Designators}). Here are the designators for the pointer
  3952. types of the example declarations in the previous section:
  3953. @example
  3954. int * /* @r{Pointer to @code{int}.} */
  3955. double * /* @r{Pointer to @code{double}.} */
  3956. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3957. @end example
  3958. Remember, to understand what type a designator stands for, imagine the
  3959. variable name that would be in the declaration, and figure out what
  3960. type it would declare that variable with. @code{double (*)[5]} can
  3961. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3962. which, when dereferenced, gives an array of 5 @code{double}s.
  3963. @node Pointer Dereference
  3964. @section Dereferencing Pointers
  3965. @cindex dereferencing pointers
  3966. @cindex pointer dereferencing
  3967. The main use of a pointer value is to @dfn{dereference it} (access the
  3968. data it points at) with the unary @samp{*} operator. For instance,
  3969. @code{*&i} is the value at @code{i}'s address---which is just
  3970. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3971. valid.
  3972. A pointer-dereference expression whose type is data (not a function)
  3973. is an lvalue.
  3974. Pointers become really useful when we store them somewhere and use
  3975. them later. Here's a simple example to illustrate the practice:
  3976. @example
  3977. @{
  3978. int i;
  3979. int *ptr;
  3980. ptr = &i;
  3981. i = 5;
  3982. @r{@dots{}}
  3983. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3984. @}
  3985. @end example
  3986. This shows how to declare the variable @code{ptr} as type
  3987. @code{int *} (pointer to @code{int}), store a pointer value into it
  3988. (pointing at @code{i}), and use it later to get the value of the
  3989. object it points at (the value in @code{i}).
  3990. If anyone can provide a useful example which is this basic,
  3991. I would be grateful.
  3992. @node Null Pointers
  3993. @section Null Pointers
  3994. @cindex null pointers
  3995. @cindex pointers, null
  3996. @c ???stdio loads sttddef
  3997. A pointer value can be @dfn{null}, which means it does not point to
  3998. any object. The cleanest way to get a null pointer is by writing
  3999. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4000. also do it by casting 0 to the desired pointer type, as in
  4001. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4002. @xref{Explicit Type Conversion}.)
  4003. You can store a null pointer in any lvalue whose data type
  4004. is a pointer type:
  4005. @example
  4006. char *foo;
  4007. foo = NULL;
  4008. @end example
  4009. These two, if consecutive, can be combined into a declaration with
  4010. initializer,
  4011. @example
  4012. char *foo = NULL;
  4013. @end example
  4014. You can also explicitly cast @code{NULL} to the specific pointer type
  4015. you want---it makes no difference.
  4016. @example
  4017. char *foo;
  4018. foo = (char *) NULL;
  4019. @end example
  4020. To test whether a pointer is null, compare it with zero or
  4021. @code{NULL}, as shown here:
  4022. @example
  4023. if (p != NULL)
  4024. /* @r{@code{p} is not null.} */
  4025. operate (p);
  4026. @end example
  4027. Since testing a pointer for not being null is basic and frequent, all
  4028. but beginners in C will understand the conditional without need for
  4029. @code{!= NULL}:
  4030. @example
  4031. if (p)
  4032. /* @r{@code{p} is not null.} */
  4033. operate (p);
  4034. @end example
  4035. @node Invalid Dereference
  4036. @section Dereferencing Null or Invalid Pointers
  4037. Trying to dereference a null pointer is an error. On most platforms,
  4038. it generally causes a signal, usually @code{SIGSEGV}
  4039. (@pxref{Signals}).
  4040. @example
  4041. char *foo = NULL;
  4042. c = *foo; /* @r{This causes a signal and terminates.} */
  4043. @end example
  4044. @noindent
  4045. Likewise a pointer that has the wrong alignment for the target data type
  4046. (on most types of computer), or points to a part of memory that has
  4047. not been allocated in the process's address space.
  4048. The signal terminates the program, unless the program has arranged to
  4049. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4050. The GNU C Library Reference Manual}).
  4051. However, the signal might not happen if the dereference is optimized
  4052. away. In the example above, if you don't subsequently use the value
  4053. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4054. can prevent such optimization using the @code{volatile} qualifier, as
  4055. shown here:
  4056. @example
  4057. volatile char *p;
  4058. volatile char c;
  4059. c = *p;
  4060. @end example
  4061. You can use this to test whether @code{p} points to unallocated
  4062. memory. Set up a signal handler first, so the signal won't terminate
  4063. the program.
  4064. @node Void Pointers
  4065. @section Void Pointers
  4066. @cindex void pointers
  4067. @cindex pointers, void
  4068. The peculiar type @code{void *}, a pointer whose target type is
  4069. @code{void}, is used often in C@. It represents a pointer to
  4070. we-don't-say-what. Thus,
  4071. @example
  4072. void *numbered_slot_pointer (int);
  4073. @end example
  4074. @noindent
  4075. declares a function @code{numbered_slot_pointer} that takes an
  4076. integer parameter and returns a pointer, but we don't say what type of
  4077. data it points to.
  4078. With type @code{void *}, you can pass the pointer around and test
  4079. whether it is null. However, dereferencing it gives a @code{void}
  4080. value that can't be used (@pxref{The Void Type}). To dereference the
  4081. pointer, first convert it to some other pointer type.
  4082. Assignments convert @code{void *} automatically to any other pointer
  4083. type, if the left operand has a pointer type; for instance,
  4084. @example
  4085. @{
  4086. int *p;
  4087. /* @r{Converts return value to @code{int *}.} */
  4088. p = numbered_slot_pointer (5);
  4089. @r{@dots{}}
  4090. @}
  4091. @end example
  4092. Passing an argument of type @code{void *} for a parameter that has a
  4093. pointer type also converts. For example, supposing the function
  4094. @code{hack} is declared to require type @code{float *} for its
  4095. argument, this will convert the null pointer to that type.
  4096. @example
  4097. /* @r{Declare @code{hack} that way.}
  4098. @r{We assume it is defined somewhere else.} */
  4099. void hack (float *);
  4100. @dots{}
  4101. /* @r{Now call @code{hack}.} */
  4102. @{
  4103. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4104. @r{to @code{float *} to pass it to @code{hack}.} */
  4105. hack (numbered_slot_pointer (5));
  4106. @r{@dots{}}
  4107. @}
  4108. @end example
  4109. You can also convert to another pointer type with an explicit cast
  4110. (@pxref{Explicit Type Conversion}), like this:
  4111. @example
  4112. (int *) numbered_slot_pointer (5)
  4113. @end example
  4114. Here is an example which decides at run time which pointer
  4115. type to convert to:
  4116. @example
  4117. void
  4118. extract_int_or_double (void *ptr, bool its_an_int)
  4119. @{
  4120. if (its_an_int)
  4121. handle_an_int (*(int *)ptr);
  4122. else
  4123. handle_a_double (*(double *)ptr);
  4124. @}
  4125. @end example
  4126. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4127. to type @code{int *}, then dereference it.
  4128. @node Pointer Comparison
  4129. @section Pointer Comparison
  4130. @cindex pointer comparison
  4131. @cindex comparison, pointer
  4132. Two pointer values are equal if they point to the same location, or if
  4133. they are both null. You can test for this with @code{==} and
  4134. @code{!=}. Here's a trivial example:
  4135. @example
  4136. @{
  4137. int i;
  4138. int *p, *q;
  4139. p = &i;
  4140. q = &i;
  4141. if (p == q)
  4142. printf ("This will be printed.\n");
  4143. if (p != q)
  4144. printf ("This won't be printed.\n");
  4145. @}
  4146. @end example
  4147. Ordering comparisons such as @code{>} and @code{>=} operate on
  4148. pointers by converting them to unsigned integers. The C standard says
  4149. the two pointers must point within the same object in memory, but on
  4150. GNU/Linux systems these operations simply compare the numeric values
  4151. of the pointers.
  4152. The pointer values to be compared should in principle have the same type, but
  4153. they are allowed to differ in limited cases. First of all, if the two
  4154. pointers' target types are nearly compatible (@pxref{Compatible
  4155. Types}), the comparison is allowed.
  4156. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4157. the other is another pointer type, the comparison operator converts
  4158. the @code{void *} pointer to the other type so as to compare them.
  4159. (In standard C, this is not allowed if the other type is a function
  4160. pointer type, but that works in GNU C@.)
  4161. Comparison operators also allow comparing the integer 0 with a pointer
  4162. value. Thus works by converting 0 to a null pointer of the same type
  4163. as the other operand.
  4164. @node Pointer Arithmetic
  4165. @section Pointer Arithmetic
  4166. @cindex pointer arithmetic
  4167. @cindex arithmetic, pointer
  4168. Adding an integer (positive or negative) to a pointer is valid in C@.
  4169. It assumes that the pointer points to an element in an array, and
  4170. advances or retracts the pointer across as many array elements as the
  4171. integer specifies. Here is an example, in which adding a positive
  4172. integer advances the pointer to a later element in the same array.
  4173. @example
  4174. void
  4175. incrementing_pointers ()
  4176. @{
  4177. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4178. int elt0, elt1, elt4;
  4179. int *p = &array[0];
  4180. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4181. elt0 = *p;
  4182. ++p;
  4183. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4184. elt1 = *p;
  4185. p += 3;
  4186. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4187. elt4 = *p;
  4188. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4189. elt0, elt1, elt4);
  4190. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4191. @}
  4192. @end example
  4193. Here's an example where adding a negative integer retracts the pointer
  4194. to an earlier element in the same array.
  4195. @example
  4196. void
  4197. decrementing_pointers ()
  4198. @{
  4199. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4200. int elt0, elt3, elt4;
  4201. int *p = &array[4];
  4202. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4203. elt4 = *p;
  4204. --p;
  4205. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4206. elt3 = *p;
  4207. p -= 3;
  4208. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4209. elt0 = *p;
  4210. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4211. elt0, elt3, elt4);
  4212. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4213. @}
  4214. @end example
  4215. If one pointer value was made by adding an integer to another
  4216. pointer value, it should be possible to subtract the pointer values
  4217. and recover that integer. That works too in C@.
  4218. @example
  4219. void
  4220. subtract_pointers ()
  4221. @{
  4222. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4223. int *p0, *p3, *p4;
  4224. int *p = &array[4];
  4225. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4226. p4 = p;
  4227. --p;
  4228. /* @r{Now @code{p} points at element 3. Save the value.} */
  4229. p3 = p;
  4230. p -= 3;
  4231. /* @r{Now @code{p} points at element 0. Save the value.} */
  4232. p0 = p;
  4233. printf ("%d, %d, %d, %d\n",
  4234. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4235. /* @r{Prints 4, 0, 3, -3.} */
  4236. @}
  4237. @end example
  4238. The addition operation does not know where arrays are. All it does is
  4239. add the integer (multiplied by object size) to the value of the
  4240. pointer. When the initial pointer and the result point into a single
  4241. array, the result is well-defined.
  4242. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4243. into different memory objects.
  4244. The difference between two pointers has type @code{int}, or
  4245. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4246. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4247. file @file{stddef.h}.
  4248. This definition of pointer subtraction is consistent with
  4249. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4250. @code{p3}, as in ordinary algebra.
  4251. In standard C, addition and subtraction are not allowed on @code{void
  4252. *}, since the target type's size is not defined in that case.
  4253. Likewise, they are not allowed on pointers to function types.
  4254. However, these operations work in GNU C, and the ``size of the target
  4255. type'' is taken as 1.
  4256. @node Pointers and Arrays
  4257. @section Pointers and Arrays
  4258. @cindex pointers and arrays
  4259. @cindex arrays and pointers
  4260. The clean way to refer to an array element is
  4261. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4262. same job is to get the address of that element as a pointer, then
  4263. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4264. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4265. pointer to element zero, then increments it with @code{+} to point to
  4266. the desired element, then gets the value from there.
  4267. That pointer-arithmetic construct is the @emph{definition} of square
  4268. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4269. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4270. symmetrically, so one must be a pointer and the other an integer; it
  4271. does not matter which comes first.
  4272. Since indexing with square brackets is defined in terms of addition
  4273. and dereference, that too is symmetrical. Thus, you can write
  4274. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4275. would be foolish to write @code{3[array]}, since it has no advantage
  4276. and could confuse people who read the code.
  4277. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4278. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4279. instead. Why is this valid? The name of the array, when used by
  4280. itself as an expression (other than in @code{sizeof}), stands for a
  4281. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4282. converts @code{array} implicitly to @code{&array[0]}, and the result
  4283. is a pointer to element 3, equivalent to @code{&array[3]}.
  4284. Since square brackets are defined in terms of such addition,
  4285. @code{array[3]} first converts @code{array} to a pointer. That's why
  4286. it works to use an array directly in that construct.
  4287. @node Pointer Arithmetic Low Level
  4288. @section Pointer Arithmetic at Low Level
  4289. @cindex pointer arithmetic, low level
  4290. @cindex low level pointer arithmetic
  4291. The behavior of pointer arithmetic is theoretically defined only when
  4292. the pointer values all point within one object allocated in memory.
  4293. But the addition and subtraction operators can't tell whether the
  4294. pointer values are all within one object. They don't know where
  4295. objects start and end. So what do they really do?
  4296. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4297. address, which is in fact an integer---call it @var{pint}. It treats
  4298. @var{i} as a number of elements of the type that @var{p} points to.
  4299. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4300. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4301. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4302. If the starting pointer value @var{p} and the result do not point at
  4303. parts of the same object, the operation is not officially legitimate,
  4304. and C code is not ``supposed'' to do it. But you can do it anyway,
  4305. and it gives precisely the results described by the procedure above.
  4306. In some special situations it can do something useful, but non-wizards
  4307. should avoid it.
  4308. Here's a function to offset a pointer value @emph{as if} it pointed to
  4309. an object of any given size, by explicitly performing that calculation:
  4310. @example
  4311. #include <stdint.h>
  4312. void *
  4313. ptr_add (void *p, int i, int objsize)
  4314. @{
  4315. intptr_t p_address = (long) p;
  4316. intptr_t totalsize = i * objsize;
  4317. intptr_t new_address = p_address + totalsize;
  4318. return (void *) new_address;
  4319. @}
  4320. @end example
  4321. @noindent
  4322. @cindex @code{intptr_t}
  4323. This does the same job as @code{@var{p} + @var{i}} with the proper
  4324. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4325. defined in the header file @file{stdint.h}. (In practice, @code{long
  4326. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4327. @node Pointer Increment/Decrement
  4328. @section Pointer Increment and Decrement
  4329. @cindex pointer increment and decrement
  4330. @cindex incrementing pointers
  4331. @cindex decrementing pointers
  4332. The @samp{++} operator adds 1 to a variable. We have seen it for
  4333. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4334. For instance, suppose we have a series of positive integers,
  4335. terminated by a zero, and we want to add them all up.
  4336. @example
  4337. int
  4338. sum_array_till_0 (int *p)
  4339. @{
  4340. int sum = 0;
  4341. for (;;)
  4342. @{
  4343. /* @r{Fetch the next integer.} */
  4344. int next = *p++;
  4345. /* @r{Exit the loop if it's 0.} */
  4346. if (next == 0)
  4347. break;
  4348. /* @r{Add it into running total.} */
  4349. sum += next;
  4350. @}
  4351. return sum;
  4352. @}
  4353. @end example
  4354. @noindent
  4355. The statement @samp{break;} will be explained further on (@pxref{break
  4356. Statement}). Used in this way, it immediately exits the surrounding
  4357. @code{for} statement.
  4358. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4359. takes precedence over a prefix operator. Therefore, it dereferences
  4360. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4361. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4362. pointer, adding 1 to it advances it by the width of the datum it
  4363. points to---in this case, one @code{int}. Therefore, each iteration
  4364. of the loop picks up the next integer from the series and puts it into
  4365. @code{next}.
  4366. This @code{for}-loop has no initialization expression since @code{p}
  4367. and @code{sum} are already initialized, it has no end-test since the
  4368. @samp{break;} statement will exit it, and needs no expression to
  4369. advance it since that's done within the loop by incrementing @code{p}
  4370. and @code{sum}. Thus, those three expressions after @code{for} are
  4371. left empty.
  4372. Another way to write this function is by keeping the parameter value unchanged
  4373. and using indexing to access the integers in the table.
  4374. @example
  4375. int
  4376. sum_array_till_0_indexing (int *p)
  4377. @{
  4378. int i;
  4379. int sum = 0;
  4380. for (i = 0; ; i++)
  4381. @{
  4382. /* @r{Fetch the next integer.} */
  4383. int next = p[i];
  4384. /* @r{Exit the loop if it's 0.} */
  4385. if (next == 0)
  4386. break;
  4387. /* @r{Add it into running total.} */
  4388. sum += next;
  4389. @}
  4390. return sum;
  4391. @}
  4392. @end example
  4393. In this program, instead of advancing @code{p}, we advance @code{i}
  4394. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4395. i)}.) Either way, it uses the same address to get the next integer.
  4396. It makes no difference in this program whether we write @code{i++} or
  4397. @code{++i}, because the value is not used. All that matters is the
  4398. effect, to increment @code{i}.
  4399. The @samp{--} operator also works on pointers; it can be used
  4400. to scan backwards through an array, like this:
  4401. @example
  4402. int
  4403. after_last_nonzero (int *p, int len)
  4404. @{
  4405. /* @r{Set up @code{q} to point just after the last array element.} */
  4406. int *q = p + len;
  4407. while (q != p)
  4408. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4409. if (*--q != 0)
  4410. /* @r{Return the index of the element after that nonzero.} */
  4411. return q - p + 1;
  4412. return 0;
  4413. @}
  4414. @end example
  4415. That function returns the length of the nonzero part of the
  4416. array specified by its arguments; that is, the index of the
  4417. first zero of the run of zeros at the end.
  4418. @node Pointer Arithmetic Drawbacks
  4419. @section Drawbacks of Pointer Arithmetic
  4420. @cindex drawbacks of pointer arithmetic
  4421. @cindex pointer arithmetic, drawbacks
  4422. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4423. major security flaw in the C language. Theoretically, it is only
  4424. valid to adjust a pointer within one object allocated as a unit in
  4425. memory. However, if you unintentionally adjust a pointer across the
  4426. bounds of the object and into some other object, the system has no way
  4427. to detect this error.
  4428. A bug which does that can easily result in clobbering part of another
  4429. object. For example, with @code{array[-1]} you can read or write the
  4430. nonexistent element before the beginning of an array---probably part
  4431. of some other data.
  4432. Combining pointer arithmetic with casts between pointer types, you can
  4433. create a pointer that fails to be properly aligned for its type. For
  4434. example,
  4435. @example
  4436. int a[2];
  4437. char *pa = (char *)a;
  4438. int *p = (int *)(pa + 1);
  4439. @end example
  4440. @noindent
  4441. gives @code{p} a value pointing to an ``integer'' that includes part
  4442. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4443. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4444. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4445. ``works,'' it may be quite slow. It can also cause aliasing
  4446. confusions (@pxref{Aliasing}).
  4447. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4448. unless it is really necessary.
  4449. @node Pointer-Integer Conversion
  4450. @section Pointer-Integer Conversion
  4451. @cindex pointer-integer conversion
  4452. @cindex conversion between pointers and integers
  4453. @cindex @code{uintptr_t}
  4454. On modern computers, an address is simply a number. It occupies the
  4455. same space as some size of integer. In C, you can convert a pointer
  4456. to the appropriate integer types and vice versa, without losing
  4457. information. The appropriate integer types are @code{uintptr_t} (an
  4458. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4459. in @file{stdint.h}.
  4460. For instance,
  4461. @example
  4462. #include <stdint.h>
  4463. #include <stdio.h>
  4464. void
  4465. print_pointer (void *ptr)
  4466. @{
  4467. uintptr_t converted = (uintptr_t) ptr;
  4468. printf ("Pointer value is 0x%x\n",
  4469. (unsigned int) converted);
  4470. @}
  4471. @end example
  4472. @noindent
  4473. The specification @samp{%x} in the template (the first argument) for
  4474. @code{printf} means to represent this argument using hexadecimal
  4475. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4476. printing treats the number as unsigned, but it won't actually matter:
  4477. all @code{printf} gets to see is the series of bits in the number.
  4478. @strong{Warning:} Converting pointers to integers is risky---don't do
  4479. it unless it is really necessary.
  4480. @node Printing Pointers
  4481. @section Printing Pointers
  4482. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4483. For example:
  4484. @example
  4485. void
  4486. print_pointer (void *ptr)
  4487. @{
  4488. printf ("Pointer value is %p\n", ptr);
  4489. @}
  4490. @end example
  4491. The specification @samp{%p} works with any pointer type. It prints
  4492. @samp{0x} followed by the address in hexadecimal, printed as the
  4493. appropriate unsigned integer type.
  4494. @node Structures
  4495. @chapter Structures
  4496. @cindex structures
  4497. @findex struct
  4498. @cindex fields in structures
  4499. A @dfn{structure} is a user-defined data type that holds various
  4500. @dfn{fields} of data. Each field has a name and a data type specified
  4501. in the structure's definition.
  4502. Here we define a structure suitable for storing a linked list of
  4503. integers. Each list item will hold one integer, plus a pointer
  4504. to the next item.
  4505. @example
  4506. struct intlistlink
  4507. @{
  4508. int datum;
  4509. struct intlistlink *next;
  4510. @};
  4511. @end example
  4512. The structure definition has a @dfn{type tag} so that the code can
  4513. refer to this structure. The type tag here is @code{intlistlink}.
  4514. The definition refers recursively to the same structure through that
  4515. tag.
  4516. You can define a structure without a type tag, but then you can't
  4517. refer to it again. That is useful only in some special contexts, such
  4518. as inside a @code{typedef} or a @code{union}.
  4519. The contents of the structure are specified by the @dfn{field
  4520. declarations} inside the braces. Each field in the structure needs a
  4521. declaration there. The fields in one structure definition must have
  4522. distinct names, but these names do not conflict with any other names
  4523. in the program.
  4524. A field declaration looks just like a variable declaration. You can
  4525. combine field declarations with the same beginning, just as you can
  4526. combine variable declarations.
  4527. This structure has two fields. One, named @code{datum}, has type
  4528. @code{int} and will hold one integer in the list. The other, named
  4529. @code{next}, is a pointer to another @code{struct intlistlink}
  4530. which would be the rest of the list. In the last list item, it would
  4531. be @code{NULL}.
  4532. This structure definition is recursive, since the type of the
  4533. @code{next} field refers to the structure type. Such recursion is not
  4534. a problem; in fact, you can use the type @code{struct intlistlink *}
  4535. before the definition of the type @code{struct intlistlink} itself.
  4536. That works because pointers to all kinds of structures really look the
  4537. same at the machine level.
  4538. After defining the structure, you can declare a variable of type
  4539. @code{struct intlistlink} like this:
  4540. @example
  4541. struct intlistlink foo;
  4542. @end example
  4543. The structure definition itself can serve as the beginning of a
  4544. variable declaration, so you can declare variables immediately after,
  4545. like this:
  4546. @example
  4547. struct intlistlink
  4548. @{
  4549. int datum;
  4550. struct intlistlink *next;
  4551. @} foo;
  4552. @end example
  4553. @noindent
  4554. But that is ugly. It is almost always clearer to separate the
  4555. definition of the structure from its uses.
  4556. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4557. the scope of the structure type name to that block. That means the
  4558. structure type is recognized only within that block. Declaring it in
  4559. a function parameter list, as here,
  4560. @example
  4561. int f (struct foo @{int a, b@} parm);
  4562. @end example
  4563. @noindent
  4564. (assuming that @code{struct foo} is not already defined) limits the
  4565. scope of the structure type @code{struct foo} to that parameter list;
  4566. that is basically useless, so it triggers a warning.
  4567. Standard C requires at least one field in a structure.
  4568. GNU C does not require this.
  4569. @menu
  4570. * Referencing Fields:: Accessing field values in a structure object.
  4571. * Dynamic Memory Allocation:: Allocating space for objects
  4572. while the program is running.
  4573. * Field Offset:: Memory layout of fields within a structure.
  4574. * Structure Layout:: Planning the memory layout of fields.
  4575. * Packed Structures:: Packing structure fields as close as possible.
  4576. * Bit Fields:: Dividing integer fields
  4577. into fields with fewer bits.
  4578. * Bit Field Packing:: How bit fields pack together in integers.
  4579. * const Fields:: Making structure fields immutable.
  4580. * Zero Length:: Zero-length array as a variable-length object.
  4581. * Flexible Array Fields:: Another approach to variable-length objects.
  4582. * Overlaying Structures:: Casting one structure type
  4583. over an object of another structure type.
  4584. * Structure Assignment:: Assigning values to structure objects.
  4585. * Unions:: Viewing the same object in different types.
  4586. * Packing With Unions:: Using a union type to pack various types into
  4587. the same memory space.
  4588. * Cast to Union:: Casting a value one of the union's alternative
  4589. types to the type of the union itself.
  4590. * Structure Constructors:: Building new structure objects.
  4591. * Unnamed Types as Fields:: Fields' types do not always need names.
  4592. * Incomplete Types:: Types which have not been fully defined.
  4593. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4594. * Type Tags:: Scope of structure and union type tags.
  4595. @end menu
  4596. @node Referencing Fields
  4597. @section Referencing Structure Fields
  4598. @cindex referencing structure fields
  4599. @cindex structure fields, referencing
  4600. To make a structure useful, there has to be a way to examine and store
  4601. its fields. The @samp{.} (period) operator does that; its use looks
  4602. like @code{@var{object}.@var{field}}.
  4603. Given this structure and variable,
  4604. @example
  4605. struct intlistlink
  4606. @{
  4607. int datum;
  4608. struct intlistlink *next;
  4609. @};
  4610. struct intlistlink foo;
  4611. @end example
  4612. @noindent
  4613. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4614. fields in the value of @code{foo}. These fields are lvalues, so you
  4615. can store values into them, and read the values out again.
  4616. Most often, structures are dynamically allocated (see the next
  4617. section), and we refer to the objects via pointers.
  4618. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4619. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4620. contains this declaration:
  4621. @example
  4622. struct intlistlink *ptr;
  4623. @end example
  4624. @noindent
  4625. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4626. to the two fields in the object that @code{ptr} points to.
  4627. If a unary operator precedes an expression using @samp{->},
  4628. the @samp{->} nests inside:
  4629. @example
  4630. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4631. @end example
  4632. You can intermix @samp{->} and @samp{.} without parentheses,
  4633. as shown here:
  4634. @example
  4635. struct @{ double d; struct intlistlink l; @} foo;
  4636. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4637. @end example
  4638. @node Dynamic Memory Allocation
  4639. @section Dynamic Memory Allocation
  4640. @cindex dynamic memory allocation
  4641. @cindex memory allocation, dynamic
  4642. @cindex allocating memory dynamically
  4643. To allocate an object dynamically, call the library function
  4644. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4645. Reference Manual}). Here is how to allocate an object of type
  4646. @code{struct intlistlink}. To make this code work, include the file
  4647. @file{stdlib.h}, like this:
  4648. @example
  4649. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4650. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4651. @dots{}
  4652. struct intlistlink *
  4653. alloc_intlistlink ()
  4654. @{
  4655. struct intlistlink *p;
  4656. p = malloc (sizeof (struct intlistlink));
  4657. if (p == NULL)
  4658. fatal ("Ran out of storage");
  4659. /* @r{Initialize the contents.} */
  4660. p->datum = 0;
  4661. p->next = NULL;
  4662. return p;
  4663. @}
  4664. @end example
  4665. @noindent
  4666. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4667. will automatically convert it to type @code{struct intlistlink *}.
  4668. The return value of @code{malloc} is always sufficiently aligned
  4669. (@pxref{Type Alignment}) that it is valid for any data type.
  4670. The test for @code{p == NULL} is necessary because @code{malloc}
  4671. returns a null pointer if it cannot get any storage. We assume that
  4672. the program defines the function @code{fatal} to report a fatal error
  4673. to the user.
  4674. Here's how to add one more integer to the front of such a list:
  4675. @example
  4676. struct intlistlink *my_list = NULL;
  4677. void
  4678. add_to_mylist (int my_int)
  4679. @{
  4680. struct intlistlink *p = alloc_intlistlink ();
  4681. p->datum = my_int;
  4682. p->next = mylist;
  4683. mylist = p;
  4684. @}
  4685. @end example
  4686. The way to free the objects is by calling @code{free}. Here's
  4687. a function to free all the links in one of these lists:
  4688. @example
  4689. void
  4690. free_intlist (struct intlistlink *p)
  4691. @{
  4692. while (p)
  4693. @{
  4694. struct intlistlink *q = p;
  4695. p = p->next;
  4696. free (q);
  4697. @}
  4698. @}
  4699. @end example
  4700. We must extract the @code{next} pointer from the object before freeing
  4701. it, because @code{free} can clobber the data that was in the object.
  4702. For the same reason, the program must not use the list any more after
  4703. freeing its elements. To make sure it won't, it is best to clear out
  4704. the variable where the list was stored, like this:
  4705. @example
  4706. free_intlist (mylist);
  4707. mylist = NULL;
  4708. @end example
  4709. @node Field Offset
  4710. @section Field Offset
  4711. @cindex field offset
  4712. @cindex structure field offset
  4713. @cindex offset of structure fields
  4714. To determine the offset of a given field @var{field} in a structure
  4715. type @var{type}, use the macro @code{offsetof}, which is defined in
  4716. the file @file{stddef.h}. It is used like this:
  4717. @example
  4718. offsetof (@var{type}, @var{field})
  4719. @end example
  4720. Here is an example:
  4721. @example
  4722. struct foo
  4723. @{
  4724. int element;
  4725. struct foo *next;
  4726. @};
  4727. offsetof (struct foo, next)
  4728. /* @r{On most machines that is 4. It may be 8.} */
  4729. @end example
  4730. @node Structure Layout
  4731. @section Structure Layout
  4732. @cindex structure layout
  4733. @cindex layout of structures
  4734. The rest of this chapter covers advanced topics about structures. If
  4735. you are just learning C, you can skip it.
  4736. The precise layout of a @code{struct} type is crucial when using it to
  4737. overlay hardware registers, to access data structures in shared
  4738. memory, or to assemble and disassemble packets for network
  4739. communication. It is also important for avoiding memory waste when
  4740. the program makes many objects of that type. However, the layout
  4741. depends on the target platform. Each platform has conventions for
  4742. structure layout, which compilers need to follow.
  4743. Here are the conventions used on most platforms.
  4744. The structure's fields appear in the structure layout in the order
  4745. they are declared. When possible, consecutive fields occupy
  4746. consecutive bytes within the structure. However, if a field's type
  4747. demands more alignment than it would get that way, C gives it the
  4748. alignment it requires by leaving a gap after the previous field.
  4749. Once all the fields have been laid out, it is possible to determine
  4750. the structure's alignment and size. The structure's alignment is the
  4751. maximum alignment of any of the fields in it. Then the structure's
  4752. size is rounded up to a multiple of its alignment. That may require
  4753. leaving a gap at the end of the structure.
  4754. Here are some examples, where we assume that @code{char} has size and
  4755. alignment 1 (always true), and @code{int} has size and alignment 4
  4756. (true on most kinds of computers):
  4757. @example
  4758. struct foo
  4759. @{
  4760. char a, b;
  4761. int c;
  4762. @};
  4763. @end example
  4764. @noindent
  4765. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4766. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4767. There is a gap of 2 bytes before @code{c}.
  4768. Contrast that with this structure:
  4769. @example
  4770. struct foo
  4771. @{
  4772. char a;
  4773. int c;
  4774. char b;
  4775. @};
  4776. @end example
  4777. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4778. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4779. gaps: three bytes before @code{c}, and three bytes at the end.
  4780. These two structures have the same contents at the C level, but one
  4781. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4782. fields. A reliable way to avoid this sort of wastage is to order the
  4783. fields by size, biggest fields first.
  4784. @node Packed Structures
  4785. @section Packed Structures
  4786. @cindex packed structures
  4787. @cindex @code{__attribute__((packed))}
  4788. In GNU C you can force a structure to be laid out with no gaps by
  4789. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4790. end of the structure type declaration). Here's an example:
  4791. @example
  4792. struct __attribute__((packed)) foo
  4793. @{
  4794. char a;
  4795. int c;
  4796. char b;
  4797. @};
  4798. @end example
  4799. Without @code{__attribute__((packed))}, this structure occupies 12
  4800. bytes (as described in the previous section), assuming 4-byte
  4801. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4802. only 6 bytes long---the sum of the lengths of its fields.
  4803. Use of @code{__attribute__((packed))} often results in fields that
  4804. don't have the normal alignment for their types. Taking the address
  4805. of such a field can result in an invalid pointer because of its
  4806. improper alignment. Dereferencing such a pointer can cause a
  4807. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4808. unaligned pointers.
  4809. @xref{Attributes}.
  4810. @node Bit Fields
  4811. @section Bit Fields
  4812. @cindex bit fields
  4813. A structure field declaration with an integer type can specify the
  4814. number of bits the field should occupy. We call that a @dfn{bit
  4815. field}. These are useful because consecutive bit fields are packed
  4816. into a larger storage unit. For instance,
  4817. @example
  4818. unsigned char opcode: 4;
  4819. @end example
  4820. @noindent
  4821. specifies that this field takes just 4 bits.
  4822. Since it is unsigned, its possible values range
  4823. from 0 to 15. A signed field with 4 bits, such as this,
  4824. @example
  4825. signed char small: 4;
  4826. @end example
  4827. @noindent
  4828. can hold values from -8 to 7.
  4829. You can subdivide a single byte into those two parts by writing
  4830. @example
  4831. unsigned char opcode: 4;
  4832. signed char small: 4;
  4833. @end example
  4834. @noindent
  4835. in the structure. With bit fields, these two numbers fit into
  4836. a single @code{char}.
  4837. Here's how to declare a one-bit field that can hold either 0 or 1:
  4838. @example
  4839. unsigned char special_flag: 1;
  4840. @end example
  4841. You can also use the @code{bool} type for bit fields:
  4842. @example
  4843. bool special_flag: 1;
  4844. @end example
  4845. Except when using @code{bool} (which is always unsigned,
  4846. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4847. for a bit field. There is a default, if that's not specified: the bit
  4848. field is signed if plain @code{char} is signed, except that the option
  4849. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4850. is cleaner not to depend on this default.
  4851. Bit fields are special in that you cannot take their address with
  4852. @samp{&}. They are not stored with the size and alignment appropriate
  4853. for the specified type, so they cannot be addressed through pointers
  4854. to that type.
  4855. @node Bit Field Packing
  4856. @section Bit Field Packing
  4857. Programs to communicate with low-level hardware interfaces need to
  4858. define bit fields laid out to match the hardware data. This section
  4859. explains how to do that.
  4860. Consecutive bit fields are packed together, but each bit field must
  4861. fit within a single object of its specified type. In this example,
  4862. @example
  4863. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4864. @end example
  4865. @noindent
  4866. all five fields fit consecutively into one two-byte @code{short}.
  4867. They need 15 bits, and one @code{short} provides 16. By contrast,
  4868. @example
  4869. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4870. @end example
  4871. @noindent
  4872. needs three bytes. It fits @code{a} and @code{b} into one
  4873. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4874. add up to 9 bits). So @code{c} and @code{d} go into a second
  4875. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4876. Then @code{e} needs a third @code{char}. By contrast,
  4877. @example
  4878. unsigned char a : 3, b : 3;
  4879. unsigned int c : 3;
  4880. unsigned char d : 3, e : 3;
  4881. @end example
  4882. @noindent
  4883. needs only two bytes: the type @code{unsigned int}
  4884. allows @code{c} to straddle bytes that are in the same word.
  4885. You can leave a gap of a specified number of bits by defining a
  4886. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4887. It is allocated space in the structure just as a named bit field would
  4888. be allocated.
  4889. You can force the following bit field to advance to the following
  4890. aligned memory object with @code{@var{type} : 0;}.
  4891. Both of these constructs can syntactically share @var{type} with
  4892. ordinary bit fields. This example illustrates both:
  4893. @example
  4894. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4895. @end example
  4896. @noindent
  4897. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4898. between them. Then @code{: 0} advances to the next @code{int},
  4899. so @code{c} and @code{d} fit into that one.
  4900. These rules for packing bit fields apply to most target platforms,
  4901. including all the usual real computers. A few embedded controllers
  4902. have special layout rules.
  4903. @node const Fields
  4904. @section @code{const} Fields
  4905. @cindex const fields
  4906. @cindex structure fields, constant
  4907. @c ??? Is this a C standard feature?
  4908. A structure field declared @code{const} cannot be assigned to
  4909. (@pxref{const}). For instance, let's define this modified version of
  4910. @code{struct intlistlink}:
  4911. @example
  4912. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4913. @{
  4914. const int datum;
  4915. struct intlistlink *next;
  4916. @};
  4917. @end example
  4918. This structure can be used to prevent part of the code from modifying
  4919. the @code{datum} field:
  4920. @example
  4921. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4922. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4923. struct intlistlink_ro *q
  4924. = (struct intlistlink_ro *) p;
  4925. q->datum = 5; /* @r{Error!} */
  4926. p->datum = 5; /* @r{Valid since @code{*p} is}
  4927. @r{not a @code{struct intlistlink_ro}.} */
  4928. @end example
  4929. A @code{const} field can get a value in two ways: by initialization of
  4930. the whole structure, and by making a pointer-to-structure point to an object
  4931. in which that field already has a value.
  4932. Any @code{const} field in a structure type makes assignment impossible
  4933. for structures of that type (@pxref{Structure Assignment}). That is
  4934. because structure assignment works by assigning the structure's
  4935. fields, one by one.
  4936. @node Zero Length
  4937. @section Arrays of Length Zero
  4938. @cindex array of length zero
  4939. @cindex zero-length arrays
  4940. @cindex length-zero arrays
  4941. GNU C allows zero-length arrays. They are useful as the last element
  4942. of a structure that is really a header for a variable-length object.
  4943. Here's an example, where we construct a variable-size structure
  4944. to hold a line which is @code{this_length} characters long:
  4945. @example
  4946. struct line @{
  4947. int length;
  4948. char contents[0];
  4949. @};
  4950. struct line *thisline
  4951. = ((struct line *)
  4952. malloc (sizeof (struct line)
  4953. + this_length));
  4954. thisline->length = this_length;
  4955. @end example
  4956. In ISO C90, we would have to give @code{contents} a length of 1, which
  4957. means either wasting space or complicating the argument to @code{malloc}.
  4958. @node Flexible Array Fields
  4959. @section Flexible Array Fields
  4960. @cindex flexible array fields
  4961. @cindex array fields, flexible
  4962. The C99 standard adopted a more complex equivalent of zero-length
  4963. array fields. It's called a @dfn{flexible array}, and it's indicated
  4964. by omitting the length, like this:
  4965. @example
  4966. struct line
  4967. @{
  4968. int length;
  4969. char contents[];
  4970. @};
  4971. @end example
  4972. The flexible array has to be the last field in the structure, and there
  4973. must be other fields before it.
  4974. Under the C standard, a structure with a flexible array can't be part
  4975. of another structure, and can't be an element of an array.
  4976. GNU C allows static initialization of flexible array fields. The effect
  4977. is to ``make the array long enough'' for the initializer.
  4978. @example
  4979. struct f1 @{ int x; int y[]; @} f1
  4980. = @{ 1, @{ 2, 3, 4 @} @};
  4981. @end example
  4982. @noindent
  4983. This defines a structure variable named @code{f1}
  4984. whose type is @code{struct f1}. In C, a variable name or function name
  4985. never conflicts with a structure type tag.
  4986. Omitting the flexible array field's size lets the initializer
  4987. determine it. This is allowed only when the flexible array is defined
  4988. in the outermost structure and you declare a variable of that
  4989. structure type. For example:
  4990. @example
  4991. struct foo @{ int x; int y[]; @};
  4992. struct bar @{ struct foo z; @};
  4993. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4994. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4995. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4996. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4997. @end example
  4998. @node Overlaying Structures
  4999. @section Overlaying Different Structures
  5000. @cindex overlaying structures
  5001. @cindex structures, overlaying
  5002. Be careful about using different structure types to refer to the same
  5003. memory within one function, because GNU C can optimize code assuming
  5004. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5005. aliasing that can cause the problem:
  5006. @example
  5007. struct a @{ int size; char *data; @};
  5008. struct b @{ int size; char *data; @};
  5009. struct a foo;
  5010. struct b *q = (struct b *) &foo;
  5011. @end example
  5012. Here @code{q} points to the same memory that the variable @code{foo}
  5013. occupies, but they have two different types. The two types
  5014. @code{struct a} and @code{struct b} are defined alike, but they are
  5015. not the same type. Interspersing references using the two types,
  5016. like this,
  5017. @example
  5018. p->size = 0;
  5019. q->size = 1;
  5020. x = p->size;
  5021. @end example
  5022. @noindent
  5023. allows GNU C to assume that @code{p->size} is still zero when it is
  5024. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5025. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5026. Other compilers might also do this optimization. The ISO C standard
  5027. considers such code erroneous, precisely so that this optimization
  5028. will be valid.
  5029. @node Structure Assignment
  5030. @section Structure Assignment
  5031. @cindex structure assignment
  5032. @cindex assigning structures
  5033. Assignment operating on a structure type copies the structure. The
  5034. left and right operands must have the same type. Here is an example:
  5035. @example
  5036. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5037. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5038. @r{@dots{}}
  5039. struct point @{ double x, y; @};
  5040. struct point *
  5041. copy_point (struct point point)
  5042. @{
  5043. struct point *p
  5044. = (struct point *) malloc (sizeof (struct point));
  5045. if (p == NULL)
  5046. fatal ("Out of memory");
  5047. *p = point;
  5048. return p;
  5049. @}
  5050. @end example
  5051. Notionally, assignment on a structure type works by copying each of
  5052. the fields. Thus, if any of the fields has the @code{const}
  5053. qualifier, that structure type does not allow assignment:
  5054. @example
  5055. struct point @{ const double x, y; @};
  5056. struct point a, b;
  5057. a = b; /* @r{Error!} */
  5058. @end example
  5059. @xref{Assignment Expressions}.
  5060. @node Unions
  5061. @section Unions
  5062. @cindex unions
  5063. @findex union
  5064. A @dfn{union type} defines alternative ways of looking at the same
  5065. piece of memory. Each alternative view is defined with a data type,
  5066. and identified by a name. A union definition looks like this:
  5067. @example
  5068. union @var{name}
  5069. @{
  5070. @var{alternative declarations}@r{@dots{}}
  5071. @};
  5072. @end example
  5073. Each alternative declaration looks like a structure field declaration,
  5074. except that it can't be a bit field. For instance,
  5075. @example
  5076. union number
  5077. @{
  5078. long int integer;
  5079. double float;
  5080. @}
  5081. @end example
  5082. @noindent
  5083. lets you store either an integer (type @code{long int}) or a floating
  5084. point number (type @code{double}) in the same place in memory. The
  5085. length and alignment of the union type are the maximum of all the
  5086. alternatives---they do not have to be the same. In this union
  5087. example, @code{double} probably takes more space than @code{long int},
  5088. but that doesn't cause a problem in programs that use the union in the
  5089. normal way.
  5090. The members don't have to be different in data type. Sometimes
  5091. each member pertains to a way the data will be used. For instance,
  5092. @example
  5093. union datum
  5094. @{
  5095. double latitude;
  5096. double longitude;
  5097. double height;
  5098. double weight;
  5099. int continent;
  5100. @}
  5101. @end example
  5102. This union holds one of several kinds of data; most kinds are floating
  5103. points, but the value can also be a code for a continent which is an
  5104. integer. You @emph{could} use one member of type @code{double} to
  5105. access all the values which have that type, but the different member
  5106. names will make the program clearer.
  5107. The alignment of a union type is the maximum of the alignments of the
  5108. alternatives. The size of the union type is the maximum of the sizes
  5109. of the alternatives, rounded up to a multiple of the alignment
  5110. (because every type's size must be a multiple of its alignment).
  5111. All the union alternatives start at the address of the union itself.
  5112. If an alternative is shorter than the union as a whole, it occupies
  5113. the first part of the union's storage, leaving the last part unused
  5114. @emph{for that alternative}.
  5115. @strong{Warning:} if the code stores data using one union alternative
  5116. and accesses it with another, the results depend on the kind of
  5117. computer in use. Only wizards should try to do this. However, when
  5118. you need to do this, a union is a clean way to do it.
  5119. Assignment works on any union type by copying the entire value.
  5120. @node Packing With Unions
  5121. @section Packing With Unions
  5122. Sometimes we design a union with the intention of packing various
  5123. kinds of objects into a certain amount of memory space. For example.
  5124. @example
  5125. union bytes8
  5126. @{
  5127. long long big_int_elt;
  5128. double double_elt;
  5129. struct @{ int first, second; @} two_ints;
  5130. struct @{ void *first, *second; @} two_ptrs;
  5131. @};
  5132. union bytes8 *p;
  5133. @end example
  5134. This union makes it possible to look at 8 bytes of data that @code{p}
  5135. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5136. single floating-point number (@code{p->double_elt}), as a pair of
  5137. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5138. as a pair of pointers (@code{p->two_ptrs.first} and
  5139. @code{p->two_ptrs.second}).
  5140. To pack storage with such a union makes assumptions about the sizes of
  5141. all the types involved. This particular union was written expecting a
  5142. pointer to have the same size as @code{int}. On a machine where one
  5143. pointer takes 8 bytes, the code using this union probably won't work
  5144. as expected. The union, as such, will function correctly---if you
  5145. store two values through @code{two_ints} and extract them through
  5146. @code{two_ints}, you will get the same integers back---but the part of
  5147. the program that expects the union to be 8 bytes long could
  5148. malfunction, or at least use too much space.
  5149. The above example shows one case where a @code{struct} type with no
  5150. tag can be useful. Another way to get effectively the same result
  5151. is with arrays as members of the union:
  5152. @example
  5153. union eight_bytes
  5154. @{
  5155. long long big_int_elt;
  5156. double double_elt;
  5157. int two_ints[2];
  5158. void *two_ptrs[2];
  5159. @};
  5160. @end example
  5161. @node Cast to Union
  5162. @section Cast to a Union Type
  5163. @cindex cast to a union
  5164. @cindex union, casting to a
  5165. In GNU C, you can explicitly cast any of the alternative types to the
  5166. union type; for instance,
  5167. @example
  5168. (union eight_bytes) (long long) 5
  5169. @end example
  5170. @noindent
  5171. makes a value of type @code{union eight_bytes} which gets its contents
  5172. through the alternative named @code{big_int_elt}.
  5173. The value being cast must exactly match the type of the alternative,
  5174. so this is not valid:
  5175. @example
  5176. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5177. @end example
  5178. A cast to union type looks like any other cast, except that the type
  5179. specified is a union type. You can specify the type either with
  5180. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5181. Typedef Names}).
  5182. Using the cast as the right-hand side of an assignment to a variable of
  5183. union type is equivalent to storing in an alternative of the union:
  5184. @example
  5185. union foo u;
  5186. u = (union foo) x @r{means} u.i = x
  5187. u = (union foo) y @r{means} u.d = y
  5188. @end example
  5189. You can also use the union cast as a function argument:
  5190. @example
  5191. void hack (union foo);
  5192. @r{@dots{}}
  5193. hack ((union foo) x);
  5194. @end example
  5195. @node Structure Constructors
  5196. @section Structure Constructors
  5197. @cindex structure constructors
  5198. @cindex constructors, structure
  5199. You can construct a structure value by writing its type in
  5200. parentheses, followed by an initializer that would be valid in a
  5201. declaration for that type. For instance, given this declaration,
  5202. @example
  5203. struct foo @{int a; char b[2];@} structure;
  5204. @end example
  5205. @noindent
  5206. you can create a @code{struct foo} value as follows:
  5207. @example
  5208. ((struct foo) @{x + y, 'a', 0@})
  5209. @end example
  5210. @noindent
  5211. This specifies @code{x + y} for field @code{a},
  5212. the character @samp{a} for field @code{b}'s element 0,
  5213. and the null character for field @code{b}'s element 1.
  5214. The parentheses around that constructor are to necessary, but we
  5215. recommend writing them to make the nesting of the containing
  5216. expression clearer.
  5217. You can also show the nesting of the two by writing it like
  5218. this:
  5219. @example
  5220. ((struct foo) @{x + y, @{'a', 0@} @})
  5221. @end example
  5222. Each of those is equivalent to writing the following statement
  5223. expression (@pxref{Statement Exprs}):
  5224. @example
  5225. (@{
  5226. struct foo temp = @{x + y, 'a', 0@};
  5227. temp;
  5228. @})
  5229. @end example
  5230. You can also create a union value this way, but it is not especially
  5231. useful since that is equivalent to doing a cast:
  5232. @example
  5233. ((union whosis) @{@var{value}@})
  5234. @r{is equivalent to}
  5235. ((union whosis) (@var{value}))
  5236. @end example
  5237. @node Unnamed Types as Fields
  5238. @section Unnamed Types as Fields
  5239. @cindex unnamed structures
  5240. @cindex unnamed unions
  5241. @cindex structures, unnamed
  5242. @cindex unions, unnamed
  5243. A structure or a union can contain, as fields,
  5244. unnamed structures and unions. Here's an example:
  5245. @example
  5246. struct
  5247. @{
  5248. int a;
  5249. union
  5250. @{
  5251. int b;
  5252. float c;
  5253. @};
  5254. int d;
  5255. @} foo;
  5256. @end example
  5257. @noindent
  5258. You can access the fields of the unnamed union within @code{foo} as if they
  5259. were individual fields at the same level as the union definition:
  5260. @example
  5261. foo.a = 42;
  5262. foo.b = 47;
  5263. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5264. foo.d = 314;
  5265. @end example
  5266. Avoid using field names that could cause ambiguity. For example, with
  5267. this definition:
  5268. @example
  5269. struct
  5270. @{
  5271. int a;
  5272. struct
  5273. @{
  5274. int a;
  5275. float b;
  5276. @};
  5277. @} foo;
  5278. @end example
  5279. @noindent
  5280. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5281. an error when a definition is ambiguous in this way.
  5282. @node Incomplete Types
  5283. @section Incomplete Types
  5284. @cindex incomplete types
  5285. @cindex types, incomplete
  5286. A type that has not been fully defined is called an @dfn{incomplete
  5287. type}. Structure and union types are incomplete when the code makes a
  5288. forward reference, such as @code{struct foo}, before defining the
  5289. type. An array type is incomplete when its length is unspecified.
  5290. You can't use an incomplete type to declare a variable or field, or
  5291. use it for a function parameter or return type. The operators
  5292. @code{sizeof} and @code{_Alignof} give errors when used on an
  5293. incomplete type.
  5294. However, you can define a pointer to an incomplete type, and declare a
  5295. variable or field with such a pointer type. In general, you can do
  5296. everything with such pointers except dereference them. For example:
  5297. @example
  5298. extern void bar (struct mysterious_value *);
  5299. void
  5300. foo (struct mysterious_value *arg)
  5301. @{
  5302. bar (arg);
  5303. @}
  5304. @r{@dots{}}
  5305. @{
  5306. struct mysterious_value *p, **q;
  5307. p = *q;
  5308. foo (p);
  5309. @}
  5310. @end example
  5311. @noindent
  5312. These examples are valid because the code doesn't try to understand
  5313. what @code{p} points to; it just passes the pointer around.
  5314. (Presumably @code{bar} is defined in some other file that really does
  5315. have a definition for @code{struct mysterious_value}.) However,
  5316. dereferencing the pointer would get an error; that requires a
  5317. definition for the structure type.
  5318. @node Intertwined Incomplete Types
  5319. @section Intertwined Incomplete Types
  5320. When several structure types contain pointers to each other, you can
  5321. define the types in any order because pointers to types that come
  5322. later are incomplete types. Thus,
  5323. Here is an example.
  5324. @example
  5325. /* @r{An employee record points to a group.} */
  5326. struct employee
  5327. @{
  5328. char *name;
  5329. @r{@dots{}}
  5330. struct group *group; /* @r{incomplete type.} */
  5331. @r{@dots{}}
  5332. @};
  5333. /* @r{An employee list points to employees.} */
  5334. struct employee_list
  5335. @{
  5336. struct employee *this_one;
  5337. struct employee_list *next; /* @r{incomplete type.} */
  5338. @r{@dots{}}
  5339. @};
  5340. /* @r{A group points to one employee_list.} */
  5341. struct group
  5342. @{
  5343. char *name;
  5344. @r{@dots{}}
  5345. struct employee_list *employees;
  5346. @r{@dots{}}
  5347. @};
  5348. @end example
  5349. @node Type Tags
  5350. @section Type Tags
  5351. @cindex type tags
  5352. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5353. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5354. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5355. name or function name; the type tags have a separate @dfn{name space}.
  5356. Thus, there is no name conflict in this code:
  5357. @example
  5358. struct pair @{ int a, b; @};
  5359. int pair = 1;
  5360. @end example
  5361. @noindent
  5362. nor in this one:
  5363. @example
  5364. struct pair @{ int a, b; @} pair;
  5365. @end example
  5366. @noindent
  5367. where @code{pair} is both a structure type tag and a variable name.
  5368. However, @code{struct}, @code{union}, and @code{enum} share the same
  5369. name space of tags, so this is a conflict:
  5370. @example
  5371. struct pair @{ int a, b; @};
  5372. enum pair @{ c, d @};
  5373. @end example
  5374. @noindent
  5375. and so is this:
  5376. @example
  5377. struct pair @{ int a, b; @};
  5378. struct pair @{ int c, d; @};
  5379. @end example
  5380. When the code defines a type tag inside a block, the tag's scope is
  5381. limited to that block (as for local variables). Two definitions for
  5382. one type tag do not conflict if they are in different scopes; rather,
  5383. each is valid in its scope. For example,
  5384. @example
  5385. struct pair @{ int a, b; @};
  5386. void
  5387. pair_up_doubles (int len, double array[])
  5388. @{
  5389. struct pair @{ double a, b; @};
  5390. @r{@dots{}}
  5391. @}
  5392. @end example
  5393. @noindent
  5394. has two definitions for @code{struct pair} which do not conflict. The
  5395. one inside the function applies only within the definition of
  5396. @code{pair_up_doubles}. Within its scope, that definition
  5397. @dfn{shadows} the outer definition.
  5398. If @code{struct pair} appears inside the function body, before the
  5399. inner definition, it refers to the outer definition---the only one
  5400. that has been seen at that point. Thus, in this code,
  5401. @example
  5402. struct pair @{ int a, b; @};
  5403. void
  5404. pair_up_doubles (int len, double array[])
  5405. @{
  5406. struct two_pairs @{ struct pair *p, *q; @};
  5407. struct pair @{ double a, b; @};
  5408. @r{@dots{}}
  5409. @}
  5410. @end example
  5411. @noindent
  5412. the structure @code{two_pairs} has pointers to the outer definition of
  5413. @code{struct pair}, which is probably not desirable.
  5414. To prevent that, you can write @code{struct pair;} inside the function
  5415. body as a variable declaration with no variables. This is a
  5416. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5417. type tag local to the current block, with the details of the type to
  5418. come later. Here's an example:
  5419. @example
  5420. void
  5421. pair_up_doubles (int len, double array[])
  5422. @{
  5423. /* @r{Forward declaration for @code{pair}.} */
  5424. struct pair;
  5425. struct two_pairs @{ struct pair *p, *q; @};
  5426. /* @r{Give the details.} */
  5427. struct pair @{ double a, b; @};
  5428. @r{@dots{}}
  5429. @}
  5430. @end example
  5431. However, the cleanest practice is to avoid shadowing type tags.
  5432. @node Arrays
  5433. @chapter Arrays
  5434. @cindex array
  5435. @cindex elements of arrays
  5436. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5437. all of the same data type. Each element is identified by its numeric
  5438. @var{index} within the array.
  5439. We presented arrays of numbers in the sample programs early in this
  5440. manual (@pxref{Array Example}). However, arrays can have elements of
  5441. any data type, including pointers, structures, unions, and other
  5442. arrays.
  5443. If you know another programming language, you may suppose that you know all
  5444. about arrays, but C arrays have special quirks, so in this chapter we
  5445. collect all the information about arrays in C@.
  5446. The elements of a C array are allocated consecutively in memory,
  5447. with no gaps between them. Each element is aligned as required
  5448. for its data type (@pxref{Type Alignment}).
  5449. @menu
  5450. * Accessing Array Elements:: How to access individual elements of an array.
  5451. * Declaring an Array:: How to name and reserve space for a new array.
  5452. * Strings:: A string in C is a special case of array.
  5453. * Array Type Designators:: Referring to a specific array type.
  5454. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5455. * Limitations of C Arrays:: Arrays are not first-class objects.
  5456. * Multidimensional Arrays:: Arrays of arrays.
  5457. * Constructing Array Values:: Assigning values to an entire array at once.
  5458. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5459. @end menu
  5460. @node Accessing Array Elements
  5461. @section Accessing Array Elements
  5462. @cindex accessing array elements
  5463. @cindex array elements, accessing
  5464. If the variable @code{a} is an array, the @var{n}th element of
  5465. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5466. an element's value or to assign to it:
  5467. @example
  5468. x = a[5];
  5469. a[6] = 1;
  5470. @end example
  5471. @noindent
  5472. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5473. lvalue.
  5474. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5475. valid index is one less than the number of elements.
  5476. The C language does not check whether array indices are in bounds, so
  5477. if the code uses an out-of-range index, it will access memory outside the
  5478. array.
  5479. @strong{Warning:} Using only valid index values in C is the
  5480. programmer's responsibility.
  5481. Array indexing in C is not a primitive operation: it is defined in
  5482. terms of pointer arithmetic and dereferencing. Now that we know
  5483. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5484. its job.
  5485. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5486. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5487. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5488. When an expression with array type (such as @code{a}) appears as part
  5489. of a larger C expression, it is converted automatically to a pointer
  5490. to element zero of that array. For instance, @code{a} in an
  5491. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5492. computed as @code{*(&a[0]+i)}.
  5493. Now we can analyze how that expression gives us the desired element of
  5494. the array. It makes a pointer to element 0 of @code{a}, advances it
  5495. by the value of @code{i}, and dereferences that pointer.
  5496. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5497. @node Declaring an Array
  5498. @section Declaring an Array
  5499. @cindex declaring an array
  5500. @cindex array, declaring
  5501. To make an array declaration, write @code{[@var{length}]} after the
  5502. name being declared. This construct is valid in the declaration of a
  5503. variable, a function parameter, a function value type (the value can't
  5504. be an array, but it can be a pointer to one), a structure field, or a
  5505. union alternative.
  5506. The surrounding declaration specifies the element type of the array;
  5507. that can be any type of data, but not @code{void} or a function type.
  5508. For instance,
  5509. @example
  5510. double a[5];
  5511. @end example
  5512. @noindent
  5513. declares @code{a} as an array of 5 @code{double}s.
  5514. @example
  5515. struct foo bstruct[length];
  5516. @end example
  5517. @noindent
  5518. declares @code{bstruct} as an array of @code{length} objects of type
  5519. @code{struct foo}. A variable array size like this is allowed when
  5520. the array is not file-scope.
  5521. Other declaration constructs can nest within the array declaration
  5522. construct. For instance:
  5523. @example
  5524. struct foo *b[length];
  5525. @end example
  5526. @noindent
  5527. declares @code{b} as an array of @code{length} pointers to
  5528. @code{struct foo}. This shows that the length need not be a constant
  5529. (@pxref{Arrays of Variable Length}).
  5530. @example
  5531. double (*c)[5];
  5532. @end example
  5533. @noindent
  5534. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5535. @example
  5536. char *(*f (int))[5];
  5537. @end example
  5538. @noindent
  5539. declares @code{f} as a function taking an @code{int} argument and
  5540. returning a pointer to an array of 5 strings (pointers to
  5541. @code{char}s).
  5542. @example
  5543. double aa[5][10];
  5544. @end example
  5545. @noindent
  5546. declares @code{aa} as an array of 5 elements, each of which is an
  5547. array of 10 @code{double}s. This shows how to declare a
  5548. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5549. All these declarations specify the array's length, which is needed in
  5550. these cases in order to allocate storage for the array.
  5551. @node Strings
  5552. @section Strings
  5553. @cindex string
  5554. A string in C is a sequence of elements of type @code{char},
  5555. terminated with the null character, the character with code zero.
  5556. Programs often need to use strings with specific, fixed contents. To
  5557. write one in a C program, use a @dfn{string constant} such as
  5558. @code{"Take me to your leader!"}. The data type of a string constant
  5559. is @code{char *}. For the full syntactic details of writing string
  5560. constants, @ref{String Constants}.
  5561. To declare a place to store a non-constant string, declare an array of
  5562. @code{char}. Keep in mind that it must include one extra @code{char}
  5563. for the terminating null. For instance,
  5564. @example
  5565. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5566. @end example
  5567. @noindent
  5568. declares an array named @samp{text} with six elements---five letters
  5569. and the terminating null character. An equivalent way to get the same
  5570. result is this,
  5571. @example
  5572. char text[] = "Hello";
  5573. @end example
  5574. @noindent
  5575. which copies the elements of the string constant, including @emph{its}
  5576. terminating null character.
  5577. @example
  5578. char message[200];
  5579. @end example
  5580. @noindent
  5581. declares an array long enough to hold a string of 199 ASCII characters
  5582. plus the terminating null character.
  5583. When you store a string into @code{message} be sure to check or prove
  5584. that the length does not exceed its size. For example,
  5585. @example
  5586. void
  5587. set_message (char *text)
  5588. @{
  5589. int i;
  5590. for (i = 0; i < sizeof (message); i++)
  5591. @{
  5592. message[i] = text[i];
  5593. if (text[i] == 0)
  5594. return;
  5595. @}
  5596. fatal_error ("Message is too long for `message');
  5597. @}
  5598. @end example
  5599. It's easy to do this with the standard library function
  5600. @code{strncpy}, which fills out the whole destination array (up to a
  5601. specified length) with null characters. Thus, if the last character
  5602. of the destination is not null, the string did not fit. Many system
  5603. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5604. to run faster than an explicit @code{for}-loop.
  5605. Here's what the code looks like:
  5606. @example
  5607. void
  5608. set_message (char *text)
  5609. @{
  5610. strncpy (message, text, sizeof (message));
  5611. if (message[sizeof (message) - 1] != 0)
  5612. fatal_error ("Message is too long for `message');
  5613. @}
  5614. @end example
  5615. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5616. Library Reference Manual}, for more information about the standard
  5617. library functions for operating on strings.
  5618. You can avoid putting a fixed length limit on strings you construct or
  5619. operate on by allocating the space for them dynamically.
  5620. @xref{Dynamic Memory Allocation}.
  5621. @node Array Type Designators
  5622. @section Array Type Designators
  5623. Every C type has a type designator, which you make by deleting the
  5624. variable name and the semicolon from a declaration (@pxref{Type
  5625. Designators}). The designators for array types follow this rule, but
  5626. they may appear surprising.
  5627. @example
  5628. @r{type} int a[5]; @r{designator} int [5]
  5629. @r{type} double a[5][3]; @r{designator} double [5][3]
  5630. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5631. @end example
  5632. @node Incomplete Array Types
  5633. @section Incomplete Array Types
  5634. @cindex incomplete array types
  5635. @cindex array types, incomplete
  5636. An array is equivalent, for most purposes, to a pointer to its zeroth
  5637. element. When that is true, the length of the array is irrelevant.
  5638. The length needs to be known only for allocating space for the array, or
  5639. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5640. contexts C allows
  5641. @itemize @bullet
  5642. @item
  5643. An @code{extern} declaration says how to refer to a variable allocated
  5644. elsewhere. It does not need to allocate space for the variable,
  5645. so if it is an array, you can omit the length. For example,
  5646. @example
  5647. extern int foo[];
  5648. @end example
  5649. @item
  5650. When declaring a function parameter as an array, the argument value
  5651. passed to the function is really a pointer to the array's zeroth
  5652. element. This value does not say how long the array really is, there
  5653. is no need to declare it. For example,
  5654. @example
  5655. int
  5656. func (int foo[])
  5657. @end example
  5658. @end itemize
  5659. These declarations are examples of @dfn{incomplete} array types, types
  5660. that are not fully specified. The incompleteness makes no difference
  5661. for accessing elements of the array, but it matters for some other
  5662. things. For instance, @code{sizeof} is not allowed on an incomplete
  5663. type.
  5664. With multidimensional arrays, only the first dimension can be omitted:
  5665. @example
  5666. extern struct chesspiece *funnyboard foo[][8];
  5667. @end example
  5668. In other words, the code doesn't have to say how many rows there are,
  5669. but it must state how big each row is.
  5670. @node Limitations of C Arrays
  5671. @section Limitations of C Arrays
  5672. @cindex limitations of C arrays
  5673. @cindex first-class object
  5674. Arrays have quirks in C because they are not ``first-class objects'':
  5675. there is no way in C to operate on an array as a unit.
  5676. The other composite objects in C, structures and unions, are
  5677. first-class objects: a C program can copy a structure or union value
  5678. in an assignment, or pass one as an argument to a function, or make a
  5679. function return one. You can't do those things with an array in C@.
  5680. That is because a value you can operate on never has an array type.
  5681. An expression in C can have an array type, but that doesn't produce
  5682. the array as a value. Instead it is converted automatically to a
  5683. pointer to the array's element at index zero. The code can operate
  5684. on the pointer, and through that on individual elements of the array,
  5685. but it can't get and operate on the array as a unit.
  5686. There are three exceptions to this conversion rule, but none of them
  5687. offers a way to operate on the array as a whole.
  5688. First, @samp{&} applied to an expression with array type gives you the
  5689. address of the array, as an array type. However, you can't operate on the
  5690. whole array that way---if you apply @samp{*} to get the array back,
  5691. that expression converts, as usual, to a pointer to its zeroth
  5692. element.
  5693. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5694. @code{typeof} do not convert the array to a pointer; they leave it as
  5695. an array. But they don't operate on the array's data---they only give
  5696. information about its type.
  5697. Third, a string constant used as an initializer for an array is not
  5698. converted to a pointer---rather, the declaration copies the
  5699. @emph{contents} of that string in that one special case.
  5700. You @emph{can} copy the contents of an array, just not with an
  5701. assignment operator. You can do it by calling the library function
  5702. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5703. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5704. when a structure contains just an array, you can copy that structure.
  5705. An array itself is an lvalue if it is a declared variable, or part of
  5706. a structure or union that is an lvalue. When you construct an array
  5707. from elements (@pxref{Constructing Array Values}), that array is not
  5708. an lvalue.
  5709. @node Multidimensional Arrays
  5710. @section Multidimensional Arrays
  5711. @cindex multidimensional arrays
  5712. @cindex array, multidimensional
  5713. Strictly speaking, all arrays in C are unidimensional. However, you
  5714. can create an array of arrays, which is more or less equivalent to a
  5715. multidimensional array. For example,
  5716. @example
  5717. struct chesspiece *board[8][8];
  5718. @end example
  5719. @noindent
  5720. declares an array of 8 arrays of 8 pointers to @code{struct
  5721. chesspiece}. This data type could represent the state of a chess
  5722. game. To access one square's contents requires two array index
  5723. operations, one for each dimension. For instance, you can write
  5724. @code{board[row][column]}, assuming @code{row} and @code{column}
  5725. are variables with integer values in the proper range.
  5726. How does C understand @code{board[row][column]}? First of all,
  5727. @code{board} is converted automatically to a pointer to the zeroth
  5728. element (at index zero) of @code{board}. Adding @code{row} to that
  5729. makes it point to the desired element. Thus, @code{board[row]}'s
  5730. value is an element of @code{board}---an array of 8 pointers.
  5731. However, as an expression with array type, it is converted
  5732. automatically to a pointer to the array's zeroth element. The second
  5733. array index operation, @code{[column]}, accesses the chosen element
  5734. from that array.
  5735. As this shows, pointer-to-array types are meaningful in C@.
  5736. You can declare a variable that points to a row in a chess board
  5737. like this:
  5738. @example
  5739. struct chesspiece *(*rowptr)[8];
  5740. @end example
  5741. @noindent
  5742. This points to an array of 8 pointers to @code{struct chesspiece}.
  5743. You can assign to it as follows:
  5744. @example
  5745. rowptr = &board[5];
  5746. @end example
  5747. The dimensions don't have to be equal in length. Here we declare
  5748. @code{statepop} as an array to hold the population of each state in
  5749. the United States for each year since 1900:
  5750. @example
  5751. #define NSTATES 50
  5752. @{
  5753. int nyears = current_year - 1900 + 1;
  5754. int statepop[NSTATES][nyears];
  5755. @r{@dots{}}
  5756. @}
  5757. @end example
  5758. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5759. each indexed by the year (counting from 1900). Thus, to get the
  5760. element for a particular state and year, we must subscript it first
  5761. by the number that indicates the state, and second by the index for
  5762. the year:
  5763. @example
  5764. statepop[state][year - 1900]
  5765. @end example
  5766. @cindex array, layout in memory
  5767. The subarrays within the multidimensional array are allocated
  5768. consecutively in memory, and within each subarray, its elements are
  5769. allocated consecutively in memory. The most efficient way to process
  5770. all the elements in the array is to scan the last subscript in the
  5771. innermost loop. This means consecutive accesses go to consecutive
  5772. memory locations, which optimizes use of the processor's memory cache.
  5773. For example:
  5774. @example
  5775. int total = 0;
  5776. float average;
  5777. for (int state = 0; state < NSTATES, ++state)
  5778. @{
  5779. for (int year = 0; year < nyears; ++year)
  5780. @{
  5781. total += statepop[state][year];
  5782. @}
  5783. @}
  5784. average = total / nyears;
  5785. @end example
  5786. C's layout for multidimensional arrays is different from Fortran's
  5787. layout. In Fortran, a multidimensional array is not an array of
  5788. arrays; rather, multidimensional arrays are a primitive feature, and
  5789. it is the first index that varies most rapidly between consecutive
  5790. memory locations. Thus, the memory layout of a 50x114 array in C
  5791. matches that of a 114x50 array in Fortran.
  5792. @node Constructing Array Values
  5793. @section Constructing Array Values
  5794. @cindex constructing array values
  5795. @cindex array values, constructing
  5796. You can construct an array from elements by writing them inside
  5797. braces, and preceding all that with the array type's designator in
  5798. parentheses. There is no need to specify the array length, since the
  5799. number of elements determines that. The constructor looks like this:
  5800. @example
  5801. (@var{elttype}[]) @{ @var{elements} @};
  5802. @end example
  5803. Here is an example, which constructs an array of string pointers:
  5804. @example
  5805. (char *[]) @{ "x", "y", "z" @};
  5806. @end example
  5807. That's equivalent in effect to declaring an array with the same
  5808. initializer, like this:
  5809. @example
  5810. char *array[] = @{ "x", "y", "z" @};
  5811. @end example
  5812. and then using the array.
  5813. If all the elements are simple constant expressions, or made up of
  5814. such, then the compound literal can be coerced to a pointer to its
  5815. zeroth element and used to initialize a file-scope variable
  5816. (@pxref{File-Scope Variables}), as shown here:
  5817. @example
  5818. char **foo = (char *[]) @{ "x", "y", "z" @};
  5819. @end example
  5820. @noindent
  5821. The data type of @code{foo} is @code{char **}, which is a pointer
  5822. type, not an array type. The declaration is equivalent to defining
  5823. and then using an array-type variable:
  5824. @example
  5825. char *nameless_array[] = @{ "x", "y", "z" @};
  5826. char **foo = &nameless_array[0];
  5827. @end example
  5828. @node Arrays of Variable Length
  5829. @section Arrays of Variable Length
  5830. @cindex array of variable length
  5831. @cindex variable-length arrays
  5832. In GNU C, you can declare variable-length arrays like any other
  5833. arrays, but with a length that is not a constant expression. The
  5834. storage is allocated at the point of declaration and deallocated when
  5835. the block scope containing the declaration exits. For example:
  5836. @example
  5837. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5838. #include <string.h> /* @r{Declares @code{str}.} */
  5839. FILE *
  5840. concat_fopen (char *s1, char *s2, char *mode)
  5841. @{
  5842. char str[strlen (s1) + strlen (s2) + 1];
  5843. strcpy (str, s1);
  5844. strcat (str, s2);
  5845. return fopen (str, mode);
  5846. @}
  5847. @end example
  5848. @noindent
  5849. (This uses some standard library functions; see @ref{String and Array
  5850. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5851. The length of an array is computed once when the storage is allocated
  5852. and is remembered for the scope of the array in case it is used in
  5853. @code{sizeof}.
  5854. @strong{Warning:} don't allocate a variable-length array if the size
  5855. might be very large (more than 100,000), or in a recursive function,
  5856. because that is likely to cause stack overflow. Allocate the array
  5857. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5858. Jumping or breaking out of the scope of the array name deallocates the
  5859. storage. Jumping into the scope is not allowed; that gives an error
  5860. message.
  5861. You can also use variable-length arrays as arguments to functions:
  5862. @example
  5863. struct entry
  5864. tester (int len, char data[len][len])
  5865. @{
  5866. @r{@dots{}}
  5867. @}
  5868. @end example
  5869. As usual, a function argument declared with an array type
  5870. is really a pointer to an array that already exists.
  5871. Calling the function does not allocate the array, so there's no
  5872. particular danger of stack overflow in using this construct.
  5873. To pass the array first and the length afterward, use a forward
  5874. declaration in the function's parameter list (another GNU extension).
  5875. For example,
  5876. @example
  5877. struct entry
  5878. tester (int len; char data[len][len], int len)
  5879. @{
  5880. @r{@dots{}}
  5881. @}
  5882. @end example
  5883. The @code{int len} before the semicolon is a @dfn{parameter forward
  5884. declaration}, and it serves the purpose of making the name @code{len}
  5885. known when the declaration of @code{data} is parsed.
  5886. You can write any number of such parameter forward declarations in the
  5887. parameter list. They can be separated by commas or semicolons, but
  5888. the last one must end with a semicolon, which is followed by the
  5889. ``real'' parameter declarations. Each forward declaration must match
  5890. a ``real'' declaration in parameter name and data type. ISO C11 does
  5891. not support parameter forward declarations.
  5892. @node Enumeration Types
  5893. @chapter Enumeration Types
  5894. @cindex enumeration types
  5895. @cindex types, enumeration
  5896. @cindex enumerator
  5897. An @dfn{enumeration type} represents a limited set of integer values,
  5898. each with a name. It is effectively equivalent to a primitive integer
  5899. type.
  5900. Suppose we have a list of possible emotional states to store in an
  5901. integer variable. We can give names to these alternative values with
  5902. an enumeration:
  5903. @example
  5904. enum emotion_state @{ neutral, happy, sad, worried,
  5905. calm, nervous @};
  5906. @end example
  5907. @noindent
  5908. (Never mind that this is a simplistic way to classify emotional states;
  5909. it's just a code example.)
  5910. The names inside the enumeration are called @dfn{enumerators}. The
  5911. enumeration type defines them as constants, and their values are
  5912. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5913. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5914. the enumerators explicitly like this:
  5915. @example
  5916. enum emotion_state @{ neutral = 2, happy = 5,
  5917. sad = 20, worried = 10,
  5918. calm = -5, nervous = -300 @};
  5919. @end example
  5920. Each enumerator which does not specify a value gets value zero
  5921. (if it is at the beginning) or the next consecutive integer.
  5922. @example
  5923. /* @r{@code{neutral} is 0 by default,}
  5924. @r{and @code{worried} is 21 by default.} */
  5925. enum emotion_state @{ neutral,
  5926. happy = 5, sad = 20, worried,
  5927. calm = -5, nervous = -300 @};
  5928. @end example
  5929. If an enumerator is obsolete, you can specify that using it should
  5930. cause a warning, by including an attribute in the enumerator's
  5931. declaration. Here is how @code{happy} would look with this
  5932. attribute:
  5933. @example
  5934. happy __attribute__
  5935. ((deprecated
  5936. ("impossible under plutocratic rule")))
  5937. = 5,
  5938. @end example
  5939. @xref{Attributes}.
  5940. You can declare variables with the enumeration type:
  5941. @example
  5942. enum emotion_state feelings_now;
  5943. @end example
  5944. In the C code itself, this is equivalent to declaring the variable
  5945. @code{int}. (If all the enumeration values are positive, it is
  5946. equivalent to @code{unsigned int}.) However, declaring it with the
  5947. enumeration type has an advantage in debugging, because GDB knows it
  5948. should display the current value of the variable using the
  5949. corresponding name. If the variable's type is @code{int}, GDB can
  5950. only show the value as a number.
  5951. The identifier that follows @code{enum} is called a @dfn{type tag}
  5952. since it distinguishes different enumeration types. Type tags are in
  5953. a separate name space and belong to scopes like most other names in C@.
  5954. @xref{Type Tags}, for explanation.
  5955. You can predeclare an @code{enum} type tag like a structure or union
  5956. type tag, like this:
  5957. @example
  5958. enum foo;
  5959. @end example
  5960. @noindent
  5961. The @code{enum} type is incomplete until you finish defining it.
  5962. You can optionally include a trailing comma at the end of a list of
  5963. enumeration values:
  5964. @example
  5965. enum emotion_state @{ neutral, happy, sad, worried,
  5966. calm, nervous, @};
  5967. @end example
  5968. @noindent
  5969. This is useful in some macro definitions, since it enables you to
  5970. assemble the list of enumerators without knowing which one is last.
  5971. The extra comma does not change the meaning of the enumeration in any
  5972. way.
  5973. @node Defining Typedef Names
  5974. @chapter Defining Typedef Names
  5975. @cindex typedef names
  5976. @findex typedef
  5977. You can define a data type keyword as an alias for any type, and then
  5978. use the alias syntactically like a built-in type keyword such as
  5979. @code{int}. You do this using @code{typedef}, so these aliases are
  5980. also called @dfn{typedef names}.
  5981. @code{typedef} is followed by text that looks just like a variable
  5982. declaration, but instead of declaring variables it defines data type
  5983. keywords.
  5984. Here's how to define @code{fooptr} as a typedef alias for the type
  5985. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5986. with that type:
  5987. @example
  5988. typedef struct foo *fooptr;
  5989. fooptr x, y;
  5990. @end example
  5991. @noindent
  5992. That declaration is equivalent to the following one:
  5993. @example
  5994. struct foo *x, *y;
  5995. @end example
  5996. You can define a typedef alias for any type. For instance, this makes
  5997. @code{frobcount} an alias for type @code{int}:
  5998. @example
  5999. typedef int frobcount;
  6000. @end example
  6001. @noindent
  6002. This doesn't define a new type distinct from @code{int}. Rather,
  6003. @code{frobcount} is another name for the type @code{int}. Once the
  6004. variable is declared, it makes no difference which name the
  6005. declaration used.
  6006. There is a syntactic difference, however, between @code{frobcount} and
  6007. @code{int}: A typedef name cannot be used with
  6008. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6009. to specify the type all by itself. So you can't write this:
  6010. @example
  6011. unsigned frobcount f1; /* @r{Error!} */
  6012. @end example
  6013. But you can write this:
  6014. @example
  6015. typedef unsigned int unsigned_frobcount;
  6016. unsigned_frobcount f1;
  6017. @end example
  6018. In other words, a typedef name is not an alias for @emph{a keyword}
  6019. such as @code{int}. It stands for a @emph{type}, and that could be
  6020. the type @code{int}.
  6021. Typedef names are in the same namespace as functions and variables, so
  6022. you can't use the same name for a typedef and a function, or a typedef
  6023. and a variable. When a typedef is declared inside a code block, it is
  6024. in scope only in that block.
  6025. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6026. because many of these have standard meanings.
  6027. You can redefine a typedef name to the exact same type as its first
  6028. definition, but you cannot redefine a typedef name to a
  6029. different type, even if the two types are compatible. For example, this
  6030. is valid:
  6031. @example
  6032. typedef int frobcount;
  6033. typedef int frotzcount;
  6034. typedef frotzcount frobcount;
  6035. typedef frobcount frotzcount;
  6036. @end example
  6037. @noindent
  6038. because each typedef name is always defined with the same type
  6039. (@code{int}), but this is not valid:
  6040. @example
  6041. enum foo @{f1, f2, f3@};
  6042. typedef enum foo frobcount;
  6043. typedef int frobcount;
  6044. @end example
  6045. @noindent
  6046. Even though the type @code{enum foo} is compatible with @code{int},
  6047. they are not the @emph{same} type.
  6048. @node Statements
  6049. @chapter Statements
  6050. @cindex statements
  6051. A @dfn{statement} specifies computations to be done for effect; it
  6052. does not produce a value, as an expression would. In general a
  6053. statement ends with a semicolon (@samp{;}), but blocks (which are
  6054. statements, more or less) are an exception to that rule.
  6055. @ifnottex
  6056. @xref{Blocks}.
  6057. @end ifnottex
  6058. The places to use statements are inside a block, and inside a
  6059. complex statement. A @dfn{complex statement} contains one or two
  6060. components that are nested statements. Each such component must
  6061. consist of one and only one statement. The way to put multiple
  6062. statements in such a component is to group them into a @dfn{block}
  6063. (@pxref{Blocks}), which counts as one statement.
  6064. The following sections describe the various kinds of statement.
  6065. @menu
  6066. * Expression Statement:: Evaluate an expression, as a statement,
  6067. usually done for a side effect.
  6068. * if Statement:: Basic conditional execution.
  6069. * if-else Statement:: Multiple branches for conditional execution.
  6070. * Blocks:: Grouping multiple statements together.
  6071. * return Statement:: Return a value from a function.
  6072. * Loop Statements:: Repeatedly executing a statement or block.
  6073. * switch Statement:: Multi-way conditional choices.
  6074. * switch Example:: A plausible example of using @code{switch}.
  6075. * Duffs Device:: A special way to use @code{switch}.
  6076. * Case Ranges:: Ranges of values for @code{switch} cases.
  6077. * Null Statement:: A statement that does nothing.
  6078. * goto Statement:: Jump to another point in the source code,
  6079. identified by a label.
  6080. * Local Labels:: Labels with limited scope.
  6081. * Labels as Values:: Getting the address of a label.
  6082. * Statement Exprs:: A series of statements used as an expression.
  6083. @end menu
  6084. @node Expression Statement
  6085. @section Expression Statement
  6086. @cindex expression statement
  6087. @cindex statement, expression
  6088. The most common kind of statement in C is an @dfn{expression statement}.
  6089. It consists of an expression followed by a
  6090. semicolon. The expression's value is discarded, so the expressions
  6091. that are useful are those that have side effects: assignment
  6092. expressions, increment and decrement expressions, and function calls.
  6093. Here are examples of expression statements:
  6094. @smallexample
  6095. x = 5; /* @r{Assignment expression.} */
  6096. p++; /* @r{Increment expression.} */
  6097. printf ("Done\n"); /* @r{Function call expression.} */
  6098. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6099. x + y; /* @r{Useless statement without effect.} */
  6100. @end smallexample
  6101. In very unusual circumstances we use an expression statement
  6102. whose purpose is to get a fault if an address is invalid:
  6103. @smallexample
  6104. volatile char *p;
  6105. @r{@dots{}}
  6106. *p; /* @r{Cause signal if @code{p} is null.} */
  6107. @end smallexample
  6108. If the target of @code{p} is not declared @code{volatile}, the
  6109. compiler might optimize away the memory access, since it knows that
  6110. the value isn't really used. @xref{volatile}.
  6111. @node if Statement
  6112. @section @code{if} Statement
  6113. @cindex @code{if} statement
  6114. @cindex statement, @code{if}
  6115. @findex if
  6116. An @code{if} statement computes an expression to decide
  6117. whether to execute the following statement or not.
  6118. It looks like this:
  6119. @example
  6120. if (@var{condition})
  6121. @var{execute-if-true}
  6122. @end example
  6123. The first thing this does is compute the value of @var{condition}. If
  6124. that is true (nonzero), then it executes the statement
  6125. @var{execute-if-true}. If the value of @var{condition} is false
  6126. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6127. nothing.
  6128. This is a @dfn{complex statement} because it contains a component
  6129. @var{if-true-substatement} that is a nested statement. It must be one
  6130. and only one statement. The way to put multiple statements there is
  6131. to group them into a @dfn{block} (@pxref{Blocks}).
  6132. @node if-else Statement
  6133. @section @code{if-else} Statement
  6134. @cindex @code{if}@dots{}@code{else} statement
  6135. @cindex statement, @code{if}@dots{}@code{else}
  6136. @findex else
  6137. An @code{if}-@code{else} statement computes an expression to decide
  6138. which of two nested statements to execute.
  6139. It looks like this:
  6140. @example
  6141. if (@var{condition})
  6142. @var{if-true-substatement}
  6143. else
  6144. @var{if-false-substatement}
  6145. @end example
  6146. The first thing this does is compute the value of @var{condition}. If
  6147. that is true (nonzero), then it executes the statement
  6148. @var{if-true-substatement}. If the value of @var{condition} is false
  6149. (zero), then it executes the statement @var{if-false-substatement} instead.
  6150. This is a @dfn{complex statement} because it contains components
  6151. @var{if-true-substatement} and @var{if-else-substatement} that are
  6152. nested statements. Each must be one and only one statement. The way
  6153. to put multiple statements in such a component is to group them into a
  6154. @dfn{block} (@pxref{Blocks}).
  6155. @node Blocks
  6156. @section Blocks
  6157. @cindex block
  6158. @cindex compound statement
  6159. A @dfn{block} is a construct that contains multiple statements of any
  6160. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6161. series of statements and declarations in between. Another name for
  6162. blocks is @dfn{compound statements}.
  6163. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6164. normal statement---it does not end with a semicolon. But you can
  6165. @emph{use} it like a statement; anywhere that a statement is required
  6166. or allowed, you can write a block and consider that block a statement.
  6167. So far it seems that a block is a kind of statement with an unusual
  6168. syntax. But that is not entirely true: a function body is also a
  6169. block, and that block is definitely not a statement. The text after a
  6170. function header is not treated as a statement; only a function body is
  6171. allowed there, and nothing else would be meaningful there.
  6172. In a formal grammar we would have to choose---either a block is a kind
  6173. of statement or it is not. But this manual is meant for humans, not
  6174. for parser generators. The clearest answer for humans is, ``a block
  6175. is a statement, in some ways.''
  6176. @cindex nested block
  6177. @cindex internal block
  6178. A block that isn't a function body is called an @dfn{internal block}
  6179. or a @dfn{nested block}. You can put a nested block directly inside
  6180. another block, but more often the nested block is inside some complex
  6181. statement, such as a @code{for} statement or an @code{if} statement.
  6182. There are two uses for nested blocks in C:
  6183. @itemize @bullet
  6184. @item
  6185. To specify the scope for local declarations. For instance, a local
  6186. variable's scope is the rest of the innermost containing block.
  6187. @item
  6188. To write a series of statements where, syntactically, one statement is
  6189. called for. For instance, the @var{execute-if-true} of an @code{if}
  6190. statement is one statement. To put multiple statements there, they
  6191. have to be wrapped in a block, like this:
  6192. @example
  6193. if (x < 0)
  6194. @{
  6195. printf ("x was negative\n");
  6196. x = -x;
  6197. @}
  6198. @end example
  6199. @end itemize
  6200. This example (repeated from above) shows a nested block which serves
  6201. both purposes: it includes two statements (plus a declaration) in the
  6202. body of a @code{while} statement, and it provides the scope for the
  6203. declaration of @code{q}.
  6204. @example
  6205. void
  6206. free_intlist (struct intlistlink *p)
  6207. @{
  6208. while (p)
  6209. @{
  6210. struct intlistlink *q = p;
  6211. p = p->next;
  6212. free (q);
  6213. @}
  6214. @}
  6215. @end example
  6216. @node return Statement
  6217. @section @code{return} Statement
  6218. @cindex @code{return} statement
  6219. @cindex statement, @code{return}
  6220. @findex return
  6221. The @code{return} statement makes the containing function return
  6222. immediately. It has two forms. This one specifies no value to
  6223. return:
  6224. @example
  6225. return;
  6226. @end example
  6227. @noindent
  6228. That form is meant for functions whose return type is @code{void}
  6229. (@pxref{The Void Type}). You can also use it in a function that
  6230. returns nonvoid data, but that's a bad idea, since it makes the
  6231. function return garbage.
  6232. The form that specifies a value looks like this:
  6233. @example
  6234. return @var{value};
  6235. @end example
  6236. @noindent
  6237. which computes the expression @var{value} and makes the function
  6238. return that. If necessary, the value undergoes type conversion to
  6239. the function's declared return value type, which works like
  6240. assigning the value to a variable of that type.
  6241. @node Loop Statements
  6242. @section Loop Statements
  6243. @cindex loop statements
  6244. @cindex statements, loop
  6245. @cindex iteration
  6246. You can use a loop statement when you need to execute a series of
  6247. statements repeatedly, making an @dfn{iteration}. C provides several
  6248. different kinds of loop statements, described in the following
  6249. subsections.
  6250. Every kind of loop statement is a complex statement because contains a
  6251. component, here called @var{body}, which is a nested statement.
  6252. Most often the body is a block.
  6253. @menu
  6254. * while Statement:: Loop as long as a test expression is true.
  6255. * do-while Statement:: Execute a loop once, with further looping
  6256. as long as a test expression is true.
  6257. * break Statement:: End a loop immediately.
  6258. * for Statement:: Iterative looping.
  6259. * Example of for:: An example of iterative looping.
  6260. * Omitted for-Expressions:: for-loop expression options.
  6261. * for-Index Declarations:: for-loop declaration options.
  6262. * continue Statement:: Begin the next cycle of a loop.
  6263. @end menu
  6264. @node while Statement
  6265. @subsection @code{while} Statement
  6266. @cindex @code{while} statement
  6267. @cindex statement, @code{while}
  6268. @findex while
  6269. The @code{while} statement is the simplest loop construct.
  6270. It looks like this:
  6271. @example
  6272. while (@var{test})
  6273. @var{body}
  6274. @end example
  6275. Here, @var{body} is a statement (often a nested block) to repeat, and
  6276. @var{test} is the test expression that controls whether to repeat it again.
  6277. Each iteration of the loop starts by computing @var{test} and, if it
  6278. is true (nonzero), that means the loop should execute @var{body} again
  6279. and then start over.
  6280. Here's an example of advancing to the last structure in a chain of
  6281. structures chained through the @code{next} field:
  6282. @example
  6283. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6284. @r{@dots{}}
  6285. while (chain->next != NULL)
  6286. chain = chain->next;
  6287. @end example
  6288. @noindent
  6289. This code assumes the chain isn't empty to start with; if the chain is
  6290. empty (that is, if @code{chain} is a null pointer), the code gets a
  6291. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6292. @node do-while Statement
  6293. @subsection @code{do-while} Statement
  6294. @cindex @code{do}--@code{while} statement
  6295. @cindex statement, @code{do}--@code{while}
  6296. @findex do
  6297. The @code{do}--@code{while} statement is a simple loop construct that
  6298. performs the test at the end of the iteration.
  6299. @example
  6300. do
  6301. @var{body}
  6302. while (@var{test});
  6303. @end example
  6304. Here, @var{body} is a statement (possibly a block) to repeat, and
  6305. @var{test} is an expression that controls whether to repeat it again.
  6306. Each iteration of the loop starts by executing @var{body}. Then it
  6307. computes @var{test} and, if it is true (nonzero), that means to go
  6308. back and start over with @var{body}. If @var{test} is false (zero),
  6309. then the loop stops repeating and execution moves on past it.
  6310. @node break Statement
  6311. @subsection @code{break} Statement
  6312. @cindex @code{break} statement
  6313. @cindex statement, @code{break}
  6314. @findex break
  6315. The @code{break} statement looks like @samp{break;}. Its effect is to
  6316. exit immediately from the innermost loop construct or @code{switch}
  6317. statement (@pxref{switch Statement}).
  6318. For example, this loop advances @code{p} until the next null
  6319. character or newline.
  6320. @example
  6321. while (*p)
  6322. @{
  6323. /* @r{End loop if we have reached a newline.} */
  6324. if (*p == '\n')
  6325. break;
  6326. p++
  6327. @}
  6328. @end example
  6329. When there are nested loops, the @code{break} statement exits from the
  6330. innermost loop containing it.
  6331. @example
  6332. struct list_if_tuples
  6333. @{
  6334. struct list_if_tuples next;
  6335. int length;
  6336. data *contents;
  6337. @};
  6338. void
  6339. process_all_elements (struct list_if_tuples *list)
  6340. @{
  6341. while (list)
  6342. @{
  6343. /* @r{Process all the elements in this node's vector,}
  6344. @r{stopping when we reach one that is null.} */
  6345. for (i = 0; i < list->length; i++
  6346. @{
  6347. /* @r{Null element terminates this node's vector.} */
  6348. if (list->contents[i] == NULL)
  6349. /* @r{Exit the @code{for} loop.} */
  6350. break;
  6351. /* @r{Operate on the next element.} */
  6352. process_element (list->contents[i]);
  6353. @}
  6354. list = list->next;
  6355. @}
  6356. @}
  6357. @end example
  6358. The only way in C to exit from an outer loop is with
  6359. @code{goto} (@pxref{goto Statement}).
  6360. @node for Statement
  6361. @subsection @code{for} Statement
  6362. @cindex @code{for} statement
  6363. @cindex statement, @code{for}
  6364. @findex for
  6365. A @code{for} statement uses three expressions written inside a
  6366. parenthetical group to define the repetition of the loop. The first
  6367. expression says how to prepare to start the loop. The second says how
  6368. to test, before each iteration, whether to continue looping. The
  6369. third says how to advance, at the end of an iteration, for the next
  6370. iteration. All together, it looks like this:
  6371. @example
  6372. for (@var{start}; @var{continue-test}; @var{advance})
  6373. @var{body}
  6374. @end example
  6375. The first thing the @code{for} statement does is compute @var{start}.
  6376. The next thing it does is compute the expression @var{continue-test}.
  6377. If that expression is false (zero), the @code{for} statement finishes
  6378. immediately, so @var{body} is executed zero times.
  6379. However, if @var{continue-test} is true (nonzero), the @code{for}
  6380. statement executes @var{body}, then @var{advance}. Then it loops back
  6381. to the not-quite-top to test @var{continue-test} again. But it does
  6382. not compute @var{start} again.
  6383. @node Example of for
  6384. @subsection Example of @code{for}
  6385. Here is the @code{for} statement from the iterative Fibonacci
  6386. function:
  6387. @example
  6388. int i;
  6389. for (i = 1; i < n; ++i)
  6390. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6391. /* @r{since @code{i < n} is false the first time.} */
  6392. @{
  6393. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6394. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6395. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6396. int next = prev + last;
  6397. /* @r{Shift the values down.} */
  6398. prev = last;
  6399. last = next;
  6400. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6401. @r{and @var{prev} is @code{fib (@var{i})}.}
  6402. @r{But that won't stay true for long,}
  6403. @r{because we are about to increment @var{i}.} */
  6404. @}
  6405. @end example
  6406. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6407. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6408. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6409. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6410. that contains a declaration and two statements.
  6411. @node Omitted for-Expressions
  6412. @subsection Omitted @code{for}-Expressions
  6413. A fully-fleshed @code{for} statement contains all these parts,
  6414. @example
  6415. for (@var{start}; @var{continue-test}; @var{advance})
  6416. @var{body}
  6417. @end example
  6418. @noindent
  6419. but you can omit any of the three expressions inside the parentheses.
  6420. The parentheses and the two semicolons are required syntactically, but
  6421. the expressions between them may be missing. A missing expression
  6422. means this loop doesn't use that particular feature of the @code{for}
  6423. statement.
  6424. Instead of using @var{start}, you can do the loop preparation
  6425. before the @code{for} statement: the effect is the same. So we
  6426. could have written the beginning of the previous example this way:
  6427. @example
  6428. int i = 0;
  6429. for (; i < n; ++i)
  6430. @end example
  6431. @noindent
  6432. instead of this way:
  6433. @example
  6434. int i;
  6435. for (i = 0; i < n; ++i)
  6436. @end example
  6437. Omitting @var{continue-test} means the loop runs forever (or until
  6438. something else causes exit from it). Statements inside the loop can
  6439. test conditions for termination and use @samp{break;} to exit. This
  6440. is more flexible since you can put those tests anywhere in the loop,
  6441. not solely at the beginning.
  6442. Putting an expression in @var{advance} is almost equivalent to writing
  6443. it at the end of the loop body; it does almost the same thing. The
  6444. only difference is for the @code{continue} statement (@pxref{continue
  6445. Statement}). So we could have written this:
  6446. @example
  6447. for (i = 0; i < n;)
  6448. @{
  6449. @r{@dots{}}
  6450. ++i;
  6451. @}
  6452. @end example
  6453. @noindent
  6454. instead of this:
  6455. @example
  6456. for (i = 0; i < n; ++i)
  6457. @{
  6458. @r{@dots{}}
  6459. @}
  6460. @end example
  6461. The choice is mainly a matter of what is more readable for
  6462. programmers. However, there is also a syntactic difference:
  6463. @var{advance} is an expression, not a statement. It can't include
  6464. loops, blocks, declarations, etc.
  6465. @node for-Index Declarations
  6466. @subsection @code{for}-Index Declarations
  6467. You can declare loop-index variables directly in the @var{start}
  6468. portion of the @code{for}-loop, like this:
  6469. @example
  6470. for (int i = 0; i < n; ++i)
  6471. @{
  6472. @r{@dots{}}
  6473. @}
  6474. @end example
  6475. This kind of @var{start} is limited to a single declaration; it can
  6476. declare one or more variables, separated by commas, all of which are
  6477. the same @var{basetype} (@code{int}, in this example):
  6478. @example
  6479. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6480. @{
  6481. @r{@dots{}}
  6482. @}
  6483. @end example
  6484. @noindent
  6485. The scope of these variables is the @code{for} statement as a whole.
  6486. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6487. Variables declared in @code{for} statements should have initializers.
  6488. Omitting the initialization gives the variables unpredictable initial
  6489. values, so this code is erroneous.
  6490. @example
  6491. for (int i; i < n; ++i)
  6492. @{
  6493. @r{@dots{}}
  6494. @}
  6495. @end example
  6496. @node continue Statement
  6497. @subsection @code{continue} Statement
  6498. @cindex @code{continue} statement
  6499. @cindex statement, @code{continue}
  6500. @findex continue
  6501. The @code{continue} statement looks like @samp{continue;}, and its
  6502. effect is to jump immediately to the end of the innermost loop
  6503. construct. If it is a @code{for}-loop, the next thing that happens
  6504. is to execute the loop's @var{advance} expression.
  6505. For example, this loop increments @code{p} until the next null character
  6506. or newline, and operates (in some way not shown) on all the characters
  6507. in the line except for spaces. All it does with spaces is skip them.
  6508. @example
  6509. for (;*p; ++p)
  6510. @{
  6511. /* @r{End loop if we have reached a newline.} */
  6512. if (*p == '\n')
  6513. break;
  6514. /* @r{Pay no attention to spaces.} */
  6515. if (*p == ' ')
  6516. continue;
  6517. /* @r{Operate on the next character.} */
  6518. @r{@dots{}}
  6519. @}
  6520. @end example
  6521. @noindent
  6522. Executing @samp{continue;} skips the loop body but it does not
  6523. skip the @var{advance} expression, @code{p++}.
  6524. We could also write it like this:
  6525. @example
  6526. for (;*p; ++p)
  6527. @{
  6528. /* @r{Exit if we have reached a newline.} */
  6529. if (*p == '\n')
  6530. break;
  6531. /* @r{Pay no attention to spaces.} */
  6532. if (*p != ' ')
  6533. @{
  6534. /* @r{Operate on the next character.} */
  6535. @r{@dots{}}
  6536. @}
  6537. @}
  6538. @end example
  6539. The advantage of using @code{continue} is that it reduces the
  6540. depth of nesting.
  6541. Contrast @code{continue} with the @code{break} statement. @xref{break
  6542. Statement}.
  6543. @node switch Statement
  6544. @section @code{switch} Statement
  6545. @cindex @code{switch} statement
  6546. @cindex statement, @code{switch}
  6547. @findex switch
  6548. @findex case
  6549. @findex default
  6550. The @code{switch} statement selects code to run according to the value
  6551. of an expression. The expression, in parentheses, follows the keyword
  6552. @code{switch}. After that come all the cases to select among,
  6553. inside braces. It looks like this:
  6554. @example
  6555. switch (@var{selector})
  6556. @{
  6557. @var{cases}@r{@dots{}}
  6558. @}
  6559. @end example
  6560. A case can look like this:
  6561. @example
  6562. case @var{value}:
  6563. @var{statements}
  6564. break;
  6565. @end example
  6566. @noindent
  6567. which means ``come here if @var{selector} happens to have the value
  6568. @var{value},'' or like this (a GNU C extension):
  6569. @example
  6570. case @var{rangestart} ... @var{rangeend}:
  6571. @var{statements}
  6572. break;
  6573. @end example
  6574. @noindent
  6575. which means ``come here if @var{selector} happens to have a value
  6576. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6577. Ranges}.
  6578. The values in @code{case} labels must reduce to integer constants.
  6579. They can use arithmetic, and @code{enum} constants, but they cannot
  6580. refer to data in memory, because they have to be computed at compile
  6581. time. It is an error if two @code{case} labels specify the same
  6582. value, or ranges that overlap, or if one is a range and the other is a
  6583. value in that range.
  6584. You can also define a default case to handle ``any other value,'' like
  6585. this:
  6586. @example
  6587. default:
  6588. @var{statements}
  6589. break;
  6590. @end example
  6591. If the @code{switch} statement has no @code{default:} label, then it
  6592. does nothing when the value matches none of the cases.
  6593. The brace-group inside the @code{switch} statement is a block, and you
  6594. can declare variables with that scope just as in any other block
  6595. (@pxref{Blocks}). However, initializers in these declarations won't
  6596. necessarily be executed every time the @code{switch} statement runs,
  6597. so it is best to avoid giving them initializers.
  6598. @code{break;} inside a @code{switch} statement exits immediately from
  6599. the @code{switch} statement. @xref{break Statement}.
  6600. If there is no @code{break;} at the end of the code for a case,
  6601. execution continues into the code for the following case. This
  6602. happens more often by mistake than intentionally, but since this
  6603. feature is used in real code, we cannot eliminate it.
  6604. @strong{Warning:} When one case is intended to fall through to the
  6605. next, write a comment like @samp{falls through} to say it's
  6606. intentional. That way, other programmers won't assume it was an error
  6607. and ``fix'' it erroneously.
  6608. Consecutive @code{case} statements could, pedantically, be considered
  6609. an instance of falling through, but we don't consider or treat them that
  6610. way because they won't confuse anyone.
  6611. @node switch Example
  6612. @section Example of @code{switch}
  6613. Here's an example of using the @code{switch} statement
  6614. to distinguish among characters:
  6615. @cindex counting vowels and punctuation
  6616. @example
  6617. struct vp @{ int vowels, punct; @};
  6618. struct vp
  6619. count_vowels_and_punct (char *string)
  6620. @{
  6621. int c;
  6622. int vowels = 0;
  6623. int punct = 0;
  6624. /* @r{Don't change the parameter itself.} */
  6625. /* @r{That helps in debugging.} */
  6626. char *p = string;
  6627. struct vp value;
  6628. while (c = *p++)
  6629. switch (c)
  6630. @{
  6631. case 'y':
  6632. case 'Y':
  6633. /* @r{We assume @code{y_is_consonant} will check surrounding
  6634. letters to determine whether this y is a vowel.} */
  6635. if (y_is_consonant (p - 1))
  6636. break;
  6637. /* @r{Falls through} */
  6638. case 'a':
  6639. case 'e':
  6640. case 'i':
  6641. case 'o':
  6642. case 'u':
  6643. case 'A':
  6644. case 'E':
  6645. case 'I':
  6646. case 'O':
  6647. case 'U':
  6648. vowels++;
  6649. break;
  6650. case '.':
  6651. case ',':
  6652. case ':':
  6653. case ';':
  6654. case '?':
  6655. case '!':
  6656. case '\"':
  6657. case '\'':
  6658. punct++;
  6659. break;
  6660. @}
  6661. value.vowels = vowels;
  6662. value.punct = punct;
  6663. return value;
  6664. @}
  6665. @end example
  6666. @node Duffs Device
  6667. @section Duff's Device
  6668. @cindex Duff's device
  6669. The cases in a @code{switch} statement can be inside other control
  6670. constructs. For instance, we can use a technique known as @dfn{Duff's
  6671. device} to optimize this simple function,
  6672. @example
  6673. void
  6674. copy (char *to, char *from, int count)
  6675. @{
  6676. while (count > 0)
  6677. *to++ = *from++, count--;
  6678. @}
  6679. @end example
  6680. @noindent
  6681. which copies memory starting at @var{from} to memory starting at
  6682. @var{to}.
  6683. Duff's device involves unrolling the loop so that it copies
  6684. several characters each time around, and using a @code{switch} statement
  6685. to enter the loop body at the proper point:
  6686. @example
  6687. void
  6688. copy (char *to, char *from, int count)
  6689. @{
  6690. if (count <= 0)
  6691. return;
  6692. int n = (count + 7) / 8;
  6693. switch (count % 8)
  6694. @{
  6695. do @{
  6696. case 0: *to++ = *from++;
  6697. case 7: *to++ = *from++;
  6698. case 6: *to++ = *from++;
  6699. case 5: *to++ = *from++;
  6700. case 4: *to++ = *from++;
  6701. case 3: *to++ = *from++;
  6702. case 2: *to++ = *from++;
  6703. case 1: *to++ = *from++;
  6704. @} while (--n > 0);
  6705. @}
  6706. @}
  6707. @end example
  6708. @node Case Ranges
  6709. @section Case Ranges
  6710. @cindex case ranges
  6711. @cindex ranges in case statements
  6712. You can specify a range of consecutive values in a single @code{case} label,
  6713. like this:
  6714. @example
  6715. case @var{low} ... @var{high}:
  6716. @end example
  6717. @noindent
  6718. This has the same effect as the proper number of individual @code{case}
  6719. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6720. This feature is especially useful for ranges of ASCII character codes:
  6721. @example
  6722. case 'A' ... 'Z':
  6723. @end example
  6724. @strong{Be careful:} with integers, write spaces around the @code{...}
  6725. to prevent it from being parsed wrong. For example, write this:
  6726. @example
  6727. case 1 ... 5:
  6728. @end example
  6729. @noindent
  6730. rather than this:
  6731. @example
  6732. case 1...5:
  6733. @end example
  6734. @node Null Statement
  6735. @section Null Statement
  6736. @cindex null statement
  6737. @cindex statement, null
  6738. A @dfn{null statement} is just a semicolon. It does nothing.
  6739. A null statement is a placeholder for use where a statement is
  6740. grammatically required, but there is nothing to be done. For
  6741. instance, sometimes all the work of a @code{for}-loop is done in the
  6742. @code{for}-header itself, leaving no work for the body. Here is an
  6743. example that searches for the first newline in @code{array}:
  6744. @example
  6745. for (p = array; *p != '\n'; p++)
  6746. ;
  6747. @end example
  6748. @node goto Statement
  6749. @section @code{goto} Statement and Labels
  6750. @cindex @code{goto} statement
  6751. @cindex statement, @code{goto}
  6752. @cindex label
  6753. @findex goto
  6754. The @code{goto} statement looks like this:
  6755. @example
  6756. goto @var{label};
  6757. @end example
  6758. @noindent
  6759. Its effect is to transfer control immediately to another part of the
  6760. current function---where the label named @var{label} is defined.
  6761. An ordinary label definition looks like this:
  6762. @example
  6763. @var{label}:
  6764. @end example
  6765. @noindent
  6766. and it can appear before any statement. You can't use @code{default}
  6767. as a label, since that has a special meaning for @code{switch}
  6768. statements.
  6769. An ordinary label doesn't need a separate declaration; defining it is
  6770. enough.
  6771. Here's an example of using @code{goto} to implement a loop
  6772. equivalent to @code{do}--@code{while}:
  6773. @example
  6774. @{
  6775. loop_restart:
  6776. @var{body}
  6777. if (@var{condition})
  6778. goto loop_restart;
  6779. @}
  6780. @end example
  6781. The name space of labels is separate from that of variables and functions.
  6782. Thus, there is no error in using a single name in both ways:
  6783. @example
  6784. @{
  6785. int foo; // @r{Variable @code{foo}.}
  6786. foo: // @r{Label @code{foo}.}
  6787. @var{body}
  6788. if (foo > 0) // @r{Variable @code{foo}.}
  6789. goto foo; // @r{Label @code{foo}.}
  6790. @}
  6791. @end example
  6792. Blocks have no effect on ordinary labels; each label name is defined
  6793. throughout the whole of the function it appears in. It looks strange to
  6794. jump into a block with @code{goto}, but it works. For example,
  6795. @example
  6796. if (x < 0)
  6797. goto negative;
  6798. if (y < 0)
  6799. @{
  6800. negative:
  6801. printf ("Negative\n");
  6802. return;
  6803. @}
  6804. @end example
  6805. If the goto jumps into the scope of a variable, it does not
  6806. initialize the variable. For example, if @code{x} is negative,
  6807. @example
  6808. if (x < 0)
  6809. goto negative;
  6810. if (y < 0)
  6811. @{
  6812. int i = 5;
  6813. negative:
  6814. printf ("Negative, and i is %d\n", i);
  6815. return;
  6816. @}
  6817. @end example
  6818. @noindent
  6819. prints junk because @code{i} was not initialized.
  6820. If the block declares a variable-length automatic array, jumping into
  6821. it gives a compilation error. However, jumping out of the scope of a
  6822. variable-length array works fine, and deallocates its storage.
  6823. A label can't come directly before a declaration, so the code can't
  6824. jump directly to one. For example, this is not allowed:
  6825. @example
  6826. @{
  6827. goto foo;
  6828. foo:
  6829. int x = 5;
  6830. bar(&x);
  6831. @}
  6832. @end example
  6833. @noindent
  6834. The workaround is to add a statement, even an empty statement,
  6835. directly after the label. For example:
  6836. @example
  6837. @{
  6838. goto foo;
  6839. foo:
  6840. ;
  6841. int x = 5;
  6842. bar(&x);
  6843. @}
  6844. @end example
  6845. Likewise, a label can't be the last thing in a block. The workaround
  6846. solution is the same: add a semicolon after the label.
  6847. These unnecessary restrictions on labels make no sense, and ought in
  6848. principle to be removed; but they do only a little harm since labels
  6849. and @code{goto} are rarely the best way to write a program.
  6850. These examples are all artificial; it would be more natural to
  6851. write them in other ways, without @code{goto}. For instance,
  6852. the clean way to write the example that prints @samp{Negative} is this:
  6853. @example
  6854. if (x < 0 || y < 0)
  6855. @{
  6856. printf ("Negative\n");
  6857. return;
  6858. @}
  6859. @end example
  6860. @noindent
  6861. It is hard to construct simple examples where @code{goto} is actually
  6862. the best way to write a program. Its rare good uses tend to be in
  6863. complex code, thus not apt for the purpose of explaining the meaning
  6864. of @code{goto}.
  6865. The only good time to use @code{goto} is when it makes the code
  6866. simpler than any alternative. Jumping backward is rarely desirable,
  6867. because usually the other looping and control constructs give simpler
  6868. code. Using @code{goto} to jump forward is more often desirable, for
  6869. instance when a function needs to do some processing in an error case
  6870. and errors can occur at various different places within the function.
  6871. @node Local Labels
  6872. @section Locally Declared Labels
  6873. @cindex local labels
  6874. @cindex macros, local labels
  6875. @findex __label__
  6876. In GNU C you can declare @dfn{local labels} in any nested block
  6877. scope. A local label is used in a @code{goto} statement just like an
  6878. ordinary label, but you can only reference it within the block in
  6879. which it was declared.
  6880. A local label declaration looks like this:
  6881. @example
  6882. __label__ @var{label};
  6883. @end example
  6884. @noindent
  6885. or
  6886. @example
  6887. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6888. @end example
  6889. Local label declarations must come at the beginning of the block,
  6890. before any ordinary declarations or statements.
  6891. The label declaration declares the label @emph{name}, but does not define
  6892. the label itself. That's done in the usual way, with
  6893. @code{@var{label}:}, before one of the statements in the block.
  6894. The local label feature is useful for complex macros. If a macro
  6895. contains nested loops, a @code{goto} can be useful for breaking out of
  6896. them. However, an ordinary label whose scope is the whole function
  6897. cannot be used: if the macro can be expanded several times in one
  6898. function, the label will be multiply defined in that function. A
  6899. local label avoids this problem. For example:
  6900. @example
  6901. #define SEARCH(value, array, target) \
  6902. do @{ \
  6903. __label__ found; \
  6904. __auto_type _SEARCH_target = (target); \
  6905. __auto_type _SEARCH_array = (array); \
  6906. int i, j; \
  6907. int value; \
  6908. for (i = 0; i < max; i++) \
  6909. for (j = 0; j < max; j++) \
  6910. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6911. @{ (value) = i; goto found; @} \
  6912. (value) = -1; \
  6913. found:; \
  6914. @} while (0)
  6915. @end example
  6916. This could also be written using a statement expression
  6917. (@pxref{Statement Exprs}):
  6918. @example
  6919. #define SEARCH(array, target) \
  6920. (@{ \
  6921. __label__ found; \
  6922. __auto_type _SEARCH_target = (target); \
  6923. __auto_type _SEARCH_array = (array); \
  6924. int i, j; \
  6925. int value; \
  6926. for (i = 0; i < max; i++) \
  6927. for (j = 0; j < max; j++) \
  6928. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6929. @{ value = i; goto found; @} \
  6930. value = -1; \
  6931. found: \
  6932. value; \
  6933. @})
  6934. @end example
  6935. Ordinary labels are visible throughout the function where they are
  6936. defined, and only in that function. However, explicitly declared
  6937. local labels of a block are visible in nested functions declared
  6938. within that block. @xref{Nested Functions}, for details.
  6939. @xref{goto Statement}.
  6940. @node Labels as Values
  6941. @section Labels as Values
  6942. @cindex labels as values
  6943. @cindex computed gotos
  6944. @cindex goto with computed label
  6945. @cindex address of a label
  6946. In GNU C, you can get the address of a label defined in the current
  6947. function (or a local label defined in the containing function) with
  6948. the unary operator @samp{&&}. The value has type @code{void *}. This
  6949. value is a constant and can be used wherever a constant of that type
  6950. is valid. For example:
  6951. @example
  6952. void *ptr;
  6953. @r{@dots{}}
  6954. ptr = &&foo;
  6955. @end example
  6956. To use these values requires a way to jump to one. This is done
  6957. with the computed goto statement@footnote{The analogous feature in
  6958. Fortran is called an assigned goto, but that name seems inappropriate in
  6959. C, since you can do more with label addresses than store them in special label
  6960. variables.}, @code{goto *@var{exp};}. For example,
  6961. @example
  6962. goto *ptr;
  6963. @end example
  6964. @noindent
  6965. Any expression of type @code{void *} is allowed.
  6966. @xref{goto Statement}.
  6967. @menu
  6968. * Label Value Uses:: Examples of using label values.
  6969. * Label Value Caveats:: Limitations of label values.
  6970. @end menu
  6971. @node Label Value Uses
  6972. @subsection Label Value Uses
  6973. One use for label-valued constants is to initialize a static array to
  6974. serve as a jump table:
  6975. @example
  6976. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6977. @end example
  6978. Then you can select a label with indexing, like this:
  6979. @example
  6980. goto *array[i];
  6981. @end example
  6982. @noindent
  6983. Note that this does not check whether the subscript is in bounds---array
  6984. indexing in C never checks that.
  6985. You can make the table entries offsets instead of addresses
  6986. by subtracting one label from the others. Here is an example:
  6987. @example
  6988. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6989. &&hack - &&foo @};
  6990. goto *(&&foo + array[i]);
  6991. @end example
  6992. @noindent
  6993. Using offsets is preferable in shared libraries, as it avoids the need
  6994. for dynamic relocation of the array elements; therefore, the array can
  6995. be read-only.
  6996. An array of label values or offsets serves a purpose much like that of
  6997. the @code{switch} statement. The @code{switch} statement is cleaner,
  6998. so use @code{switch} by preference when feasible.
  6999. Another use of label values is in an interpreter for threaded code.
  7000. The labels within the interpreter function can be stored in the
  7001. threaded code for super-fast dispatching.
  7002. @node Label Value Caveats
  7003. @subsection Label Value Caveats
  7004. Jumping to a label defined in another function does not work.
  7005. It can cause unpredictable results.
  7006. The best way to avoid this is to store label values only in
  7007. automatic variables, or static variables whose names are declared
  7008. within the function. Never pass them as arguments.
  7009. @cindex cloning
  7010. An optimization known as @dfn{cloning} generates multiple simplified
  7011. variants of a function's code, for use with specific fixed arguments.
  7012. Using label values in certain ways, such as saving the address in one
  7013. call to the function and using it again in another call, would make cloning
  7014. give incorrect results. These functions must disable cloning.
  7015. Inlining calls to the function would also result in multiple copies of
  7016. the code, each with its own value of the same label. Using the label
  7017. in a computed goto is no problem, because the computed goto inhibits
  7018. inlining. However, using the label value in some other way, such as
  7019. an indication of where an error occurred, would be optimized wrong.
  7020. These functions must disable inlining.
  7021. To prevent inlining or cloning of a function, specify
  7022. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7023. @xref{Attributes}.
  7024. When a function uses a label value in a static variable initializer,
  7025. that automatically prevents inlining or cloning the function.
  7026. @node Statement Exprs
  7027. @section Statements and Declarations in Expressions
  7028. @cindex statements inside expressions
  7029. @cindex declarations inside expressions
  7030. @cindex expressions containing statements
  7031. @c the above section title wrapped and causes an underfull hbox.. i
  7032. @c changed it from "within" to "in". --mew 4feb93
  7033. A block enclosed in parentheses can be used as an expression in GNU
  7034. C@. This provides a way to use local variables, loops and switches within
  7035. an expression. We call it a @dfn{statement expression}.
  7036. Recall that a block is a sequence of statements
  7037. surrounded by braces. In this construct, parentheses go around the
  7038. braces. For example:
  7039. @example
  7040. (@{ int y = foo (); int z;
  7041. if (y > 0) z = y;
  7042. else z = - y;
  7043. z; @})
  7044. @end example
  7045. @noindent
  7046. is a valid (though slightly more complex than necessary) expression
  7047. for the absolute value of @code{foo ()}.
  7048. The last statement in the block should be an expression statement; an
  7049. expression followed by a semicolon, that is. The value of this
  7050. expression serves as the value of statement expression. If the last
  7051. statement is anything else, the statement expression's value is
  7052. @code{void}.
  7053. This feature is mainly useful in making macro definitions compute each
  7054. operand exactly once. @xref{Macros and Auto Type}.
  7055. Statement expressions are not allowed in expressions that must be
  7056. constant, such as the value for an enumerator, the width of a
  7057. bit-field, or the initial value of a static variable.
  7058. Jumping into a statement expression---with @code{goto}, or using a
  7059. @code{switch} statement outside the statement expression---is an
  7060. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7061. compiler can't detect the error, but it still won't work.
  7062. Jumping out of a statement expression is permitted, but since
  7063. subexpressions in C are not computed in a strict order, it is
  7064. unpredictable which other subexpressions will have been computed by
  7065. then. For example,
  7066. @example
  7067. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7068. @end example
  7069. @noindent
  7070. calls @code{foo} and @code{bar1} before it jumps, and never
  7071. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7072. does get called, that occurs after @code{foo} and before @code{bar1}.
  7073. @node Variables
  7074. @chapter Variables
  7075. @cindex variables
  7076. Every variable used in a C program needs to be made known by a
  7077. @dfn{declaration}. It can be used only after it has been declared.
  7078. It is an error to declare a variable name more than once in the same
  7079. scope; an exception is that @code{extern} declarations and tentative
  7080. definitions can coexist with another declaration of the same
  7081. variable.
  7082. Variables can be declared anywhere within a block or file. (Older
  7083. versions of C required that all variable declarations within a block
  7084. occur before any statements.)
  7085. Variables declared within a function or block are @dfn{local} to
  7086. it. This means that the variable name is visible only until the end
  7087. of that function or block, and the memory space is allocated only
  7088. while control is within it.
  7089. Variables declared at the top level in a file are called @dfn{file-scope}.
  7090. They are assigned fixed, distinct memory locations, so they retain
  7091. their values for the whole execution of the program.
  7092. @menu
  7093. * Variable Declarations:: Name a variable and and reserve space for it.
  7094. * Initializers:: Assigning inital values to variables.
  7095. * Designated Inits:: Assigning initial values to array elements
  7096. at particular array indices.
  7097. * Auto Type:: Obtaining the type of a variable.
  7098. * Local Variables:: Variables declared in function definitions.
  7099. * File-Scope Variables:: Variables declared outside of
  7100. function definitions.
  7101. * Static Local Variables:: Variables declared within functions,
  7102. but with permanent storage allocation.
  7103. * Extern Declarations:: Declaring a variable
  7104. which is allocated somewhere else.
  7105. * Allocating File-Scope:: When is space allocated
  7106. for file-scope variables?
  7107. * auto and register:: Historically used storage directions.
  7108. * Omitting Types:: The bad practice of declaring variables
  7109. with implicit type.
  7110. @end menu
  7111. @node Variable Declarations
  7112. @section Variable Declarations
  7113. @cindex variable declarations
  7114. @cindex declaration of variables
  7115. Here's what a variable declaration looks like:
  7116. @example
  7117. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7118. @end example
  7119. The @var{keywords} specify how to handle the scope of the variable
  7120. name and the allocation of its storage. Most declarations have
  7121. no keywords because the defaults are right for them.
  7122. C allows these keywords to come before or after @var{basetype}, or
  7123. even in the middle of it as in @code{unsigned static int}, but don't
  7124. do that---it would surprise other programmers. Always write the
  7125. keywords first.
  7126. The @var{basetype} can be any of the predefined types of C, or a type
  7127. keyword defined with @code{typedef}. It can also be @code{struct
  7128. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7129. addition, it can include type qualifiers such as @code{const} and
  7130. @code{volatile} (@pxref{Type Qualifiers}).
  7131. In the simplest case, @var{decorated-variable} is just the variable
  7132. name. That declares the variable with the type specified by
  7133. @var{basetype}. For instance,
  7134. @example
  7135. int foo;
  7136. @end example
  7137. @noindent
  7138. uses @code{int} as the @var{basetype} and @code{foo} as the
  7139. @var{decorated-variable}. It declares @code{foo} with type
  7140. @code{int}.
  7141. @example
  7142. struct tree_node foo;
  7143. @end example
  7144. @noindent
  7145. declares @code{foo} with type @code{struct tree_node}.
  7146. @menu
  7147. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7148. array and pointer types.
  7149. * Combining Variable Declarations:: More than one variable declaration
  7150. in a single statement.
  7151. @end menu
  7152. @node Declaring Arrays and Pointers
  7153. @subsection Declaring Arrays and Pointers
  7154. @cindex declaring arrays and pointers
  7155. @cindex array, declaring
  7156. @cindex pointers, declaring
  7157. To declare a variable that is an array, write
  7158. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7159. @example
  7160. int foo[5];
  7161. @end example
  7162. To declare a variable that has a pointer type, write
  7163. @code{*@var{variable}} for @var{decorated-variable}:
  7164. @example
  7165. struct list_elt *foo;
  7166. @end example
  7167. These constructs nest. For instance,
  7168. @example
  7169. int foo[3][5];
  7170. @end example
  7171. @noindent
  7172. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7173. @example
  7174. struct list_elt *foo[5];
  7175. @end example
  7176. @noindent
  7177. declares @code{foo} as an array of 5 pointers to structures, and
  7178. @example
  7179. struct list_elt **foo;
  7180. @end example
  7181. @noindent
  7182. declares @code{foo} as a pointer to a pointer to a structure.
  7183. @example
  7184. int **(*foo[30])(int, double);
  7185. @end example
  7186. @noindent
  7187. declares @code{foo} as an array of 30 pointers to functions
  7188. (@pxref{Function Pointers}), each of which must accept two arguments
  7189. (one @code{int} and one @code{double}) and return type @code{int **}.
  7190. @example
  7191. void
  7192. bar (int size)
  7193. @{
  7194. int foo[size];
  7195. @r{@dots{}}
  7196. @}
  7197. @end example
  7198. @noindent
  7199. declares @code{foo} as an array of integers with a size specified at
  7200. run time when the function @code{bar} is called.
  7201. @node Combining Variable Declarations
  7202. @subsection Combining Variable Declarations
  7203. @cindex combining variable declarations
  7204. @cindex variable declarations, combining
  7205. @cindex declarations, combining
  7206. When multiple declarations have the same @var{keywords} and
  7207. @var{basetype}, you can combine them using commas. Thus,
  7208. @example
  7209. @var{keywords} @var{basetype}
  7210. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7211. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7212. @end example
  7213. @noindent
  7214. is equivalent to
  7215. @example
  7216. @var{keywords} @var{basetype}
  7217. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7218. @var{keywords} @var{basetype}
  7219. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7220. @end example
  7221. Here are some simple examples:
  7222. @example
  7223. int a, b;
  7224. int a = 1, b = 2;
  7225. int a, *p, array[5];
  7226. int a = 0, *p = &a, array[5] = @{1, 2@};
  7227. @end example
  7228. @noindent
  7229. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7230. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7231. Since the initializer for @code{array} specifies only two elements,
  7232. the other three elements are initialized to zero.
  7233. @node Initializers
  7234. @section Initializers
  7235. @cindex initializers
  7236. A variable's declaration, unless it is @code{extern}, should also
  7237. specify its initial value. For numeric and pointer-type variables,
  7238. the initializer is an expression for the value. If necessary, it is
  7239. converted to the variable's type, just as in an assignment.
  7240. You can also initialize a local structure-type (@pxref{Structures}) or
  7241. local union-type (@pxref{Unions}) variable this way, from an
  7242. expression whose value has the same type. But you can't initialize an
  7243. array this way (@pxref{Arrays}), since arrays are not first-class
  7244. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7245. assignment.
  7246. You can initialize arrays and structures componentwise,
  7247. with a list of the elements or components. You can initialize
  7248. a union with any one of its alternatives.
  7249. @itemize @bullet
  7250. @item
  7251. A component-wise initializer for an array consists of element values
  7252. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7253. don't cover all the elements in the array, the remaining elements are
  7254. initialized to zero.
  7255. You can omit the size of the array when you declare it, and let
  7256. the initializer specify the size:
  7257. @example
  7258. int array[] = @{ 3, 9, 12 @};
  7259. @end example
  7260. @item
  7261. A component-wise initializer for a structure consists of field values
  7262. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7263. order as the fields are declared in the structure. If the values in
  7264. the initializer don't cover all the fields in the structure, the
  7265. remaining fields are initialized to zero.
  7266. @item
  7267. The initializer for a union-type variable has the form @code{@{
  7268. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7269. in the union definition.
  7270. @end itemize
  7271. For an array of arrays, a structure containing arrays, an array of
  7272. structures, etc., you can nest these constructs. For example,
  7273. @example
  7274. struct point @{ double x, y; @};
  7275. struct point series[]
  7276. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7277. @end example
  7278. You can omit a pair of inner braces if they contain the right
  7279. number of elements for the sub-value they initialize, so that
  7280. no elements or fields need to be filled in with zeros.
  7281. But don't do that very much, as it gets confusing.
  7282. An array of @code{char} can be initialized using a string constant.
  7283. Recall that the string constant includes an implicit null character at
  7284. the end (@pxref{String Constants}). Using a string constant as
  7285. initializer means to use its contents as the initial values of the
  7286. array elements. Here are examples:
  7287. @example
  7288. char text[6] = "text!"; /* @r{Includes the null.} */
  7289. char text[5] = "text!"; /* @r{Excludes the null.} */
  7290. char text[] = "text!"; /* @r{Gets length 6.} */
  7291. char text[]
  7292. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7293. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7294. @end example
  7295. @noindent
  7296. and this kind of initializer can be nested inside braces to initialize
  7297. structures or arrays that contain a @code{char}-array.
  7298. In like manner, you can use a wide string constant to initialize
  7299. an array of @code{wchar_t}.
  7300. @node Designated Inits
  7301. @section Designated Initializers
  7302. @cindex initializers with labeled elements
  7303. @cindex labeled elements in initializers
  7304. @cindex case labels in initializers
  7305. @cindex designated initializers
  7306. In a complex structure or long array, it's useful to indicate
  7307. which field or element we are initializing.
  7308. To designate specific array elements during initialization, include
  7309. the array index in brackets, and an assignment operator, for each
  7310. element:
  7311. @example
  7312. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7313. @end example
  7314. @noindent
  7315. This does the same thing as:
  7316. @example
  7317. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7318. @end example
  7319. The array initialization can include non-designated element values
  7320. alongside designated indices; these follow the expected ordering
  7321. of the array initialization, so that
  7322. @example
  7323. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7324. @end example
  7325. @noindent
  7326. does the same thing as:
  7327. @example
  7328. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7329. @end example
  7330. Note that you can only use constant expressions as array index values,
  7331. not variables.
  7332. If you need to initialize a subsequence of sequential array elements to
  7333. the same value, you can specify a range:
  7334. @example
  7335. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7336. @end example
  7337. @noindent
  7338. Using a range this way is a GNU C extension.
  7339. When subsequence ranges overlap, each element is initialized by the
  7340. last specification that applies to it. Thus, this initialization is
  7341. equivalent to the previous one.
  7342. @example
  7343. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7344. @end example
  7345. @noindent
  7346. as the second overrides the first for elements 0 through 19.
  7347. The value used to initialize a range of elements is evaluated only
  7348. once, for the first element in the range. So for example, this code
  7349. @example
  7350. int random_values[100]
  7351. = @{ [0 ... 99] = get_random_number() @};
  7352. @end example
  7353. @noindent
  7354. would initialize all 100 elements of the array @code{random_values} to
  7355. the same value---probably not what is intended.
  7356. Similarly, you can initialize specific fields of a structure variable
  7357. by specifying the field name prefixed with a dot:
  7358. @example
  7359. struct point @{ int x; int y; @};
  7360. struct point foo = @{ .y = 42; @};
  7361. @end example
  7362. @noindent
  7363. The same syntax works for union variables as well:
  7364. @example
  7365. union int_double @{ int i; double d; @};
  7366. union int_double foo = @{ .d = 34 @};
  7367. @end example
  7368. @noindent
  7369. This casts the integer value 34 to a double and stores it
  7370. in the union variable @code{foo}.
  7371. You can designate both array elements and structure elements in
  7372. the same initialization; for example, here's an array of point
  7373. structures:
  7374. @example
  7375. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7376. @end example
  7377. Along with the capability to specify particular array and structure
  7378. elements to initialize comes the possibility of initializing the same
  7379. element more than once:
  7380. @example
  7381. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7382. @end example
  7383. @noindent
  7384. In such a case, the last initialization value is retained.
  7385. @node Auto Type
  7386. @section Referring to a Type with @code{__auto_type}
  7387. @findex __auto_type
  7388. @findex typeof
  7389. @cindex macros, types of arguments
  7390. You can declare a variable copying the type from
  7391. the initializer by using @code{__auto_type} instead of a particular type.
  7392. Here's an example:
  7393. @example
  7394. #define max(a,b) \
  7395. (@{ __auto_type _a = (a); \
  7396. __auto_type _b = (b); \
  7397. _a > _b ? _a : _b @})
  7398. @end example
  7399. This defines @code{_a} to be of the same type as @code{a}, and
  7400. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7401. to do in a macro that ought to be able to handle any type of data
  7402. (@pxref{Macros and Auto Type}).
  7403. The original GNU C method for obtaining the type of a value is to use
  7404. @code{typeof}, which takes as an argument either a value or the name of
  7405. a type. The previous example could also be written as:
  7406. @example
  7407. #define max(a,b) \
  7408. (@{ typeof(a) _a = (a); \
  7409. typeof(b) _b = (b); \
  7410. _a > _b ? _a : _b @})
  7411. @end example
  7412. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7413. principal use case for @code{typeof} is in variable declarations with
  7414. initialization, which is exactly what @code{__auto_type} handles.
  7415. @node Local Variables
  7416. @section Local Variables
  7417. @cindex local variables
  7418. @cindex variables, local
  7419. Declaring a variable inside a function definition (@pxref{Function
  7420. Definitions}) makes the variable name @dfn{local} to the containing
  7421. block---that is, the containing pair of braces. More precisely, the
  7422. variable's name is visible starting just after where it appears in the
  7423. declaration, and its visibility continues until the end of the block.
  7424. Local variables in C are generally @dfn{automatic} variables: each
  7425. variable's storage exists only from the declaration to the end of the
  7426. block. Execution of the declaration allocates the storage, computes
  7427. the initial value, and stores it in the variable. The end of the
  7428. block deallocates the storage.@footnote{Due to compiler optimizations,
  7429. allocation and deallocation don't necessarily really happen at
  7430. those times.}
  7431. @strong{Warning:} Two declarations for the same local variable
  7432. in the same scope are an error.
  7433. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7434. The total space for the program's stack may be limited; therefore,
  7435. in using very large arrays, it may be necessary to allocate
  7436. them in some other way to stop the program from crashing.
  7437. @strong{Warning:} If the declaration of an automatic variable does not
  7438. specify an initial value, the variable starts out containing garbage.
  7439. In this example, the value printed could be anything at all:
  7440. @example
  7441. @{
  7442. int i;
  7443. printf ("Print junk %d\n", i);
  7444. @}
  7445. @end example
  7446. In a simple test program, that statement is likely to print 0, simply
  7447. because every process starts with memory zeroed. But don't rely on it
  7448. to be zero---that is erroneous.
  7449. @strong{Note:} Make sure to store a value into each local variable (by
  7450. assignment, or by initialization) before referring to its value.
  7451. @node File-Scope Variables
  7452. @section File-Scope Variables
  7453. @cindex file-scope variables
  7454. @cindex global variables
  7455. @cindex variables, file-scope
  7456. @cindex variables, global
  7457. A variable declaration at the top level in a file (not inside a
  7458. function definition) declares a @dfn{file-scope variable}. Loading a
  7459. program allocates the storage for all the file-scope variables in it,
  7460. and initializes them too.
  7461. Each file-scope variable is either @dfn{static} (limited to one
  7462. compilation module) or @dfn{global} (shared with all compilation
  7463. modules in the program). To make the variable static, write the
  7464. keyword @code{static} at the start of the declaration. Omitting
  7465. @code{static} makes the variable global.
  7466. The initial value for a file-scope variable can't depend on the
  7467. contents of storage, and can't call any functions.
  7468. @example
  7469. int foo = 5; /* @r{Valid.} */
  7470. int bar = foo; /* @r{Invalid!} */
  7471. int bar = sin (1.0); /* @r{Invalid!} */
  7472. @end example
  7473. But it can use the address of another file-scope variable:
  7474. @example
  7475. int foo;
  7476. int *bar = &foo; /* @r{Valid.} */
  7477. int arr[5];
  7478. int *bar3 = &arr[3]; /* @r{Valid.} */
  7479. int *bar4 = arr + 4; /* @r{Valid.} */
  7480. @end example
  7481. It is valid for a module to have multiple declarations for a
  7482. file-scope variable, as long as they are all global or all static, but
  7483. at most one declaration can specify an initial value for it.
  7484. @node Static Local Variables
  7485. @section Static Local Variables
  7486. @cindex static local variables
  7487. @cindex variables, static local
  7488. @findex static
  7489. The keyword @code{static} in a local variable declaration says to
  7490. allocate the storage for the variable permanently, just like a
  7491. file-scope variable, even if the declaration is within a function.
  7492. Here's an example:
  7493. @example
  7494. int
  7495. increment_counter ()
  7496. @{
  7497. static int counter = 0;
  7498. return ++counter;
  7499. @}
  7500. @end example
  7501. The scope of the name @code{counter} runs from the declaration to the
  7502. end of the containing block, just like an automatic local variable,
  7503. but its storage is permanent, so the value persists from one call to
  7504. the next. As a result, each call to @code{increment_counter}
  7505. returns a different, unique value.
  7506. The initial value of a static local variable has the same limitations
  7507. as for file-scope variables: it can't depend on the contents of
  7508. storage or call any functions. It can use the address of a file-scope
  7509. variable or a static local variable, because those addresses are
  7510. determined before the program runs.
  7511. @node Extern Declarations
  7512. @section @code{extern} Declarations
  7513. @cindex @code{extern} declarations
  7514. @cindex declarations, @code{extern}
  7515. @findex extern
  7516. An @code{extern} declaration is used to refer to a global variable
  7517. whose principal declaration comes elsewhere---in the same module, or in
  7518. another compilation module. It looks like this:
  7519. @example
  7520. extern @var{basetype} @var{decorated-variable};
  7521. @end example
  7522. Its meaning is that, in the current scope, the variable name refers to
  7523. the file-scope variable of that name---which needs to be declared in a
  7524. non-@code{extern}, non-@code{static} way somewhere else.
  7525. For instance, if one compilation module has this global variable
  7526. declaration
  7527. @example
  7528. int error_count = 0;
  7529. @end example
  7530. @noindent
  7531. then other compilation modules can specify this
  7532. @example
  7533. extern int error_count;
  7534. @end example
  7535. @noindent
  7536. to allow reference to the same variable.
  7537. The usual place to write an @code{extern} declaration is at top level
  7538. in a source file, but you can write an @code{extern} declaration
  7539. inside a block to make a global or static file-scope variable
  7540. accessible in that block.
  7541. Since an @code{extern} declaration does not allocate space for the
  7542. variable, it can omit the size of an array:
  7543. @example
  7544. extern int array[];
  7545. @end example
  7546. You can use @code{array} normally in all contexts where it is
  7547. converted automatically to a pointer. However, to use it as the
  7548. operand of @code{sizeof} is an error, since the size is unknown.
  7549. It is valid to have multiple @code{extern} declarations for the same
  7550. variable, even in the same scope, if they give the same type. They do
  7551. not conflict---they agree. For an array, it is legitimate for some
  7552. @code{extern} declarations can specify the size while others omit it.
  7553. However, if two declarations give different sizes, that is an error.
  7554. Likewise, you can use @code{extern} declarations at file scope
  7555. (@pxref{File-Scope Variables}) followed by an ordinary global
  7556. (non-static) declaration of the same variable. They do not conflict,
  7557. because they say compatible things about the same meaning of the variable.
  7558. @node Allocating File-Scope
  7559. @section Allocating File-Scope Variables
  7560. @cindex allocation file-scope variables
  7561. @cindex file-scope variables, allocating
  7562. Some file-scope declarations allocate space for the variable, and some
  7563. don't.
  7564. A file-scope declaration with an initial value @emph{must} allocate
  7565. space for the variable; if there are two of such declarations for the
  7566. same variable, even in different compilation modules, they conflict.
  7567. An @code{extern} declaration @emph{never} allocates space for the variable.
  7568. If all the top-level declarations of a certain variable are
  7569. @code{extern}, the variable never gets memory space. If that variable
  7570. is used anywhere in the program, the use will be reported as an error,
  7571. saying that the variable is not defined.
  7572. @cindex tentative definition
  7573. A file-scope declaration without an initial value is called a
  7574. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7575. allocate space for the variable, but does not insist. So it causes no
  7576. conflict, no error, if the variable has another declaration that
  7577. allocates space for it, perhaps in another compilation module. But if
  7578. nothing else allocates space for the variable, the tentative
  7579. definition will do it. Any number of compilation modules can declare
  7580. the same variable in this way, and that is sufficient for all of them
  7581. to use the variable.
  7582. @c @opindex -fno-common
  7583. @c @opindex --warn_common
  7584. In programs that are very large or have many contributors, it may be
  7585. wise to adopt the convention of never using tentative definitions.
  7586. You can use the compilation option @option{-fno-common} to make them
  7587. an error, or @option{--warn-common} to warn about them.
  7588. If a file-scope variable gets its space through a tentative
  7589. definition, it starts out containing all zeros.
  7590. @node auto and register
  7591. @section @code{auto} and @code{register}
  7592. @cindex @code{auto} declarations
  7593. @cindex @code{register} declarations
  7594. @findex auto
  7595. @findex register
  7596. For historical reasons, you can write @code{auto} or @code{register}
  7597. before a local variable declaration. @code{auto} merely emphasizes
  7598. that the variable isn't static; it changes nothing.
  7599. @code{register} suggests to the compiler storing this variable in a
  7600. register. However, GNU C ignores this suggestion, since it can
  7601. choose the best variables to store in registers without any hints.
  7602. It is an error to take the address of a variable declared
  7603. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7604. If the variable is an array, you can't use it at all (other than as
  7605. the operand of @code{sizeof}), which makes it rather useless.
  7606. @node Omitting Types
  7607. @section Omitting Types in Declarations
  7608. @cindex omitting types in declarations
  7609. The syntax of C traditionally allows omitting the data type in a
  7610. declaration if it specifies a storage class, a type qualifier (see the
  7611. next chapter), or @code{auto} or @code{register}. Then the type
  7612. defaults to @code{int}. For example:
  7613. @example
  7614. auto foo = 42;
  7615. @end example
  7616. This is bad practice; if you see it, fix it.
  7617. @node Type Qualifiers
  7618. @chapter Type Qualifiers
  7619. A declaration can include type qualifiers to advise the compiler
  7620. about how the variable will be used. There are three different
  7621. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7622. pertain to different issues, so you can use more than one together.
  7623. For instance, @code{const volatile} describes a value that the
  7624. program is not allowed to change, but might have a different value
  7625. each time the program examines it. (This might perhaps be a special
  7626. hardware register, or part of shared memory.)
  7627. If you are just learning C, you can skip this chapter.
  7628. @menu
  7629. * const:: Variables whose values don't change.
  7630. * volatile:: Variables whose values may be accessed
  7631. or changed outside of the control of
  7632. this program.
  7633. * restrict Pointers:: Restricted pointers for code optimization.
  7634. * restrict Pointer Example:: Example of how that works.
  7635. @end menu
  7636. @node const
  7637. @section @code{const} Variables and Fields
  7638. @cindex @code{const} variables and fields
  7639. @cindex variables, @code{const}
  7640. @findex const
  7641. You can mark a variable as ``constant'' by writing @code{const} in
  7642. front of the declaration. This says to treat any assignment to that
  7643. variable as an error. It may also permit some compiler
  7644. optimizations---for instance, to fetch the value only once to satisfy
  7645. multiple references to it. The construct looks like this:
  7646. @example
  7647. const double pi = 3.14159;
  7648. @end example
  7649. After this definition, the code can use the variable @code{pi}
  7650. but cannot assign a different value to it.
  7651. @example
  7652. pi = 3.0; /* @r{Error!} */
  7653. @end example
  7654. Simple variables that are constant can be used for the same purposes
  7655. as enumeration constants, and they are not limited to integers. The
  7656. constantness of the variable propagates into pointers, too.
  7657. A pointer type can specify that the @emph{target} is constant. For
  7658. example, the pointer type @code{const double *} stands for a pointer
  7659. to a constant @code{double}. That's the typethat results from taking
  7660. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7661. left side of an assignment.
  7662. @example
  7663. *(&pi) = 3.0; /* @r{Error!} */
  7664. @end example
  7665. Nonconstant pointers can be converted automatically to constant
  7666. pointers, but not vice versa. For instance,
  7667. @example
  7668. const double *cptr;
  7669. double *ptr;
  7670. cptr = &pi; /* @r{Valid.} */
  7671. cptr = ptr; /* @r{Valid.} */
  7672. ptr = cptr; /* @r{Error!} */
  7673. ptr = &pi; /* @r{Error!} */
  7674. @end example
  7675. This is not an ironclad protection against modifying the value. You
  7676. can always cast the constant pointer to a nonconstant pointer type:
  7677. @example
  7678. ptr = (double *)cptr; /* @r{Valid.} */
  7679. ptr = (double *)&pi; /* @r{Valid.} */
  7680. @end example
  7681. However, @code{const} provides a way to show that a certain function
  7682. won't modify the data structure whose address is passed to it. Here's
  7683. an example:
  7684. @example
  7685. int
  7686. string_length (const char *string)
  7687. @{
  7688. int count = 0;
  7689. while (*string++)
  7690. count++;
  7691. return count;
  7692. @}
  7693. @end example
  7694. @noindent
  7695. Using @code{const char *} for the parameter is a way of saying this
  7696. function never modifies the memory of the string itself.
  7697. In calling @code{string_length}, you can specify an ordinary
  7698. @code{char *} since that can be converted automatically to @code{const
  7699. char *}.
  7700. @node volatile
  7701. @section @code{volatile} Variables and Fields
  7702. @cindex @code{volatile} variables and fields
  7703. @cindex variables, @code{volatile}
  7704. @findex volatile
  7705. The GNU C compiler often performs optimizations that eliminate the
  7706. need to write or read a variable. For instance,
  7707. @example
  7708. int foo;
  7709. foo = 1;
  7710. foo++;
  7711. @end example
  7712. @noindent
  7713. might simply store the value 2 into @code{foo}, without ever storing 1.
  7714. These optimizations can also apply to structure fields in some cases.
  7715. If the memory containing @code{foo} is shared with another program,
  7716. or if it is examined asynchronously by hardware, such optimizations
  7717. could confuse the communication. Using @code{volatile} is one way
  7718. to prevent them.
  7719. Writing @code{volatile} with the type in a variable or field declaration
  7720. says that the value may be examined or changed for reasons outside the
  7721. control of the program at any moment. Therefore, the program must
  7722. execute in a careful way to assure correct interaction with those
  7723. accesses, whenever they may occur.
  7724. The simplest use looks like this:
  7725. @example
  7726. volatile int lock;
  7727. @end example
  7728. This directs the compiler not to do certain common optimizations on
  7729. use of the variable @code{lock}. All the reads and writes for a volatile
  7730. variable or field are really done, and done in the order specified
  7731. by the source code. Thus, this code:
  7732. @example
  7733. lock = 1;
  7734. list = list->next;
  7735. if (lock)
  7736. lock_broken (&lock);
  7737. lock = 0;
  7738. @end example
  7739. @noindent
  7740. really stores the value 1 in @code{lock}, even though there is no
  7741. sign it is really used, and the @code{if} statement reads and
  7742. checks the value of @code{lock}, rather than assuming it is still 1.
  7743. A limited amount of optimization can be done, in principle, on
  7744. @code{volatile} variables and fields: multiple references between two
  7745. sequence points (@pxref{Sequence Points}) can be simplified together.
  7746. Use of @code{volatile} does not eliminate the flexibility in ordering
  7747. the computation of the operands of most operators. For instance, in
  7748. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7749. @code{foo} is not specified, so they may be done in either order; the
  7750. fact that @code{lock} is @code{volatile} has no effect on that.
  7751. @node restrict Pointers
  7752. @section @code{restrict}-Qualified Pointers
  7753. @cindex @code{restrict} pointers
  7754. @cindex pointers, @code{restrict}-qualified
  7755. @findex restrict
  7756. You can declare a pointer as ``restricted'' using the @code{restrict}
  7757. type qualifier, like this:
  7758. @example
  7759. int *restrict p = x;
  7760. @end example
  7761. @noindent
  7762. This enables better optimization of code that uses the pointer.
  7763. If @code{p} is declared with @code{restrict}, and then the code
  7764. references the object that @code{p} points to (using @code{*p} or
  7765. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7766. code will not access that object in any other way---only through
  7767. @code{p}.
  7768. For instance, it means the code must not use another pointer
  7769. to access the same space, as shown here:
  7770. @example
  7771. int *restrict p = @var{whatever};
  7772. int *q = p;
  7773. foo (*p, *q);
  7774. @end example
  7775. @noindent
  7776. That contradicts the @code{restrict} promise by accessing the object
  7777. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7778. Likewise, it must not do this:
  7779. @example
  7780. int *restrict p = @var{whatever};
  7781. struct @{ int *a, *b; @} s;
  7782. s.a = p;
  7783. foo (*p, *s.a);
  7784. @end example
  7785. @noindent
  7786. This example uses a structure field instead of the variable @code{q}
  7787. to hold the other pointer, and that contradicts the promise just the
  7788. same.
  7789. The keyword @code{restrict} also promises that @code{p} won't point to
  7790. the allocated space of any automatic or static variable. So the code
  7791. must not do this:
  7792. @example
  7793. int a;
  7794. int *restrict p = &a;
  7795. foo (*p, a);
  7796. @end example
  7797. @noindent
  7798. because that does direct access to the object (@code{a}) that @code{p}
  7799. points to, which bypasses @code{p}.
  7800. If the code makes such promises with @code{restrict} then breaks them,
  7801. execution is unpredictable.
  7802. @node restrict Pointer Example
  7803. @section @code{restrict} Pointer Example
  7804. Here are examples where @code{restrict} enables real optimization.
  7805. In this example, @code{restrict} assures GCC that the array @code{out}
  7806. points to does not overlap with the array @code{in} points to.
  7807. @example
  7808. void
  7809. process_data (const char *in,
  7810. char * restrict out,
  7811. size_t size)
  7812. @{
  7813. for (i = 0; i < size; i++)
  7814. out[i] = in[i] + in[i + 1];
  7815. @}
  7816. @end example
  7817. Here's a simple tree structure, where each tree node holds data of
  7818. type @code{PAYLOAD} plus two subtrees.
  7819. @example
  7820. struct foo
  7821. @{
  7822. PAYLOAD payload;
  7823. struct foo *left;
  7824. struct foo *right;
  7825. @};
  7826. @end example
  7827. Now here's a function to null out both pointers in the @code{left}
  7828. subtree.
  7829. @example
  7830. void
  7831. null_left (struct foo *a)
  7832. @{
  7833. a->left->left = NULL;
  7834. a->left->right = NULL;
  7835. @}
  7836. @end example
  7837. Since @code{*a} and @code{*a->left} have the same data type,
  7838. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7839. the compiled code for @code{null_left} must read @code{a->left}
  7840. again from memory when executing the second assignment statement.
  7841. We can enable optimization, so that it does not need to read
  7842. @code{a->left} again, by writing @code{null_left} this in a less
  7843. obvious way.
  7844. @example
  7845. void
  7846. null_left (struct foo *a)
  7847. @{
  7848. struct foo *b = a->left;
  7849. b->left = NULL;
  7850. b->right = NULL;
  7851. @}
  7852. @end example
  7853. A more elegant way to fix this is with @code{restrict}.
  7854. @example
  7855. void
  7856. null_left (struct foo *restrict a)
  7857. @{
  7858. a->left->left = NULL;
  7859. a->left->right = NULL;
  7860. @}
  7861. @end example
  7862. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7863. as @code{a->left} will not point to the same memory space as @code{a}.
  7864. Therefore, the memory location @code{a->left->left} cannot be the same
  7865. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7866. reloading @code{a->left} for the second statement.
  7867. @node Functions
  7868. @chapter Functions
  7869. @cindex functions
  7870. We have already presented many examples of functions, so if you've
  7871. read this far, you basically understand the concept of a function. It
  7872. is vital, nonetheless, to have a chapter in the manual that collects
  7873. all the information about functions.
  7874. @menu
  7875. * Function Definitions:: Writing the body of a function.
  7876. * Function Declarations:: Declaring the interface of a function.
  7877. * Function Calls:: Using functions.
  7878. * Function Call Semantics:: Call-by-value argument passing.
  7879. * Function Pointers:: Using references to functions.
  7880. * The main Function:: Where execution of a GNU C program begins.
  7881. * Advanced Definitions:: Advanced features of function definitions.
  7882. * Obsolete Definitions:: Obsolete features still used
  7883. in function definitions in old code.
  7884. @end menu
  7885. @node Function Definitions
  7886. @section Function Definitions
  7887. @cindex function definitions
  7888. @cindex defining functions
  7889. We have already presented many examples of function definitions. To
  7890. summarize the rules, a function definition looks like this:
  7891. @example
  7892. @var{returntype}
  7893. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7894. @{
  7895. @var{body}
  7896. @}
  7897. @end example
  7898. The part before the open-brace is called the @dfn{function header}.
  7899. Write @code{void} as the @var{returntype} if the function does
  7900. not return a value.
  7901. @menu
  7902. * Function Parameter Variables:: Syntax and semantics
  7903. of function parameters.
  7904. * Forward Function Declarations:: Functions can only be called after
  7905. they have been defined or declared.
  7906. * Static Functions:: Limiting visibility of a function.
  7907. * Arrays as Parameters:: Functions that accept array arguments.
  7908. * Structs as Parameters:: Functions that accept structure arguments.
  7909. @end menu
  7910. @node Function Parameter Variables
  7911. @subsection Function Parameter Variables
  7912. @cindex function parameter variables
  7913. @cindex parameter variables in functions
  7914. @cindex parameter list
  7915. A function parameter variable is a local variable (@pxref{Local
  7916. Variables}) used within the function to store the value passed as an
  7917. argument in a call to the function. Usually we say ``function
  7918. parameter'' or ``parameter'' for short, not mentioning the fact that
  7919. it's a variable.
  7920. We declare these variables in the beginning of the function
  7921. definition, in the @dfn{parameter list}. For example,
  7922. @example
  7923. fib (int n)
  7924. @end example
  7925. @noindent
  7926. has a parameter list with one function parameter @code{n}, which has
  7927. type @code{int}.
  7928. Function parameter declarations differ from ordinary variable
  7929. declarations in several ways:
  7930. @itemize @bullet
  7931. @item
  7932. Inside the function definition header, commas separate parameter
  7933. declarations, and each parameter needs a complete declaration
  7934. including the type. For instance, if a function @code{foo} has two
  7935. @code{int} parameters, write this:
  7936. @example
  7937. foo (int a, int b)
  7938. @end example
  7939. You can't share the common @code{int} between the two declarations:
  7940. @example
  7941. foo (int a, b) /* @r{Invalid!} */
  7942. @end example
  7943. @item
  7944. A function parameter variable is initialized to whatever value is
  7945. passed in the function call, so its declaration cannot specify an
  7946. initial value.
  7947. @item
  7948. Writing an array type in a function parameter declaration has the
  7949. effect of declaring it as a pointer. The size specified for the array
  7950. has no effect at all, and we normally omit the size. Thus,
  7951. @example
  7952. foo (int a[5])
  7953. foo (int a[])
  7954. foo (int *a)
  7955. @end example
  7956. @noindent
  7957. are equivalent.
  7958. @item
  7959. The scope of the parameter variables is the entire function body,
  7960. notwithstanding the fact that they are written in the function header,
  7961. which is just outside the function body.
  7962. @end itemize
  7963. If a function has no parameters, it would be most natural for the
  7964. list of parameters in its definition to be empty. But that, in C, has
  7965. a special meaning for historical reasons: ``Do not check that calls to
  7966. this function have the right number of arguments.'' Thus,
  7967. @example
  7968. int
  7969. foo ()
  7970. @{
  7971. return 5;
  7972. @}
  7973. int
  7974. bar (int x)
  7975. @{
  7976. return foo (x);
  7977. @}
  7978. @end example
  7979. @noindent
  7980. would not report a compilation error in passing @code{x} as an
  7981. argument to @code{foo}. By contrast,
  7982. @example
  7983. int
  7984. foo (void)
  7985. @{
  7986. return 5;
  7987. @}
  7988. int
  7989. bar (int x)
  7990. @{
  7991. return foo (x);
  7992. @}
  7993. @end example
  7994. @noindent
  7995. would report an error because @code{foo} is supposed to receive
  7996. no arguments.
  7997. @node Forward Function Declarations
  7998. @subsection Forward Function Declarations
  7999. @cindex forward function declarations
  8000. @cindex function declarations, forward
  8001. The order of the function definitions in the source code makes no
  8002. difference, except that each function needs to be defined or declared
  8003. before code uses it.
  8004. The definition of a function also declares its name for the rest of
  8005. the containing scope. But what if you want to call the function
  8006. before its definition? To permit that, write a compatible declaration
  8007. of the same function, before the first call. A declaration that
  8008. prefigures a subsequent definition in this way is called a
  8009. @dfn{forward declaration}. The function declaration can be at top
  8010. @c ??? file scope
  8011. level or within a block, and it applies until the end of the containing
  8012. scope.
  8013. @xref{Function Declarations}, for more information about these
  8014. declarations.
  8015. @node Static Functions
  8016. @subsection Static Functions
  8017. @cindex static functions
  8018. @cindex functions, static
  8019. @findex static
  8020. The keyword @code{static} in a function definition limits the
  8021. visibility of the name to the current compilation module. (That's the
  8022. same thing @code{static} does in variable declarations;
  8023. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8024. contains this code:
  8025. @example
  8026. static int
  8027. foo (void)
  8028. @{
  8029. @r{@dots{}}
  8030. @}
  8031. @end example
  8032. @noindent
  8033. then the code of that compilation module can call @code{foo} anywhere
  8034. after the definition, but other compilation modules cannot refer to it
  8035. at all.
  8036. @cindex forward declaration
  8037. @cindex static function, declaration
  8038. To call @code{foo} before its definition, it needs a forward
  8039. declaration, which should use @code{static} since the function
  8040. definition does. For this function, it looks like this:
  8041. @example
  8042. static int foo (void);
  8043. @end example
  8044. It is generally wise to use @code{static} on the definitions of
  8045. functions that won't be called from outside the same compilation
  8046. module. This makes sure that calls are not added in other modules.
  8047. If programmers decide to change the function's calling convention, or
  8048. understand all the consequences of its use, they will only have to
  8049. check for calls in the same compilation module.
  8050. @node Arrays as Parameters
  8051. @subsection Arrays as Parameters
  8052. @cindex array as parameters
  8053. @cindex functions with array parameters
  8054. Arrays in C are not first-class objects: it is impossible to copy
  8055. them. So they cannot be passed as arguments like other values.
  8056. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8057. a special way.
  8058. @menu
  8059. * Array Parm Pointer::
  8060. * Passing Array Args::
  8061. * Array Parm Qualifiers::
  8062. @end menu
  8063. @node Array Parm Pointer
  8064. @subsubsection Array parameters are pointers
  8065. Declaring a function parameter variable as an array really gives it a
  8066. pointer type. C does this because an expression with array type, if
  8067. used as an argument in a function call, is converted automatically to
  8068. a pointer (to the zeroth element of the array). If you declare the
  8069. corresponding parameter as an ``array'', it will work correctly with
  8070. the pointer value that really gets passed.
  8071. This relates to the fact that C does not check array bounds in access
  8072. to elements of the array (@pxref{Accessing Array Elements}).
  8073. For example, in this function,
  8074. @example
  8075. void
  8076. clobber4 (int array[20])
  8077. @{
  8078. array[4] = 0;
  8079. @}
  8080. @end example
  8081. @noindent
  8082. the parameter @code{array}'s real type is @code{int *}; the specified
  8083. length, 20, has no effect on the program. You can leave out the length
  8084. and write this:
  8085. @example
  8086. void
  8087. clobber4 (int array[])
  8088. @{
  8089. array[4] = 0;
  8090. @}
  8091. @end example
  8092. @noindent
  8093. or write the parameter declaration explicitly as a pointer:
  8094. @example
  8095. void
  8096. clobber4 (int *array)
  8097. @{
  8098. array[4] = 0;
  8099. @}
  8100. @end example
  8101. They are all equivalent.
  8102. @node Passing Array Args
  8103. @subsubsection Passing array arguments
  8104. The function call passes this pointer by
  8105. value, like all argument values in C@. However, the result is
  8106. paradoxical in that the array itself is passed by reference: its
  8107. contents are treated as shared memory---shared between the caller and
  8108. the called function, that is. When @code{clobber4} assigns to element
  8109. 4 of @code{array}, the effect is to alter element 4 of the array
  8110. specified in the call.
  8111. @example
  8112. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8113. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8114. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8115. int
  8116. main (void)
  8117. @{
  8118. int data[] = @{1, 2, 3, 4, 5, 6@};
  8119. int i;
  8120. /* @r{Show the initial value of element 4.} */
  8121. for (i = 0; i < 6; i++)
  8122. printf ("data[%d] = %d\n", i, data[i]);
  8123. printf ("\n");
  8124. clobber4 (data);
  8125. /* @r{Show that element 4 has been changed.} */
  8126. for (i = 0; i < 6; i++)
  8127. printf ("data[%d] = %d\n", i, data[i]);
  8128. printf ("\n");
  8129. return EXIT_SUCCESS;
  8130. @}
  8131. @end example
  8132. @noindent
  8133. shows that @code{data[4]} has become zero after the call to
  8134. @code{clobber4}.
  8135. The array @code{data} has 6 elements, but passing it to a function
  8136. whose argument type is written as @code{int [20]} is not an error,
  8137. because that really stands for @code{int *}. The pointer that is the
  8138. real argument carries no indication of the length of the array it
  8139. points into. It is not required to point to the beginning of the
  8140. array, either. For instance,
  8141. @example
  8142. clobber4 (data+1);
  8143. @end example
  8144. @noindent
  8145. passes an ``array'' that starts at element 1 of @code{data}, and the
  8146. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8147. If all calls to the function will provide an array of a particular
  8148. size, you can specify the size of the array to be @code{static}:
  8149. @example
  8150. void
  8151. clobber4 (int array[static 20])
  8152. @r{@dots{}}
  8153. @end example
  8154. @noindent
  8155. This is a promise to the compiler that the function will always be
  8156. called with an array of 20 elements, so that the compiler can optimize
  8157. code accordingly. If the code breaks this promise and calls the
  8158. function with, for example, a shorter array, unpredictable things may
  8159. happen.
  8160. @node Array Parm Qualifiers
  8161. @subsubsection Type qualifiers on array parameters
  8162. You can use the type qualifiers @code{const}, @code{restrict}, and
  8163. @code{volatile} with array parameters; for example:
  8164. @example
  8165. void
  8166. clobber4 (volatile int array[20])
  8167. @r{@dots{}}
  8168. @end example
  8169. @noindent
  8170. denotes that @code{array} is equivalent to a pointer to a volatile
  8171. @code{int}. Alternatively:
  8172. @example
  8173. void
  8174. clobber4 (int array[const 20])
  8175. @r{@dots{}}
  8176. @end example
  8177. @noindent
  8178. makes the array parameter equivalent to a constant pointer to an
  8179. @code{int}. If we want the @code{clobber4} function to succeed, it
  8180. would not make sense to write
  8181. @example
  8182. void
  8183. clobber4 (const int array[20])
  8184. @r{@dots{}}
  8185. @end example
  8186. @noindent
  8187. as this would tell the compiler that the parameter should point to an
  8188. array of constant @code{int} values, and then we would not be able to
  8189. store zeros in them.
  8190. In a function with multiple array parameters, you can use @code{restrict}
  8191. to tell the compiler that each array parameter passed in will be distinct:
  8192. @example
  8193. void
  8194. foo (int array1[restrict 10], int array2[restrict 10])
  8195. @r{@dots{}}
  8196. @end example
  8197. @noindent
  8198. Using @code{restrict} promises the compiler that callers will
  8199. not pass in the same array for more than one @code{restrict} array
  8200. parameter. Knowing this enables the compiler to perform better code
  8201. optimization. This is the same effect as using @code{restrict}
  8202. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8203. the code that an array of a specific size is expected.
  8204. @node Structs as Parameters
  8205. @subsection Functions That Accept Structure Arguments
  8206. Structures in GNU C are first-class objects, so using them as function
  8207. parameters and arguments works in the natural way. This function
  8208. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8209. and returns a structure of the same type but with the fields
  8210. exchanged.
  8211. @example
  8212. struct foo @{ int a, b; @};
  8213. struct foo x;
  8214. struct foo
  8215. swapfoo (struct foo inval)
  8216. @{
  8217. struct foo outval;
  8218. outval.a = inval.b;
  8219. outval.b = inval.a;
  8220. return outval;
  8221. @}
  8222. @end example
  8223. This simpler definition of @code{swapfoo} avoids using a local
  8224. variable to hold the result about to be return, by using a structure
  8225. constructor (@pxref{Structure Constructors}), like this:
  8226. @example
  8227. struct foo
  8228. swapfoo (struct foo inval)
  8229. @{
  8230. return (struct foo) @{ inval.b, inval.a @};
  8231. @}
  8232. @end example
  8233. It is valid to define a structure type in a function's parameter list,
  8234. as in
  8235. @example
  8236. int
  8237. frob_bar (struct bar @{ int a, b; @} inval)
  8238. @{
  8239. @var{body}
  8240. @}
  8241. @end example
  8242. @noindent
  8243. and @var{body} can access the fields of @var{inval} since the
  8244. structure type @code{struct bar} is defined for the whole function
  8245. body. However, there is no way to create a @code{struct bar} argument
  8246. to pass to @code{frob_bar}, except with kludges. As a result,
  8247. defining a structure type in a parameter list is useless in practice.
  8248. @node Function Declarations
  8249. @section Function Declarations
  8250. @cindex function declarations
  8251. @cindex declararing functions
  8252. To call a function, or use its name as a pointer, a @dfn{function
  8253. declaration} for the function name must be in effect at that point in
  8254. the code. The function's definition serves as a declaration of that
  8255. function for the rest of the containing scope, but to use the function
  8256. in code before the definition, or from another compilation module, a
  8257. separate function declaration must precede the use.
  8258. A function declaration looks like the start of a function definition.
  8259. It begins with the return value type (@code{void} if none) and the
  8260. function name, followed by argument declarations in parentheses
  8261. (though these can sometimes be omitted). But that's as far as the
  8262. similarity goes: instead of the function body, the declaration uses a
  8263. semicolon.
  8264. @cindex function prototype
  8265. @cindex prototype of a function
  8266. A declaration that specifies argument types is called a @dfn{function
  8267. prototype}. You can include the argument names or omit them. The
  8268. names, if included in the declaration, have no effect, but they may
  8269. serve as documentation.
  8270. This form of prototype specifies fixed argument types:
  8271. @example
  8272. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8273. @end example
  8274. @noindent
  8275. This form says the function takes no arguments:
  8276. @example
  8277. @var{rettype} @var{function} (void);
  8278. @end example
  8279. @noindent
  8280. This form declares types for some arguments, and allows additional
  8281. arguments whose types are not specified:
  8282. @example
  8283. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8284. @end example
  8285. For a parameter that's an array of variable length, you can write
  8286. its declaration with @samp{*} where the ``length'' of the array would
  8287. normally go; for example, these are all equivalent.
  8288. @example
  8289. double maximum (int n, int m, double a[n][m]);
  8290. double maximum (int n, int m, double a[*][*]);
  8291. double maximum (int n, int m, double a[ ][*]);
  8292. double maximum (int n, int m, double a[ ][m]);
  8293. @end example
  8294. @noindent
  8295. The old-fashioned form of declaration, which is not a prototype, says
  8296. nothing about the types of arguments or how many they should be:
  8297. @example
  8298. @var{rettype} @var{function} ();
  8299. @end example
  8300. @strong{Warning:} Arguments passed to a function declared without a
  8301. prototype are converted with the default argument promotions
  8302. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8303. types are unspecified.
  8304. Function declarations are usually written at the top level in a source file,
  8305. but you can also put them inside code blocks. Then the function name
  8306. is visible for the rest of the containing scope. For example:
  8307. @example
  8308. void
  8309. foo (char *file_name)
  8310. @{
  8311. void save_file (char *);
  8312. save_file (file_name);
  8313. @}
  8314. @end example
  8315. If another part of the code tries to call the function
  8316. @code{save_file}, this declaration won't be in effect there. So the
  8317. function will get an implicit declaration of the form @code{extern int
  8318. save_file ();}. That conflicts with the explicit declaration
  8319. here, and the discrepancy generates a warning.
  8320. The syntax of C traditionally allows omitting the data type in a
  8321. function declaration if it specifies a storage class or a qualifier.
  8322. Then the type defaults to @code{int}. For example:
  8323. @example
  8324. static foo (double x);
  8325. @end example
  8326. @noindent
  8327. defaults the return type to @code{int}.
  8328. This is bad practice; if you see it, fix it.
  8329. Calling a function that is undeclared has the effect of an creating
  8330. @dfn{implicit} declaration in the innermost containing scope,
  8331. equivalent to this:
  8332. @example
  8333. extern int @dfn{function} ();
  8334. @end example
  8335. @noindent
  8336. This declaration says that the function returns @code{int} but leaves
  8337. its argument types unspecified. If that does not accurately fit the
  8338. function, then the program @strong{needs} an explicit declaration of
  8339. the function with argument types in order to call it correctly.
  8340. Implicit declarations are deprecated, and a function call that creates one
  8341. causes a warning.
  8342. @node Function Calls
  8343. @section Function Calls
  8344. @cindex function calls
  8345. @cindex calling functions
  8346. Starting a program automatically calls the function named @code{main}
  8347. (@pxref{The main Function}). Aside from that, a function does nothing
  8348. except when it is @dfn{called}. That occurs during the execution of a
  8349. function-call expression specifying that function.
  8350. A function-call expression looks like this:
  8351. @example
  8352. @var{function} (@var{arguments}@r{@dots{}})
  8353. @end example
  8354. Most of the time, @var{function} is a function name. However, it can
  8355. also be an expression with a function pointer value; that way, the
  8356. program can determine at run time which function to call.
  8357. The @var{arguments} are a series of expressions separated by commas.
  8358. Each expression specifies one argument to pass to the function.
  8359. The list of arguments in a function call looks just like use of the
  8360. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8361. the parentheses of a function call gives it a different meaning.
  8362. Here's an example of a function call, taken from an example near the
  8363. beginning (@pxref{Complete Program}).
  8364. @example
  8365. printf ("Fibonacci series item %d is %d\n",
  8366. 19, fib (19));
  8367. @end example
  8368. The three arguments given to @code{printf} are a constant string, the
  8369. integer 19, and the integer returned by @code{fib (19)}.
  8370. @node Function Call Semantics
  8371. @section Function Call Semantics
  8372. @cindex function call semantics
  8373. @cindex semantics of function calls
  8374. @cindex call-by-value
  8375. The meaning of a function call is to compute the specified argument
  8376. expressions, convert their values according to the function's
  8377. declaration, then run the function giving it copies of the converted
  8378. values. (This method of argument passing is known as
  8379. @dfn{call-by-value}.) When the function finishes, the value it
  8380. returns becomes the value of the function-call expression.
  8381. Call-by-value implies that an assignment to the function argument
  8382. variable has no direct effect on the caller. For instance,
  8383. @example
  8384. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8385. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8386. void
  8387. subroutine (int x)
  8388. @{
  8389. x = 5;
  8390. @}
  8391. void
  8392. main (void)
  8393. @{
  8394. int y = 20;
  8395. subroutine (y);
  8396. printf ("y is %d\n", y);
  8397. return EXIT_SUCCESS;
  8398. @}
  8399. @end example
  8400. @noindent
  8401. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8402. from the value of @code{y}, but this does not establish any other
  8403. relationship between the two variables. Thus, the assignment to
  8404. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8405. If an argument's type is specified by the function's declaration, the
  8406. function call converts the argument expression to that type if
  8407. possible. If the conversion is impossible, that is an error.
  8408. If the function's declaration doesn't specify the type of that
  8409. argument, then the @emph{default argument promotions} apply.
  8410. @xref{Argument Promotions}.
  8411. @node Function Pointers
  8412. @section Function Pointers
  8413. @cindex function pointers
  8414. @cindex pointers to functions
  8415. A function name refers to a fixed function. Sometimes it is useful to
  8416. call a function to be determined at run time; to do this, you can use
  8417. a @dfn{function pointer value} that points to the chosen function
  8418. (@pxref{Pointers}).
  8419. Pointer-to-function types can be used to declare variables and other
  8420. data, including array elements, structure fields, and union
  8421. alternatives. They can also be used for function arguments and return
  8422. values. These types have the peculiarity that they are never
  8423. converted automatically to @code{void *} or vice versa. However, you
  8424. can do that conversion with a cast.
  8425. @menu
  8426. * Declaring Function Pointers:: How to declare a pointer to a function.
  8427. * Assigning Function Pointers:: How to assign values to function pointers.
  8428. * Calling Function Pointers:: How to call functions through pointers.
  8429. @end menu
  8430. @node Declaring Function Pointers
  8431. @subsection Declaring Function Pointers
  8432. @cindex declaring function pointers
  8433. @cindex function pointers, declaring
  8434. The declaration of a function pointer variable (or structure field)
  8435. looks almost like a function declaration, except it has an additional
  8436. @samp{*} just before the variable name. Proper nesting requires a
  8437. pair of parentheses around the two of them. For instance, @code{int
  8438. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8439. an @code{int}-returning function.''
  8440. Contrast these three declarations:
  8441. @example
  8442. /* @r{Declare a function returning @code{char *}.} */
  8443. char *a (char *);
  8444. /* @r{Declare a pointer to a function returning @code{char}.} */
  8445. char (*a) (char *);
  8446. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8447. char *(*a) (char *);
  8448. @end example
  8449. The possible argument types of the function pointed to are the same
  8450. as in a function declaration. You can write a prototype
  8451. that specifies all the argument types:
  8452. @example
  8453. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8454. @end example
  8455. @noindent
  8456. or one that specifies some and leaves the rest unspecified:
  8457. @example
  8458. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8459. @end example
  8460. @noindent
  8461. or one that says there are no arguments:
  8462. @example
  8463. @var{rettype} (*@var{function}) (void);
  8464. @end example
  8465. You can also write a non-prototype declaration that says
  8466. nothing about the argument types:
  8467. @example
  8468. @var{rettype} (*@var{function}) ();
  8469. @end example
  8470. For example, here's a declaration for a variable that should
  8471. point to some arithmetic function that operates on two @code{double}s:
  8472. @example
  8473. double (*binary_op) (double, double);
  8474. @end example
  8475. Structure fields, union alternatives, and array elements can be
  8476. function pointers; so can parameter variables. The function pointer
  8477. declaration construct can also be combined with other operators
  8478. allowed in declarations. For instance,
  8479. @example
  8480. int **(*foo)();
  8481. @end example
  8482. @noindent
  8483. declares @code{foo} as a pointer to a function that returns
  8484. type @code{int **}, and
  8485. @example
  8486. int **(*foo[30])();
  8487. @end example
  8488. @noindent
  8489. declares @code{foo} as an array of 30 pointers to functions that
  8490. return type @code{int **}.
  8491. @example
  8492. int **(**foo)();
  8493. @end example
  8494. @noindent
  8495. declares @code{foo} as a pointer to a pointer to a function that
  8496. returns type @code{int **}.
  8497. @node Assigning Function Pointers
  8498. @subsection Assigning Function Pointers
  8499. @cindex assigning function pointers
  8500. @cindex function pointers, assigning
  8501. Assuming we have declared the variable @code{binary_op} as in the
  8502. previous section, giving it a value requires a suitable function to
  8503. use. So let's define a function suitable for the variable to point
  8504. to. Here's one:
  8505. @example
  8506. double
  8507. double_add (double a, double b)
  8508. @{
  8509. return a+b;
  8510. @}
  8511. @end example
  8512. Now we can give it a value:
  8513. @example
  8514. binary_op = double_add;
  8515. @end example
  8516. The target type of the function pointer must be upward compatible with
  8517. the type of the function (@pxref{Compatible Types}).
  8518. There is no need for @samp{&} in front of @code{double_add}.
  8519. Using a function name such as @code{double_add} as an expression
  8520. automatically converts it to the function's address, with the
  8521. appropriate function pointer type. However, it is ok to use
  8522. @samp{&} if you feel that is clearer:
  8523. @example
  8524. binary_op = &double_add;
  8525. @end example
  8526. @node Calling Function Pointers
  8527. @subsection Calling Function Pointers
  8528. @cindex calling function pointers
  8529. @cindex function pointers, calling
  8530. To call the function specified by a function pointer, just write the
  8531. function pointer value in a function call. For instance, here's a
  8532. call to the function @code{binary_op} points to:
  8533. @example
  8534. binary_op (x, 5)
  8535. @end example
  8536. Since the data type of @code{binary_op} explicitly specifies type
  8537. @code{double} for the arguments, the call converts @code{x} and 5 to
  8538. @code{double}.
  8539. The call conceptually dereferences the pointer @code{binary_op} to
  8540. ``get'' the function it points to, and calls that function. If you
  8541. wish, you can explicitly represent the derefence by writing the
  8542. @code{*} operator:
  8543. @example
  8544. (*binary_op) (x, 5)
  8545. @end example
  8546. The @samp{*} reminds people reading the code that @code{binary_op} is
  8547. a function pointer rather than the name of a specific function.
  8548. @node The main Function
  8549. @section The @code{main} Function
  8550. @cindex @code{main} function
  8551. @findex main
  8552. Every complete executable program requires at least one function,
  8553. called @code{main}, which is where execution begins. You do not have
  8554. to explicitly declare @code{main}, though GNU C permits you to do so.
  8555. Conventionally, @code{main} should be defined to follow one of these
  8556. calling conventions:
  8557. @example
  8558. int main (void) @{@r{@dots{}}@}
  8559. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8560. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8561. @end example
  8562. @noindent
  8563. Using @code{void} as the parameter list means that @code{main} does
  8564. not use the arguments. You can write @code{char **argv} instead of
  8565. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8566. constructs are equivalent.
  8567. @ignore @c Not so at present
  8568. Defining @code{main} in any other way generates a warning. Your
  8569. program will still compile, but you may get unexpected results when
  8570. executing it.
  8571. @end ignore
  8572. You can call @code{main} from C code, as you can call any other
  8573. function, though that is an unusual thing to do. When you do that,
  8574. you must write the call to pass arguments that match the parameters in
  8575. the definition of @code{main}.
  8576. The @code{main} function is not actually the first code that runs when
  8577. a program starts. In fact, the first code that runs is system code
  8578. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8579. code, but in GNU we replaced it with C code. Its job is to find
  8580. the arguments for @code{main} and call that.
  8581. @menu
  8582. * Values from main:: Returning values from the main function.
  8583. * Command-line Parameters:: Accessing command-line parameters
  8584. provided to the program.
  8585. * Environment Variables:: Accessing system environment variables.
  8586. @end menu
  8587. @node Values from main
  8588. @subsection Returning Values from @code{main}
  8589. @cindex returning values from @code{main}
  8590. @cindex success
  8591. @cindex failure
  8592. @cindex exit status
  8593. When @code{main} returns, the process terminates. Whatever value
  8594. @code{main} returns becomes the exit status which is reported to the
  8595. parent process. While nominally the return value is of type
  8596. @code{int}, in fact the exit status gets truncated to eight bits; if
  8597. @code{main} returns the value 256, the exit status is 0.
  8598. Normally, programs return only one of two values: 0 for success,
  8599. and 1 for failure. For maximum portability, use the macro
  8600. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8601. @code{stdlib.h}. Here's an example:
  8602. @cindex @code{EXIT_FAILURE}
  8603. @cindex @code{EXIT_SUCCESS}
  8604. @example
  8605. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8606. /* @r{and @code{EXIT_FAILURE}.} */
  8607. int
  8608. main (void)
  8609. @{
  8610. @r{@dots{}}
  8611. if (foo)
  8612. return EXIT_SUCCESS;
  8613. else
  8614. return EXIT_FAILURE;
  8615. @}
  8616. @end example
  8617. Some types of programs maintain special conventions for various return
  8618. values; for example, comparison programs including @code{cmp} and
  8619. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8620. the comparison couldn't be performed.
  8621. @node Command-line Parameters
  8622. @subsection Accessing Command-line Parameters
  8623. @cindex command-line parameters
  8624. @cindex parameters, command-line
  8625. If the program was invoked with any command-line arguments, it can
  8626. access them through the arguments of @code{main}, @code{argc} and
  8627. @code{argv}. (You can give these arguments any names, but the names
  8628. @code{argc} and @code{argv} are customary.)
  8629. The value of @code{argv} is an array containing all of the
  8630. command-line arguments as strings, with the name of the command
  8631. invoked as the first string. @code{argc} is an integer that says how
  8632. many strings @code{argv} contains. Here is an example of accessing
  8633. the command-line parameters, retrieving the program's name and
  8634. checking for the standard @option{--version} and @option{--help} options:
  8635. @example
  8636. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8637. int
  8638. main (int argc, char *argv[])
  8639. @{
  8640. char *program_name = argv[0];
  8641. for (int i = 1; i < argc; i++)
  8642. @{
  8643. if (!strcmp (argv[i], "--version"))
  8644. @{
  8645. /* @r{Print version information and exit.} */
  8646. @r{@dots{}}
  8647. @}
  8648. else if (!strcmp (argv[i], "--help"))
  8649. @{
  8650. /* @r{Print help information and exit.} */
  8651. @r{@dots{}}
  8652. @}
  8653. @}
  8654. @r{@dots{}}
  8655. @}
  8656. @end example
  8657. @node Environment Variables
  8658. @subsection Accessing Environment Variables
  8659. @cindex environment variables
  8660. You can optionally include a third parameter to @code{main}, another
  8661. array of strings, to capture the environment variables available to
  8662. the program. Unlike what happens with @code{argv}, there is no
  8663. additional parameter for the count of environment variables; rather,
  8664. the array of environment variables concludes with a null pointer.
  8665. @example
  8666. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8667. int
  8668. main (int argc, char *argv[], char *envp[])
  8669. @{
  8670. /* @r{Print out all environment variables.} */
  8671. int i = 0;
  8672. while (envp[i])
  8673. @{
  8674. printf ("%s\n", envp[i]);
  8675. i++;
  8676. @}
  8677. @}
  8678. @end example
  8679. Another method of retrieving environment variables is to use the
  8680. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8681. Using @code{getenv} does not require defining @code{main} to accept the
  8682. @code{envp} pointer. For example, here is a program that fetches and prints
  8683. the user's home directory (if defined):
  8684. @example
  8685. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8686. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8687. int
  8688. main (void)
  8689. @{
  8690. char *home_directory = getenv ("HOME");
  8691. if (home_directory)
  8692. printf ("My home directory is: %s\n", home_directory);
  8693. else
  8694. printf ("My home directory is not defined!\n");
  8695. @}
  8696. @end example
  8697. @node Advanced Definitions
  8698. @section Advanced Function Features
  8699. This section describes some advanced or obscure features for GNU C
  8700. function definitions. If you are just learning C, you can skip the
  8701. rest of this chapter.
  8702. @menu
  8703. * Variable-Length Array Parameters:: Functions that accept arrays
  8704. of variable length.
  8705. * Variable Number of Arguments:: Variadic functions.
  8706. * Nested Functions:: Defining functions within functions.
  8707. * Inline Function Definitions:: A function call optimization technique.
  8708. @end menu
  8709. @node Variable-Length Array Parameters
  8710. @subsection Variable-Length Array Parameters
  8711. @cindex variable-length array parameters
  8712. @cindex array parameters, variable-length
  8713. @cindex functions that accept variable-length arrays
  8714. An array parameter can have variable length: simply declare the array
  8715. type with a size that isn't constant. In a nested function, the
  8716. length can refer to a variable defined in a containing scope. In any
  8717. function, it can refer to a previous parameter, like this:
  8718. @example
  8719. struct entry
  8720. tester (int len, char data[len][len])
  8721. @{
  8722. @r{@dots{}}
  8723. @}
  8724. @end example
  8725. Alternatively, in function declarations (but not in function
  8726. definitions), you can use @code{[*]} to denote that the array
  8727. parameter is of a variable length, such that these two declarations
  8728. mean the same thing:
  8729. @example
  8730. struct entry
  8731. tester (int len, char data[len][len]);
  8732. @end example
  8733. @example
  8734. struct entry
  8735. tester (int len, char data[*][*]);
  8736. @end example
  8737. @noindent
  8738. The two forms of input are equivalent in GNU C, but emphasizing that
  8739. the array parameter is variable-length may be helpful to those
  8740. studying the code.
  8741. You can also omit the length parameter, and instead use some other
  8742. in-scope variable for the length in the function definition:
  8743. @example
  8744. struct entry
  8745. tester (char data[*][*]);
  8746. @r{@dots{}}
  8747. int dataLength = 20;
  8748. @r{@dots{}}
  8749. struct entry
  8750. tester (char data[dataLength][dataLength])
  8751. @{
  8752. @r{@dots{}}
  8753. @}
  8754. @end example
  8755. @c ??? check text above
  8756. @cindex parameter forward declaration
  8757. In GNU C, to pass the array first and the length afterward, you can
  8758. use a @dfn{parameter forward declaration}, like this:
  8759. @example
  8760. struct entry
  8761. tester (int len; char data[len][len], int len)
  8762. @{
  8763. @r{@dots{}}
  8764. @}
  8765. @end example
  8766. The @samp{int len} before the semicolon is the parameter forward
  8767. declaration; it serves the purpose of making the name @code{len} known
  8768. when the declaration of @code{data} is parsed.
  8769. You can write any number of such parameter forward declarations in the
  8770. parameter list. They can be separated by commas or semicolons, but
  8771. the last one must end with a semicolon, which is followed by the
  8772. ``real'' parameter declarations. Each forward declaration must match
  8773. a subsequent ``real'' declaration in parameter name and data type.
  8774. Standard C does not support parameter forward declarations.
  8775. @node Variable Number of Arguments
  8776. @subsection Variable-Length Parameter Lists
  8777. @cindex variable-length parameter lists
  8778. @cindex parameters lists, variable length
  8779. @cindex function parameter lists, variable length
  8780. @cindex variadic function
  8781. A function that takes a variable number of arguments is called a
  8782. @dfn{variadic function}. In C, a variadic function must specify at
  8783. least one fixed argument with an explicitly declared data type.
  8784. Additional arguments can follow, and can vary in both quantity and
  8785. data type.
  8786. In the function header, declare the fixed parameters in the normal
  8787. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8788. example of a variadic function header:
  8789. @example
  8790. int add_multiple_values (int number, ...)
  8791. @end example
  8792. @cindex @code{va_list}
  8793. @cindex @code{va_start}
  8794. @cindex @code{va_end}
  8795. The function body can refer to fixed arguments by their parameter
  8796. names, but the additional arguments have no names. Accessing them in
  8797. the function body uses certain standard macros. They are defined in
  8798. the library header file @file{stdarg.h}, so the code must
  8799. @code{#include} that file.
  8800. In the body, write
  8801. @example
  8802. va_list ap;
  8803. va_start (ap, @var{last_fixed_parameter});
  8804. @end example
  8805. @noindent
  8806. This declares the variable @code{ap} (you can use any name for it)
  8807. and then sets it up to point before the first additional argument.
  8808. Then, to fetch the next consecutive additional argument, write this:
  8809. @example
  8810. va_arg (ap, @var{type})
  8811. @end example
  8812. After fetching all the additional arguments (or as many as need to be
  8813. used), write this:
  8814. @example
  8815. va_end (ap);
  8816. @end example
  8817. Here's an example of a variadic function definition that adds any
  8818. number of @code{int} arguments. The first (fixed) argument says how
  8819. many more arguments follow.
  8820. @example
  8821. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8822. @r{@dots{}}
  8823. int
  8824. add_multiple_values (int argcount, ...)
  8825. @{
  8826. int counter, total = 0;
  8827. /* @r{Declare a variable of type @code{va_list}.} */
  8828. va_list argptr;
  8829. /* @r{Initialize that variable..} */
  8830. va_start (argptr, argcount);
  8831. for (counter = 0; counter < argcount; counter++)
  8832. @{
  8833. /* @r{Get the next additional argument.} */
  8834. total += va_arg (argptr, int);
  8835. @}
  8836. /* @r{End use of the @code{argptr} variable.} */
  8837. va_end (argptr);
  8838. return total;
  8839. @}
  8840. @end example
  8841. With GNU C, @code{va_end} is superfluous, but some other compilers
  8842. might make @code{va_start} allocate memory so that calling
  8843. @code{va_end} is necessary to avoid a memory leak. Before doing
  8844. @code{va_start} again with the same variable, do @code{va_end}
  8845. first.
  8846. @cindex @code{va_copy}
  8847. Because of this possible memory allocation, it is risky (in principle)
  8848. to copy one @code{va_list} variable to another with assignment.
  8849. Instead, use @code{va_copy}, which copies the substance but allocates
  8850. separate memory in the variable you copy to. The call looks like
  8851. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8852. @var{from} should be variables of type @code{va_list}. In principle,
  8853. do @code{va_end} on each of these variables before its scope ends.
  8854. Since the additional arguments' types are not specified in the
  8855. function's definition, the default argument promotions
  8856. (@pxref{Argument Promotions}) apply to them in function calls. The
  8857. function definition must take account of this; thus, if an argument
  8858. was passed as @code{short}, the function should get it as @code{int}.
  8859. If an argument was passed as @code{float}, the function should get it
  8860. as @code{double}.
  8861. C has no mechanism to tell the variadic function how many arguments
  8862. were passed to it, so its calling convention must give it a way to
  8863. determine this. That's why @code{add_multiple_values} takes a fixed
  8864. argument that says how many more arguments follow. Thus, you can
  8865. call the function like this:
  8866. @example
  8867. sum = add_multiple_values (3, 12, 34, 190);
  8868. /* @r{Value is 12+34+190.} */
  8869. @end example
  8870. In GNU C, there is no actual need to use the @code{va_end} function.
  8871. In fact, it does nothing. It's used for compatibility with other
  8872. compilers, when that matters.
  8873. It is a mistake to access variables declared as @code{va_list} except
  8874. in the specific ways described here. Just what that type consists of
  8875. is an implementation detail, which could vary from one platform to
  8876. another.
  8877. @node Nested Functions
  8878. @subsection Nested Functions
  8879. @cindex nested functions
  8880. @cindex functions, nested
  8881. @cindex downward funargs
  8882. @cindex thunks
  8883. A @dfn{nested function} is a function defined inside another function.
  8884. The nested function's name is local to the block where it is defined.
  8885. For example, here we define a nested function named @code{square}, and
  8886. call it twice:
  8887. @example
  8888. @group
  8889. foo (double a, double b)
  8890. @{
  8891. double square (double z) @{ return z * z; @}
  8892. return square (a) + square (b);
  8893. @}
  8894. @end group
  8895. @end example
  8896. The nested function can access all the variables of the containing
  8897. function that are visible at the point of its definition. This is
  8898. called @dfn{lexical scoping}. For example, here we show a nested
  8899. function that uses an inherited variable named @code{offset}:
  8900. @example
  8901. @group
  8902. bar (int *array, int offset, int size)
  8903. @{
  8904. int access (int *array, int index)
  8905. @{ return array[index + offset]; @}
  8906. int i;
  8907. @r{@dots{}}
  8908. for (i = 0; i < size; i++)
  8909. @r{@dots{}} access (array, i) @r{@dots{}}
  8910. @}
  8911. @end group
  8912. @end example
  8913. Nested function definitions can appear wherever automatic variable
  8914. declarations are allowed; that is, in any block, interspersed with the
  8915. other declarations and statements in the block.
  8916. The nested function's name is visible only within the parent block;
  8917. the name's scope starts from its definition and continues to the end
  8918. of the containing block. If the nested function's name
  8919. is the same as the parent function's name, there wil be
  8920. no way to refer to the parent function inside the scope of the
  8921. name of the nested function.
  8922. Using @code{extern} or @code{static} on a nested function definition
  8923. is an error.
  8924. It is possible to call the nested function from outside the scope of its
  8925. name by storing its address or passing the address to another function.
  8926. You can do this safely, but you must be careful:
  8927. @example
  8928. @group
  8929. hack (int *array, int size, int addition)
  8930. @{
  8931. void store (int index, int value)
  8932. @{ array[index] = value + addition; @}
  8933. intermediate (store, size);
  8934. @}
  8935. @end group
  8936. @end example
  8937. Here, the function @code{intermediate} receives the address of
  8938. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8939. the arguments given to @code{store} are used to store into @code{array}.
  8940. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8941. It is safe for @code{intermediate} to call @code{store} because
  8942. @code{hack}'s stack frame, with its arguments and local variables,
  8943. continues to exist during the call to @code{intermediate}.
  8944. Calling the nested function through its address after the containing
  8945. function has exited is asking for trouble. If it is called after a
  8946. containing scope level has exited, and if it refers to some of the
  8947. variables that are no longer in scope, it will refer to memory
  8948. containing junk or other data. It's not wise to take the risk.
  8949. The GNU C Compiler implements taking the address of a nested function
  8950. using a technique called @dfn{trampolines}. This technique was
  8951. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8952. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8953. A nested function can jump to a label inherited from a containing
  8954. function, provided the label was explicitly declared in the containing
  8955. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8956. containing function, exiting the nested function that did the
  8957. @code{goto} and any intermediate function invocations as well. Here
  8958. is an example:
  8959. @example
  8960. @group
  8961. bar (int *array, int offset, int size)
  8962. @{
  8963. /* @r{Explicitly declare the label @code{failure}.} */
  8964. __label__ failure;
  8965. int access (int *array, int index)
  8966. @{
  8967. if (index > size)
  8968. /* @r{Exit this function,}
  8969. @r{and return to @code{bar}.} */
  8970. goto failure;
  8971. return array[index + offset];
  8972. @}
  8973. @end group
  8974. @group
  8975. int i;
  8976. @r{@dots{}}
  8977. for (i = 0; i < size; i++)
  8978. @r{@dots{}} access (array, i) @r{@dots{}}
  8979. @r{@dots{}}
  8980. return 0;
  8981. /* @r{Control comes here from @code{access}
  8982. if it does the @code{goto}.} */
  8983. failure:
  8984. return -1;
  8985. @}
  8986. @end group
  8987. @end example
  8988. To declare the nested function before its definition, use
  8989. @code{auto} (which is otherwise meaningless for function declarations;
  8990. @pxref{auto and register}). For example,
  8991. @example
  8992. bar (int *array, int offset, int size)
  8993. @{
  8994. auto int access (int *, int);
  8995. @r{@dots{}}
  8996. @r{@dots{}} access (array, i) @r{@dots{}}
  8997. @r{@dots{}}
  8998. int access (int *array, int index)
  8999. @{
  9000. @r{@dots{}}
  9001. @}
  9002. @r{@dots{}}
  9003. @}
  9004. @end example
  9005. @node Inline Function Definitions
  9006. @subsection Inline Function Definitions
  9007. @cindex inline function definitions
  9008. @cindex function definitions, inline
  9009. @findex inline
  9010. To declare a function inline, use the @code{inline} keyword in its
  9011. definition. Here's a simple function that takes a pointer-to-@code{int}
  9012. and increments the integer stored there---declared inline.
  9013. @example
  9014. struct list
  9015. @{
  9016. struct list *first, *second;
  9017. @};
  9018. inline struct list *
  9019. list_first (struct list *p)
  9020. @{
  9021. return p->first;
  9022. @}
  9023. inline struct list *
  9024. list_second (struct list *p)
  9025. @{
  9026. return p->second;
  9027. @}
  9028. @end example
  9029. optimized compilation can substitute the inline function's body for
  9030. any call to it. This is called @emph{inlining} the function. It
  9031. makes the code that contains the call run faster, significantly so if
  9032. the inline function is small.
  9033. Here's a function that uses @code{pair_second}:
  9034. @example
  9035. int
  9036. pairlist_length (struct list *l)
  9037. @{
  9038. int length = 0;
  9039. while (l)
  9040. @{
  9041. length++;
  9042. l = pair_second (l);
  9043. @}
  9044. return length;
  9045. @}
  9046. @end example
  9047. Substituting the code of @code{pair_second} into the definition of
  9048. @code{pairlist_length} results in this code, in effect:
  9049. @example
  9050. int
  9051. pairlist_length (struct list *l)
  9052. @{
  9053. int length = 0;
  9054. while (l)
  9055. @{
  9056. length++;
  9057. l = l->second;
  9058. @}
  9059. return length;
  9060. @}
  9061. @end example
  9062. Since the definition of @code{pair_second} does not say @code{extern}
  9063. or @code{static}, that definition is used only for inlining. It
  9064. doesn't generate code that can be called at run time. If not all the
  9065. calls to the function are inlined, there must be a definition of the
  9066. same function name in another module for them to call.
  9067. @cindex inline functions, omission of
  9068. @c @opindex fkeep-inline-functions
  9069. Adding @code{static} to an inline function definition means the
  9070. function definition is limited to this compilation module. Also, it
  9071. generates run-time code if necessary for the sake of any calls that
  9072. were not inlined. If all calls are inlined then the function
  9073. definition does not generate run-time code, but you can force
  9074. generation of run-time code with the option
  9075. @option{-fkeep-inline-functions}.
  9076. @cindex extern inline function
  9077. Specifying @code{extern} along with @code{inline} means the function is
  9078. external and generates run-time code to be called from other
  9079. separately compiled modules, as well as inlined. You can define the
  9080. function as @code{inline} without @code{extern} in other modules so as
  9081. to inline calls to the same function in those modules.
  9082. Why are some calls not inlined? First of all, inlining is an
  9083. optimization, so non-optimized compilation does not inline.
  9084. Some calls cannot be inlined for technical reasons. Also, certain
  9085. usages in a function definition can make it unsuitable for inline
  9086. substitution. Among these usages are: variadic functions, use of
  9087. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9088. use of nonlocal goto. The option @option{-Winline} requests a warning
  9089. when a function marked @code{inline} is unsuitable to be inlined. The
  9090. warning explains what obstacle makes it unsuitable.
  9091. Just because a call @emph{can} be inlined does not mean it
  9092. @emph{should} be inlined. The GNU C compiler weighs costs and
  9093. benefits to decide whether inlining a particular call is advantageous.
  9094. You can force inlining of all calls to a given function that can be
  9095. inlined, even in a non-optimized compilation. by specifying the
  9096. @samp{always_inline} attribute for the function, like this:
  9097. @example
  9098. /* @r{Prototype.} */
  9099. inline void foo (const char) __attribute__((always_inline));
  9100. @end example
  9101. @noindent
  9102. This is a GNU C extension. @xref{Attributes}.
  9103. A function call may be inlined even if not declared @code{inline} in
  9104. special cases where the compiler can determine this is correct and
  9105. desirable. For instance, when a static function is called only once,
  9106. it will very likely be inlined. With @option{-flto}, link-time
  9107. optimization, any function might be inlined. To absolutely prevent
  9108. inlining of a specific function, specify
  9109. @code{__attribute__((__noinline__))} in the function's definition.
  9110. @node Obsolete Definitions
  9111. @section Obsolete Function Features
  9112. These features of function definitions are still used in old
  9113. programs, but you shouldn't write code this way today.
  9114. If you are just learning C, you can skip this section.
  9115. @menu
  9116. * Old GNU Inlining:: An older inlining technique.
  9117. * Old-Style Function Definitions:: Original K&R style functions.
  9118. @end menu
  9119. @node Old GNU Inlining
  9120. @subsection Older GNU C Inlining
  9121. The GNU C spec for inline functions, before GCC version 5, defined
  9122. @code{extern inline} on a function definition to mean to inline calls
  9123. to it but @emph{not} generate code for the function that could be
  9124. called at run time. By contrast, @code{inline} without @code{extern}
  9125. specified to generate run-time code for the function. In effect, ISO
  9126. incompatibly flipped the meanings of these two cases. We changed GCC
  9127. in version 5 to adopt the ISO specification.
  9128. Many programs still use these cases with the previous GNU C meanings.
  9129. You can specify use of those meanings with the option
  9130. @option{-fgnu89-inline}. You can also specify this for a single
  9131. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9132. @example
  9133. inline __attribute__ ((gnu_inline))
  9134. int
  9135. inc (int *a)
  9136. @{
  9137. (*a)++;
  9138. @}
  9139. @end example
  9140. @node Old-Style Function Definitions
  9141. @subsection Old-Style Function Definitions
  9142. @cindex old-style function definitions
  9143. @cindex function definitions, old-style
  9144. @cindex K&R-style function definitions
  9145. The syntax of C traditionally allows omitting the data type in a
  9146. function declaration if it specifies a storage class or a qualifier.
  9147. Then the type defaults to @code{int}. For example:
  9148. @example
  9149. static foo (double x);
  9150. @end example
  9151. @noindent
  9152. defaults the return type to @code{int}. This is bad practice; if you
  9153. see it, fix it.
  9154. An @dfn{old-style} (or ``K&R'') function definition is the way
  9155. function definitions were written in the 1980s. It looks like this:
  9156. @example
  9157. @var{rettype}
  9158. @var{function} (@var{parmnames})
  9159. @var{parm_declarations}
  9160. @{
  9161. @var{body}
  9162. @}
  9163. @end example
  9164. In @var{parmnames}, only the parameter names are listed, separated by
  9165. commas. Then @var{parm_declarations} declares their data types; these
  9166. declarations look just like variable declarations. If a parameter is
  9167. listed in @var{parmnames} but has no declaration, it is implicitly
  9168. declared @code{int}.
  9169. There is no reason to write a definition this way nowadays, but they
  9170. can still be seen in older GNU programs.
  9171. An old-style variadic function definition looks like this:
  9172. @example
  9173. #include <varargs.h>
  9174. int
  9175. add_multiple_values (va_alist)
  9176. va_dcl
  9177. @{
  9178. int argcount;
  9179. int counter, total = 0;
  9180. /* @r{Declare a variable of type @code{va_list}.} */
  9181. va_list argptr;
  9182. /* @r{Initialize that variable.} */
  9183. va_start (argptr);
  9184. /* @r{Get the first argument (fixed).} */
  9185. argcount = va_arg (int);
  9186. for (counter = 0; counter < argcount; counter++)
  9187. @{
  9188. /* @r{Get the next additional argument.} */
  9189. total += va_arg (argptr, int);
  9190. @}
  9191. /* @r{End use of the @code{argptr} variable.} */
  9192. va_end (argptr);
  9193. return total;
  9194. @}
  9195. @end example
  9196. Note that the old-style variadic function definition has no fixed
  9197. parameter variables; all arguments must be obtained with
  9198. @code{va_arg}.
  9199. @node Compatible Types
  9200. @chapter Compatible Types
  9201. @cindex compatible types
  9202. @cindex types, compatible
  9203. Declaring a function or variable twice is valid in C only if the two
  9204. declarations specify @dfn{compatible} types. In addition, some
  9205. operations on pointers require operands to have compatible target
  9206. types.
  9207. In C, two different primitive types are never compatible. Likewise for
  9208. the defined types @code{struct}, @code{union} and @code{enum}: two
  9209. separately defined types are incompatible unless they are defined
  9210. exactly the same way.
  9211. However, there are a few cases where different types can be
  9212. compatible:
  9213. @itemize @bullet
  9214. @item
  9215. Every enumeration type is compatible with some integer type. In GNU
  9216. C, the choice of integer type depends on the largest enumeration
  9217. value.
  9218. @c ??? Which one, in GCC?
  9219. @c ??? ... it varies, depending on the enum values. Testing on
  9220. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9221. @c ??? then moves on to an 8-byte signed integer. These details
  9222. @c ??? might be platform-dependent, as the C standard says that even
  9223. @c ??? char could be used as an enum type, but it's at least true
  9224. @c ??? that GCC chooses a type that is at least large enough to
  9225. @c ??? hold the largest enum value.
  9226. @item
  9227. Array types are compatible if the element types are compatible
  9228. and the sizes (when specified) match.
  9229. @item
  9230. Pointer types are compatible if the pointer target types are
  9231. compatible.
  9232. @item
  9233. Function types that specify argument types are compatible if the
  9234. return types are compatible and the argument types are compatible,
  9235. argument by argument. In addition, they must all agree in whether
  9236. they use @code{...} to allow additional arguments.
  9237. @item
  9238. Function types that don't specify argument types are compatible if the
  9239. return types are.
  9240. @item
  9241. Function types that specify the argument types are compatible with
  9242. function types that omit them, if the return types are compatible and
  9243. the specified argument types are unaltered by the argument promotions
  9244. (@pxref{Argument Promotions}).
  9245. @end itemize
  9246. In order for types to be compatible, they must agree in their type
  9247. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9248. It follows that @code{const int *} and @code{int *} are incompatible
  9249. too (they are pointers to types that are not compatible).
  9250. If two types are compatible ignoring the qualifiers, we call them
  9251. @dfn{nearly compatible}. (If they are array types, we ignore
  9252. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9253. Comparison of pointers is valid if the pointers' target types are
  9254. nearly compatible. Likewise, the two branches of a conditional
  9255. expression may be pointers to nearly compatible target types.
  9256. If two types are compatible ignoring the qualifiers, and the first
  9257. type has all the qualifiers of the second type, we say the first is
  9258. @dfn{upward compatible} with the second. Assignment of pointers
  9259. requires the assigned pointer's target type to be upward compatible
  9260. with the right operand (the new value)'s target type.
  9261. @node Type Conversions
  9262. @chapter Type Conversions
  9263. @cindex type conversions
  9264. @cindex conversions, type
  9265. C converts between data types automatically when that seems clearly
  9266. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9267. @menu
  9268. * Explicit Type Conversion:: Casting a value from one type to another.
  9269. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9270. * Argument Promotions:: Automatic conversion of function parameters.
  9271. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9272. * Common Type:: When operand types differ, which one is used?
  9273. @end menu
  9274. @node Explicit Type Conversion
  9275. @section Explicit Type Conversion
  9276. @cindex cast
  9277. @cindex explicit type conversion
  9278. You can do explicit conversions using the unary @dfn{cast} operator,
  9279. which is written as a type designator (@pxref{Type Designators}) in
  9280. parentheses. For example, @code{(int)} is the operator to cast to
  9281. type @code{int}. Here's an example of using it:
  9282. @example
  9283. @{
  9284. double d = 5.5;
  9285. printf ("Floating point value: %f\n", d);
  9286. printf ("Rounded to integer: %d\n", (int) d);
  9287. @}
  9288. @end example
  9289. Using @code{(int) d} passes an @code{int} value as argument to
  9290. @code{printf}, so you can print it with @samp{%d}. Using just
  9291. @code{d} without the cast would pass the value as @code{double}.
  9292. That won't work at all with @samp{%d}; the results would be gibberish.
  9293. To divide one integer by another without rounding,
  9294. cast either of the integers to @code{double} first:
  9295. @example
  9296. (double) @var{dividend} / @var{divisor}
  9297. @var{dividend} / (double) @var{divisor}
  9298. @end example
  9299. It is enough to cast one of them, because that forces the common type
  9300. to @code{double} so the other will be converted automatically.
  9301. The valid cast conversions are:
  9302. @itemize @bullet
  9303. @item
  9304. One numerical type to another.
  9305. @item
  9306. One pointer type to another.
  9307. (Converting between pointers that point to functions
  9308. and pointers that point to data is not standard C.)
  9309. @item
  9310. A pointer type to an integer type.
  9311. @item
  9312. An integer type to a pointer type.
  9313. @item
  9314. To a union type, from the type of any alternative in the union
  9315. (@pxref{Unions}). (This is a GNU extension.)
  9316. @item
  9317. Anything, to @code{void}.
  9318. @end itemize
  9319. @node Assignment Type Conversions
  9320. @section Assignment Type Conversions
  9321. @cindex assignment type conversions
  9322. Certain type conversions occur automatically in assignments
  9323. and certain other contexts. These are the conversions
  9324. assignments can do:
  9325. @itemize @bullet
  9326. @item
  9327. Converting any numeric type to any other numeric type.
  9328. @item
  9329. Converting @code{void *} to any other pointer type
  9330. (except pointer-to-function types).
  9331. @item
  9332. Converting any other pointer type to @code{void *}.
  9333. (except pointer-to-function types).
  9334. @item
  9335. Converting 0 (a null pointer constant) to any pointer type.
  9336. @item
  9337. Converting any pointer type to @code{bool}. (The result is
  9338. 1 if the pointer is not null.)
  9339. @item
  9340. Converting between pointer types when the left-hand target type is
  9341. upward compatible with the right-hand target type. @xref{Compatible
  9342. Types}.
  9343. @end itemize
  9344. These type conversions occur automatically in certain contexts,
  9345. which are:
  9346. @itemize @bullet
  9347. @item
  9348. An assignment converts the type of the right-hand expression
  9349. to the type wanted by the left-hand expression. For example,
  9350. @example
  9351. double i;
  9352. i = 5;
  9353. @end example
  9354. @noindent
  9355. converts 5 to @code{double}.
  9356. @item
  9357. A function call, when the function specifies the type for that
  9358. argument, converts the argument value to that type. For example,
  9359. @example
  9360. void foo (double);
  9361. foo (5);
  9362. @end example
  9363. @noindent
  9364. converts 5 to @code{double}.
  9365. @item
  9366. A @code{return} statement converts the specified value to the type
  9367. that the function is declared to return. For example,
  9368. @example
  9369. double
  9370. foo ()
  9371. @{
  9372. return 5;
  9373. @}
  9374. @end example
  9375. @noindent
  9376. also converts 5 to @code{double}.
  9377. @end itemize
  9378. In all three contexts, if the conversion is impossible, that
  9379. constitutes an error.
  9380. @node Argument Promotions
  9381. @section Argument Promotions
  9382. @cindex argument promotions
  9383. @cindex promotion of arguments
  9384. When a function's definition or declaration does not specify the type
  9385. of an argument, that argument is passed without conversion in whatever
  9386. type it has, with these exceptions:
  9387. @itemize @bullet
  9388. @item
  9389. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9390. expression is a narrow integer, such as @code{char} or @code{short},
  9391. the call converts it automatically to @code{int} (@pxref{Integer
  9392. Types}).@footnote{On an embedded controller where @code{char}
  9393. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9394. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9395. never occurs in GNU C on real computers.}
  9396. In this example, the expression @code{c} is passed as an @code{int}:
  9397. @example
  9398. char c = '$';
  9399. printf ("Character c is '%c'\n", c);
  9400. @end example
  9401. @item
  9402. If the expression
  9403. has type @code{float}, the call converts it automatically to
  9404. @code{double}.
  9405. @item
  9406. An array as argument is converted to a pointer to its zeroth element.
  9407. @item
  9408. A function name as argument is converted to a pointer to that function.
  9409. @end itemize
  9410. @node Operand Promotions
  9411. @section Operand Promotions
  9412. @cindex operand promotions
  9413. The operands in arithmetic operations undergo type conversion automatically.
  9414. These @dfn{operand promotions} are the same as the argument promotions
  9415. except without converting @code{float} to @code{double}. In other words,
  9416. the operand promotions convert
  9417. @itemize @bullet
  9418. @item
  9419. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9420. @item
  9421. an array to a pointer to its zeroth element, and
  9422. @item
  9423. a function name to a pointer to that function.
  9424. @end itemize
  9425. @node Common Type
  9426. @section Common Type
  9427. @cindex common type
  9428. Arithmetic binary operators (except the shift operators) convert their
  9429. operands to the @dfn{common type} before operating on them.
  9430. Conditional expressions also convert the two possible results to their
  9431. common type. Here are the rules for determining the common type.
  9432. If one of the numbers has a floating-point type and the other is an
  9433. integer, the common type is that floating-point type. For instance,
  9434. @example
  9435. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9436. @end example
  9437. If both are floating point, the type with the larger range is the
  9438. common type.
  9439. If both are integers but of different widths, the common type
  9440. is the wider of the two.
  9441. If they are integer types of the same width, the common type is
  9442. unsigned if either operand is unsigned, and it's @code{long} if either
  9443. operand is @code{long}. It's @code{long long} if either operand is
  9444. @code{long long}.
  9445. These rules apply to addition, subtraction, multiplication, division,
  9446. remainder, comparisons, and bitwise operations. They also apply to
  9447. the two branches of a conditional expression, and to the arithmetic
  9448. done in a modifying assignment operation.
  9449. @node Scope
  9450. @chapter Scope
  9451. @cindex scope
  9452. @cindex block scope
  9453. @cindex function scope
  9454. @cindex function prototype scope
  9455. Each definition or declaration of an identifier is visible
  9456. in certain parts of the program, which is typically less than the whole
  9457. of the program. The parts where it is visible are called its @dfn{scope}.
  9458. Normally, declarations made at the top-level in the source -- that is,
  9459. not within any blocks and function definitions -- are visible for the
  9460. entire contents of the source file after that point. This is called
  9461. @dfn{file scope} (@pxref{File-Scope Variables}).
  9462. Declarations made within blocks of code, including within function
  9463. definitions, are visible only within those blocks. This is called
  9464. @dfn{block scope}. Here is an example:
  9465. @example
  9466. @group
  9467. void
  9468. foo (void)
  9469. @{
  9470. int x = 42;
  9471. @}
  9472. @end group
  9473. @end example
  9474. @noindent
  9475. In this example, the variable @code{x} has block scope; it is visible
  9476. only within the @code{foo} function definition block. Thus, other
  9477. blocks could have their own variables, also named @code{x}, without
  9478. any conflict between those variables.
  9479. A variable declared inside a subblock has a scope limited to
  9480. that subblock,
  9481. @example
  9482. @group
  9483. void
  9484. foo (void)
  9485. @{
  9486. @{
  9487. int x = 42;
  9488. @}
  9489. // @r{@code{x} is out of scope here.}
  9490. @}
  9491. @end group
  9492. @end example
  9493. If a variable declared within a block has the same name as a variable
  9494. declared outside of that block, the definition within the block
  9495. takes precedence during its scope:
  9496. @example
  9497. @group
  9498. int x = 42;
  9499. void
  9500. foo (void)
  9501. @{
  9502. int x = 17;
  9503. printf ("%d\n", x);
  9504. @}
  9505. @end group
  9506. @end example
  9507. @noindent
  9508. This prints 17, the value of the variable @code{x} declared in the
  9509. function body block, rather than the value of the variable @code{x} at
  9510. file scope. We say that the inner declaration of @code{x}
  9511. @dfn{shadows} the outer declaration, for the extent of the inner
  9512. declaration's scope.
  9513. A declaration with block scope can be shadowed by another declaration
  9514. with the same name in a subblock.
  9515. @example
  9516. @group
  9517. void
  9518. foo (void)
  9519. @{
  9520. char *x = "foo";
  9521. @{
  9522. int x = 42;
  9523. @r{@dots{}}
  9524. exit (x / 6);
  9525. @}
  9526. @}
  9527. @end group
  9528. @end example
  9529. A function parameter's scope is the entire function body, but it can
  9530. be shadowed. For example:
  9531. @example
  9532. @group
  9533. int x = 42;
  9534. void
  9535. foo (int x)
  9536. @{
  9537. printf ("%d\n", x);
  9538. @}
  9539. @end group
  9540. @end example
  9541. @noindent
  9542. This prints the value of @code{x} the function parameter, rather than
  9543. the value of the file-scope variable @code{x}. However,
  9544. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9545. is visible for the whole of the containing function body, both before
  9546. and after the label declaration:
  9547. @example
  9548. @group
  9549. void
  9550. foo (void)
  9551. @{
  9552. @r{@dots{}}
  9553. goto bar;
  9554. @r{@dots{}}
  9555. @{ // @r{Subblock does not affect labels.}
  9556. bar:
  9557. @r{@dots{}}
  9558. @}
  9559. goto bar;
  9560. @}
  9561. @end group
  9562. @end example
  9563. Except for labels, a declared identifier is not
  9564. visible to code before its declaration. For example:
  9565. @example
  9566. @group
  9567. int x = 5;
  9568. int y = x + 10;
  9569. @end group
  9570. @end example
  9571. @noindent
  9572. will work, but:
  9573. @example
  9574. @group
  9575. int x = y + 10;
  9576. int y = 5;
  9577. @end group
  9578. @end example
  9579. @noindent
  9580. cannot refer to the variable @code{y} before its declaration.
  9581. @include cpp.texi
  9582. @node Integers in Depth
  9583. @chapter Integers in Depth
  9584. This chapter explains the machine-level details of integer types: how
  9585. they are represented as bits in memory, and the range of possible
  9586. values for each integer type.
  9587. @menu
  9588. * Integer Representations:: How integer values appear in memory.
  9589. * Maximum and Minimum Values:: Value ranges of integer types.
  9590. @end menu
  9591. @node Integer Representations
  9592. @section Integer Representations
  9593. @cindex integer representations
  9594. @cindex representation of integers
  9595. Modern computers store integer values as binary (base-2) numbers that
  9596. occupy a single unit of storage, typically either as an 8-bit
  9597. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9598. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9599. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9600. any of these types could have some other size, bit it's not worth even
  9601. a minute to cater to that possibility. It never happens on
  9602. GNU/Linux.}
  9603. @cindex @code{CHAR_BIT}
  9604. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9605. of bits in type @code{char}. On any real operating system, the value
  9606. is 8.
  9607. The fixed sizes of numeric types necessarily limits their @dfn{range
  9608. of values}, and the particular encoding of integers decides what that
  9609. range is.
  9610. @cindex two's-complement representation
  9611. For unsigned integers, the entire space is used to represent a
  9612. nonnegative value. Signed integers are stored using
  9613. @dfn{two's-complement representation}: a signed integer with @var{n}
  9614. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9615. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9616. high-order, bit is called the @dfn{sign bit}.
  9617. @c ??? Needs correcting
  9618. There is only one value that means zero, and the most negative number
  9619. lacks a positive counterpart. As a result, negating that number
  9620. causes overflow; in practice, its result is that number back again.
  9621. For example, a two's-complement signed 8-bit integer can represent all
  9622. decimal numbers from @minus{}128 to +127. We will revisit that
  9623. peculiarity shortly.
  9624. Decades ago, there were computers that didn't use two's-complement
  9625. representation for integers (@pxref{Integers in Depth}), but they are
  9626. long gone and not worth any effort to support.
  9627. @c ??? Is this duplicate?
  9628. When an arithmetic operation produces a value that is too big to
  9629. represent, the operation is said to @dfn{overflow}. In C, integer
  9630. overflow does not interrupt the control flow or signal an error.
  9631. What it does depends on signedness.
  9632. For unsigned arithmetic, the result of an operation that overflows is
  9633. the @var{n} low-order bits of the correct value. If the correct value
  9634. is representable in @var{n} bits, that is always the result;
  9635. thus we often say that ``integer arithmetic is exact,'' omitting the
  9636. crucial qualifying phrase ``as long as the exact result is
  9637. representable.''
  9638. In principle, a C program should be written so that overflow never
  9639. occurs for signed integers, but in GNU C you can specify various ways
  9640. of handling such overflow (@pxref{Integer Overflow}).
  9641. Integer representations are best understood by looking at a table for
  9642. a tiny integer size; here are the possible values for an integer with
  9643. three bits:
  9644. @multitable @columnfractions .25 .25 .25 .25
  9645. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9646. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9647. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9648. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9649. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9650. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9651. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9652. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9653. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9654. @end multitable
  9655. The parenthesized decimal numbers in the last column represent the
  9656. signed meanings of the two's-complement of the line's value. Recall
  9657. that, in two's-complement encoding, the high-order bit is 0 when
  9658. the number is nonnegative.
  9659. We can now understand the peculiar behavior of negation of the
  9660. most negative two's-complement integer: start with 0b100,
  9661. invert the bits to get 0b011, and add 1: we get
  9662. 0b100, the value we started with.
  9663. We can also see overflow behavior in two's-complement:
  9664. @example
  9665. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9666. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9667. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9668. @end example
  9669. @noindent
  9670. A sum of two nonnegative signed values that overflows has a 1 in the
  9671. sign bit, so the exact positive result is truncated to a negative
  9672. value.
  9673. @c =====================================================================
  9674. @node Maximum and Minimum Values
  9675. @section Maximum and Minimum Values
  9676. @cindex maximum integer values
  9677. @cindex minimum integer values
  9678. @cindex integer ranges
  9679. @cindex ranges of integer types
  9680. @findex INT_MAX
  9681. @findex UINT_MAX
  9682. @findex SHRT_MAX
  9683. @findex LONG_MAX
  9684. @findex LLONG_MAX
  9685. @findex USHRT_MAX
  9686. @findex ULONG_MAX
  9687. @findex ULLONG_MAX
  9688. @findex CHAR_MAX
  9689. @findex SCHAR_MAX
  9690. @findex UCHAR_MAX
  9691. For each primitive integer type, there is a standard macro defined in
  9692. @file{limits.h} that gives the largest value that type can hold. For
  9693. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9694. On a 32-bit computer, that is equal to 2,147,483,647. The
  9695. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9696. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9697. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9698. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9699. @code{ULLONG_MAX}.
  9700. Since there are three ways to specify a @code{char} type, there are
  9701. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9702. @code{UCHAR_MAX}.
  9703. For each type that is or might be signed, there is another symbol that
  9704. gives the minimum value it can hold. (Just replace @code{MAX} with
  9705. @code{MIN} in the names listed above.) There is no minimum limit
  9706. symbol for types specified with @code{unsigned} because the
  9707. minimum for them is universally zero.
  9708. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9709. two's-complement representation, the most negative number is 1 less
  9710. than the negative of the most positive number. Thus, @code{INT_MIN}
  9711. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9712. actually write the value that way in C, since it would overflow.
  9713. That's a good reason to use @code{INT_MIN} to specify
  9714. that value. Its definition is written to avoid overflow.
  9715. @include fp.texi
  9716. @node Compilation
  9717. @chapter Compilation
  9718. @cindex object file
  9719. @cindex compilation module
  9720. @cindex make rules
  9721. @cindex link
  9722. Early in the manual we explained how to compile a simple C program
  9723. that consists of a single source file (@pxref{Compile Example}).
  9724. However, we handle only short programs that way. A typical C program
  9725. consists of many source files, each of which is usually a separate
  9726. @dfn{compilation module}---meaning that it has to be compiled
  9727. separately. (The source files that are not separate compilation
  9728. modules are those that are used via @code{#include}; see @ref{Header
  9729. Files}.)
  9730. To compile a multi-module program, you compile each of the program's
  9731. compilation modules, making an @dfn{object file} for that module. The
  9732. last step is to @dfn{link} the many object files together into a
  9733. single executable for the whole program.
  9734. The full details of how to compile C programs (and other programs)
  9735. with GCC are documented in xxxx.
  9736. @c ??? ref
  9737. Here we give only a simple introduction.
  9738. These commands compile two compilation modules, @file{foo.c} and
  9739. @file{bar.c}, running the compiler for each module:
  9740. @example
  9741. gcc -c -O -g foo.c
  9742. gcc -c -O -g bar.c
  9743. @end example
  9744. @noindent
  9745. In these commands, @option{-g} says to generate debugging information,
  9746. @option{-O} says to do some optimization, and @option{-c} says to put
  9747. the compiled code for that module into a corresponding object file and
  9748. go no further. The object file for @file{foo.c} is automatically
  9749. called @file{foo.o}, and so on.
  9750. If you wish, you can specify the additional compilation options. For
  9751. instance, @option{-Wformat -Wparenthesis -Wstrict-prototypes} request
  9752. additional warnings.
  9753. @cindex linking object files
  9754. After you compile all the program's modules, you link the object files
  9755. into a combined executable, like this:
  9756. @example
  9757. gcc -o foo foo.o bar.o
  9758. @end example
  9759. @noindent
  9760. In this command, @option{-o foo} species the file name for the
  9761. executable file, and the other arguments are the object files to link.
  9762. Always specify the executable file name in a command that generates
  9763. one.
  9764. One reason to divide a large program into multiple compilation modules
  9765. is to control how each module can access the internals of the others.
  9766. When a module declares a function or variable @code{extern}, other
  9767. modules can access it. The other functions and variables defined in a
  9768. module can't be accessed from outside that module.
  9769. The other reason for using multiple modules is so that changing one
  9770. source file does not require recompiling all of them in order to try
  9771. the modified program. It is sufficient to recompile the source file
  9772. that you changed, then link them all again. Dividing a large program
  9773. into many substantial modules in this way typically makes
  9774. recompilation much faster.
  9775. Normally we don't run any of these commands directly. Instead we
  9776. write a set of @dfn{make rules} for the program, then use the
  9777. @command{make} program to recompile only the source files that need to
  9778. be recompiled, by following those rules. @xref{Top, The GNU Make
  9779. Mamual, , Make, The GNU Make Manual}).
  9780. @node Directing Compilation
  9781. @chapter Directing Compilation
  9782. This chapter describes C constructs that don't alter the program's
  9783. meaning @emph{as such}, but rather direct the compiler how to treat
  9784. some aspects of the program.
  9785. @menu
  9786. * Pragmas:: Controling compilation of some constructs.
  9787. * Static Assertions:: Compile-time tests for conditions.
  9788. @end menu
  9789. @node Pragmas
  9790. @section Pragmas
  9791. A @dfn{pragma} is an annotation in a program that gives direction to
  9792. the compiler.
  9793. @menu
  9794. * Pragma Basics:: Pragma syntax and usage.
  9795. * Severity Pragmas:: Settings for compile-time pragma output.
  9796. * Optimization Pragmas:: Controlling optimizations.
  9797. @end menu
  9798. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9799. @node Pragma Basics
  9800. @subsection Pragma Basics
  9801. C defines two syntactical forms for pragmas, the line form and the
  9802. token form. You can write any pragma in either form, with the same
  9803. meaning.
  9804. The line form is a line in the source code, like this:
  9805. @example
  9806. #pragma @var{line}
  9807. @end example
  9808. @noindent
  9809. The line pragma has no effect on the parsing of the lines around it.
  9810. This form has the drawback that it can't be generated by a macro expansion.
  9811. The token form is a series of tokens; it can appear anywhere in the
  9812. program between the other tokens.
  9813. @example
  9814. _Pragma (@var{stringconstant})
  9815. @end example
  9816. @noindent
  9817. The pragma has no effect on the syntax of the tokens that surround it;
  9818. thus, here's a pragma in the middle of an @code{if} statement:
  9819. @example
  9820. if _Pragma ("hello") (x > 1)
  9821. @end example
  9822. @noindent
  9823. However, that's an unclear thing to do; for the sake of
  9824. understandability, it is better to put a pragma on a line by itself
  9825. and not embedded in the middle of another construct.
  9826. Both forms of pragma have a textual argument. In a line pragma, the
  9827. text is the rest of the line. The textual argument to @code{_Pragma}
  9828. uses the same syntax as a C string constant: surround the text with
  9829. two @samp{"} characters, and add a backslash before each @samp{"} or
  9830. @samp{\} character in it.
  9831. With either syntax, the textual argument specifies what to do.
  9832. It begins with one or several words that specify the operation.
  9833. If the compiler does not recognize them, it ignores the pragma.
  9834. Here are the pragma operations supported in GNU C@.
  9835. @c ??? Verify font for []
  9836. @table @code
  9837. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9838. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9839. Declares that the current source file depends on @var{file}, so GNU C
  9840. compares the file times and gives a warning if @var{file} is newer
  9841. than the current source file.
  9842. This directive searches for @var{file} the way @code{#include}
  9843. searches for a non-system header file.
  9844. If @var{message} is given, the warning message includes that text.
  9845. Examples:
  9846. @example
  9847. #pragma GCC dependency "parse.y"
  9848. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9849. rerun fixincludes")
  9850. @end example
  9851. @item #pragma GCC poison @var{identifiers}
  9852. @itemx _Pragma ("GCC poison @var{identifiers}")
  9853. Poisons the identifiers listed in @var{identifiers}.
  9854. This is useful to make sure all mention of @var{identifiers} has been
  9855. deleted from the program and that no reference to them creeps back in.
  9856. If any of those identifiers appears anywhere in the source after the
  9857. directive, it causes a compilation error. For example,
  9858. @example
  9859. #pragma GCC poison printf sprintf fprintf
  9860. sprintf(some_string, "hello");
  9861. @end example
  9862. @noindent
  9863. generates an error.
  9864. If a poisoned identifier appears as part of the expansion of a macro
  9865. that was defined before the identifier was poisoned, it will @emph{not}
  9866. cause an error. Thus, system headers that define macros that use
  9867. the identifier will not cause errors.
  9868. For example,
  9869. @example
  9870. #define strrchr rindex
  9871. _Pragma ("GCC poison rindex")
  9872. strrchr(some_string, 'h');
  9873. @end example
  9874. @noindent
  9875. does not cause a compilation error.
  9876. @item #pragma GCC system_header
  9877. @itemx _Pragma ("GCC system_header")
  9878. Specify treating the rest of the current source file as if it came
  9879. from a system header file. @xref{System Headers, System Headers,
  9880. System Headers, gcc, Using the GNU Compiler Collection}.
  9881. @item #pragma GCC warning @var{message}
  9882. @itemx _Pragma ("GCC warning @var{message}")
  9883. Equivalent to @code{#warning}. Its advantage is that the
  9884. @code{_Pragma} form can be included in a macro definition.
  9885. @item #pragma GCC error @var{message}
  9886. @itemx _Pragma ("GCC error @var{message}")
  9887. Equivalent to @code{#error}. Its advantage is that the
  9888. @code{_Pragma} form can be included in a macro definition.
  9889. @item #pragma GCC message @var{message}
  9890. @itemx _Pragma ("GCC message @var{message}")
  9891. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9892. informational message, and could be used to include additional warning
  9893. or error text without triggering more warnings or errors. (Note that
  9894. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9895. @samp{GCC} as part of the pragma.)
  9896. @end table
  9897. @node Severity Pragmas
  9898. @subsection Severity Pragmas
  9899. These pragmas control the severity of classes of diagnostics.
  9900. You can specify the class of diagnostic with the GCC option that causes
  9901. those diagnostics to be generated.
  9902. @table @code
  9903. @item #pragma GCC diagnostic error @var{option}
  9904. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9905. For code following this pragma, treat diagnostics of the variety
  9906. specified by @var{option} as errors. For example:
  9907. @example
  9908. _Pragma ("GCC diagnostic error -Wformat")
  9909. @end example
  9910. @noindent
  9911. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9912. as errors rather than warnings.
  9913. @item #pragma GCC diagnostic warning @var{option}
  9914. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9915. For code following this pragma, treat diagnostics of the variety
  9916. specified by @var{option} as warnings. This overrides the
  9917. @var{-Werror} option which says to treat warnings as errors.
  9918. @item #pragma GCC diagnostic ignore @var{option}
  9919. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9920. For code following this pragma, refrain from reporting any diagnostics
  9921. of the variety specified by @var{option}.
  9922. @item #pragma GCC diagnostic push
  9923. @itemx _Pragma ("GCC diagnostic push")
  9924. @itemx #pragma GCC diagnostic pop
  9925. @itemx _Pragma ("GCC diagnostic pop")
  9926. These pragmas maintain a stack of states for severity settings.
  9927. @samp{GCC diagnostic push} saves the current settings on the stack,
  9928. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9929. the current settings from that.
  9930. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9931. restores the settings to what they were at the start of compilation.
  9932. Here is an example:
  9933. @example
  9934. _Pragma ("GCC diagnostic error -Wformat")
  9935. /* @r{@option{-Wformat} messages treated as errors. } */
  9936. _Pragma ("GCC diagnostic push")
  9937. _Pragma ("GCC diagnostic warning -Wformat")
  9938. /* @r{@option{-Wformat} messages treated as warnings. } */
  9939. _Pragma ("GCC diagnostic push")
  9940. _Pragma ("GCC diagnostic ignored -Wformat")
  9941. /* @r{@option{-Wformat} messages suppressed. } */
  9942. _Pragma ("GCC diagnostic pop")
  9943. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9944. _Pragma ("GCC diagnostic pop")
  9945. /* @r{@option{-Wformat} messages treated as errors again. } */
  9946. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9947. _Pragma ("GCC diagnostic pop")
  9948. /* @r{@option{-Wformat} messages treated once again}
  9949. @r{as specified by the GCC command-line options.} */
  9950. @end example
  9951. @end table
  9952. @node Optimization Pragmas
  9953. @subsection Optimization Pragmas
  9954. These pragmas enable a particular optimization for specific function
  9955. definitions. The settings take effect at the end of a function
  9956. definition, so the clean place to use these pragmas is between
  9957. function definitions.
  9958. @table @code
  9959. @item #pragma GCC optimize @var{optimization}
  9960. @itemx _Pragma ("GCC optimize @var{optimization}")
  9961. These pragmas enable the optimization @var{optimization} for the
  9962. following functions. For example,
  9963. @example
  9964. _Pragma ("GCC optimize -fforward-propagate")
  9965. @end example
  9966. @noindent
  9967. says to apply the @samp{forward-propagate} optimization to all
  9968. following function definitions. Specifying optimizations for
  9969. individual functions, rather than for the entire program, is rare but
  9970. can be useful for getting around a bug in the compiler.
  9971. If @var{optimization} does not correspond to a defined optimization
  9972. option, the pragma is erroneous. To turn off an optimization, use the
  9973. corresponding @samp{-fno-} option, such as
  9974. @samp{-fno-forward-propagate}.
  9975. @item #pragma GCC target @var{optimizations}
  9976. @itemx _Pragma ("GCC target @var{optimizations}")
  9977. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9978. used for platform-specific optimizations. Thus,
  9979. @example
  9980. _Pragma ("GCC target popcnt")
  9981. @end example
  9982. @noindent
  9983. activates the optimization @samp{popcnt} for all
  9984. following function definitions. This optimization is supported
  9985. on a few common targets but not on others.
  9986. @item #pragma GCC push_options
  9987. @itemx _Pragma ("GCC push_options")
  9988. The @samp{push_options} pragma saves on a stack the current settings
  9989. specified with the @samp{target} and @samp{optimize} pragmas.
  9990. @item #pragma GCC pop_options
  9991. @itemx _Pragma ("GCC pop_options")
  9992. The @samp{pop_options} pragma pops saved settings from that stack.
  9993. Here's an example of using this stack.
  9994. @example
  9995. _Pragma ("GCC push_options")
  9996. _Pragma ("GCC optimize forward-propagate")
  9997. /* @r{Functions to compile}
  9998. @r{with the @code{forward-propagate} optimization.} */
  9999. _Pragma ("GCC pop_options")
  10000. /* @r{Ends enablement of @code{forward-propagate}.} */
  10001. @end example
  10002. @item #pragma GCC reset_options
  10003. @itemx _Pragma ("GCC reset_options")
  10004. Clears all pragma-defined @samp{target} and @samp{optimize}
  10005. optimization settings.
  10006. @end table
  10007. @node Static Assertions
  10008. @section Static Assertions
  10009. @cindex static assertions
  10010. @findex _Static_assert
  10011. You can add compiler-time tests for necessary conditions into your
  10012. code using @code{_Static_assert}. This can be useful, for example, to
  10013. check that the compilation target platform supports the type sizes
  10014. that the code expects. For example,
  10015. @example
  10016. _Static_assert ((sizeof (long int) >= 8),
  10017. "long int needs to be at least 8 bytes");
  10018. @end example
  10019. @noindent
  10020. reports a compile-time error if compiled on a system with long
  10021. integers smaller than 8 bytes, with @samp{long int needs to be at
  10022. least 8 bytes} as the error message.
  10023. Since calls @code{_Static_assert} are processed at compile time, the
  10024. expression must be computable at compile time and the error message
  10025. must be a literal string. The expression can refer to the sizes of
  10026. variables, but can't refer to their values. For example, the
  10027. following static assertion is invalid for two reasons:
  10028. @example
  10029. char *error_message
  10030. = "long int needs to be at least 8 bytes";
  10031. int size_of_long_int = sizeof (long int);
  10032. _Static_assert (size_of_long_int == 8, error_message);
  10033. @end example
  10034. @noindent
  10035. The expression @code{size_of_long_int == 8} isn't computable at
  10036. compile time, and the error message isn't a literal string.
  10037. You can, though, use preprocessor definition values with
  10038. @code{_Static_assert}:
  10039. @example
  10040. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10041. at least 8 bytes"
  10042. _Static_assert ((sizeof (long int) == 8),
  10043. LONG_INT_ERROR_MESSAGE);
  10044. @end example
  10045. Static assertions are permitted wherever a statement or declaration is
  10046. permitted, including at top level in the file, and also inside the
  10047. definition of a type.
  10048. @example
  10049. union y
  10050. @{
  10051. int i;
  10052. int *ptr;
  10053. _Static_assert (sizeof (int *) == sizeof (int),
  10054. "Pointer and int not same size");
  10055. @};
  10056. @end example
  10057. @node Type Alignment
  10058. @appendix Type Alignment
  10059. @cindex type alignment
  10060. @cindex alignment of type
  10061. @findex _Alignof
  10062. @findex __alignof__
  10063. Code for device drivers and other communication with low-level
  10064. hardware sometimes needs to be concerned with the alignment of
  10065. data objects in memory.
  10066. Each data type has a required @dfn{alignment}, always a power of 2,
  10067. that says at which memory addresses an object of that type can validly
  10068. start. A valid address for the type must be a multiple of its
  10069. alignment. If a type's alignment is 1, that means it can validly
  10070. start at any address. If a type's alignment is 2, that means it can
  10071. only start at an even address. If a type's alignment is 4, that means
  10072. it can only start at an address that is a multiple of 4.
  10073. The alignment of a type (except @code{char}) can vary depending on the
  10074. kind of computer in use. To refer to the alignment of a type in a C
  10075. program, use @code{_Alignof}, whose syntax parallels that of
  10076. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10077. operation, and it doesn't compute the value of the expression used
  10078. as its argument.
  10079. Nominally, each integer and floating-point type has an alignment equal to
  10080. the largest power of 2 that divides its size. Thus, @code{int} with
  10081. size 4 has a nominal alignment of 4, and @code{long long int} with
  10082. size 8 has a nominal alignment of 8.
  10083. However, each kind of computer generally has a maximum alignment, and
  10084. no type needs more alignment than that. If the computer's maximum
  10085. alignment is 4 (which is common), then no type's alignment is more
  10086. than 4.
  10087. The size of any type is always a multiple of its alignment; that way,
  10088. in an array whose elements have that type, all the elements are
  10089. properly aligned if the first one is.
  10090. These rules apply to all real computers today, but some embedded
  10091. controllers have odd exceptions. We don't have references to cite for
  10092. them.
  10093. @c We can't cite a nonfree manual as documentation.
  10094. Ordinary C code guarantees that every object of a given type is in
  10095. fact aligned as that type requires.
  10096. If the operand of @code{_Alignof} is a structure field, the value
  10097. is the alignment it requires. It may have a greater alignment by
  10098. coincidence, due to the other fields, but @code{_Alignof} is not
  10099. concerned about that. @xref{Structures}.
  10100. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10101. but now that the feature has been standardized, it is better
  10102. to use the standard keyword @code{_Alignof}.
  10103. @findex _Alignas
  10104. @findex __aligned__
  10105. You can explicitly specify an alignment requirement for a particular
  10106. variable or structure field by adding @code{_Alignas
  10107. (@var{alignment})} to the declaration, where @var{alignment} is a
  10108. power of 2 or a type name. For instance:
  10109. @example
  10110. char _Alignas (8) x;
  10111. @end example
  10112. @noindent
  10113. or
  10114. @example
  10115. char _Alignas (double) x;
  10116. @end example
  10117. @noindent
  10118. specifies that @code{x} must start on an address that is a multiple of
  10119. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10120. machine, that maximum is how much alignment @code{x} will get.
  10121. The older GNU C syntax for this feature looked like
  10122. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10123. declaration, and was added after the variable. For instance:
  10124. @example
  10125. char x __attribute__ ((__aligned__ 8));
  10126. @end example
  10127. @xref{Attributes}.
  10128. @node Aliasing
  10129. @appendix Aliasing
  10130. @cindex aliasing (of storage)
  10131. @cindex pointer type conversion
  10132. @cindex type conversion, pointer
  10133. We have already presented examples of casting a @code{void *} pointer
  10134. to another pointer type, and casting another pointer type to
  10135. @code{void *}.
  10136. One common kind of pointer cast is guaranteed safe: casting the value
  10137. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10138. Allocation}). It is safe because these functions do not save the
  10139. pointer anywhere else; the only way the program will access the newly
  10140. allocated memory is via the pointer just returned.
  10141. In fact, C allows casting any pointer type to any other pointer type.
  10142. Using this to access the same place in memory using two
  10143. different data types is called @dfn{aliasing}.
  10144. Aliasing is necessary in some programs that do sophisticated memory
  10145. management, such as GNU Emacs, but most C programs don't need to do
  10146. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10147. aliasing correctly requires following the rules stated below.
  10148. Otherwise, the aliasing may result in malfunctions when the program
  10149. runs.
  10150. The rest of this appendix explains the pitfalls and rules of aliasing.
  10151. @menu
  10152. * Aliasing Alignment:: Memory alignment considerations for
  10153. casting between pointer types.
  10154. * Aliasing Length:: Type size considerations for
  10155. casting between pointer types.
  10156. * Aliasing Type Rules:: Even when type alignment and size matches,
  10157. aliasing can still have surprising results.
  10158. @end menu
  10159. @node Aliasing Alignment
  10160. @appendixsection Aliasing and Alignment
  10161. In order for a type-converted pointer to be valid, it must have the
  10162. alignment that the new pointer type requires. For instance, on most
  10163. computers, @code{int} has alignment 4; the address of an @code{int}
  10164. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10165. address of a @code{char} is usually not a multiple of 4. Taking the
  10166. address of such a @code{char} and casting it to @code{int *} probably
  10167. results in an invalid pointer. Trying to dereference it may cause a
  10168. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10169. @example
  10170. foo ()
  10171. @{
  10172. char i[4];
  10173. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10174. return *p; /* @r{Crash!} */
  10175. @}
  10176. @end example
  10177. This requirement is never a problem when casting the return value
  10178. of @code{malloc} because that function always returns a pointer
  10179. with as much alignment as any type can require.
  10180. @node Aliasing Length
  10181. @appendixsection Aliasing and Length
  10182. When converting a pointer to a different pointer type, make sure the
  10183. object it really points to is at least as long as the target of the
  10184. converted pointer. For instance, suppose @code{p} has type @code{int
  10185. *} and it's cast as follows:
  10186. @example
  10187. int *p;
  10188. struct
  10189. @{
  10190. double d, e, f;
  10191. @} foo;
  10192. struct foo *q = (struct foo *)p;
  10193. q->f = 5.14159;
  10194. @end example
  10195. @noindent
  10196. the value @code{q->f} will run past the end of the @code{int} that
  10197. @code{p} points to. If @code{p} was initialized to the start of an
  10198. array of type @code{int[6]}, the object is long enough for three
  10199. @code{double}s. But if @code{p} points to something shorter,
  10200. @code{q->f} will run on beyond the end of that, overlaying some other
  10201. data. Storing that will garble that other data. Or it could extend
  10202. past the end of memory space and cause a @code{SIGSEGV} signal
  10203. (@pxref{Signals}).
  10204. @node Aliasing Type Rules
  10205. @appendixsection Type Rules for Aliasing
  10206. C code that converts a pointer to a different pointer type can use the
  10207. pointers to access the same memory locations with two different data
  10208. types. If the same address is accessed with different types in a
  10209. single control thread, optimization can make the code do surprising
  10210. things (in effect, make it malfunction).
  10211. Here's a concrete example where aliasing that can change the code's
  10212. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10213. long, like @code{int}, and so is every pointer. Thus, the structures
  10214. @code{struct a} and @code{struct b} are both 8 bytes.
  10215. @example
  10216. #include <stdio.h>
  10217. struct a @{ int size; char *data; @};
  10218. struct b @{ float size; char *data; @};
  10219. void sub (struct a *p, struct b *q)
  10220. @{
  10221.   int x;
  10222.   p->size = 0;
  10223.   q->size = 1;
  10224.   x = p->size;
  10225.   printf("x       =%d\n", x);
  10226.   printf("p->size =%d\n", (int)p->size);
  10227.   printf("q->size =%d\n", (int)q->size);
  10228. @}
  10229. int main(void)
  10230. @{
  10231.   struct a foo;
  10232.   struct a *p = &foo;
  10233.   struct b *q = (struct b *) &foo;
  10234.   sub (p, q);
  10235. @}
  10236. @end example
  10237. This code works as intended when compiled without optimization. All
  10238. the operations are carried out sequentially as written. The code
  10239. sets @code{x} to @code{p->size}, but what it actually gets is the
  10240. bits of the floating point number 1, as type @code{int}.
  10241. However, when optimizing, the compiler is allowed to assume
  10242. (mistakenly, here) that @code{q} does not point to the same storage as
  10243. @code{p}, because their data types are not allowed to alias.
  10244. From this assumption, the compiler can deduce (falsely, here) that the
  10245. assignment into @code{q->size} has no effect on the value of
  10246. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10247. be set to 0.
  10248. GNU C, following the C standard, @emph{defines} this optimization as
  10249. legitimate. Code that misbehaves when optimized following these rules
  10250. is, by definition, incorrect C code.
  10251. The rules for storage aliasing in C are based on the two data types:
  10252. the type of the object, and the type it is accessed through. The
  10253. rules permit accessing part of a storage object of type @var{t} using
  10254. only these types:
  10255. @itemize @bullet
  10256. @item
  10257. @var{t}.
  10258. @item
  10259. A type compatible with @var{t}. @xref{Compatible Types}.
  10260. @item
  10261. A signed or unsigned version of one of the above.
  10262. @item
  10263. A qualifed version of one of the above.
  10264. @xref{Type Qualifiers}.
  10265. @item
  10266. An array, structure (@pxref{Structures}), or union type
  10267. (@code{Unions}) that contains one of the above, either directly as a
  10268. field or through multiple levels of fields. If @var{t} is
  10269. @code{double}, this would include @code{struct s @{ union @{ double
  10270. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10271. inside it somewhere.
  10272. @item
  10273. A character type.
  10274. @end itemize
  10275. What do these rules say about the example in this subsection?
  10276. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10277. @code{int}. The type @code{float} is not allowed as an aliasing type
  10278. by those rules, so @code{b->size} is not supposed to alias with
  10279. elements of @code{j}. Based on that assumption, GNU C makes a
  10280. permitted optimization that was not, in this case, consistent with
  10281. what the programmer intended the program to do.
  10282. Whether GCC actually performs type-based aliasing analysis depends on
  10283. the details of the code. GCC has other ways to determine (in some cases)
  10284. whether objects alias, and if it gets a reliable answer that way, it won't
  10285. fall back on type-based heuristics.
  10286. @c @opindex -fno-strict-aliasing
  10287. The importance of knowing the type-based aliasing rules is not so as
  10288. to ensure that the optimization is done where it would be safe, but so
  10289. as to ensure it is @emph{not} done in a way that would break the
  10290. program. You can turn off type-based aliasing analysis by giving GCC
  10291. the option @option{-fno-strict-aliasing}.
  10292. @node Digraphs
  10293. @appendix Digraphs
  10294. @cindex digraphs
  10295. C accepts aliases for certain characters. Apparently in the 1990s
  10296. some computer systems had trouble inputting these characters, or
  10297. trouble displaying them. These digraphs almost never appear in C
  10298. programs nowadays, but we mention them for completeness.
  10299. @table @samp
  10300. @item <:
  10301. An alias for @samp{[}.
  10302. @item :>
  10303. An alias for @samp{]}.
  10304. @item <%
  10305. An alias for @samp{@{}.
  10306. @item %>
  10307. An alias for @samp{@}}.
  10308. @item %:
  10309. An alias for @samp{#},
  10310. used for preprocessing directives (@pxref{Directives}) and
  10311. macros (@pxref{Macros}).
  10312. @end table
  10313. @node Attributes
  10314. @appendix Attributes in Declarations
  10315. @cindex attributes
  10316. @findex __attribute__
  10317. You can specify certain additional requirements in a declaration, to
  10318. get fine-grained control over code generation, and helpful
  10319. informational messages during compilation. We use a few attributes in
  10320. code examples throughout this manual, including
  10321. @table @code
  10322. @item aligned
  10323. The @code{aligned} attribute specifies a minimum alignment for a
  10324. variable or structure field, measured in bytes:
  10325. @example
  10326. int foo __attribute__ ((aligned (8))) = 0;
  10327. @end example
  10328. @noindent
  10329. This directs GNU C to allocate @code{foo} at an address that is a
  10330. multiple of 8 bytes. However, you can't force an alignment bigger
  10331. than the computer's maximum meaningful alignment.
  10332. @item packed
  10333. The @code{packed} attribute specifies to compact the fields of a
  10334. structure by not leaving gaps between fields. For example,
  10335. @example
  10336. struct __attribute__ ((packed)) bar
  10337. @{
  10338. char a;
  10339. int b;
  10340. @};
  10341. @end example
  10342. @noindent
  10343. allocates the integer field @code{b} at byte 1 in the structure,
  10344. immediately after the character field @code{a}. The packed structure
  10345. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10346. alignment is 1, that of @code{char}.
  10347. @item deprecated
  10348. Applicable to both variables and functions, the @code{deprecated}
  10349. attribute tells the compiler to issue a warning if the variable or
  10350. function is ever used in the source file.
  10351. @example
  10352. int old_foo __attribute__ ((deprecated));
  10353. int old_quux () __attribute__ ((deprecated));
  10354. @end example
  10355. @item __noinline__
  10356. The @code{__noinline__} attribute, in a function's declaration or
  10357. definition, specifies never to inline calls to that function. All
  10358. calls to that function, in a compilation unit where it has this
  10359. attribute, will be compiled to invoke the separately compiled
  10360. function. @xref{Inline Function Definitions}.
  10361. @item __noclone__
  10362. The @code{__noclone__} attribute, in a function's declaration or
  10363. definition, specifies never to clone that function. Thus, there will
  10364. be only one compiled version of the function. @xref{Label Value
  10365. Caveats}, for more information about cloning.
  10366. @item always_inline
  10367. The @code{always_inline} attribute, in a function's declaration or
  10368. definition, specifies to inline all calls to that function (unless
  10369. something about the function makes inlining impossible). This applies
  10370. to all calls to that function in a compilation unit where it has this
  10371. attribute. @xref{Inline Function Definitions}.
  10372. @item gnu_inline
  10373. The @code{gnu_inline} attribute, in a function's declaration or
  10374. definition, specifies to handle the @code{inline} keywprd the way GNU
  10375. C originally implemented it, many years before ISO C said anything
  10376. about inlining. @xref{Inline Function Definitions}.
  10377. @end table
  10378. For full documentation of attributes, see the GCC manual.
  10379. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10380. the GNU Compiler Collection}.
  10381. @node Signals
  10382. @appendix Signals
  10383. @cindex signal
  10384. @cindex handler (for signal)
  10385. @cindex @code{SIGSEGV}
  10386. @cindex @code{SIGFPE}
  10387. @cindex @code{SIGBUS}
  10388. Some program operations bring about an error condition called a
  10389. @dfn{signal}. These signals terminate the program, by default.
  10390. There are various different kinds of signals, each with a name. We
  10391. have seen several such error conditions through this manual:
  10392. @table @code
  10393. @item SIGSEGV
  10394. This signal is generated when a program tries to read or write outside
  10395. the memory that is allocated for it, or to write memory that can only
  10396. be read. The name is an abbreviation for ``segmentation violation''.
  10397. @item SIGFPE
  10398. This signal indicates a fatal arithmetic error. The name is an
  10399. abbreviation for ``floating-point exception'', but covers all types of
  10400. arithmetic errors, including division by zero and overflow.
  10401. @item SIGBUS
  10402. This signal is generated when an invalid pointer is dereferenced,
  10403. typically the result of dereferencing an uninintalized pointer. It is
  10404. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10405. invalid access to valid memory, while @code{SIGBUS} indicates an
  10406. attempt to access an invalid address.
  10407. @end table
  10408. These kinds of signal allow the program to specify a function as a
  10409. @dfn{signal handler}. When a signal has a handler, it doesn't
  10410. terminate the program; instead it calls the handler.
  10411. There are many other kinds of signal; here we list only those that
  10412. come from run-time errors in C operations. The rest have to do with
  10413. the functioning of the operating system. The GNU C Library Reference
  10414. Manual gives more explanation about signals (@pxref{Program Signal
  10415. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10416. Manual}).
  10417. @node GNU Free Documentation License
  10418. @appendix GNU Free Documentation License
  10419. @include fdl.texi
  10420. @node Symbol Index
  10421. @unnumbered Index of Symbols and Keywords
  10422. @printindex fn
  10423. @node Concept Index
  10424. @unnumbered Concept Index
  10425. @printindex cp
  10426. @bye