c.texi 422 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057
  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 in programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are provided by
  112. functions defined in the standard library, which is automatically
  113. available in every C program. @xref{Top, The GNU C Library, , libc,
  114. The GNU C Library Reference Manual}.
  115. GNU/Linux systems use the GNU C Library to do this job. It is itself
  116. a C program, so once you know C you can read its source code and see
  117. how its library functions do their jobs. Some fraction of the
  118. functions are implemented as @dfn{system calls}, which means they
  119. contain a special instruction that asks the system kernel (Linux) to
  120. do a specific task. To understand how those are implemented, you'd
  121. need to read Linux source code instead. Whether a library function is
  122. a system call is an internal implementation detail that makes no
  123. difference for how to call the function.
  124. This manual incorporates the former GNU C Preprocessor Manual, which
  125. was among the earliest GNU manuals. It also uses some text from the
  126. earlier GNU C Manual that was written by Trevis Rothwell and James
  127. Youngman.
  128. GNU C has many obscure features, each one either for historical
  129. compatibility or meant for very special situations. We have left them
  130. to a companion manual, the GNU C Obscurities Manual, which will be
  131. published digitally later.
  132. Please report errors and suggestions to c-manual@@gnu.org.
  133. @menu
  134. * The First Example:: Getting started with basic C code.
  135. * Complete Program:: A whole example program
  136. that can be compiled and run.
  137. * Storage:: Basic layout of storage; bytes.
  138. * Beyond Integers:: Exploring different numeric types.
  139. * Lexical Syntax:: The various lexical components of C programs.
  140. * Arithmetic:: Numeric computations.
  141. * Assignment Expressions:: Storing values in variables.
  142. * Execution Control Expressions:: Expressions combining values in various ways.
  143. * Binary Operator Grammar:: An overview of operator precedence.
  144. * Order of Execution:: The order of program execution.
  145. * Primitive Types:: More details about primitive data types.
  146. * Constants:: Explicit constant values:
  147. details and examples.
  148. * Type Size:: The memory space occupied by a type.
  149. * Pointers:: Creating and manipulating memory pointers.
  150. * Structures:: Compound data types built
  151. by grouping other types.
  152. * Arrays:: Creating and manipulating arrays.
  153. * Enumeration Types:: Sets of integers with named values.
  154. * Defining Typedef Names:: Using @code{typedef} to define type names.
  155. * Statements:: Controling program flow.
  156. * Variables:: Details about declaring, initializing,
  157. and using variables.
  158. * Type Qualifiers:: Mark variables for certain intended uses.
  159. * Functions:: Declaring, defining, and calling functions.
  160. * Compatible Types:: How to tell if two types are compatible
  161. with each other.
  162. * Type Conversions:: Converting between types.
  163. * Scope:: Different categories of identifier scope.
  164. * Preprocessing:: Using the GNU C preprocessor.
  165. * Integers in Depth:: How integer numbers are represented.
  166. * Floating Point in Depth:: How floating-point numbers are represented.
  167. * Compilation:: How to compile multi-file programs.
  168. * Directing Compilation:: Operations that affect compilation
  169. but don't change the program.
  170. Appendices
  171. * Type Alignment:: Where in memory a type can validly start.
  172. * Aliasing:: Accessing the same data in two types.
  173. * Digraphs:: Two-character aliases for some characters.
  174. * Attributes:: Specifying additional information
  175. in a declaration.
  176. * Signals:: Fatal errors triggered in various scenarios.
  177. * GNU Free Documentation License:: The license for this manual.
  178. * Symbol Index:: Keyword and symbol index.
  179. * Concept Index:: Detailed topical index.
  180. @detailmenu
  181. --- The Detailed Node Listing ---
  182. * Recursive Fibonacci:: Writing a simple function recursively.
  183. * Stack:: Each function call uses space in the stack.
  184. * Iterative Fibonacci:: Writing the same function iteratively.
  185. * Complete Example:: Turn the simple function into a full program.
  186. * Complete Explanation:: Explanation of each part of the example.
  187. * Complete Line-by-Line:: Explaining each line of the example.
  188. * Compile Example:: Using GCC to compile the example.
  189. * Float Example:: A function that uses floating-point numbers.
  190. * Array Example:: A function that works with arrays.
  191. * Array Example Call:: How to call that function.
  192. * Array Example Variations:: Different ways to write the call example.
  193. Lexical Syntax
  194. * English:: Write programs in English!
  195. * Characters:: The characters allowed in C programs.
  196. * Whitespace:: The particulars of whitespace characters.
  197. * Comments:: How to include comments in C code.
  198. * Identifiers:: How to form identifiers (names).
  199. * Operators/Punctuation:: Characters used as operators or punctuation.
  200. * Line Continuation:: Splitting one line into multiple lines.
  201. * Digraphs:: Two-character substitutes for some characters.
  202. Arithmetic
  203. * Basic Arithmetic:: Addition, subtraction, multiplication,
  204. and division.
  205. * Integer Arithmetic:: How C performs arithmetic with integer values.
  206. * Integer Overflow:: When an integer value exceeds the range
  207. of its type.
  208. * Mixed Mode:: Calculating with both integer values
  209. and floating-point values.
  210. * Division and Remainder:: How integer division works.
  211. * Numeric Comparisons:: Comparing numeric values for
  212. equality or order.
  213. * Shift Operations:: Shift integer bits left or right.
  214. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  215. Assignment Expressions
  216. * Simple Assignment:: The basics of storing a value.
  217. * Lvalues:: Expressions into which a value can be stored.
  218. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  219. * Increment/Decrement:: Shorthand for incrementing and decrementing
  220. an lvalue's contents.
  221. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  222. * Assignment in Subexpressions:: How to avoid ambiguity.
  223. * Write Assignments Separately:: Write assignments as separate statements.
  224. Execution Control Expressions
  225. * Logical Operators:: Logical conjunction, disjunction, negation.
  226. * Logicals and Comparison:: Logical operators with comparison operators.
  227. * Logicals and Assignments:: Assignments with logical operators.
  228. * Conditional Expression:: An if/else construct inside expressions.
  229. * Comma Operator:: Build a sequence of subexpressions.
  230. Order of Execution
  231. * Reordering of Operands:: Operations in C are not necessarily computed
  232. in the order they are written.
  233. * Associativity and Ordering:: Some associative operations are performed
  234. in a particular order; others are not.
  235. * Sequence Points:: Some guarantees about the order of operations.
  236. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  237. * Ordering of Operands:: Evaluation order of operands
  238. and function arguments.
  239. * Optimization and Ordering:: Compiler optimizations can reorder operations
  240. only if it has no impact on program results.
  241. Primitive Data Types
  242. * Integer Types:: Description of integer types.
  243. * Floating-Point Data Types:: Description of floating-point types.
  244. * Complex Data Types:: Description of complex number types.
  245. * The Void Type:: A type indicating no value at all.
  246. * Other Data Types:: A brief summary of other types.
  247. Constants
  248. * Integer Constants:: Literal integer values.
  249. * Integer Const Type:: Types of literal integer values.
  250. * Floating Constants:: Literal floating-point values.
  251. * Imaginary Constants:: Literal imaginary number values.
  252. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  253. * Character Constants:: Literal character values.
  254. * Unicode Character Codes:: Unicode characters represented
  255. in either UTF-16 or UTF-32.
  256. * Wide Character Constants:: Literal characters values larger than 8 bits.
  257. * String Constants:: Literal string values.
  258. * UTF-8 String Constants:: Literal UTF-8 string values.
  259. * Wide String Constants:: Literal string values made up of
  260. 16- or 32-bit characters.
  261. Pointers
  262. * Address of Data:: Using the ``address-of'' operator.
  263. * Pointer Types:: For each type, there is a pointer type.
  264. * Pointer Declarations:: Declaring variables with pointer types.
  265. * Pointer Type Designators:: Designators for pointer types.
  266. * Pointer Dereference:: Accessing what a pointer points at.
  267. * Null Pointers:: Pointers which do not point to any object.
  268. * Invalid Dereference:: Dereferencing null or invalid pointers.
  269. * Void Pointers:: Totally generic pointers, can cast to any.
  270. * Pointer Comparison:: Comparing memory address values.
  271. * Pointer Arithmetic:: Computing memory address values.
  272. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  273. * Pointer Arithmetic Low Level:: More about computing memory address values.
  274. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  275. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  276. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  277. * Printing Pointers:: Using @code{printf} for a pointer's value.
  278. Structures
  279. * Referencing Fields:: Accessing field values in a structure object.
  280. * Dynamic Memory Allocation:: Allocating space for objects
  281. while the program is running.
  282. * Field Offset:: Memory layout of fields within a structure.
  283. * Structure Layout:: Planning the memory layout of fields.
  284. * Packed Structures:: Packing structure fields as close as possible.
  285. * Bit Fields:: Dividing integer fields
  286. into fields with fewer bits.
  287. * Bit Field Packing:: How bit fields pack together in integers.
  288. * const Fields:: Making structure fields immutable.
  289. * Zero Length:: Zero-length array as a variable-length object.
  290. * Flexible Array Fields:: Another approach to variable-length objects.
  291. * Overlaying Structures:: Casting one structure type
  292. over an object of another structure type.
  293. * Structure Assignment:: Assigning values to structure objects.
  294. * Unions:: Viewing the same object in different types.
  295. * Packing With Unions:: Using a union type to pack various types into
  296. the same memory space.
  297. * Cast to Union:: Casting a value one of the union's alternative
  298. types to the type of the union itself.
  299. * Structure Constructors:: Building new structure objects.
  300. * Unnamed Types as Fields:: Fields' types do not always need names.
  301. * Incomplete Types:: Types which have not been fully defined.
  302. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  303. * Type Tags:: Scope of structure and union type tags.
  304. Arrays
  305. * Accessing Array Elements:: How to access individual elements of an array.
  306. * Declaring an Array:: How to name and reserve space for a new array.
  307. * Strings:: A string in C is a special case of array.
  308. * Incomplete Array Types:: Naming, but not allocating, a new array.
  309. * Limitations of C Arrays:: Arrays are not first-class objects.
  310. * Multidimensional Arrays:: Arrays of arrays.
  311. * Constructing Array Values:: Assigning values to an entire array at once.
  312. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  313. Statements
  314. * Expression Statement:: Evaluate an expression, as a statement,
  315. usually done for a side effect.
  316. * if Statement:: Basic conditional execution.
  317. * if-else Statement:: Multiple branches for conditional execution.
  318. * Blocks:: Grouping multiple statements together.
  319. * return Statement:: Return a value from a function.
  320. * Loop Statements:: Repeatedly executing a statement or block.
  321. * switch Statement:: Multi-way conditional choices.
  322. * switch Example:: A plausible example of using @code{switch}.
  323. * Duffs Device:: A special way to use @code{switch}.
  324. * Case Ranges:: Ranges of values for @code{switch} cases.
  325. * Null Statement:: A statement that does nothing.
  326. * goto Statement:: Jump to another point in the source code,
  327. identified by a label.
  328. * Local Labels:: Labels with limited scope.
  329. * Labels as Values:: Getting the address of a label.
  330. * Statement Exprs:: A series of statements used as an expression.
  331. Variables
  332. * Variable Declarations:: Name a variable and and reserve space for it.
  333. * Initializers:: Assigning inital values to variables.
  334. * Designated Inits:: Assigning initial values to array elements
  335. at particular array indices.
  336. * Auto Type:: Obtaining the type of a variable.
  337. * Local Variables:: Variables declared in function definitions.
  338. * File-Scope Variables:: Variables declared outside of
  339. function definitions.
  340. * Static Local Variables:: Variables declared within functions,
  341. but with permanent storage allocation.
  342. * Extern Declarations:: Declaring a variable
  343. which is allocated somewhere else.
  344. * Allocating File-Scope:: When is space allocated
  345. for file-scope variables?
  346. * auto and register:: Historically used storage directions.
  347. * Omitting Types:: The bad practice of declaring variables
  348. with implicit type.
  349. Type Qualifiers
  350. * const:: Variables whose values don't change.
  351. * volatile:: Variables whose values may be accessed
  352. or changed outside of the control of
  353. this program.
  354. * restrict Pointers:: Restricted pointers for code optimization.
  355. * restrict Pointer Example:: Example of how that works.
  356. Functions
  357. * Function Definitions:: Writing the body of a function.
  358. * Function Declarations:: Declaring the interface of a function.
  359. * Function Calls:: Using functions.
  360. * Function Call Semantics:: Call-by-value argument passing.
  361. * Function Pointers:: Using references to functions.
  362. * The main Function:: Where execution of a GNU C program begins.
  363. Type Conversions
  364. * Explicit Type Conversion:: Casting a value from one type to another.
  365. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  366. * Argument Promotions:: Automatic conversion of function parameters.
  367. * Operand Promotions:: Automatic conversion of arithmetic operands.
  368. * Common Type:: When operand types differ, which one is used?
  369. Scope
  370. * Scope:: Different categories of identifier scope.
  371. Preprocessing
  372. * Preproc Overview:: Introduction to the C preprocessor.
  373. * Directives:: The form of preprocessor directives.
  374. * Preprocessing Tokens:: The lexical elements of preprocessing.
  375. * Header Files:: Including one source file in another.
  376. * Macros:: Macro expansion by the preprocessor.
  377. * Conditionals:: Controling whether to compile some lines
  378. or ignore them.
  379. * Diagnostics:: Reporting warnings and errors.
  380. * Line Control:: Reporting source line numbers.
  381. * Null Directive:: A preprocessing no-op.
  382. Integers in Depth
  383. * Integer Representations:: How integer values appear in memory.
  384. * Maximum and Minimum Values:: Value ranges of integer types.
  385. Floating Point in Depth
  386. * Floating Representations:: How floating-point values appear in memory.
  387. * Floating Type Specs:: Precise details of memory representations.
  388. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  389. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  390. * Exception Flags:: Handling certain conditions in floating point.
  391. * Exact Floating-Point:: Not all floating calculations lose precision.
  392. * Rounding:: When a floating result can't be represented
  393. exactly in the floating-point type in use.
  394. * Rounding Issues:: Avoid magnifying rounding errors.
  395. * Significance Loss:: Subtracting numbers that are almost equal.
  396. * Fused Multiply-Add:: Taking advantage of a special floating-point
  397. instruction for faster execution.
  398. * Error Recovery:: Determining rounding errors.
  399. * Exact Floating Constants:: Precisely specified floating-point numbers.
  400. * Handling Infinity:: When floating calculation is out of range.
  401. * Handling NaN:: What floating calculation is undefined.
  402. * Signed Zeros:: Positive zero vs. negative zero.
  403. * Scaling by the Base:: A useful exact floating-point operation.
  404. * Rounding Control:: Specifying some rounding behaviors.
  405. * Machine Epsilon:: The smallest number you can add to 1.0
  406. and get a sum which is larger than 1.0.
  407. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  408. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  409. * Further Reading:: References for floating-point numbers.
  410. Directing Compilation
  411. * Pragmas:: Controling compilation of some constructs.
  412. * Static Assertions:: Compile-time tests for conditions.
  413. @end detailmenu
  414. @end menu
  415. @node The First Example
  416. @chapter The First Example
  417. This chapter presents the source code for a very simple C program and
  418. uses it to explain a few features of the language. If you already
  419. know the basic points of C presented in this chapter, you can skim it
  420. or skip it.
  421. We present examples of C source code (other than comments) using a
  422. fixed-width typeface, since that's the way they look when you edit
  423. them in an editor such as GNU Emacs.
  424. @menu
  425. * Recursive Fibonacci:: Writing a simple function recursively.
  426. * Stack:: Each function call uses space in the stack.
  427. * Iterative Fibonacci:: Writing the same function iteratively.
  428. @end menu
  429. @node Recursive Fibonacci
  430. @section Example: Recursive Fibonacci
  431. @cindex recursive Fibonacci function
  432. @cindex Fibonacci function, recursive
  433. To introduce the most basic features of C, let's look at code for a
  434. simple mathematical function that does calculations on integers. This
  435. function calculates the @var{n}th number in the Fibonacci series, in
  436. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  437. 13, 21, 34, 55, @dots{}.
  438. @example
  439. int
  440. fib (int n)
  441. @{
  442. if (n <= 2) /* @r{This avoids infinite recursion.} */
  443. return 1;
  444. else
  445. return fib (n - 1) + fib (n - 2);
  446. @}
  447. @end example
  448. This very simple program illustrates several features of C:
  449. @itemize @bullet
  450. @item
  451. A function definition, whose first two lines constitute the function
  452. header. @xref{Function Definitions}.
  453. @item
  454. A function parameter @code{n}, referred to as the variable @code{n}
  455. inside the function body. @xref{Function Parameter Variables}.
  456. A function definition uses parameters to refer to the argument
  457. values provided in a call to that function.
  458. @item
  459. Arithmetic. C programs add with @samp{+} and subtract with
  460. @samp{-}. @xref{Arithmetic}.
  461. @item
  462. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  463. equal.'' @xref{Numeric Comparisons}.
  464. @item
  465. Integer constants written in base 10.
  466. @xref{Integer Constants}.
  467. @item
  468. A function call. The function call @code{fib (n - 1)} calls the
  469. function @code{fib}, passing as its argument the value @code{n - 1}.
  470. @xref{Function Calls}.
  471. @item
  472. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  473. comment has no effect on the execution of the program. Its purpose is
  474. to provide explanations to people reading the source code. Including
  475. comments in the code is tremendously important---they provide
  476. background information so others can understand the code more quickly.
  477. @xref{Comments}.
  478. In this manual, we present comment text in the variable-width typeface
  479. used for the text of the chapters, not in the fixed-width typeface
  480. used for the rest of the code. That is to make comments easier to
  481. read. This distinction of typeface does not exist in a real file of C
  482. source code.
  483. @item
  484. Two kinds of statements, the @code{return} statement and the
  485. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  486. @item
  487. Recursion. The function @code{fib} calls itself; that is called a
  488. @dfn{recursive call}. These are valid in C, and quite common.
  489. The @code{fib} function would not be useful if it didn't return.
  490. Thus, recursive definitions, to be of any use, must avoid
  491. @dfn{infinite recursion}.
  492. This function definition prevents infinite recursion by specially
  493. handling the case where @code{n} is two or less. Thus the maximum
  494. depth of recursive calls is less than @code{n}.
  495. @end itemize
  496. @menu
  497. * Function Header:: The function's name and how it is called.
  498. * Function Body:: Declarations and statements that implement the function.
  499. @end menu
  500. @node Function Header
  501. @subsection Function Header
  502. @cindex function header
  503. In our example, the first two lines of the function definition are the
  504. @dfn{header}. Its purpose is to state the function's name and say how
  505. it is called:
  506. @example
  507. int
  508. fib (int n)
  509. @end example
  510. @noindent
  511. says that the function returns an integer (type @code{int}), its name is
  512. @code{fib}, and it takes one argument named @code{n} which is also an
  513. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  514. @node Function Body
  515. @subsection Function Body
  516. @cindex function body
  517. @cindex recursion
  518. The rest of the function definition is called the @dfn{function body}.
  519. Like every function body, this one starts with @samp{@{}, ends with
  520. @samp{@}}, and contains zero or more @dfn{statements} and
  521. @dfn{declarations}. Statements specify actions to take, whereas
  522. declarations define names of variables, functions, and so on. Each
  523. statement and each declaration ends with a semicolon (@samp{;}).
  524. Statements and declarations often contain @dfn{expressions}; an
  525. expression is a construct whose execution produces a @dfn{value} of
  526. some data type, but may also take actions through ``side effects''
  527. that alter subsequent execution. A statement, by contrast, does not
  528. have a value; it affects further execution of the program only through
  529. the actions it takes.
  530. This function body contains no declarations, and just one statement,
  531. but that one is a complex statement in that it contains nested
  532. statements. This function uses two kinds of statements:
  533. @table @code
  534. @item return
  535. The @code{return} statement makes the function return immediately.
  536. It looks like this:
  537. @example
  538. return @var{value};
  539. @end example
  540. Its meaning is to compute the expression @var{value} and exit the
  541. function, making it return whatever value that expression produced.
  542. For instance,
  543. @example
  544. return 1;
  545. @end example
  546. @noindent
  547. returns the integer 1 from the function, and
  548. @example
  549. return fib (n - 1) + fib (n - 2);
  550. @end example
  551. @noindent
  552. returns a value computed by performing two function calls
  553. as specified and adding their results.
  554. @item @code{if}@dots{}@code{else}
  555. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  556. Each time it executes, it chooses one of its two substatements to execute
  557. and ignores the other. It looks like this:
  558. @example
  559. if (@var{condition})
  560. @var{if-true-statement}
  561. else
  562. @var{if-false-statement}
  563. @end example
  564. Its meaning is to compute the expression @var{condition} and, if it's
  565. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  566. @var{if-false-statement}. @xref{if-else Statement}.
  567. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  568. simply an expression. It's considered ``true'' if its value is
  569. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  570. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  571. Comparisons}.) Thus,
  572. @example
  573. if (n <= 2)
  574. return 1;
  575. else
  576. return fib (n - 1) + fib (n - 2);
  577. @end example
  578. @noindent
  579. first tests whether the value of @code{n} is less than or equal to 2.
  580. If so, the expression @code{n <= 2} has the value 1. So execution
  581. continues with the statement
  582. @example
  583. return 1;
  584. @end example
  585. @noindent
  586. Otherwise, execution continues with this statement:
  587. @example
  588. return fib (n - 1) + fib (n - 2);
  589. @end example
  590. Each of these statements ends the execution of the function and
  591. provides a value for it to return. @xref{return Statement}.
  592. @end table
  593. Calculating @code{fib} using ordinary integers in C works only for
  594. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  595. in type @code{int}. The addition operation that tries to add
  596. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  597. This occurrence is called @dfn{integer overflow}.
  598. Overflow can manifest itself in various ways, but one thing that can't
  599. possibly happen is to produce the correct value, since that can't fit
  600. in the space for the value. @xref{Integer Overflow}.
  601. @xref{Functions}, for a full explanation about functions.
  602. @node Stack
  603. @section The Stack, And Stack Overflow
  604. @cindex stack
  605. @cindex stack frame
  606. @cindex stack overflow
  607. @cindex recursion, drawbacks of
  608. @cindex stack frame
  609. Recursion has a drawback: there are limits to how many nested levels of
  610. function calls a program can make. In C, each function call allocates a block
  611. of memory which it uses until the call returns. C allocates these
  612. blocks consecutively within a large area of memory known as the
  613. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  614. The size of the stack is limited; if the program tries to use too
  615. much, that causes the program to fail because the stack is full. This
  616. is called @dfn{stack overflow}.
  617. @cindex crash
  618. @cindex segmentation fault
  619. Stack overflow on GNU/Linux typically manifests itself as the
  620. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  621. fault.'' By default, this signal terminates the program immediately,
  622. rather than letting the program try to recover, or reach an expected
  623. ending point. (We commonly say in this case that the program
  624. ``crashes''). @xref{Signals}.
  625. It is inconvenient to observe a crash by passing too large
  626. an argument to recursive Fibonacci, because the program would run a
  627. long time before it crashes. This algorithm is simple but
  628. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  629. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  630. the final result.
  631. However, you can observe stack overflow very quickly if you use
  632. this function instead:
  633. @example
  634. int
  635. fill_stack (int n)
  636. @{
  637. if (n <= 1) /* @r{This limits the depth of recursion.} */
  638. return 1;
  639. else
  640. return fill_stack (n - 1);
  641. @}
  642. @end example
  643. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  644. and using the default configuration, an experiment showed there is
  645. enough stack space to do 261906 nested calls to that function. One
  646. more, and the stack overflows and the program crashes. On another
  647. platform, with a different configuration, or with a different
  648. function, the limit might be bigger or smaller.
  649. @node Iterative Fibonacci
  650. @section Example: Iterative Fibonacci
  651. @cindex iterative Fibonacci function
  652. @cindex Fibonacci function, iterative
  653. Here's a much faster algorithm for computing the same Fibonacci
  654. series. It is faster for two reasons. First, it uses @dfn{iteration}
  655. (that is, repetition or looping) rather than recursion, so it doesn't
  656. take time for a large number of function calls. But mainly, it is
  657. faster because the number of repetitions is small---only @code{@var{n}}.
  658. @c If you change this, change the duplicate in node Example of for.
  659. @example
  660. int
  661. fib (int n)
  662. @{
  663. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  664. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  665. int i;
  666. for (i = 1; i < n; ++i)
  667. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  668. /* @r{since @code{i < n} is false the first time.} */
  669. @{
  670. /* @r{Now @code{last} is @code{fib (@code{i})}}
  671. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  672. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  673. int next = prev + last;
  674. /* @r{Shift the values down.} */
  675. prev = last;
  676. last = next;
  677. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  678. @r{and @code{prev} is @code{fib (@code{i})}.}
  679. @r{But that won't stay true for long,}
  680. @r{because we are about to increment @code{i}.} */
  681. @}
  682. return last;
  683. @}
  684. @end example
  685. This definition computes @code{fib (@var{n})} in a time proportional
  686. to @code{@var{n}}. The comments in the definition explain how it works: it
  687. advances through the series, always keeps the last two values in
  688. @code{last} and @code{prev}, and adds them to get the next value.
  689. Here are the additional C features that this definition uses:
  690. @table @asis
  691. @item Internal blocks
  692. Within a function, wherever a statement is called for, you can write a
  693. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  694. more statements and declarations. (You can also use additional
  695. blocks as statements in a block.)
  696. The function body also counts as a block, which is why it can contain
  697. statements and declarations.
  698. @xref{Blocks}.
  699. @item Declarations of local variables
  700. This function body contains declarations as well as statements. There
  701. are three declarations directly in the function body, as well as a
  702. fourth declaration in an internal block. Each starts with @code{int}
  703. because it declares a variable whose type is integer. One declaration
  704. can declare several variables, but each of these declarations is
  705. simple and declares just one variable.
  706. Variables declared inside a block (either a function body or an
  707. internal block) are @dfn{local variables}. These variables exist only
  708. within that block; their names are not defined outside the block, and
  709. exiting the block deallocates their storage. This example declares
  710. four local variables: @code{last}, @code{prev}, @code{i}, and
  711. @code{next}.
  712. The most basic local variable declaration looks like this:
  713. @example
  714. @var{type} @var{variablename};
  715. @end example
  716. For instance,
  717. @example
  718. int i;
  719. @end example
  720. @noindent
  721. declares the local variable @code{i} as an integer.
  722. @xref{Variable Declarations}.
  723. @item Initializers
  724. When you declare a variable, you can also specify its initial value,
  725. like this:
  726. @example
  727. @var{type} @var{variablename} = @var{value};
  728. @end example
  729. For instance,
  730. @example
  731. int last = 1;
  732. @end example
  733. @noindent
  734. declares the local variable @code{last} as an integer (type
  735. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  736. @item Assignment
  737. Assignment: a specific kind of expression, written with the @samp{=}
  738. operator, that stores a new value in a variable or other place. Thus,
  739. @example
  740. @var{variable} = @var{value}
  741. @end example
  742. @noindent
  743. is an expression that computes @code{@var{value}} and stores the value in
  744. @code{@var{variable}}. @xref{Assignment Expressions}.
  745. @item Expression statements
  746. An expression statement is an expression followed by a semicolon.
  747. That computes the value of the expression, then ignores the value.
  748. An expression statement is useful when the expression changes some
  749. data or has other side effects---for instance, with function calls, or
  750. with assignments as in this example. @xref{Expression Statement}.
  751. Using an expression with no side effects in an expression statement is
  752. pointless except in very special cases. For instance, the expression
  753. statement @code{x;} would examine the value of @code{x} and ignore it.
  754. That is not useful.
  755. @item Increment operator
  756. The increment operator is @samp{++}. @code{++i} is an
  757. expression that is short for @code{i = i + 1}.
  758. @xref{Increment/Decrement}.
  759. @item @code{for} statements
  760. A @code{for} statement is a clean way of executing a statement
  761. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  762. @example
  763. for (i = 1; i < n; ++i)
  764. @var{body}
  765. @end example
  766. @noindent
  767. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  768. for the loop. The loop itself consists of
  769. @itemize @bullet
  770. @item
  771. Testing @code{i < n} and exiting the loop if that's false.
  772. @item
  773. Executing @var{body}.
  774. @item
  775. Advancing the loop (executing @code{++i}, which increments @code{i}).
  776. @end itemize
  777. The net result is to execute @var{body} with 1 in @code{i},
  778. then with 2 in @code{i}, and so on, stopping just before the repetition
  779. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  780. the loop will execute the body zero times.
  781. The body of the @code{for} statement must be one and only one
  782. statement. You can't write two statements in a row there; if you try
  783. to, only the first of them will be treated as part of the loop.
  784. The way to put multiple statements in such a place is to group them
  785. with a block, and that's what we do in this example.
  786. @end table
  787. @node Complete Program
  788. @chapter A Complete Program
  789. @cindex complete example program
  790. @cindex example program, complete
  791. It's all very well to write a Fibonacci function, but you cannot run
  792. it by itself. It is a useful program, but it is not a complete
  793. program.
  794. In this chapter we present a complete program that contains the
  795. @code{fib} function. This example shows how to make the program
  796. start, how to make it finish, how to do computation, and how to print
  797. a result.
  798. @menu
  799. * Complete Example:: Turn the simple function into a full program.
  800. * Complete Explanation:: Explanation of each part of the example.
  801. * Complete Line-by-Line:: Explaining each line of the example.
  802. * Compile Example:: Using GCC to compile the example.
  803. @end menu
  804. @node Complete Example
  805. @section Complete Program Example
  806. Here is the complete program that uses the simple, recursive version
  807. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  808. @example
  809. #include <stdio.h>
  810. int
  811. fib (int n)
  812. @{
  813. if (n <= 2) /* @r{This avoids infinite recursion.} */
  814. return 1;
  815. else
  816. return fib (n - 1) + fib (n - 2);
  817. @}
  818. int
  819. main (void)
  820. @{
  821. printf ("Fibonacci series item %d is %d\n",
  822. 20, fib (20));
  823. return 0;
  824. @}
  825. @end example
  826. @noindent
  827. This program prints a message that shows the value of @code{fib (20)}.
  828. Now for an explanation of what that code means.
  829. @node Complete Explanation
  830. @section Complete Program Explanation
  831. @ifnottex
  832. Here's the explanation of the code of the example in the
  833. previous section.
  834. @end ifnottex
  835. This sample program prints a message that shows the value of @code{fib
  836. (20)}, and exits with code 0 (which stands for successful execution).
  837. Every C program is started by running the function named @code{main}.
  838. Therefore, the example program defines a function named @code{main} to
  839. provide a way to start it. Whatever that function does is what the
  840. program does. @xref{The main Function}.
  841. The @code{main} function is the first one called when the program
  842. runs, but it doesn't come first in the example code. The order of the
  843. function definitions in the source code makes no difference to the
  844. program's meaning.
  845. The initial call to @code{main} always passes certain arguments, but
  846. @code{main} does not have to pay attention to them. To ignore those
  847. arguments, define @code{main} with @code{void} as the parameter list.
  848. (@code{void} as a function's parameter list normally means ``call with
  849. no arguments,'' but @code{main} is a special case.)
  850. The function @code{main} returns 0 because that is
  851. the conventional way for @code{main} to indicate successful execution.
  852. It could instead return a positive integer to indicate failure, and
  853. some utility programs have specific conventions for the meaning of
  854. certain numeric @dfn{failure codes}. @xref{Values from main}.
  855. @cindex @code{printf}
  856. The simplest way to print text in C is by calling the @code{printf}
  857. function, so here we explain very briefly what that function does.
  858. For a full explanation of @code{printf} and the other standard I/O
  859. functions, see @ref{I/O on Streams, The GNU C Library, , libc, The GNU
  860. C Library Reference Manual}.
  861. @cindex standard output
  862. The first argument to @code{printf} is a @dfn{string constant}
  863. (@pxref{String Constants}) that is a template for output. The
  864. function @code{printf} copies most of that string directly as output,
  865. including the newline character at the end of the string, which is
  866. written as @samp{\n}. The output goes to the program's @dfn{standard
  867. output} destination, which in the usual case is the terminal.
  868. @samp{%} in the template introduces a code that substitutes other text
  869. into the output. Specifically, @samp{%d} means to take the next
  870. argument to @code{printf} and substitute it into the text as a decimal
  871. number. (The argument for @samp{%d} must be of type @code{int}; if it
  872. isn't, @code{printf} will malfunction.) So the output is a line that
  873. looks like this:
  874. @example
  875. Fibonacci series item 20 is 6765
  876. @end example
  877. This program does not contain a definition for @code{printf} because
  878. it is defined by the C library, which makes it available in all C
  879. programs. However, each program does need to @dfn{declare}
  880. @code{printf} so it will be called correctly. The @code{#include}
  881. line takes care of that; it includes a @dfn{header file} called
  882. @file{stdio.h} into the program's code. That file is provided by the
  883. operating system and it contains declarations for the many standard
  884. input/output functions in the C library, one of which is
  885. @code{printf}.
  886. Don't worry about header files for now; we'll explain them later in
  887. @ref{Header Files}.
  888. The first argument of @code{printf} does not have to be a string
  889. constant; it can be any string (@pxref{Strings}). However, using a
  890. constant is the most common case.
  891. @node Complete Line-by-Line
  892. @section Complete Program, Line by Line
  893. Here's the same example, explained line by line.
  894. @strong{Beginners, do you find this helpful or not?
  895. Would you prefer a different layout for the example?
  896. Please tell rms@@gnu.org.}
  897. @example
  898. #include <stdio.h> /* @r{Include declaration of usual} */
  899. /* @r{I/O functions such as @code{printf}.} */
  900. /* @r{Most programs need these.} */
  901. int /* @r{This function returns an @code{int}.} */
  902. fib (int n) /* @r{Its name is @code{fib};} */
  903. /* @r{its argument is called @code{n}.} */
  904. @{ /* @r{Start of function body.} */
  905. /* @r{This stops the recursion from being infinite.} */
  906. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  907. return 1; /* @r{make @code{fib} return 1.} */
  908. else /* @r{otherwise, add the two previous} */
  909. /* @r{fibonacci numbers.} */
  910. return fib (n - 1) + fib (n - 2);
  911. @}
  912. int /* @r{This function returns an @code{int}.} */
  913. main (void) /* @r{Start here; ignore arguments.} */
  914. @{ /* @r{Print message with numbers in it.} */
  915. printf ("Fibonacci series item %d is %d\n",
  916. 20, fib (20));
  917. return 0; /* @r{Terminate program, report success.} */
  918. @}
  919. @end example
  920. @node Compile Example
  921. @section Compiling the Example Program
  922. @cindex compiling
  923. @cindex executable file
  924. To run a C program requires converting the source code into an
  925. @dfn{executable file}. This is called @dfn{compiling} the program,
  926. and the command to do that using GNU C is @command{gcc}.
  927. This example program consists of a single source file. If we
  928. call that file @file{fib1.c}, the complete command to compile it is
  929. this:
  930. @example
  931. gcc -g -O -o fib1 fib1.c
  932. @end example
  933. @noindent
  934. Here, @option{-g} says to generate debugging information, @option{-O}
  935. says to optimize at the basic level, and @option{-o fib1} says to put
  936. the executable program in the file @file{fib1}.
  937. To run the program, use its file name as a shell command.
  938. For instance,
  939. @example
  940. ./fib1
  941. @end example
  942. @noindent
  943. However, unless you are sure the program is correct, you should
  944. expect to need to debug it. So use this command,
  945. @example
  946. gdb fib1
  947. @end example
  948. @noindent
  949. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  950. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  951. debug the executable program @code{fib1}.
  952. Richard Stallman's advice, from personal experience, is to turn to the
  953. debugger as soon as you can reproduce the problem. Don't try to avoid
  954. it by using other methods instead---occasionally they are shortcuts,
  955. but usually they waste an unbounded amount of time. With the
  956. debugger, you will surely find the bug in a reasonable time; overall,
  957. you will get your work done faster. The sooner you get serious and
  958. start the debugger, the sooner you are likely to find the bug.
  959. @xref{Compilation}, for an introduction to compiling more complex
  960. programs which consist of more than one source file.
  961. @node Storage
  962. @chapter Storage and Data
  963. @cindex bytes
  964. @cindex storage organization
  965. @cindex memory organization
  966. Storage in C programs is made up of units called @dfn{bytes}. On
  967. nearly all computers, a byte consists of 8 bits, but there are a few
  968. peculiar computers (mostly ``embedded controllers'' for very small
  969. systems) where a byte is longer than that. This manual does not try
  970. to explain the peculiarity of those computers; we assume that a byte
  971. is 8 bits.
  972. Every C data type is made up of a certain number of bytes; that number
  973. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  974. types @code{signed char} and @code{unsigned char} are one byte long;
  975. use those types to operate on data byte by byte. @xref{Signed and
  976. Unsigned Types}. You can refer to a series of consecutive bytes as an
  977. array of @code{char} elements; that's what an ASCII string looks like
  978. in memory. @xref{String Constants}.
  979. @node Beyond Integers
  980. @chapter Beyond Integers
  981. So far we've presented programs that operate on integers. In this
  982. chapter we'll present examples of handling non-integral numbers and
  983. arrays of numbers.
  984. @menu
  985. * Float Example:: A function that uses floating-point numbers.
  986. * Array Example:: A function that works with arrays.
  987. * Array Example Call:: How to call that function.
  988. * Array Example Variations:: Different ways to write the call example.
  989. @end menu
  990. @node Float Example
  991. @section An Example with Non-Integer Numbers
  992. @cindex floating point example
  993. Here's a function that operates on and returns @dfn{floating point}
  994. numbers that don't have to be integers. Floating point represents a
  995. number as a fraction together with a power of 2. (For more detail,
  996. @pxref{Floating-Point Data Types}.) This example calculates the
  997. average of three floating point numbers that are passed to it as
  998. arguments:
  999. @example
  1000. double
  1001. average_of_three (double a, double b, double c)
  1002. @{
  1003. return (a + b + c) / 3;
  1004. @}
  1005. @end example
  1006. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  1007. integers, and even when they happen to be integers, most likely their
  1008. average is not an integer.
  1009. @code{double} is the usual data type in C for calculations on
  1010. floating-point numbers.
  1011. To print a @code{double} with @code{printf}, we must use @samp{%f}
  1012. instead of @samp{%d}:
  1013. @example
  1014. printf ("Average is %f\n",
  1015. average_of_three (1.1, 9.8, 3.62));
  1016. @end example
  1017. The code that calls @code{printf} must pass a @code{double} for
  1018. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  1019. If the argument has the wrong type, @code{printf} will produce garbage
  1020. output.
  1021. Here's a complete program that computes the average of three
  1022. specific numbers and prints the result:
  1023. @example
  1024. double
  1025. average_of_three (double a, double b, double c)
  1026. @{
  1027. return (a + b + c) / 3;
  1028. @}
  1029. int
  1030. main (void)
  1031. @{
  1032. printf ("Average is %f\n",
  1033. average_of_three (1.1, 9.8, 3.62));
  1034. return 0;
  1035. @}
  1036. @end example
  1037. From now on we will not present examples of calls to @code{main}.
  1038. Instead we encourage you to write them for yourself when you want
  1039. to test executing some code.
  1040. @node Array Example
  1041. @section An Example with Arrays
  1042. @cindex array example
  1043. A function to take the average of three numbers is very specific and
  1044. limited. A more general function would take the average of any number
  1045. of numbers. That requires passing the numbers in an array. An array
  1046. is an object in memory that contains a series of values of the same
  1047. data type. This chapter presents the basic concepts and use of arrays
  1048. through an example; for the full explanation, see @ref{Arrays}.
  1049. Here's a function definition to take the average of several
  1050. floating-point numbers, passed as type @code{double}. The first
  1051. parameter, @code{length}, specifies how many numbers are passed. The
  1052. second parameter, @code{input_data}, is an array that holds those
  1053. numbers.
  1054. @example
  1055. double
  1056. avg_of_double (int length, double input_data[])
  1057. @{
  1058. double sum = 0;
  1059. int i;
  1060. for (i = 0; i < length; i++)
  1061. sum = sum + input_data[i];
  1062. return sum / length;
  1063. @}
  1064. @end example
  1065. This introduces the expression to refer to an element of an array:
  1066. @code{input_data[i]} means the element at index @code{i} in
  1067. @code{input_data}. The index of the element can be any expression
  1068. with an integer value; in this case, the expression is @code{i}.
  1069. @xref{Accessing Array Elements}.
  1070. @cindex zero-origin indexing
  1071. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1072. valid index is one less than the number of elements. (This is known
  1073. as @dfn{zero-origin indexing}.)
  1074. This example also introduces the way to declare that a function
  1075. parameter is an array. Such declarations are modeled after the syntax
  1076. for an element of the array. Just as @code{double foo} declares that
  1077. @code{foo} is of type @code{double}, @code{double input_data[]}
  1078. declares that each element of @code{input_data} is of type
  1079. @code{double}. Therefore, @code{input_data} itself has type ``array
  1080. of @code{double}.''
  1081. When declaring an array parameter, it's not necessary to say how long
  1082. the array is. In this case, the parameter @code{input_data} has no
  1083. length information. That's why the function needs another parameter,
  1084. @code{length}, for the caller to provide that information to the
  1085. function @code{avg_of_double}.
  1086. @node Array Example Call
  1087. @section Calling the Array Example
  1088. To call the function @code{avg_of_double} requires making an
  1089. array and then passing it as an argument. Here is an example.
  1090. @example
  1091. @{
  1092. /* @r{The array of values to average.} */
  1093. double nums_to_average[5];
  1094. /* @r{The average, once we compute it.} */
  1095. double average;
  1096. /* @r{Fill in elements of @code{nums_to_average}.} */
  1097. nums_to_average[0] = 58.7;
  1098. nums_to_average[1] = 5.1;
  1099. nums_to_average[2] = 7.7;
  1100. nums_to_average[3] = 105.2;
  1101. nums_to_average[4] = -3.14159;
  1102. average = avg_of_double (5, nums_to_average);
  1103. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1104. @}
  1105. @end example
  1106. This shows an array subscripting expression again, this time
  1107. on the left side of an assignment, storing a value into an
  1108. element of an array.
  1109. It also shows how to declare a local variable that is an array:
  1110. @code{double nums_to_average[5];}. Since this declaration allocates the
  1111. space for the array, it needs to know the array's length. You can
  1112. specify the length with any expression whose value is an integer, but
  1113. in this declaration the length is a constant, the integer 5.
  1114. The name of the array, when used by itself as an expression, stands
  1115. for the address of the array's data, and that's what gets passed to
  1116. the function @code{avg_of_double} in @code{avg_of_double (5,
  1117. nums_to_average)}.
  1118. We can make the code easier to maintain by avoiding the need to write
  1119. 5, the array length, when calling @code{avg_of_double}. That way, if
  1120. we change the array to include more elements, we won't have to change
  1121. that call. One way to do this is with the @code{sizeof} operator:
  1122. @example
  1123. average = avg_of_double ((sizeof (nums_to_average)
  1124. / sizeof (nums_to_average[0])),
  1125. nums_to_average);
  1126. @end example
  1127. This computes the number of elements in @code{nums_to_average} by dividing
  1128. its total size by the size of one element. @xref{Type Size}, for more
  1129. details of using @code{sizeof}.
  1130. We don't show in this example what happens after storing the result of
  1131. @code{avg_of_double} in the variable @code{average}. Presumably
  1132. more code would follow that uses that result somehow. (Why compute
  1133. the average and not use it?) But that isn't part of this topic.
  1134. @node Array Example Variations
  1135. @section Variations for Array Example
  1136. The code to call @code{avg_of_double} has two declarations that
  1137. start with the same data type:
  1138. @example
  1139. /* @r{The array of values to average.} */
  1140. double nums_to_average[5];
  1141. /* @r{The average, once we compute it.} */
  1142. double average;
  1143. @end example
  1144. In C, you can combine the two, like this:
  1145. @example
  1146. double nums_to_average[5], average;
  1147. @end example
  1148. This declares @code{nums_to_average} so each of its elements is a
  1149. @code{double}, and @code{average} so that it simply is a
  1150. @code{double}.
  1151. However, while you @emph{can} combine them, that doesn't mean you
  1152. @emph{should}. If it is useful to write comments about the variables,
  1153. and usually it is, then it's clearer to keep the declarations separate
  1154. so you can put a comment on each one.
  1155. We set all of the elements of the array @code{nums_to_average} with
  1156. assignments, but it is more convenient to use an initializer in the
  1157. declaration:
  1158. @example
  1159. @{
  1160. /* @r{The array of values to average.} */
  1161. double nums_to_average[]
  1162. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1163. /* @r{The average, once we compute it.} */
  1164. average = avg_of_double ((sizeof (nums_to_average)
  1165. / sizeof (nums_to_average[0])),
  1166. nums_to_average);
  1167. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1168. @}
  1169. @end example
  1170. The array initializer is a comma-separated list of values, delimited
  1171. by braces. @xref{Initializers}.
  1172. Note that the declaration does not specify a size for
  1173. @code{nums_to_average}, so the size is determined from the
  1174. initializer. There are five values in the initializer, so
  1175. @code{nums_to_average} gets length 5. If we add another element to
  1176. the initializer, @code{nums_to_average} will have six elements.
  1177. Because the code computes the number of elements from the size of
  1178. the array, using @code{sizeof}, the program will operate on all the
  1179. elements in the initializer, regardless of how many those are.
  1180. @node Lexical Syntax
  1181. @chapter Lexical Syntax
  1182. @cindex lexical syntax
  1183. @cindex token
  1184. To start the full description of the C language, we explain the
  1185. lexical syntax and lexical units of C code. The lexical units of a
  1186. programming language are known as @dfn{tokens}. This chapter covers
  1187. all the tokens of C except for constants, which are covered in a later
  1188. chapter (@pxref{Constants}). One vital kind of token is the
  1189. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1190. kind.
  1191. @menu
  1192. * English:: Write programs in English!
  1193. * Characters:: The characters allowed in C programs.
  1194. * Whitespace:: The particulars of whitespace characters.
  1195. * Comments:: How to include comments in C code.
  1196. * Identifiers:: How to form identifiers (names).
  1197. * Operators/Punctuation:: Characters used as operators or punctuation.
  1198. * Line Continuation:: Splitting one line into multiple lines.
  1199. @end menu
  1200. @node English
  1201. @section Write Programs in English!
  1202. In principle, you can write the function and variable names in a
  1203. program, and the comments, in any human language. C allows any kinds
  1204. of characters in comments, and you can put non-ASCII characters into
  1205. identifiers with a special prefix. However, to enable programmers in
  1206. all countries to understand and develop the program, it is best given
  1207. today's circumstances to write identifiers and comments in
  1208. English.
  1209. English is the one language that programmers in all countries
  1210. generally study. If a program's names are in English, most
  1211. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1212. understand them. Most programmers in those countries can speak
  1213. English, or at least read it, but they do not read each other's
  1214. languages at all. In India, with so many languages, two programmers
  1215. may have no common language other than English.
  1216. If you don't feel confident in writing English, do the best you can,
  1217. and follow each English comment with a version in a language you
  1218. write better; add a note asking others to translate that to English.
  1219. Someone will eventually do that.
  1220. The program's user interface is a different matter. We don't need to
  1221. choose one language for that; it is easy to support multiple languages
  1222. and let each user choose the language to use. This requires writing
  1223. the program to support localization of its interface. (The
  1224. @code{gettext} package exists to support this; @pxref{Message
  1225. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1226. Manual}.) Then a community-based translation effort can provide
  1227. support for all the languages users want to use.
  1228. @node Characters
  1229. @section Characters
  1230. @cindex character set
  1231. @cindex Unicode
  1232. @c ??? How to express ¶?
  1233. GNU C source files are usually written in the
  1234. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1235. was defined in the 1960s for English. However, they can also include
  1236. Unicode characters represented in the
  1237. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1238. This makes it possible to represent accented letters such as @samp{á},
  1239. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1240. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1241. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1242. manual.}
  1243. In C source code, non-ASCII characters are valid in comments, in wide
  1244. character constants (@pxref{Wide Character Constants}), and in string
  1245. constants (@pxref{String Constants}).
  1246. @c ??? valid in identifiers?
  1247. Another way to specify non-ASCII characters in constants (character or
  1248. string) and identifiers is with an escape sequence starting with
  1249. backslash, specifying the intended Unicode character. (@xref{Unicode
  1250. Character Codes}.) This specifies non-ASCII characters without
  1251. putting a real non-ASCII character in the source file itself.
  1252. C accepts two-character aliases called @dfn{digraphs} for certain
  1253. characters. @xref{Digraphs}.
  1254. @node Whitespace
  1255. @section Whitespace
  1256. @cindex whitespace characters in source files
  1257. @cindex space character in source
  1258. @cindex tab character in source
  1259. @cindex formfeed in source
  1260. @cindex linefeed in source
  1261. @cindex newline in source
  1262. @cindex carriage return in source
  1263. @cindex vertical tab in source
  1264. Whitespace means characters that exist in a file but appear blank in a
  1265. printed listing of a file (or traditionally did appear blank, several
  1266. decades ago). The C language requires whitespace in order to separate
  1267. two consecutive identifiers, or to separate an identifier from a
  1268. numeric constant. Other than that, and a few special situations
  1269. described later, whitespace is optional; you can put it in when you
  1270. wish, to make the code easier to read.
  1271. Space and tab in C code are treated as whitespace characters. So are
  1272. line breaks. You can represent a line break with the newline
  1273. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1274. the CRLF sequence (two characters: carriage return followed by a
  1275. newline character).
  1276. The @dfn{formfeed} character, Control-L, was traditionally used to
  1277. divide a file into pages. It is still used this way in source code,
  1278. and the tools that generate nice printouts of source code still start
  1279. a new page after each ``formfeed'' character. Dividing code into
  1280. pages separated by formfeed characters is a good way to break it up
  1281. into comprehensible pieces and show other programmers where they start
  1282. and end.
  1283. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1284. make printing advance down to the next section of a page. We know of
  1285. no particular reason to use it in source code, but it is still
  1286. accepted as whitespace in C.
  1287. Comments are also syntactically equivalent to whitespace.
  1288. @ifinfo
  1289. @xref{Comments}.
  1290. @end ifinfo
  1291. @node Comments
  1292. @section Comments
  1293. @cindex comments
  1294. A comment encapsulates text that has no effect on the program's
  1295. execution or meaning.
  1296. The purpose of comments is to explain the code to people that read it.
  1297. Writing good comments for your code is tremendously important---they
  1298. should provide background information that helps programmers
  1299. understand the reasons why the code is written the way it is. You,
  1300. returning to the code six months from now, will need the help of these
  1301. comments to remember why you wrote it this way.
  1302. Outdated comments that become incorrect are counterproductive, so part
  1303. of the software developer's responsibility is to update comments as
  1304. needed to correspond with changes to the program code.
  1305. C allows two kinds of comment syntax, the traditional style and the
  1306. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1307. with @samp{*/}. For instance,
  1308. @example
  1309. /* @r{This is a comment in traditional C syntax.} */
  1310. @end example
  1311. A traditional comment can contain @samp{/*}, but these delimiters do
  1312. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1313. whether it contains @samp{/*} sequences.
  1314. @example
  1315. /* @r{This} /* @r{is a comment} */ But this is not! */
  1316. @end example
  1317. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1318. For instance,
  1319. @example
  1320. // @r{This is a comment in C@t{++} style.}
  1321. @end example
  1322. Line comments do nest, in effect, because @samp{//} inside a line
  1323. comment is part of that comment:
  1324. @example
  1325. // @r{this whole line is} // @r{one comment}
  1326. This is code, not comment.
  1327. @end example
  1328. It is safe to put line comments inside block comments, or vice versa.
  1329. @example
  1330. @group
  1331. /* @r{traditional comment}
  1332. // @r{contains line comment}
  1333. @r{more traditional comment}
  1334. */ text here is not a comment
  1335. // @r{line comment} /* @r{contains traditional comment} */
  1336. @end group
  1337. @end example
  1338. But beware of commenting out one end of a traditional comment with a line
  1339. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1340. inside an already-started comment.
  1341. @example
  1342. @group
  1343. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1344. Oops! The line comment has ended;
  1345. this isn't a comment any more. */
  1346. @end group
  1347. @end example
  1348. Comments are not recognized within string constants. @t{@w{"/* blah
  1349. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1350. string.
  1351. In this manual we show the text in comments in a variable-width font,
  1352. for readability, but this font distinction does not exist in source
  1353. files.
  1354. A comment is syntactically equivalent to whitespace, so it always
  1355. separates tokens. Thus,
  1356. @example
  1357. @group
  1358. int/* @r{comment} */foo;
  1359. @r{is equivalent to}
  1360. int foo;
  1361. @end group
  1362. @end example
  1363. @noindent
  1364. but clean code always uses real whitespace to separate the comment
  1365. visually from surrounding code.
  1366. @node Identifiers
  1367. @section Identifiers
  1368. @cindex identifiers
  1369. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1370. as well as @samp{_}, that does not start with a digit. Most compilers
  1371. also allow @samp{$}. An identifier can be as long as you like; for
  1372. example,
  1373. @example
  1374. int anti_dis_establishment_arian_ism;
  1375. @end example
  1376. @cindex case of letters in identifiers
  1377. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1378. and @code{A} are two different identifiers.
  1379. @cindex keyword
  1380. @cindex reserved words
  1381. Identifiers in C are used as variable names, function names, typedef
  1382. names, enumeration constants, type tags, field names, and labels.
  1383. Certain identifiers in C are @dfn{keywords}, which means they have
  1384. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1385. meaning you cannot use them in any other way. For instance, you can't
  1386. define a variable or function named @code{return} or @code{if}.
  1387. You can also include other characters, even non-ASCII characters, in
  1388. identifiers by writing their Unicode character names, which start with
  1389. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1390. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1391. characters in identifiers, and when they are written in English, they
  1392. never need non-ASCII characters. @xref{English}.
  1393. Whitespace is required to separate two consecutive identifiers, or to
  1394. separate an identifier from a preceding or following numeric
  1395. constant.
  1396. @node Operators/Punctuation
  1397. @section Operators and Punctuation
  1398. @cindex operators
  1399. @cindex punctuation
  1400. Here we describe the lexical syntax of operators and punctuation in C.
  1401. The specific operators of C and their meanings are presented in
  1402. subsequent chapters.
  1403. Most operators in C consist of one or two characters that can't be
  1404. used in identifiers. The characters used for operators in C are
  1405. @samp{!~^&|*/%+-=<>,.?:}.
  1406. Some operators are a single character. For instance, @samp{-} is the
  1407. operator for negation (with one operand) and the operator for
  1408. subtraction (with two operands).
  1409. Some operators are two characters. For example, @samp{++} is the
  1410. increment operator. Recognition of multicharacter operators works by
  1411. grouping together as many consecutive characters as can constitute one
  1412. operator.
  1413. For instance, the character sequence @samp{++} is always interpreted
  1414. as the increment operator; therefore, if we want to write two
  1415. consecutive instances of the operator @samp{+}, we must separate them
  1416. with a space so that they do not combine as one token. Applying the
  1417. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1418. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1419. of a valid C program and the former could not (since @code{a++}
  1420. is not an lvalue and thus can't be the operand of @code{++}).
  1421. A few C operators are keywords rather than special characters. They
  1422. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1423. (@pxref{Type Alignment}).
  1424. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1425. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1426. @samp{@}}) begin and end a block at the statement level
  1427. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1428. for a variable with multiple elements or components (such as arrays or
  1429. structures).
  1430. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1431. @code{array[5]}.
  1432. Parentheses are used in expressions for explicit nesting of
  1433. expressions (@pxref{Basic Arithmetic}), around the parameter
  1434. declarations in a function declaration or definition, and around the
  1435. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1436. (@pxref{Function Calls}). Several kinds of statements also use
  1437. parentheses as part of their syntax---for instance, @code{if}
  1438. statements, @code{for} statements, @code{while} statements, and
  1439. @code{switch} statements. @xref{if Statement}, and following
  1440. sections.
  1441. Parentheses are also required around the operand of the operator
  1442. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1443. type rather than a value. @xref{Type Size}.
  1444. @node Line Continuation
  1445. @section Line Continuation
  1446. @cindex line continuation
  1447. @cindex continuation of lines
  1448. The sequence of a backslash and a newline is ignored absolutely
  1449. anywhere in a C program. This makes it possible to split a single
  1450. source line into multiple lines in the source file. GNU C tolerates
  1451. and ignores other whitespace between the backslash and the newline.
  1452. In particular, it always ignores a CR (carriage return) character
  1453. there, in case some text editor decided to end the line with the CRLF
  1454. sequence.
  1455. The main use of line continuation in C is for macro definitions that
  1456. would be inconveniently long for a single line (@pxref{Macros}).
  1457. It is possible to continue a line comment onto another line with
  1458. backslash-newline. You can put backslash-newline in the middle of an
  1459. identifier, even a keyword, or an operator. You can even split
  1460. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1461. backslash-newline. Here's an ugly example:
  1462. @example
  1463. @group
  1464. /\
  1465. *
  1466. */ fo\
  1467. o +\
  1468. = 1\
  1469. 0;
  1470. @end group
  1471. @end example
  1472. @noindent
  1473. That's equivalent to @samp{/* */ foo += 10;}.
  1474. Don't do those things in real programs, since they make code hard to
  1475. read.
  1476. @strong{Note:} For the sake of using certain tools on the source code, it is
  1477. wise to end every source file with a newline character which is not
  1478. preceded by a backslash, so that it really ends the last line.
  1479. @node Arithmetic
  1480. @chapter Arithmetic
  1481. @cindex arithmetic operators
  1482. @cindex operators, arithmetic
  1483. @c ??? Duplication with other sections -- get rid of that?
  1484. Arithmetic operators in C attempt to be as similar as possible to the
  1485. abstract arithmetic operations, but it is impossible to do this
  1486. perfectly. Numbers in a computer have a finite range of possible
  1487. values, and non-integer values have a limit on their possible
  1488. accuracy. Nonetheless, in most cases you will encounter no surprises
  1489. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1490. for multiplication.
  1491. Each C operator has a @dfn{precedence}, which is its rank in the
  1492. grammatical order of the various operators. The operators with the
  1493. highest precedence grab adjoining operands first; these expressions
  1494. then become operands for operators of lower precedence. We give some
  1495. information about precedence of operators in this chapter where we
  1496. describe the operators; for the full explanation, see @ref{Binary
  1497. Operator Grammar}.
  1498. The arithmetic operators always @dfn{promote} their operands before
  1499. operating on them. This means converting narrow integer data types to
  1500. a wider data type (@pxref{Operand Promotions}). If you are just
  1501. learning C, don't worry about this yet.
  1502. Given two operands that have different types, most arithmetic
  1503. operations convert them both to their @dfn{common type}. For
  1504. instance, if one is @code{int} and the other is @code{double}, the
  1505. common type is @code{double}. (That's because @code{double} can
  1506. represent all the values that an @code{int} can hold, but not vice
  1507. versa.) For the full details, see @ref{Common Type}.
  1508. @menu
  1509. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1510. and division.
  1511. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1512. * Integer Overflow:: When an integer value exceeds the range
  1513. of its type.
  1514. * Mixed Mode:: Calculating with both integer values
  1515. and floating-point values.
  1516. * Division and Remainder:: How integer division works.
  1517. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1518. * Shift Operations:: Shift integer bits left or right.
  1519. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1520. @end menu
  1521. @node Basic Arithmetic
  1522. @section Basic Arithmetic
  1523. @cindex addition operator
  1524. @cindex subtraction operator
  1525. @cindex multiplication operator
  1526. @cindex division operator
  1527. @cindex negation operator
  1528. @cindex operator, addition
  1529. @cindex operator, subtraction
  1530. @cindex operator, multiplication
  1531. @cindex operator, division
  1532. @cindex operator, negation
  1533. Basic arithmetic in C is done with the usual binary operators of
  1534. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1535. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1536. used to change the sign of a number. The unary @code{+} operator also
  1537. exists; it yields its operand unaltered.
  1538. @samp{/} is the division operator, but dividing integers may not give
  1539. the result you expect. Its value is an integer, which is not equal to
  1540. the mathematical quotient when that is a fraction. Use @samp{%} to
  1541. get the corresponding integer remainder when necessary.
  1542. @xref{Division and Remainder}. Floating point division yields value
  1543. as close as possible to the mathematical quotient.
  1544. These operators use algebraic syntax with the usual algebraic
  1545. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1546. and division are done before addition and subtraction, but you can use
  1547. parentheses to explicitly specify how the operators nest. They are
  1548. left-associative (@pxref{Associativity and Ordering}). Thus,
  1549. @example
  1550. -a + b - c + d * e / f
  1551. @end example
  1552. @noindent
  1553. is equivalent to
  1554. @example
  1555. (((-a) + b) - c) + ((d * e) / f)
  1556. @end example
  1557. @node Integer Arithmetic
  1558. @section Integer Arithmetic
  1559. @cindex integer arithmetic
  1560. Each of the basic arithmetic operations in C has two variants for
  1561. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1562. by the data types of their operands.
  1563. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1564. A signed type can hold a range of positive and negative numbers, with
  1565. zero near the middle of the range. An unsigned type can hold only
  1566. nonnegative numbers; its range starts with zero and runs upward.
  1567. The most basic integer types are @code{int}, which normally can hold
  1568. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1569. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1570. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1571. computers but not always on embedded controllers.) @xref{Integer
  1572. Types}, for full information about integer types.
  1573. When a basic arithmetic operation is given two signed operands, it
  1574. does signed arithmetic. Given two unsigned operands, it does
  1575. unsigned arithmetic.
  1576. If one operand is @code{unsigned int} and the other is @code{int}, the
  1577. operator treats them both as unsigned. More generally, the common
  1578. type of the operands determines whether the operation is signed or
  1579. not. @xref{Common Type}.
  1580. Printing the results of unsigned arithmetic with @code{printf} using
  1581. @samp{%d} can produce surprising results for values far away from
  1582. zero. Even though the rules above say that the computation was done
  1583. with unsigned arithmetic, the printed result may appear to be signed!
  1584. The explanation is that the bit pattern resulting from addition,
  1585. subtraction or multiplication is actually the same for signed and
  1586. unsigned operations. The difference is only in the data type of the
  1587. result, which affects the @emph{interpretation} of the result bit pattern,
  1588. and whether the arithmetic operation can overflow (see the next section).
  1589. But @samp{%d} doesn't know its argument's data type. It sees only the
  1590. value's bit pattern, and it is defined to interpret that as
  1591. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1592. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1593. libc, The GNU C Library Reference Manual}.
  1594. Arithmetic in C never operates directly on narrow integer types (those
  1595. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1596. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1597. @node Integer Overflow
  1598. @section Integer Overflow
  1599. @cindex integer overflow
  1600. @cindex overflow, integer
  1601. When the mathematical value of an arithmetic operation doesn't fit in
  1602. the range of the data type in use, that's called @dfn{overflow}.
  1603. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1604. Integer overflow happens only in arithmetic operations. Type conversion
  1605. operations, by definition, do not cause overflow, not even when the
  1606. result can't fit in its new type. @xref{Integer Conversion}.
  1607. Signed numbers use two's-complement representation, in which the most
  1608. negative number lacks a positive counterpart (@pxref{Integers in
  1609. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1610. overflow.
  1611. @menu
  1612. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1613. * Signed Overflow:: Overlow in signed integer arithmetic.
  1614. @end menu
  1615. @node Unsigned Overflow
  1616. @subsection Overflow with Unsigned Integers
  1617. Unsigned arithmetic in C ignores overflow; it produces the true result
  1618. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1619. in the data type. We say it ``truncates'' the true result to the
  1620. lowest @var{n} bits.
  1621. A true result that is negative, when taken modulo the @var{n}th power
  1622. of 2, yields a positive number. For instance,
  1623. @example
  1624. unsigned int x = 1;
  1625. unsigned int y;
  1626. y = -x;
  1627. @end example
  1628. @noindent
  1629. causes overflow because the negative number @minus{}1 can't be stored
  1630. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1631. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1632. is the largest value that the unsigned data type can store. For a
  1633. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1634. and Minimum Values}.
  1635. Adding that number to itself, as here,
  1636. @example
  1637. unsigned int z;
  1638. z = y + y;
  1639. @end example
  1640. @noindent
  1641. ought to yield 8,489,934,590; however, that is again too large to fit,
  1642. so overflow truncates the value to 4,294,967,294. If that were a
  1643. signed integer, it would mean @minus{}2, which (not by coincidence)
  1644. equals @minus{}1 + @minus{}1.
  1645. @node Signed Overflow
  1646. @subsection Overflow with Signed Integers
  1647. @cindex compiler options for integer overflow
  1648. @cindex integer overflow, compiler options
  1649. @cindex overflow, compiler options
  1650. For signed integers, the result of overflow in C is @emph{in
  1651. principle} undefined, meaning that anything whatsoever could happen.
  1652. Therefore, C compilers can do optimizations that treat the overflow
  1653. case with total unconcern. (Since the result of overflow is undefined
  1654. in principle, one cannot claim that these optimizations are
  1655. erroneous.)
  1656. @strong{Watch out:} These optimizations can do surprising things. For
  1657. instance,
  1658. @example
  1659. int i;
  1660. @r{@dots{}}
  1661. if (i < i + 1)
  1662. x = 5;
  1663. @end example
  1664. @noindent
  1665. could be optimized to do the assignment unconditionally, because the
  1666. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1667. GCC offers compiler options to control handling signed integer
  1668. overflow. These options operate per module; that is, each module
  1669. behaves according to the options it was compiled with.
  1670. These two options specify particular ways to handle signed integer
  1671. overflow, other than the default way:
  1672. @table @option
  1673. @item -fwrapv
  1674. Make signed integer operations well-defined, like unsigned integer
  1675. operations: they produce the @var{n} low-order bits of the true
  1676. result. The highest of those @var{n} bits is the sign bit of the
  1677. result. With @option{-fwrapv}, these out-of-range operations are not
  1678. considered overflow, so (strictly speaking) integer overflow never
  1679. happens.
  1680. The option @option{-fwrapv} enables some optimizations based on the
  1681. defined values of out-of-range results. In GCC 8, it disables
  1682. optimizations that are based on assuming signed integer operations
  1683. will not overflow.
  1684. @item -ftrapv
  1685. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1686. This terminates the program unless the program handles the signal.
  1687. @xref{Signals}.
  1688. @end table
  1689. One other option is useful for finding where overflow occurs:
  1690. @ignore
  1691. @item -fno-strict-overflow
  1692. Disable optimizations that are based on assuming signed integer
  1693. operations will not overflow.
  1694. @end ignore
  1695. @table @option
  1696. @item -fsanitize=signed-integer-overflow
  1697. Output a warning message at run time when signed integer overflow
  1698. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1699. This takes priority over @option{-ftrapv}.
  1700. @end table
  1701. @node Mixed Mode
  1702. @section Mixed-Mode Arithmetic
  1703. Mixing integers and floating-point numbers in a basic arithmetic
  1704. operation converts the integers automatically to floating point.
  1705. In most cases, this gives exactly the desired results.
  1706. But sometimes it matters precisely where the conversion occurs.
  1707. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1708. as an integer, then converts the sum to floating point for the
  1709. multiplication. If the addition gets an overflow, that is not
  1710. equivalent to converting both integers to floating point and then
  1711. adding them. You can get the latter result by explicitly converting
  1712. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1713. @xref{Explicit Type Conversion}.
  1714. @c Eggert's report
  1715. Adding or multiplying several values, including some integers and some
  1716. floating point, does the operations left to right. Thus, @code{3.0 +
  1717. i + j} converts @code{i} to floating point, then adds 3.0, then
  1718. converts @code{j} to floating point and adds that. You can specify a
  1719. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1720. and @code{j} first and then adds that result (converting to floating
  1721. point) to 3.0. In this respect, C differs from other languages, such
  1722. as Fortran.
  1723. @node Division and Remainder
  1724. @section Division and Remainder
  1725. @cindex remainder operator
  1726. @cindex modulus
  1727. @cindex operator, remainder
  1728. Division of integers in C rounds the result to an integer. The result
  1729. is always rounded towards zero.
  1730. @example
  1731. 16 / 3 @result{} 5
  1732. -16 / 3 @result{} -5
  1733. 16 / -3 @result{} -5
  1734. -16 / -3 @result{} 5
  1735. @end example
  1736. @noindent
  1737. To get the corresponding remainder, use the @samp{%} operator:
  1738. @example
  1739. 16 % 3 @result{} 1
  1740. -16 % 3 @result{} -1
  1741. 16 % -3 @result{} 1
  1742. -16 % -3 @result{} -1
  1743. @end example
  1744. @noindent
  1745. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1746. From the rounded quotient and the remainder, you can reconstruct
  1747. the dividend, like this:
  1748. @example
  1749. int
  1750. original_dividend (int divisor, int quotient, int remainder)
  1751. @{
  1752. return divisor * quotient + remainder;
  1753. @}
  1754. @end example
  1755. To do unrounded division, use floating point. If only one operand is
  1756. floating point, @samp{/} converts the other operand to floating
  1757. point.
  1758. @example
  1759. 16.0 / 3 @result{} 5.333333333333333
  1760. 16 / 3.0 @result{} 5.333333333333333
  1761. 16.0 / 3.0 @result{} 5.333333333333333
  1762. 16 / 3 @result{} 5
  1763. @end example
  1764. The remainder operator @samp{%} is not allowed for floating-point
  1765. operands, because it is not needed. The concept of remainder makes
  1766. sense for integers because the result of division of integers has to
  1767. be an integer. For floating point, the result of division is a
  1768. floating-point number, in other words a fraction, which will differ
  1769. from the exact result only by a very small amount.
  1770. There are functions in the standard C library to calculate remainders
  1771. from integral-values division of floating-point numbers.
  1772. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1773. Reference Manual}.
  1774. Integer division overflows in one specific case: dividing the smallest
  1775. negative value for the data type (@pxref{Maximum and Minimum Values})
  1776. by @minus{}1. That's because the correct result, which is the
  1777. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1778. in the same number of bits. On some computers now in use, this always
  1779. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1780. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1781. Division by zero leads to unpredictable results---depending on the
  1782. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1783. produce a numeric result.
  1784. @cindex division by zero
  1785. @cindex zero, division by
  1786. @strong{Watch out:} Make sure the program does not divide by zero. If
  1787. you can't prove that the divisor is not zero, test whether it is zero,
  1788. and skip the division if so.
  1789. @node Numeric Comparisons
  1790. @section Numeric Comparisons
  1791. @cindex numeric comparisons
  1792. @cindex comparisons
  1793. @cindex operators, comparison
  1794. @cindex equal operator
  1795. @cindex not-equal operator
  1796. @cindex less-than operator
  1797. @cindex greater-than operator
  1798. @cindex less-or-equal operator
  1799. @cindex greater-or-equal operator
  1800. @cindex operator, equal
  1801. @cindex operator, not-equal
  1802. @cindex operator, less-than
  1803. @cindex operator, greater-than
  1804. @cindex operator, less-or-equal
  1805. @cindex operator, greater-or-equal
  1806. @cindex truth value
  1807. There are two kinds of comparison operators: @dfn{equality} and
  1808. @dfn{ordering}. Equality comparisons test whether two expressions
  1809. have the same value. The result is a @dfn{truth value}: a number that
  1810. is 1 for ``true'' and 0 for ``false.''
  1811. @example
  1812. a == b /* @r{Test for equal.} */
  1813. a != b /* @r{Test for not equal.} */
  1814. @end example
  1815. The equality comparison is written @code{==} because plain @code{=}
  1816. is the assignment operator.
  1817. Ordering comparisons test which operand is greater or less. Their
  1818. results are truth values. These are the ordering comparisons of C:
  1819. @example
  1820. a < b /* @r{Test for less-than.} */
  1821. a > b /* @r{Test for greater-than.} */
  1822. a <= b /* @r{Test for less-than-or-equal.} */
  1823. a >= b /* @r{Test for greater-than-or-equal.} */
  1824. @end example
  1825. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1826. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1827. mathematics. However, if @code{a} and @code{b} are special floating
  1828. point values (not ordinary numbers), all three can be false.
  1829. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1830. @node Shift Operations
  1831. @section Shift Operations
  1832. @cindex shift operators
  1833. @cindex operators, shift
  1834. @cindex operators, shift
  1835. @cindex shift count
  1836. @dfn{Shifting} an integer means moving the bit values to the left or
  1837. right within the bits of the data type. Shifting is defined only for
  1838. integers. Here's the way to write it:
  1839. @example
  1840. /* @r{Left shift.} */
  1841. 5 << 2 @result{} 20
  1842. /* @r{Right shift.} */
  1843. 5 >> 2 @result{} 1
  1844. @end example
  1845. @noindent
  1846. The left operand is the value to be shifted, and the right operand
  1847. says how many bits to shift it (the @dfn{shift count}). The left
  1848. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1849. operates on a narrow integer type; it's always either @code{int} or
  1850. wider. The value of the shift operator has the same type as the
  1851. promoted left operand.
  1852. @menu
  1853. * Bits Shifted In:: How shifting makes new bits to shift in.
  1854. * Shift Caveats:: Caveats of shift operations.
  1855. * Shift Hacks:: Clever tricks with shift operations.
  1856. @end menu
  1857. @node Bits Shifted In
  1858. @subsection Shifting Makes New Bits
  1859. A shift operation shifts towards one end of the number and has to
  1860. generate new bits at the other end.
  1861. Shifting left one bit must generate a new least significant bit. It
  1862. always brings in zero there. It is equivalent to multiplying by the
  1863. appropriate power of 2. For example,
  1864. @example
  1865. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1866. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1867. @end example
  1868. The meaning of shifting right depends on whether the data type is
  1869. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1870. data type, it performs ``arithmetic shift,'' which keeps the number's
  1871. sign unchanged by duplicating the sign bit. For an unsigned data
  1872. type, it performs ``logical shift,'' which always shifts in zeros at
  1873. the most significant bit.
  1874. In both cases, shifting right one bit is division by two, rounding
  1875. towards negative infinity. For example,
  1876. @example
  1877. (unsigned) 19 >> 2 @result{} 4
  1878. (unsigned) 20 >> 2 @result{} 5
  1879. (unsigned) 21 >> 2 @result{} 5
  1880. @end example
  1881. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1882. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1883. zero.
  1884. The shift count must be zero or greater. Shifting by a negative
  1885. number of bits gives machine-dependent results.
  1886. @node Shift Caveats
  1887. @subsection Caveats for Shift Operations
  1888. @strong{Warning:} If the shift count is greater than or equal to the
  1889. width in bits of the first operand, the results are machine-dependent.
  1890. Logically speaking, the ``correct'' value would be either -1 (for
  1891. right shift of a negative number) or 0 (in all other cases), but what
  1892. it really generates is whatever the machine's shift instruction does in
  1893. that case. So unless you can prove that the second operand is not too
  1894. large, write code to check it at run time.
  1895. @strong{Warning:} Never rely on how the shift operators relate in
  1896. precedence to other arithmetic binary operators. Programmers don't
  1897. remember these precedences, and won't understand the code. Always use
  1898. parentheses to explicitly specify the nesting, like this:
  1899. @example
  1900. a + (b << 5) /* @r{Shift first, then add.} */
  1901. (a + b) << 5 /* @r{Add first, then shift.} */
  1902. @end example
  1903. Note: according to the C standard, shifting of signed values isn't
  1904. guaranteed to work properly when the value shifted is negative, or
  1905. becomes negative during the operation of shifting left. However, only
  1906. pedants have a reason to be concerned about this; only computers with
  1907. strange shift instructions could plausibly do this wrong. In GNU C,
  1908. the operation always works as expected,
  1909. @node Shift Hacks
  1910. @subsection Shift Hacks
  1911. You can use the shift operators for various useful hacks. For
  1912. example, given a date specified by day of the month @code{d}, month
  1913. @code{m}, and year @code{y}, you can store the entire date in a single
  1914. integer @code{date}:
  1915. @example
  1916. unsigned int d = 12;
  1917. unsigned int m = 6;
  1918. unsigned int y = 1983;
  1919. unsigned int date = ((y << 4) + m) << 5) + d;
  1920. @end example
  1921. @noindent
  1922. To extract the original day, month, and year out of
  1923. @code{date}, use a combination of shift and remainder.
  1924. @example
  1925. d = date % 32;
  1926. m = (date >> 5) % 16;
  1927. y = date >> 9;
  1928. @end example
  1929. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1930. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1931. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1932. multiplication, since negating a value is equivalent to multiplying it
  1933. by @minus{}1.
  1934. @node Bitwise Operations
  1935. @section Bitwise Operations
  1936. @cindex bitwise operators
  1937. @cindex operators, bitwise
  1938. @cindex negation, bitwise
  1939. @cindex conjunction, bitwise
  1940. @cindex disjunction, bitwise
  1941. Bitwise operators operate on integers, treating each bit independently.
  1942. They are not allowed for floating-point types.
  1943. The examples in this section use binary constants, starting with
  1944. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1945. of type @code{int}.
  1946. @table @code
  1947. @item ~@code{a}
  1948. Unary operator for bitwise negation; this changes each bit of
  1949. @code{a} from 1 to 0 or from 0 to 1.
  1950. @example
  1951. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1952. ~0 @result{} 0b11111111111111111111111111111111
  1953. ~0b11111111111111111111111111111111 @result{} 0
  1954. ~ (-1) @result{} 0
  1955. @end example
  1956. It is useful to remember that @code{~@var{x} + 1} equals
  1957. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1958. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1959. as @var{x}.
  1960. @item @code{a} & @code{b}
  1961. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1962. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1963. @example
  1964. 0b10101010 & 0b11001100 @result{} 0b10001000
  1965. @end example
  1966. @item @code{a} | @code{b}
  1967. Binary operator for bitwise ``or'' (``inclusive or'' or
  1968. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1969. either @code{a} or @code{b}.
  1970. @example
  1971. 0b10101010 | 0b11001100 @result{} 0b11101110
  1972. @end example
  1973. @item @code{a} ^ @code{b}
  1974. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1975. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1976. @example
  1977. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1978. @end example
  1979. @end table
  1980. To understand the effect of these operators on signed integers, keep
  1981. in mind that all modern computers use two's-complement representation
  1982. (@pxref{Integer Representations}) for negative integers. This means
  1983. that the highest bit of the number indicates the sign; it is 1 for a
  1984. negative number and 0 for a positive number. In a negative number,
  1985. the value in the other bits @emph{increases} as the number gets closer
  1986. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1987. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1988. @strong{Warning:} C defines a precedence ordering for the bitwise
  1989. binary operators, but you should never rely on it. You should
  1990. never rely on how bitwise binary operators relate in precedence to the
  1991. arithmetic and shift binary operators. Other programmers don't
  1992. remember this precedence ordering, so always use parentheses to
  1993. explicitly specify the nesting.
  1994. For example, suppose @code{offset} is an integer that specifies
  1995. the offset within shared memory of a table, except that its bottom few
  1996. bits (@code{LOWBITS} says how many) are special flags. Here's
  1997. how to get just that offset and add it to the base address.
  1998. @example
  1999. shared_mem_base + (offset & (-1 << LOWBITS))
  2000. @end example
  2001. Thanks to the outer set of parentheses, we don't need to know whether
  2002. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  2003. set, we don't need to know whether @samp{&} has higher precedence than
  2004. @samp{<<}. But we can rely on all unary operators to have higher
  2005. precedence than any binary operator, so we don't need parentheses
  2006. around the left operand of @samp{<<}.
  2007. @node Assignment Expressions
  2008. @chapter Assignment Expressions
  2009. @cindex assignment expressions
  2010. @cindex operators, assignment
  2011. As a general concept in programming, an @dfn{assignment} is a
  2012. construct that stores a new value into a place where values can be
  2013. stored---for instance, in a variable. Such places are called
  2014. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  2015. An assignment in C is an expression because it has a value; we call
  2016. it an @dfn{assignment expression}. A simple assignment looks like
  2017. @example
  2018. @var{lvalue} = @var{value-to-store}
  2019. @end example
  2020. @noindent
  2021. We say it assigns the value of the expression @var{value-to-store} to
  2022. the location @var{lvalue}, or that it stores @var{value-to-store}
  2023. there. You can think of the ``l'' in ``lvalue'' as standing for
  2024. ``left,'' since that's what you put on the left side of the assignment
  2025. operator.
  2026. However, that's not the only way to use an lvalue, and not all lvalues
  2027. can be assigned to. To use the lvalue in the left side of an
  2028. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2029. not declared with the type qualifier @code{const} (@pxref{const}).
  2030. The value of the assignment expression is that of @var{lvalue} after
  2031. the new value is stored in it. This means you can use an assignment
  2032. inside other expressions. Assignment operators are right-associative
  2033. so that
  2034. @example
  2035. x = y = z = 0;
  2036. @end example
  2037. @noindent
  2038. is equivalent to
  2039. @example
  2040. x = (y = (z = 0));
  2041. @end example
  2042. This is the only useful way for them to associate;
  2043. the other way,
  2044. @example
  2045. ((x = y) = z) = 0;
  2046. @end example
  2047. @noindent
  2048. would be invalid since an assignment expression such as @code{x = y}
  2049. is not valid as an lvalue.
  2050. @strong{Warning:} Write parentheses around an assignment if you nest
  2051. it inside another expression, unless that is a conditional expression,
  2052. or comma-separated series, or another assignment.
  2053. @menu
  2054. * Simple Assignment:: The basics of storing a value.
  2055. * Lvalues:: Expressions into which a value can be stored.
  2056. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2057. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2058. an lvalue's contents.
  2059. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2060. * Assignment in Subexpressions:: How to avoid ambiguity.
  2061. * Write Assignments Separately:: Write assignments as separate statements.
  2062. @end menu
  2063. @node Simple Assignment
  2064. @section Simple Assignment
  2065. @cindex simple assignment
  2066. @cindex assignment, simple
  2067. A @dfn{simple assignment expression} computes the value of the right
  2068. operand and stores it into the lvalue on the left. Here is a simple
  2069. assignment expression that stores 5 in @code{i}:
  2070. @example
  2071. i = 5
  2072. @end example
  2073. @noindent
  2074. We say that this is an @dfn{assignment to} the variable @code{i} and
  2075. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2076. because it is an expression (so it has a value). Adding a semicolon
  2077. at the end would make it a statement (@pxref{Expression Statement}).
  2078. Here is another example of a simple assignment expression. Its
  2079. operands are not simple, but the kind of assignment done here is
  2080. simple assignment.
  2081. @example
  2082. x[foo ()] = y + 6
  2083. @end example
  2084. A simple assignment with two different numeric data types converts the
  2085. right operand value to the lvalue's type, if possible. It can convert
  2086. any numeric type to any other numeric type.
  2087. Simple assignment is also allowed on some non-numeric types: pointers
  2088. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2089. unions (@pxref{Unions}).
  2090. @strong{Warning:} Assignment is not allowed on arrays because
  2091. there are no array values in C; C variables can be arrays, but these
  2092. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2093. Arrays}.
  2094. @xref{Assignment Type Conversions}, for the complete rules about data
  2095. types used in assignments.
  2096. @node Lvalues
  2097. @section Lvalues
  2098. @cindex lvalues
  2099. An expression that identifies a memory space that holds a value is
  2100. called an @dfn{lvalue}, because it is a location that can hold a value.
  2101. The standard kinds of lvalues are:
  2102. @itemize @bullet
  2103. @item
  2104. A variable.
  2105. @item
  2106. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2107. unary @samp{*}.
  2108. @item
  2109. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2110. the structure value is an lvalue.
  2111. @item
  2112. A structure field reference using @samp{->}. This is always an lvalue
  2113. since @samp{->} implies pointer dereference.
  2114. @item
  2115. A union alternative reference (@pxref{Unions}), on the same conditions
  2116. as for structure fields.
  2117. @item
  2118. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2119. is an lvalue.
  2120. @end itemize
  2121. If an expression's outermost operation is any other operator, that
  2122. expression is not an lvalue. Thus, the variable @code{x} is an
  2123. lvalue, but @code{x + 0} is not, even though these two expressions
  2124. compute the same value (assuming @code{x} is a number).
  2125. An array can be an lvalue (the rules above determine whether it is
  2126. one), but using the array in an expression converts it automatically
  2127. to a pointer to the first element. The result of this conversion is
  2128. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2129. use @code{a} by itself as the left operand of an assignment. But you
  2130. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2131. lvalue since @code{a} is an lvalue.
  2132. @node Modifying Assignment
  2133. @section Modifying Assignment
  2134. @cindex modifying assignment
  2135. @cindex assignment, modifying
  2136. You can abbreviate the common construct
  2137. @example
  2138. @var{lvalue} = @var{lvalue} + @var{expression}
  2139. @end example
  2140. @noindent
  2141. as
  2142. @example
  2143. @var{lvalue} += @var{expression}
  2144. @end example
  2145. This is known as a @dfn{modifying assignment}. For instance,
  2146. @example
  2147. i = i + 5;
  2148. i += 5;
  2149. @end example
  2150. @noindent
  2151. shows two statements that are equivalent. The first uses
  2152. simple assignment; the second uses modifying assignment.
  2153. Modifying assignment works with any binary arithmetic operator. For
  2154. instance, you can subtract something from an lvalue like this,
  2155. @example
  2156. @var{lvalue} -= @var{expression}
  2157. @end example
  2158. @noindent
  2159. or multiply it by a certain amount like this,
  2160. @example
  2161. @var{lvalue} *= @var{expression}
  2162. @end example
  2163. @noindent
  2164. or shift it by a certain amount like this.
  2165. @example
  2166. @var{lvalue} <<= @var{expression}
  2167. @var{lvalue} >>= @var{expression}
  2168. @end example
  2169. In most cases, this feature adds no power to the language, but it
  2170. provides substantial convenience. Also, when @var{lvalue} contains
  2171. code that has side effects, the simple assignment performs those side
  2172. effects twice, while the modifying assignment performs them once. For
  2173. instance,
  2174. @example
  2175. x[foo ()] = x[foo ()] + 5;
  2176. @end example
  2177. @noindent
  2178. calls @code{foo} twice, and it could return different values each
  2179. time. If @code{foo ()} returns 1 the first time and 3 the second
  2180. time, then the effect could be to add @code{x[3]} and 5 and store the
  2181. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2182. result in @code{x[3]}. We don't know which of the two it will do,
  2183. because C does not specify which call to @code{foo} is computed first.
  2184. Such a statement is not well defined, and shouldn't be used.
  2185. By contrast,
  2186. @example
  2187. x[foo ()] += 5;
  2188. @end example
  2189. @noindent
  2190. is well defined: it calls @code{foo} only once to determine which
  2191. element of @code{x} to adjust, and it adjusts that element by adding 5
  2192. to it.
  2193. @node Increment/Decrement
  2194. @section Increment and Decrement Operators
  2195. @cindex increment operator
  2196. @cindex decrement operator
  2197. @cindex operator, increment
  2198. @cindex operator, decrement
  2199. @cindex preincrement expression
  2200. @cindex predecrement expression
  2201. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2202. @dfn{decrement} operators. When used on a numeric value, they add or
  2203. subtract 1. We don't consider them assignments, but they are
  2204. equivalent to assignments.
  2205. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2206. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2207. and the result becomes the expression's value. For instance,
  2208. @example
  2209. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2210. int
  2211. main (void)
  2212. @{
  2213. int i = 5;
  2214. printf ("%d\n", i);
  2215. printf ("%d\n", ++i);
  2216. printf ("%d\n", i);
  2217. return 0;
  2218. @}
  2219. @end example
  2220. @noindent
  2221. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2222. increments @code{i} from 5 to 6, and has the value 6, so the output
  2223. from @code{printf} on that line says @samp{6}.
  2224. Using @samp{--} instead, for predecrement,
  2225. @example
  2226. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2227. int
  2228. main (void)
  2229. @{
  2230. int i = 5;
  2231. printf ("%d\n", i);
  2232. printf ("%d\n", --i);
  2233. printf ("%d\n", i);
  2234. return 0;
  2235. @}
  2236. @end example
  2237. @noindent
  2238. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2239. again @samp{4}.
  2240. @node Postincrement/Postdecrement
  2241. @section Postincrement and Postdecrement
  2242. @cindex postincrement expression
  2243. @cindex postdecrement expression
  2244. @cindex operator, postincrement
  2245. @cindex operator, postdecrement
  2246. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2247. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2248. increments or decrement it. Thus, the value of @code{i++} is the same
  2249. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2250. little later.'' This is called @dfn{postincrement} or
  2251. @dfn{postdecrement}.
  2252. For example,
  2253. @example
  2254. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2255. int
  2256. main (void)
  2257. @{
  2258. int i = 5;
  2259. printf ("%d\n", i);
  2260. printf ("%d\n", i++);
  2261. printf ("%d\n", i);
  2262. return 0;
  2263. @}
  2264. @end example
  2265. @noindent
  2266. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2267. has the value 5, which is the value of @code{i} at the time,
  2268. but it increments @code{i} from 5 to 6 just a little later.
  2269. How much later is ``just a little later''? That is flexible. The
  2270. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2271. that means by the end of the statement. @xref{Sequence Points}.
  2272. If a unary operator precedes a postincrement or postincrement expression,
  2273. the increment nests inside:
  2274. @example
  2275. -a++ @r{is equivalent to} -(a++)
  2276. @end example
  2277. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2278. it can't be incremented.
  2279. @node Assignment in Subexpressions
  2280. @section Pitfall: Assignment in Subexpressions
  2281. @cindex assignment in subexpressions
  2282. @cindex subexpressions, assignment in
  2283. In C, the order of computing parts of an expression is not fixed.
  2284. Aside from a few special cases, the operations can be computed in any
  2285. order. If one part of the expression has an assignment to @code{x}
  2286. and another part of the expression uses @code{x}, the result is
  2287. unpredictable because that use might be computed before or after the
  2288. assignment.
  2289. Here's an example of ambiguous code:
  2290. @example
  2291. x = 20;
  2292. printf ("%d %d\n", x, x = 4);
  2293. @end example
  2294. @noindent
  2295. If the second argument, @code{x}, is computed before the third argument,
  2296. @code{x = 4}, the second argument's value will be 20. If they are
  2297. computed in the other order, the second argument's value will be 4.
  2298. Here's one way to make that code unambiguous:
  2299. @example
  2300. y = 20;
  2301. printf ("%d %d\n", y, x = 4);
  2302. @end example
  2303. Here's another way, with the other meaning:
  2304. @example
  2305. x = 4;
  2306. printf ("%d %d\n", x, x);
  2307. @end example
  2308. This issue applies to all kinds of assignments, and to the increment
  2309. and decrement operators, which are equivalent to assignments.
  2310. @xref{Order of Execution}, for more information about this.
  2311. However, it can be useful to write assignments inside an
  2312. @code{if}-condition or @code{while}-test along with logical operators.
  2313. @xref{Logicals and Assignments}.
  2314. @node Write Assignments Separately
  2315. @section Write Assignments in Separate Statements
  2316. It is often convenient to write an assignment inside an
  2317. @code{if}-condition, but that can reduce the readability of the
  2318. program. Here's an example of what to avoid:
  2319. @example
  2320. if (x = advance (x))
  2321. @r{@dots{}}
  2322. @end example
  2323. The idea here is to advance @code{x} and test if the value is nonzero.
  2324. However, readers might miss the fact that it uses @samp{=} and not
  2325. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2326. inside a condition is a common error, so GNU C can give warnings when
  2327. @samp{=} appears in a way that suggests it's an error.
  2328. It is much clearer to write the assignment as a separate statement, like this:
  2329. @example
  2330. x = advance (x);
  2331. if (x != 0)
  2332. @r{@dots{}}
  2333. @end example
  2334. @noindent
  2335. This makes it unmistakably clear that @code{x} is assigned a new value.
  2336. Another method is to use the comma operator (@pxref{Comma Operator}),
  2337. like this:
  2338. @example
  2339. if (x = advance (x), x != 0)
  2340. @r{@dots{}}
  2341. @end example
  2342. @noindent
  2343. However, putting the assignment in a separate statement is usually clearer
  2344. unless the assignment is very short, because it reduces nesting.
  2345. @node Execution Control Expressions
  2346. @chapter Execution Control Expressions
  2347. @cindex execution control expressions
  2348. @cindex expressions, execution control
  2349. This chapter describes the C operators that combine expressions to
  2350. control which of those expressions execute, or in which order.
  2351. @menu
  2352. * Logical Operators:: Logical conjunction, disjunction, negation.
  2353. * Logicals and Comparison:: Logical operators with comparison operators.
  2354. * Logicals and Assignments:: Assignments with logical operators.
  2355. * Conditional Expression:: An if/else construct inside expressions.
  2356. * Comma Operator:: Build a sequence of subexpressions.
  2357. @end menu
  2358. @node Logical Operators
  2359. @section Logical Operators
  2360. @cindex logical operators
  2361. @cindex operators, logical
  2362. @cindex conjunction operator
  2363. @cindex disjunction operator
  2364. @cindex negation operator, logical
  2365. The @dfn{logical operators} combine truth values, which are normally
  2366. represented in C as numbers. Any expression with a numeric value is a
  2367. valid truth value: zero means false, and any other value means true.
  2368. A pointer type is also meaningful as a truth value; a null pointer
  2369. (which is zero) means false, and a non-null pointer means true
  2370. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2371. or 0 and has type @code{int} (@pxref{Integer Types}).
  2372. The logical operators are used mainly in the condition of an @code{if}
  2373. statement, or in the end test in a @code{for} statement or
  2374. @code{while} statement (@pxref{Statements}). However, they are valid
  2375. in any context where an integer-valued expression is allowed.
  2376. @table @samp
  2377. @item ! @var{exp}
  2378. Unary operator for logical ``not.'' The value is 1 (true) if
  2379. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2380. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2381. function call, you should write parentheses around it.
  2382. @item @var{left} && @var{right}
  2383. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2384. @var{right}. If both of the operands are true, the @samp{&&} expression
  2385. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2386. gives the value 0 (false). If @var{left} yields a false value,
  2387. that determines the overall result, so @var{right} is not computed.
  2388. @item @var{left} || @var{right}
  2389. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2390. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2391. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2392. gives the value 0 (false). If @var{left} yields a true value,
  2393. that determines the overall result, so @var{right} is not computed.
  2394. @end table
  2395. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2396. and @samp{||}. When you use them together, always use parentheses to
  2397. specify explicitly how they nest, as shown here:
  2398. @example
  2399. if ((r != 0 && x % r == 0)
  2400. ||
  2401. (s != 0 && x % s == 0))
  2402. @end example
  2403. @node Logicals and Comparison
  2404. @section Logical Operators and Comparisons
  2405. The most common thing to use inside the logical operators is a
  2406. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2407. precedence than comparison operators and arithmetic operators, so we
  2408. can write expressions like this without parentheses and get the
  2409. nesting that is natural: two comparison operations that must both be
  2410. true.
  2411. @example
  2412. if (r != 0 && x % r == 0)
  2413. @end example
  2414. @noindent
  2415. This example also shows how it is useful that @samp{&&} guarantees to
  2416. skip the right operand if the left one turns out false. Because of
  2417. that, this code never tries to divide by zero.
  2418. This is equivalent:
  2419. @example
  2420. if (r && x % r == 0)
  2421. @end example
  2422. @noindent
  2423. A truth value is simply a number, so @code{r}
  2424. as a truth value tests whether it is nonzero.
  2425. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2426. So it is better style to write the explicit @code{!= 0}.
  2427. Here's another equivalent way to write it:
  2428. @example
  2429. if (!(r == 0) && x % r == 0)
  2430. @end example
  2431. @noindent
  2432. This illustrates the unary @samp{!} operator, and the need to
  2433. write parentheses around its operand.
  2434. @node Logicals and Assignments
  2435. @section Logical Operators and Assignments
  2436. There are cases where assignments nested inside the condition can
  2437. actually make a program @emph{easier} to read. Here is an example
  2438. using a hypothetical type @code{list} which represents a list; it
  2439. tests whether the list has at least two links, using hypothetical
  2440. functions, @code{nonempty} which is true of the argument is a nonempty
  2441. list, and @code{list_next} which advances from one list link to the
  2442. next. We assume that a list is never a null pointer, so that the
  2443. assignment expressions are always ``true.''
  2444. @example
  2445. if (nonempty (list)
  2446. && (temp1 = list_next (list))
  2447. && nonempty (temp1)
  2448. && (temp2 = list_next (temp1)))
  2449. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2450. @end example
  2451. @noindent
  2452. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2453. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2454. only natural place to put the assignments is among those calls.
  2455. It would be possible to rewrite this as several statements, but that
  2456. could make it much more cumbersome. On the other hand, when the test
  2457. is even more complex than this one, splitting it into multiple
  2458. statements might be necessary for clarity.
  2459. If an empty list is a null pointer, we can dispense with calling
  2460. @code{nonempty}:
  2461. @example
  2462. if ((temp1 = list_next (list))
  2463. && (temp2 = list_next (temp1)))
  2464. @r{@dots{}}
  2465. @end example
  2466. @node Conditional Expression
  2467. @section Conditional Expression
  2468. @cindex conditional expression
  2469. @cindex expression, conditional
  2470. C has a conditional expression that selects one of two expressions
  2471. to compute and get the value from. It looks like this:
  2472. @example
  2473. @var{condition} ? @var{iftrue} : @var{iffalse}
  2474. @end example
  2475. @menu
  2476. * Conditional Rules:: Rules for the conditional operator.
  2477. * Conditional Branches:: About the two branches in a conditional.
  2478. @end menu
  2479. @node Conditional Rules
  2480. @subsection Rules for Conditional Operator
  2481. The first operand, @var{condition}, should be a value that can be
  2482. compared with zero---a number or a pointer. If it is true (nonzero),
  2483. then the conditional expression computes @var{iftrue} and its value
  2484. becomes the value of the conditional expression. Otherwise the
  2485. conditional expression computes @var{iffalse} and its value becomes
  2486. the value of the conditional expression. The conditional expression
  2487. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2488. of them.
  2489. Here's an example: the absolute value of a number @code{x}
  2490. can be written as @code{(x >= 0 ? x : -x)}.
  2491. @strong{Warning:} The conditional expression operators have rather low
  2492. syntactic precedence. Except when the conditional expression is used
  2493. as an argument in a function call, write parentheses around it. For
  2494. clarity, always write parentheses around it if it extends across more
  2495. than one line.
  2496. Assignment operators and the comma operator (@pxref{Comma Operator})
  2497. have lower precedence than conditional expression operators, so write
  2498. parentheses around those when they appear inside a conditional
  2499. expression. @xref{Order of Execution}.
  2500. @node Conditional Branches
  2501. @subsection Conditional Operator Branches
  2502. @cindex branches of conditional expression
  2503. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2504. conditional.
  2505. The two branches should normally have the same type, but a few
  2506. exceptions are allowed. If they are both numeric types, the
  2507. conditional converts both to their common type (@pxref{Common Type}).
  2508. With pointers (@pxref{Pointers}), the two values can be pointers to
  2509. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2510. result type is a similar pointer whose target type combines all the
  2511. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2512. If one branch has type @code{void *} and the other is a pointer to an
  2513. object (not to a function), the conditional converts the @code{void *}
  2514. branch to the type of the other.
  2515. If one branch is an integer constant with value zero and the other is
  2516. a pointer, the conditional converts zero to the pointer's type.
  2517. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2518. that case, if @var{condition} is nonzero, its value becomes the value of
  2519. the conditional expression, after conversion to the common type.
  2520. Thus,
  2521. @example
  2522. x ? : y
  2523. @end example
  2524. @noindent
  2525. has the value of @code{x} if that is nonzero; otherwise, the value of
  2526. @code{y}.
  2527. @cindex side effect in ?:
  2528. @cindex ?: side effect
  2529. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2530. In that case, writing that expression twice would carry out the side
  2531. effects twice, but writing it once does them just once. For example,
  2532. if we suppose that the function @code{next_element} advances a pointer
  2533. variable to point to the next element in a list and returns the new
  2534. pointer,
  2535. @example
  2536. next_element () ? : default_pointer
  2537. @end example
  2538. @noindent
  2539. is a way to advance the pointer and use its new value if it isn't
  2540. null, but use @code{default_pointer} if that is null. We must not do
  2541. it this way,
  2542. @example
  2543. next_element () ? next_element () : default_pointer
  2544. @end example
  2545. @noindent
  2546. because it would advance the pointer a second time.
  2547. @node Comma Operator
  2548. @section Comma Operator
  2549. @cindex comma operator
  2550. @cindex operator, comma
  2551. The comma operator stands for sequential execution of expressions.
  2552. The value of the comma expression comes from the last expression in
  2553. the sequence; the previous expressions are computed only for their
  2554. side effects. It looks like this:
  2555. @example
  2556. @var{exp1}, @var{exp2} @r{@dots{}}
  2557. @end example
  2558. @noindent
  2559. You can bundle any number of expressions together this way, by putting
  2560. commas between them.
  2561. @menu
  2562. * Uses of Comma:: When to use the comma operator.
  2563. * Clean Comma:: Clean use of the comma operator.
  2564. * Avoid Comma:: When to not use the comma operator.
  2565. @end menu
  2566. @node Uses of Comma
  2567. @subsection The Uses of the Comma Operator
  2568. With commas, you can put several expressions into a place that
  2569. requires just one expression---for example, in the header of a
  2570. @code{for} statement. This statement
  2571. @example
  2572. for (i = 0, j = 10, k = 20; i < n; i++)
  2573. @end example
  2574. @noindent
  2575. contains three assignment expressions, to initialize @code{i}, @code{j}
  2576. and @code{k}. The syntax of @code{for} requires just one expression
  2577. for initialization; to include three assignments, we use commas to
  2578. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2579. 20}. This technique is also useful in the loop-advance expression,
  2580. the last of the three inside the @code{for} parentheses.
  2581. In the @code{for} statement and the @code{while} statement
  2582. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2583. effect before the loop-exit test. For example,
  2584. @example
  2585. while (printf ("At the test, x = %d\n", x), x != 0)
  2586. @end example
  2587. @node Clean Comma
  2588. @subsection Clean Use of the Comma Operator
  2589. Always write parentheses around a series of comma operators, except
  2590. when it is at top level in an expression statement, or within the
  2591. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2592. statement (@pxref{Statements}). For instance, in
  2593. @example
  2594. for (i = 0, j = 10, k = 20; i < n; i++)
  2595. @end example
  2596. @noindent
  2597. the commas between the assignments are clear because they are between
  2598. a parenthesis and a semicolon.
  2599. The arguments in a function call are also separated by commas, but that is
  2600. not an instance of the comma operator. Note the difference between
  2601. @example
  2602. foo (4, 5, 6)
  2603. @end example
  2604. @noindent
  2605. which passes three arguments to @code{foo} and
  2606. @example
  2607. foo ((4, 5, 6))
  2608. @end example
  2609. @noindent
  2610. which uses the comma operator and passes just one argument
  2611. (with value 6).
  2612. @strong{Warning:} don't use the comma operator around an argument
  2613. of a function unless it helps understand the code. When you do so,
  2614. don't put part of another argument on the same line. Instead, add a
  2615. line break to make the parentheses around the comma operator easier to
  2616. see, like this.
  2617. @example
  2618. foo ((mumble (x, y), frob (z)),
  2619. *p)
  2620. @end example
  2621. @node Avoid Comma
  2622. @subsection When Not to Use the Comma Operator
  2623. You can use a comma in any subexpression, but in most cases it only
  2624. makes the code confusing, and it is clearer to raise all but the last
  2625. of the comma-separated expressions to a higher level. Thus, instead
  2626. of this:
  2627. @example
  2628. x = (y += 4, 8);
  2629. @end example
  2630. @noindent
  2631. it is much clearer to write this:
  2632. @example
  2633. y += 4, x = 8;
  2634. @end example
  2635. @noindent
  2636. or this:
  2637. @example
  2638. y += 4;
  2639. x = 8;
  2640. @end example
  2641. Use commas only in the cases where there is no clearer alternative
  2642. involving multiple statements.
  2643. By contrast, don't hesitate to use commas in the expansion in a macro
  2644. definition. The trade-offs of code clarity are different in that
  2645. case, because the @emph{use} of the macro may improve overall clarity
  2646. so much that the ugliness of the macro's @emph{definition} is a small
  2647. price to pay. @xref{Macros}.
  2648. @node Binary Operator Grammar
  2649. @chapter Binary Operator Grammar
  2650. @cindex binary operator grammar
  2651. @cindex grammar, binary operator
  2652. @cindex operator precedence
  2653. @cindex precedence, operator
  2654. @cindex left-associative
  2655. @dfn{Binary operators} are those that take two operands, one
  2656. on the left and one on the right.
  2657. All the binary operators in C are syntactically left-associative.
  2658. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2659. @var{op} b) @var{op} c}}. However, you should only write repeated
  2660. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2661. @samp{/}, because those cases are clear from algebra. So it is ok to
  2662. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2663. c} or @code{a % b % c}.
  2664. Each C operator has a @dfn{precedence}, which is its rank in the
  2665. grammatical order of the various operators. The operators with the
  2666. highest precedence grab adjoining operands first; these expressions
  2667. then become operands for operators of lower precedence.
  2668. The precedence order of operators in C is fully specified, so any
  2669. combination of operations leads to a well-defined nesting. We state
  2670. only part of the full precedence ordering here because it is bad
  2671. practice for C code to depend on the other cases. For cases not
  2672. specified in this chapter, always use parentheses to make the nesting
  2673. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2674. remembering anything about the C precedence order beyond what's stated
  2675. here. I studied the full precedence table to write the parser, and
  2676. promptly forgot it again. If you need to look up the full precedence order
  2677. to understand some C code, fix the code with parentheses so nobody else
  2678. needs to do that.}
  2679. You can depend on this subsequence of the precedence ordering
  2680. (stated from highest precedence to lowest):
  2681. @enumerate
  2682. @item
  2683. Component access (@samp{.} and @samp{->}).
  2684. @item
  2685. Unary prefix operators.
  2686. @item
  2687. Unary postfix operators.
  2688. @item
  2689. Multiplication, division, and remainder (they have the same precedence).
  2690. @item
  2691. Addition and subtraction (they have the same precedence).
  2692. @item
  2693. Comparisons---but watch out!
  2694. @item
  2695. Logical operators @samp{&&} and @samp{||}---but watch out!
  2696. @item
  2697. Conditional expression with @samp{?} and @samp{:}.
  2698. @item
  2699. Assignments.
  2700. @item
  2701. Sequential execution (the comma operator, @samp{,}).
  2702. @end enumerate
  2703. Two of the lines in the above list say ``but watch out!'' That means
  2704. that the line covers operators with subtly different precedence.
  2705. Never depend on the grammar of C to decide how two comparisons nest;
  2706. instead, always use parentheses to specify their nesting.
  2707. You can let several @samp{&&} operators associate, or several
  2708. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2709. and @samp{||} nest with each other. @xref{Logical Operators}.
  2710. There is one other precedence ordering that code can depend on:
  2711. @enumerate
  2712. @item
  2713. Unary postfix operators.
  2714. @item
  2715. Bitwise and shift operators---but watch out!
  2716. @item
  2717. Conditional expression with @samp{?} and @samp{:}.
  2718. @end enumerate
  2719. The caveat for bitwise and shift operators is like that for logical
  2720. operators: you can let multiple uses of one bitwise operator
  2721. associate, but always use parentheses to control nesting of dissimilar
  2722. operators.
  2723. These lists do not specify any precedence ordering between the bitwise
  2724. and shift operators of the second list and the binary operators above
  2725. conditional expressions in the first list. When they come together,
  2726. parenthesize them. @xref{Bitwise Operations}.
  2727. @node Order of Execution
  2728. @chapter Order of Execution
  2729. @cindex order of execution
  2730. The order of execution of a C program is not always obvious, and not
  2731. necessarily predictable. This chapter describes what you can count on.
  2732. @menu
  2733. * Reordering of Operands:: Operations in C are not necessarily computed
  2734. in the order they are written.
  2735. * Associativity and Ordering:: Some associative operations are performed
  2736. in a particular order; others are not.
  2737. * Sequence Points:: Some guarantees about the order of operations.
  2738. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2739. * Ordering of Operands:: Evaluation order of operands
  2740. and function arguments.
  2741. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2742. only if it has no impact on program results.
  2743. @end menu
  2744. @node Reordering of Operands
  2745. @section Reordering of Operands
  2746. @cindex ordering of operands
  2747. @cindex reordering of operands
  2748. @cindex operand execution ordering
  2749. The C language does not necessarily carry out operations within an
  2750. expression in the order they appear in the code. For instance, in
  2751. this expression,
  2752. @example
  2753. foo () + bar ()
  2754. @end example
  2755. @noindent
  2756. @code{foo} might be called first or @code{bar} might be called first.
  2757. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2758. results can be unpredictable.
  2759. The unpredictable order of computation of subexpressions also makes a
  2760. difference when one of them contains an assignment. We already saw
  2761. this example of bad code,
  2762. @example
  2763. x = 20;
  2764. printf ("%d %d\n", x, x = 4);
  2765. @end example
  2766. @noindent
  2767. in which the second argument, @code{x}, has a different value
  2768. depending on whether it is computed before or after the assignment in
  2769. the third argument.
  2770. @node Associativity and Ordering
  2771. @section Associativity and Ordering
  2772. @cindex associativity and ordering
  2773. An associative binary operator, such as @code{+}, when used repeatedly
  2774. can combine any number of operands. The operands' values may be
  2775. computed in any order.
  2776. If the values are integers and overflow can be ignored, they may be
  2777. combined in any order. Thus, given four functions that return
  2778. @code{unsigned int}, calling them and adding their results as here
  2779. @example
  2780. (foo () + bar ()) + (baz () + quux ())
  2781. @end example
  2782. @noindent
  2783. may add up the results in any order.
  2784. By contrast, arithmetic on signed integers, in which overflow is significant,
  2785. is not always associative (@pxref{Integer Overflow}). Thus, the
  2786. additions must be done in the order specified, obeying parentheses and
  2787. left-association. That means computing @code{(foo () + bar ())} and
  2788. @code{(baz () + quux ())} first (in either order), then adding the
  2789. two.
  2790. The same applies to arithmetic on floating-point values, since that
  2791. too is not really associative. However, the GCC option
  2792. @option{-funsafe-math-optimizations} allows the compiler to change the
  2793. order of calculation when an associative operation (associative in
  2794. exact mathematics) combines several operands. The option takes effect
  2795. when compiling a module (@pxref{Compilation}). Changing the order
  2796. of association can enable the program to pipeline the floating point
  2797. operations.
  2798. In all these cases, the four function calls can be done in any order.
  2799. There is no right or wrong about that.
  2800. @node Sequence Points
  2801. @section Sequence Points
  2802. @cindex sequence points
  2803. @cindex full expression
  2804. There are some points in the code where C makes limited guarantees
  2805. about the order of operations. These are called @dfn{sequence
  2806. points}. Here is where they occur:
  2807. @itemize @bullet
  2808. @item
  2809. At the end of a @dfn{full expression}; that is to say, an expression
  2810. that is not part of a larger expression. All side effects specified
  2811. by that expression are carried out before execution moves
  2812. on to subsequent code.
  2813. @item
  2814. At the end of the first operand of certain operators: @samp{,},
  2815. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2816. that expression are carried out before any execution of the
  2817. next operand.
  2818. The commas that separate arguments in a function call are @emph{not}
  2819. comma operators, and they do not create sequence points. The rule
  2820. for function arguments and the rule for operands are different
  2821. (@pxref{Ordering of Operands}).
  2822. @item
  2823. Just before calling a function. All side effects specified by the
  2824. argument expressions are carried out before calling the function.
  2825. If the function to be called is not constant---that is, if it is
  2826. computed by an expression---all side effects in that expression are
  2827. carried out before calling the function.
  2828. @end itemize
  2829. The ordering imposed by a sequence point applies locally to a limited
  2830. range of code, as stated above in each case. For instance, the
  2831. ordering imposed by the comma operator does not apply to code outside
  2832. that comma operator. Thus, in this code,
  2833. @example
  2834. (x = 5, foo (x)) + x * x
  2835. @end example
  2836. @noindent
  2837. the sequence point of the comma operator orders @code{x = 5} before
  2838. @code{foo (x)}, but @code{x * x} could be computed before or after
  2839. them.
  2840. @node Postincrement and Ordering
  2841. @section Postincrement and Ordering
  2842. @cindex postincrement and ordering
  2843. @cindex ordering and postincrement
  2844. Ordering requirements are loose with the postincrement and
  2845. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2846. specify side effects to happen ``a little later.'' They must happen
  2847. before the next sequence point, but that still leaves room for various
  2848. meanings. In this expression,
  2849. @example
  2850. z = x++ - foo ()
  2851. @end example
  2852. @noindent
  2853. it's unpredictable whether @code{x} gets incremented before or after
  2854. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2855. it might see the old value or it might see the incremented value.
  2856. In this perverse expression,
  2857. @example
  2858. x = x++
  2859. @end example
  2860. @noindent
  2861. @code{x} will certainly be incremented but the incremented value may
  2862. not stick. If the incrementation of @code{x} happens after the
  2863. assignment to @code{x}, the incremented value will remain in place.
  2864. But if the incrementation happens first, the assignment will overwrite
  2865. that with the not-yet-incremented value, so the expression as a whole
  2866. will leave @code{x} unchanged.
  2867. @node Ordering of Operands
  2868. @section Ordering of Operands
  2869. @cindex ordering of operands
  2870. @cindex operand ordering
  2871. Operands and arguments can be computed in any order, but there are limits to
  2872. this intermixing in GNU C:
  2873. @itemize @bullet
  2874. @item
  2875. The operands of a binary arithmetic operator can be computed in either
  2876. order, but they can't be intermixed: one of them has to come first,
  2877. followed by the other. Any side effects in the operand that's computed
  2878. first are executed before the other operand is computed.
  2879. @item
  2880. That applies to assignment operators too, except that in simple assignment
  2881. the previous value of the left operand is unused.
  2882. @item
  2883. The arguments in a function call can be computed in any order, but
  2884. they can't be intermixed. Thus, one argument is fully computed, then
  2885. another, and so on until they are all done. Any side effects in one argument
  2886. are executed before computation of another argument begins.
  2887. @end itemize
  2888. These rules don't cover side effects caused by postincrement and
  2889. postdecrement operators---those can be deferred up to the next
  2890. sequence point.
  2891. If you want to get pedantic, the fact is that GCC can reorder the
  2892. computations in many other ways provided that doesn't alter the result
  2893. of running the program. However, because they don't alter the result
  2894. of running the program, they are negligible, unless you are concerned
  2895. with the values in certain variables at various times as seen by other
  2896. processes. In those cases, you can use @code{volatile} to prevent
  2897. optimizations that would make them behave strangely. @xref{volatile}.
  2898. @node Optimization and Ordering
  2899. @section Optimization and Ordering
  2900. @cindex optimization and ordering
  2901. @cindex ordering and optimization
  2902. Sequence points limit the compiler's freedom to reorder operations
  2903. arbitrarily, but optimizations can still reorder them if the compiler
  2904. concludes that this won't alter the results. Thus, in this code,
  2905. @example
  2906. x++;
  2907. y = z;
  2908. x++;
  2909. @end example
  2910. @noindent
  2911. there is a sequence point after each statement, so the code is
  2912. supposed to increment @code{x} once before the assignment to @code{y}
  2913. and once after. However, incrementing @code{x} has no effect on
  2914. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2915. the code could be optimized into this:
  2916. @example
  2917. y = z;
  2918. x += 2;
  2919. @end example
  2920. Normally that has no effect except to make the program faster. But
  2921. there are special situations where it can cause trouble due to things
  2922. that the compiler cannot know about, such as shared memory. To limit
  2923. optimization in those places, use the @code{volatile} type qualifier
  2924. (@pxref{volatile}).
  2925. @node Primitive Types
  2926. @chapter Primitive Data Types
  2927. @cindex primitive types
  2928. @cindex types, primitive
  2929. This chapter describes all the primitive data types of C---that is,
  2930. all the data types that aren't built up from other types. They
  2931. include the types @code{int} and @code{double} that we've already covered.
  2932. @menu
  2933. * Integer Types:: Description of integer types.
  2934. * Floating-Point Data Types:: Description of floating-point types.
  2935. * Complex Data Types:: Description of complex number types.
  2936. * The Void Type:: A type indicating no value at all.
  2937. * Other Data Types:: A brief summary of other types.
  2938. * Type Designators:: Referring to a data type abstractly.
  2939. @end menu
  2940. These types are all made up of bytes (@pxref{Storage}).
  2941. @node Integer Types
  2942. @section Integer Data Types
  2943. @cindex integer types
  2944. @cindex types, integer
  2945. Here we describe all the integer types and their basic
  2946. characteristics. @xref{Integers in Depth}, for more information about
  2947. the bit-level integer data representations and arithmetic.
  2948. @menu
  2949. * Basic Integers:: Overview of the various kinds of integers.
  2950. * Signed and Unsigned Types:: Integers can either hold both negative and
  2951. non-negative values, or only non-negative.
  2952. * Narrow Integers:: When to use smaller integer types.
  2953. * Integer Conversion:: Casting a value from one integer type
  2954. to another.
  2955. * Boolean Type:: An integer type for boolean values.
  2956. * Integer Variations:: Sizes of integer types can vary
  2957. across platforms.
  2958. @end menu
  2959. @node Basic Integers
  2960. @subsection Basic Integers
  2961. @findex char
  2962. @findex int
  2963. @findex short int
  2964. @findex long int
  2965. @findex long long int
  2966. Integer data types in C can be signed or unsigned. An unsigned type
  2967. can represent only positive numbers and zero. A signed type can
  2968. represent both positive and negative numbers, in a range spread almost
  2969. equally on both sides of zero.
  2970. Aside from signedness, the integer data types vary in size: how many
  2971. bytes long they are. The size determines how many different integer
  2972. values the type can hold.
  2973. Here's a list of the signed integer data types, with the sizes they
  2974. have on most computers. Each has a corresponding unsigned type; see
  2975. @ref{Signed and Unsigned Types}.
  2976. @table @code
  2977. @item signed char
  2978. One byte (8 bits). This integer type is used mainly for integers that
  2979. represent characters, as part of arrays or other data structures.
  2980. @item short
  2981. @itemx short int
  2982. Two bytes (16 bits).
  2983. @item int
  2984. Four bytes (32 bits).
  2985. @item long
  2986. @itemx long int
  2987. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2988. platform. Typically it is 32 bits on 32-bit computers
  2989. and 64 bits on 64-bit computers, but there are exceptions.
  2990. @item long long
  2991. @itemx long long int
  2992. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2993. incorporated into standard C as of ISO C99.
  2994. @end table
  2995. You can omit @code{int} when you use @code{long} or @code{short}.
  2996. This is harmless and customary.
  2997. @node Signed and Unsigned Types
  2998. @subsection Signed and Unsigned Types
  2999. @cindex signed types
  3000. @cindex unsigned types
  3001. @cindex types, signed
  3002. @cindex types, unsigned
  3003. @findex signed
  3004. @findex unsigned
  3005. An unsigned integer type can represent only positive numbers and zero.
  3006. A signed type can represent both positive and negative number, in a
  3007. range spread almost equally on both sides of zero. For instance,
  3008. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  3009. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  3010. these types holds 256 different possible values, since they are both 8
  3011. bits wide.
  3012. Write @code{signed} or @code{unsigned} before the type keyword to
  3013. specify a signed or an unsigned type. However, the integer types
  3014. other than @code{char} are signed by default; with them, @code{signed}
  3015. is a no-op.
  3016. Plain @code{char} may be signed or unsigned; this depends on the
  3017. compiler, the machine in use, and its operating system.
  3018. In many programs, it makes no difference whether @code{char} is
  3019. signed. When it does matter, don't leave it to chance; write
  3020. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  3021. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  3022. Arctic Char. When my meal arrived, I noted that the chef had not
  3023. signed it. So I complained, ``This char is unsigned---I wanted a
  3024. signed char!'' Or rather, I would have said this if I had thought of
  3025. it fast enough.}
  3026. @node Narrow Integers
  3027. @subsection Narrow Integers
  3028. The types that are narrower than @code{int} are rarely used for
  3029. ordinary variables---we declare them @code{int} instead. This is
  3030. because C converts those narrower types to @code{int} for any
  3031. arithmetic. There is literally no reason to declare a local variable
  3032. @code{char}, for instance.
  3033. In particular, if the value is really a character, you should declare
  3034. the variable @code{int}. Not @code{char}! Using that narrow type can
  3035. force the compiler to truncate values for conversion, which is a
  3036. waste. Furthermore, some functions return either a character value,
  3037. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3038. values distinct.
  3039. The narrow integer types are useful as parts of other objects, such as
  3040. arrays and structures. Compare these array declarations, whose sizes
  3041. on 32-bit processors are shown:
  3042. @example
  3043. signed char ac[1000]; /* @r{1000 bytes} */
  3044. short as[1000]; /* @r{2000 bytes} */
  3045. int ai[1000]; /* @r{4000 bytes} */
  3046. long long all[1000]; /* @r{8000 bytes} */
  3047. @end example
  3048. In addition, character strings must be made up of @code{char}s,
  3049. because that's what all the standard library string functions expect.
  3050. Thus, array @code{ac} could be used as a character string, but the
  3051. others could not be.
  3052. @node Integer Conversion
  3053. @subsection Conversion among Integer Types
  3054. C converts between integer types implicitly in many situations. It
  3055. converts the narrow integer types, @code{char} and @code{short}, to
  3056. @code{int} whenever they are used in arithmetic. Assigning a new
  3057. value to an integer variable (or other lvalue) converts the value to
  3058. the variable's type.
  3059. You can also convert one integer type to another explicitly with a
  3060. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3061. The process of conversion to a wider type is straightforward: the
  3062. value is unchanged. The only exception is when converting a negative
  3063. value (in a signed type, obviously) to a wider unsigned type. In that
  3064. case, the result is a positive value with the same bits
  3065. (@pxref{Integers in Depth}).
  3066. @cindex truncation
  3067. Converting to a narrower type, also called @dfn{truncation}, involves
  3068. discarding some of the value's bits. This is not considered overflow
  3069. (@pxref{Integer Overflow}) because loss of significant bits is a
  3070. normal consequence of truncation. Likewise for conversion between
  3071. signed and unsigned types of the same width.
  3072. More information about conversion for assignment is in
  3073. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3074. see @ref{Argument Promotions}.
  3075. @node Boolean Type
  3076. @subsection Boolean Type
  3077. @cindex boolean type
  3078. @cindex type, boolean
  3079. @findex bool
  3080. The unsigned integer type @code{bool} holds truth values: its possible
  3081. values are 0 and 1. Converting any nonzero value to @code{bool}
  3082. results in 1. For example:
  3083. @example
  3084. bool a = 0;
  3085. bool b = 1;
  3086. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3087. @end example
  3088. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3089. the header file @file{stdbool.h}.
  3090. @node Integer Variations
  3091. @subsection Integer Variations
  3092. The integer types of C have standard @emph{names}, but what they
  3093. @emph{mean} varies depending on the kind of platform in use:
  3094. which kind of computer, which operating system, and which compiler.
  3095. It may even depend on the compiler options used.
  3096. Plain @code{char} may be signed or unsigned; this depends on the
  3097. platform, too. Even for GNU C, there is no general rule.
  3098. In theory, all of the integer types' sizes can vary. @code{char} is
  3099. always considered one ``byte'' for C, but it is not necessarily an
  3100. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3101. specifies only that none of these types is narrower than the ones
  3102. above it in the list in @ref{Basic Integers}, and that @code{short}
  3103. has at least 16 bits.
  3104. It is possible that in the future GNU C will support platforms where
  3105. @code{int} is 64 bits long. In practice, however, on today's real
  3106. computers, there is little variation; you can rely on the table
  3107. given previously (@pxref{Basic Integers}).
  3108. To be completely sure of the size of an integer type,
  3109. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3110. Their corresponding unsigned types add @samp{u} at the front.
  3111. To define these, include the header file @file{stdint.h}.
  3112. The GNU C Compiler compiles for some embedded controllers that use two
  3113. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3114. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3115. 32 bits. These processors can't support an ordinary operating system
  3116. (they may have their own specialized operating systems), and most C
  3117. programs do not try to support them.
  3118. @node Floating-Point Data Types
  3119. @section Floating-Point Data Types
  3120. @cindex floating-point types
  3121. @cindex types, floating-point
  3122. @findex double
  3123. @findex float
  3124. @findex long double
  3125. @dfn{Floating point} is the binary analogue of scientific notation:
  3126. internally it represents a number as a fraction and a binary exponent; the
  3127. value is that fraction multiplied by the specified power of 2.
  3128. For instance, to represent 6, the fraction would be 0.75 and the
  3129. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3130. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3131. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3132. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3133. -1 as the exponent.
  3134. These binary exponents are used by machine instructions. You can
  3135. write a floating-point constant this way if you wish, using
  3136. hexadecimal; but normally we write floating-point numbers in decimal.
  3137. @xref{Floating Constants}.
  3138. C has three floating-point data types:
  3139. @table @code
  3140. @item double
  3141. ``Double-precision'' floating point, which uses 64 bits. This is the
  3142. normal floating-point type, and modern computers normally do
  3143. their floating-point computations in this type, or some wider type.
  3144. Except when there is a special reason to do otherwise, this is the
  3145. type to use for floating-point values.
  3146. @item float
  3147. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3148. for floating-point values stored in structures and arrays, to save
  3149. space when the full precision of @code{double} is not needed. In
  3150. addition, single-precision arithmetic is faster on some computers, and
  3151. occasionally that is useful. But not often---most programs don't use
  3152. the type @code{float}.
  3153. C would be cleaner if @code{float} were the name of the type we
  3154. use for most floating-point values; however, for historical reasons,
  3155. that's not so.
  3156. @item long double
  3157. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3158. precision, depending on the machine in use. On some machines, which
  3159. have no floating-point format wider than @code{double}, this is
  3160. equivalent to @code{double}.
  3161. @end table
  3162. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3163. Point in Depth}, for more information.
  3164. @node Complex Data Types
  3165. @section Complex Data Types
  3166. @cindex complex numbers
  3167. @cindex types, complex
  3168. @cindex @code{_Complex} keyword
  3169. @cindex @code{__complex__} keyword
  3170. @findex _Complex
  3171. @findex __complex__
  3172. Complex numbers can include both a real part and an imaginary part.
  3173. The numeric constants covered above have real-numbered values. An
  3174. imaginary-valued constant is an ordinary real-valued constant followed
  3175. by @samp{i}.
  3176. To declare numeric variables as complex, use the @code{_Complex}
  3177. keyword.@footnote{For compatibility with older versions of GNU C, the
  3178. keyword @code{__complex__} is also allowed. Going forward, however,
  3179. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3180. standard C complex data types are floating point,
  3181. @example
  3182. _Complex float foo;
  3183. _Complex double bar;
  3184. _Complex long double quux;
  3185. @end example
  3186. @noindent
  3187. but GNU C supports integer complex types as well.
  3188. Since @code{_Complex} is a keyword just like @code{float} and
  3189. @code{double} and @code{long}, the keywords can appear in any order,
  3190. but the order shown above seems most logical.
  3191. GNU C supports constants for complex values; for instance, @code{4.0 +
  3192. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3193. @xref{Imaginary Constants}.
  3194. To pull the real and imaginary parts of the number back out, GNU C
  3195. provides the keywords @code{__real__} and @code{__imag__}:
  3196. @example
  3197. _Complex double foo = 4.0 + 3.0i;
  3198. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3199. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3200. @end example
  3201. @noindent
  3202. Standard C does not include these keywords, and instead relies on
  3203. functions defined in @code{complex.h} for accessing the real and
  3204. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3205. @code{creall} extract the real part of a float, double, or long double
  3206. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3207. @code{cimagl} extract the imaginary part.
  3208. @cindex complex conjugation
  3209. GNU C also defines @samp{~} as an operator for complex conjugation,
  3210. which means negating the imaginary part of a complex number:
  3211. @example
  3212. _Complex double foo = 4.0 + 3.0i;
  3213. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3214. @end example
  3215. @noindent
  3216. For standard C compatibility, you can use the appropriate library
  3217. function: @code{conjf}, @code{conj}, or @code{confl}.
  3218. @node The Void Type
  3219. @section The Void Type
  3220. @cindex void type
  3221. @cindex type, void
  3222. @findex void
  3223. The data type @code{void} is a dummy---it allows no operations. It
  3224. really means ``no value at all.'' When a function is meant to return
  3225. no value, we write @code{void} for its return type. Then
  3226. @code{return} statements in that function should not specify a value
  3227. (@pxref{return Statement}). Here's an example:
  3228. @example
  3229. void
  3230. print_if_positive (double x, double y)
  3231. @{
  3232. if (x <= 0)
  3233. return;
  3234. if (y <= 0)
  3235. return;
  3236. printf ("Next point is (%f,%f)\n", x, y);
  3237. @}
  3238. @end example
  3239. A @code{void}-returning function is comparable to what some other languages
  3240. call a ``procedure'' instead of a ``function.''
  3241. @c ??? Already presented
  3242. @c @samp{%f} in an output template specifies to format a @code{double} value
  3243. @c as a decimal number, using a decimal point if needed.
  3244. @node Other Data Types
  3245. @section Other Data Types
  3246. Beyond the primitive types, C provides several ways to construct new
  3247. data types. For instance, you can define @dfn{pointers}, values that
  3248. represent the addresses of other data (@pxref{Pointers}). You can
  3249. define @dfn{structures}, as in many other languages
  3250. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3251. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3252. are collections of named integer codes (@pxref{Enumeration Types}).
  3253. @dfn{Array types} in C are used for allocating space for objects,
  3254. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3255. @node Type Designators
  3256. @section Type Designators
  3257. @cindex type designator
  3258. Some C constructs require a way to designate a specific data type
  3259. independent of any particular variable or expression which has that
  3260. type. The way to do this is with a @dfn{type designator}. The
  3261. constucts that need one include casts (@pxref{Explicit Type
  3262. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3263. We also use type designators to talk about the type of a value in C,
  3264. so you will see many type designators in this manual. When we say,
  3265. ``The value has type @code{int},'' @code{int} is a type designator.
  3266. To make the designator for any type, imagine a variable declaration
  3267. for a variable of that type and delete the variable name and the final
  3268. semicolon.
  3269. For example, to designate the type of full-word integers, we start
  3270. with the declaration for a variable @code{foo} with that type,
  3271. which is this:
  3272. @example
  3273. int foo;
  3274. @end example
  3275. @noindent
  3276. Then we delete the variable name @code{foo} and the semicolon, leaving
  3277. @code{int}---exactly the keyword used in such a declaration.
  3278. Therefore, the type designator for this type is @code{int}.
  3279. What about long unsigned integers? From the declaration
  3280. @example
  3281. unsigned long int foo;
  3282. @end example
  3283. @noindent
  3284. we determine that the designator is @code{unsigned long int}.
  3285. Following this procedure, the designator for any primitive type is
  3286. simply the set of keywords which specifies that type in a declaration.
  3287. The same is true for compound types such as structures, unions, and
  3288. enumerations.
  3289. Designators for pointer types do follow the rule of deleting the
  3290. variable name and semicolon, but the result is not so simple.
  3291. @xref{Pointer Type Designators}, as part of the chapter about
  3292. pointers. @xref{Array Type Designators}), for designators for array
  3293. types.
  3294. To understand what type a designator stands for, imagine a variable
  3295. name inserted into the right place in the designator to make a valid
  3296. declaration. What type would that variable be declared as? That is the
  3297. type the designator designates.
  3298. @node Constants
  3299. @chapter Constants
  3300. @cindex constants
  3301. A @dfn{constant} is an expression that stands for a specific value by
  3302. explicitly representing the desired value. C allows constants for
  3303. numbers, characters, and strings. We have already seen numeric and
  3304. string constants in the examples.
  3305. @menu
  3306. * Integer Constants:: Literal integer values.
  3307. * Integer Const Type:: Types of literal integer values.
  3308. * Floating Constants:: Literal floating-point values.
  3309. * Imaginary Constants:: Literal imaginary number values.
  3310. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3311. * Character Constants:: Literal character values.
  3312. * String Constants:: Literal string values.
  3313. * UTF-8 String Constants:: Literal UTF-8 string values.
  3314. * Unicode Character Codes:: Unicode characters represented
  3315. in either UTF-16 or UTF-32.
  3316. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3317. * Wide String Constants:: Literal string values made up of
  3318. 16- or 32-bit characters.
  3319. @end menu
  3320. @node Integer Constants
  3321. @section Integer Constants
  3322. @cindex integer constants
  3323. @cindex constants, integer
  3324. An integer constant consists of a number to specify the value,
  3325. followed optionally by suffix letters to specify the data type.
  3326. The simplest integer constants are numbers written in base 10
  3327. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3328. constant cannot start with the character @samp{0} (zero) because
  3329. that makes the constant octal.
  3330. You can get the effect of a negative integer constant by putting a
  3331. minus sign at the beginning. Grammatically speaking, that is an
  3332. arithmetic expression rather than a constant, but it behaves just like
  3333. a true constant.
  3334. Integer constants can also be written in octal (base 8), hexadecimal
  3335. (base 16), or binary (base 2). An octal constant starts with the
  3336. character @samp{0} (zero), followed by any number of octal digits
  3337. (@samp{0} to @samp{7}):
  3338. @example
  3339. 0 // @r{zero}
  3340. 077 // @r{63}
  3341. 0403 // @r{259}
  3342. @end example
  3343. @noindent
  3344. Pedantically speaking, the constant @code{0} is an octal constant, but
  3345. we can think of it as decimal; it has the same value either way.
  3346. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3347. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3348. through @samp{f} in upper or lower case):
  3349. @example
  3350. 0xff // @r{255}
  3351. 0XA0 // @r{160}
  3352. 0xffFF // @r{65535}
  3353. @end example
  3354. @cindex binary integer constants
  3355. A binary constant starts with @samp{0b} (upper or lower case) followed
  3356. by bits (each represented by the characters @samp{0} or @samp{1}):
  3357. @example
  3358. 0b101 // @r{5}
  3359. @end example
  3360. Binary constants are a GNU C extension, not part of the C standard.
  3361. Sometimes a space is needed after an integer constant to avoid
  3362. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3363. @node Integer Const Type
  3364. @section Integer Constant Data Types
  3365. @cindex integer constant data types
  3366. @cindex constant data types, integer
  3367. @cindex types of integer constants
  3368. The type of an integer constant is normally @code{int}, if the value
  3369. fits in that type, but here are the complete rules. The type
  3370. of an integer constant is the first one in this sequence that can
  3371. properly represent the value,
  3372. @enumerate
  3373. @item
  3374. @code{int}
  3375. @item
  3376. @code{unsigned int}
  3377. @item
  3378. @code{long int}
  3379. @item
  3380. @code{unsigned long int}
  3381. @item
  3382. @code{long long int}
  3383. @item
  3384. @code{unsigned long long int}
  3385. @end enumerate
  3386. @noindent
  3387. and that isn't excluded by the following rules.
  3388. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3389. first two types (non-@code{long}).
  3390. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3391. first four types (non-@code{long long}).
  3392. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3393. the signed types.
  3394. Otherwise, if the constant is decimal, that excludes the unsigned
  3395. types.
  3396. @c ### This said @code{unsigned int} is excluded.
  3397. @c ### See 17 April 2016
  3398. Here are some examples of the suffixes.
  3399. @example
  3400. 3000000000u // @r{three billion as @code{unsigned int}.}
  3401. 0LL // @r{zero as a @code{long long int}.}
  3402. 0403l // @r{259 as a @code{long int}.}
  3403. @end example
  3404. Suffixes in integer constants are rarely used. When the precise type
  3405. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3406. Type Conversion}).
  3407. @xref{Integer Types}.
  3408. @node Floating Constants
  3409. @section Floating-Point Constants
  3410. @cindex floating-point constants
  3411. @cindex constants, floating-point
  3412. A floating-point constant must have either a decimal point, an
  3413. exponent-of-ten, or both; they distinguish it from an integer
  3414. constant.
  3415. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3416. value follows. It is always written as a decimal number; it can
  3417. optionally start with a sign. The exponent @var{n} means to multiply
  3418. the constant's value by ten to the @var{n}th power.
  3419. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3420. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3421. writing a floating-point number whose value is 1500. They are all
  3422. equivalent.
  3423. Here are more examples with decimal points:
  3424. @example
  3425. 1.0
  3426. 1000.
  3427. 3.14159
  3428. .05
  3429. .0005
  3430. @end example
  3431. For each of them, here are some equivalent constants written with
  3432. exponents:
  3433. @example
  3434. 1e0, 1.0000e0
  3435. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3436. 3.14159e0
  3437. 5e-2, .0005e+2, 5E-2, .0005E2
  3438. .05e-2
  3439. @end example
  3440. A floating-point constant normally has type @code{double}. You can
  3441. force it to type @code{float} by adding @samp{f} or @samp{F}
  3442. at the end. For example,
  3443. @example
  3444. 3.14159f
  3445. 3.14159e0f
  3446. 1000.f
  3447. 100E1F
  3448. .0005f
  3449. .05e-2f
  3450. @end example
  3451. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3452. to type @code{long double}.
  3453. You can use exponents in hexadecimal floating constants, but since
  3454. @samp{e} would be interpreted as a hexadecimal digit, the character
  3455. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3456. The exponent in a hexadecimal floating constant is a possibly-signed
  3457. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3458. multiply into the number.
  3459. Here are some examples:
  3460. @example
  3461. @group
  3462. 0xAp2 // @r{40 in decimal}
  3463. 0xAp-1 // @r{5 in decimal}
  3464. 0x2.0Bp4 // @r{16.75 decimal}
  3465. 0xE.2p3 // @r{121 decimal}
  3466. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3467. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3468. 0x100p-8 // @r{1}
  3469. 0x10p-4 // @r{1}
  3470. 0x1p+4 // @r{16}
  3471. 0x1p+8 // @r{256}
  3472. @end group
  3473. @end example
  3474. @xref{Floating-Point Data Types}.
  3475. @node Imaginary Constants
  3476. @section Imaginary Constants
  3477. @cindex imaginary constants
  3478. @cindex complex constants
  3479. @cindex constants, imaginary
  3480. A complex number consists of a real part plus an imaginary part.
  3481. (Either or both parts may be zero.) This section explains how to
  3482. write numeric constants with imaginary values. By adding these to
  3483. ordinary real-valued numeric constants, we can make constants with
  3484. complex values.
  3485. The simple way to write an imaginary-number constant is to attach the
  3486. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3487. floating-point constant. For example, @code{2.5fi} has type
  3488. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3489. The four alternative suffix letters are all equivalent.
  3490. @cindex _Complex_I
  3491. The other way to write an imaginary constant is to multiply a real
  3492. constant by @code{_Complex_I}, which represents the imaginary number
  3493. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3494. this clunky way is needed.
  3495. To write a complex constant with a nonzero real part and a nonzero
  3496. imaginary part, write the two separately and add them, like this:
  3497. @example
  3498. 4.0 + 3.0i
  3499. @end example
  3500. @noindent
  3501. That gives the value 4 + 3i, with type @code{_Complex double}.
  3502. Such a sum can include multiple real constants, or none. Likewise, it
  3503. can include multiple imaginary constants, or none. For example:
  3504. @example
  3505. _Complex double foo, bar, quux;
  3506. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3507. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3508. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3509. @end example
  3510. @xref{Complex Data Types}.
  3511. @node Invalid Numbers
  3512. @section Invalid Numbers
  3513. Some number-like constructs which are not really valid as numeric
  3514. constants are treated as numbers in preprocessing directives. If
  3515. these constructs appear outside of preprocessing, they are erroneous.
  3516. @xref{Preprocessing Tokens}.
  3517. Sometimes we need to insert spaces to separate tokens so that they
  3518. won't be combined into a single number-like construct. For example,
  3519. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3520. constant, so it is a syntax error. If what we want is the three
  3521. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3522. @node Character Constants
  3523. @section Character Constants
  3524. @cindex character constants
  3525. @cindex constants, character
  3526. @cindex escape sequence
  3527. A @dfn{character constant} is written with single quotes, as in
  3528. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3529. character that the constant should represent. The constant has type
  3530. @code{int}, and its value is the character code of that character.
  3531. For instance, @code{'a'} represents the character code for the letter
  3532. @samp{a}: 97, that is.
  3533. To put the @samp{'} character (single quote) in the character
  3534. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3535. constant looks like @code{'\''}. This sort of sequence, starting with
  3536. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3537. here functions as a kind of @dfn{escape character}.
  3538. To put the @samp{\} character (backslash) in the character constant,
  3539. quote it likewise with @samp{\} (another backslash). This character
  3540. constant looks like @code{'\\'}.
  3541. @cindex bell character
  3542. @cindex @samp{\a}
  3543. @cindex backspace
  3544. @cindex @samp{\b}
  3545. @cindex tab (ASCII character)
  3546. @cindex @samp{\t}
  3547. @cindex vertical tab
  3548. @cindex @samp{\v}
  3549. @cindex formfeed
  3550. @cindex @samp{\f}
  3551. @cindex newline
  3552. @cindex @samp{\n}
  3553. @cindex return (ASCII character)
  3554. @cindex @samp{\r}
  3555. @cindex escape (ASCII character)
  3556. @cindex @samp{\e}
  3557. Here are all the escape sequences that represent specific
  3558. characters in a character constant. The numeric values shown are
  3559. the corresponding ASCII character codes, as decimal numbers.
  3560. @example
  3561. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3562. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3563. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3564. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3565. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3566. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3567. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3568. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3569. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3570. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3571. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3572. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3573. @end example
  3574. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3575. You can also write octal and hex character codes as
  3576. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3577. option here, so octal codes do not need to start with @samp{0}.
  3578. The character constant's value has type @code{int}. However, the
  3579. character code is treated initially as a @code{char} value, which is
  3580. then converted to @code{int}. If the character code is greater than
  3581. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3582. on a platform where the type @code{char} is 8 bits long and signed.
  3583. @node String Constants
  3584. @section String Constants
  3585. @cindex string constants
  3586. @cindex constants, string
  3587. A @dfn{string constant} represents a series of characters. It starts
  3588. with @samp{"} and ends with @samp{"}; in between are the contents of
  3589. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3590. newline in the contents works in string constants as in character
  3591. constants. In a string constant, @samp{'} does not need to be quoted.
  3592. A string constant defines an array of characters which contains the
  3593. specified characters followed by the null character (code 0). Using
  3594. the string constant is equivalent to using the name of an array with
  3595. those contents. In simple cases, the length in bytes of the string
  3596. constant is one greater than the number of characters written in it.
  3597. As with any array in C, using the string constant in an expression
  3598. converts the array to a pointer (@pxref{Pointers}) to the array's
  3599. first element (@pxref{Accessing Array Elements}). This pointer will
  3600. have type @code{char *} because it points to an element of type
  3601. @code{char}. @code{char *} is an example of a type designator for a
  3602. pointer type (@pxref{Pointer Type Designators}). That type is used
  3603. for strings generally, not just the strings expressed as constants
  3604. in a program.
  3605. Thus, the string constant @code{"Foo!"} is almost
  3606. equivalent to declaring an array like this
  3607. @example
  3608. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3609. @end example
  3610. @noindent
  3611. and then using @code{string_array_1} in the program. There
  3612. are two differences, however:
  3613. @itemize @bullet
  3614. @item
  3615. The string constant doesn't define a name for the array.
  3616. @item
  3617. The string constant is probably stored in a read-only area of memory.
  3618. @end itemize
  3619. Newlines are not allowed in the text of a string constant. The motive
  3620. for this prohibition is to catch the error of omitting the closing
  3621. @samp{"}. To put a newline in a constant string, write it as
  3622. @samp{\n} in the string constant.
  3623. A real null character in the source code inside a string constant
  3624. causes a warning. To put a null character in the middle of a string
  3625. constant, write @samp{\0} or @samp{\000}.
  3626. Consecutive string constants are effectively concatenated. Thus,
  3627. @example
  3628. "Fo" "o!" @r{is equivalent to} "Foo!"
  3629. @end example
  3630. This is useful for writing a string containing multiple lines,
  3631. like this:
  3632. @example
  3633. "This message is so long that it needs more than\n"
  3634. "a single line of text. C does not allow a newline\n"
  3635. "to represent itself in a string constant, so we have to\n"
  3636. "write \\n to put it in the string. For readability of\n"
  3637. "the source code, it is advisable to put line breaks in\n"
  3638. "the source where they occur in the contents of the\n"
  3639. "constant.\n"
  3640. @end example
  3641. The sequence of a backslash and a newline is ignored anywhere
  3642. in a C program, and that includes inside a string constant.
  3643. Thus, you can write multi-line string constants this way:
  3644. @example
  3645. "This is another way to put newlines in a string constant\n\
  3646. and break the line after them in the source code."
  3647. @end example
  3648. @noindent
  3649. However, concatenation is the recommended way to do this.
  3650. You can also write perverse string constants like this,
  3651. @example
  3652. "Fo\
  3653. o!"
  3654. @end example
  3655. @noindent
  3656. but don't do that---write it like this instead:
  3657. @example
  3658. "Foo!"
  3659. @end example
  3660. Be careful to avoid passing a string constant to a function that
  3661. modifies the string it receives. The memory where the string constant
  3662. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3663. signal that normally terminates the function (@pxref{Signals}. Even
  3664. worse, the memory may not be read-only. Then the function might
  3665. modify the string constant, thus spoiling the contents of other string
  3666. constants that are supposed to contain the same value and are unified
  3667. by the compiler.
  3668. @node UTF-8 String Constants
  3669. @section UTF-8 String Constants
  3670. @cindex UTF-8 String Constants
  3671. Writing @samp{u8} immediately before a string constant, with no
  3672. intervening space, means to represent that string in UTF-8 encoding as
  3673. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3674. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3675. as multibyte sequences. Here is an example of a UTF-8 constant:
  3676. @example
  3677. u8"A cónstàñt"
  3678. @end example
  3679. This constant occupies 13 bytes plus the terminating null,
  3680. because each of the accented letters is a two-byte sequence.
  3681. Concatenating an ordinary string with a UTF-8 string conceptually
  3682. produces another UTF-8 string. However, if the ordinary string
  3683. contains character codes 128 and up, the results cannot be relied on.
  3684. @node Unicode Character Codes
  3685. @section Unicode Character Codes
  3686. @cindex Unicode character codes
  3687. @cindex universal character names
  3688. You can specify Unicode characters, for individual character constants
  3689. or as part of string constants (@pxref{String Constants}), using
  3690. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3691. hexadecimal Unicode character code. If the code value is too big for
  3692. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3693. Unicode character code. (These codes are called @dfn{universal
  3694. character names}.) For example,
  3695. @example
  3696. \u6C34 /* @r{16-bit code (UTF-16)} */
  3697. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3698. @end example
  3699. @noindent
  3700. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3701. Constants}). For instance,
  3702. @example
  3703. u8"fóó \u6C34 \U0010ABCD"
  3704. @end example
  3705. You can also use them in wide character constants (@pxref{Wide
  3706. Character Constants}), like this:
  3707. @example
  3708. u'\u6C34' /* @r{16-bit code} */
  3709. U'\U0010ABCD' /* @r{32-bit code} */
  3710. @end example
  3711. @noindent
  3712. and in wide string constants (@pxref{Wide String Constants}), like
  3713. this:
  3714. @example
  3715. u"\u6C34\u6C33" /* @r{16-bit code} */
  3716. U"\U0010ABCD" /* @r{32-bit code} */
  3717. @end example
  3718. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3719. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3720. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3721. actually ASCII control characters, and you can specify them with other
  3722. escape sequences (@pxref{Character Constants}).
  3723. @node Wide Character Constants
  3724. @section Wide Character Constants
  3725. @cindex wide character constants
  3726. @cindex constants, wide character
  3727. A @dfn{wide character constant} represents characters with more than 8
  3728. bits of character code. This is an obscure feature that we need to
  3729. document but that you probably won't ever use. If you're just
  3730. learning C, you may as well skip this section.
  3731. The original C wide character constant looks like @samp{L} (upper
  3732. case!) followed immediately by an ordinary character constant (with no
  3733. intervening space). Its data type is @code{wchar_t}, which is an
  3734. alias defined in @file{stddef.h} for one of the standard integer
  3735. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3736. it is 16 bits, these character constants use the UTF-16 form of
  3737. Unicode; if 32 bits, UTF-32.
  3738. There are also Unicode wide character constants which explicitly
  3739. specify the width. These constants start with @samp{u} or @samp{U}
  3740. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3741. character constant, and @samp{U} a 32-bit Unicode wide character
  3742. constant. Their types are, respectively, @code{char16_t} and
  3743. @w{@code{char32_t}}; they are declared in the header file
  3744. @file{uchar.h}. These character constants are valid even if
  3745. @file{uchar.h} is not included, but some uses of them may be
  3746. inconvenient without including it to declare those type names.
  3747. The character represented in a wide character constant can be an
  3748. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3749. are all valid, and they are all equal to @code{'a'}.
  3750. In all three kinds of wide character constants, you can write a
  3751. non-ASCII Unicode character in the constant itself; the constant's
  3752. value is the character's Unicode character code. Or you can specify
  3753. the Unicode character with an escape sequence (@pxref{Unicode
  3754. Character Codes}).
  3755. @node Wide String Constants
  3756. @section Wide String Constants
  3757. @cindex wide string constants
  3758. @cindex constants, wide string
  3759. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3760. characters. They are rarely used; if you're just
  3761. learning C, you may as well skip this section.
  3762. There are three kinds of wide string constants, which differ in the
  3763. data type used for each character in the string. Each wide string
  3764. constant is equivalent to an array of integers, but the data type of
  3765. those integers depends on the kind of wide string. Using the constant
  3766. in an expression will convert the array to a pointer to its first
  3767. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3768. For each kind of wide string constant, we state here what type that
  3769. pointer will be.
  3770. @table @code
  3771. @item char16_t
  3772. This is a 16-bit Unicode wide string constant: each element is a
  3773. 16-bit Unicode character code with type @code{char16_t}, so the string
  3774. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3775. @pxref{Pointer Type Designators}.) The constant is written as
  3776. @samp{u} (which must be lower case) followed (with no intervening
  3777. space) by a string constant with the usual syntax.
  3778. @item char32_t
  3779. This is a 32-bit Unicode wide string constant: each element is a
  3780. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3781. It's written as @samp{U} (which must be upper case) followed (with no
  3782. intervening space) by a string constant with the usual syntax.
  3783. @item wchar_t
  3784. This is the original kind of wide string constant. It's written as
  3785. @samp{L} (which must be upper case) followed (with no intervening
  3786. space) by a string constant with the usual syntax, and the string has
  3787. type @code{wchar_t@ *}.
  3788. The width of the data type @code{wchar_t} depends on the target
  3789. platform, which makes this kind of wide string somewhat less useful
  3790. than the newer kinds.
  3791. @end table
  3792. @code{char16_t} and @code{char32_t} are declared in the header file
  3793. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3794. Consecutive wide string constants of the same kind concatenate, just
  3795. like ordinary string constants. A wide string constant concatenated
  3796. with an ordinary string constant results in a wide string constant.
  3797. You can't concatenate two wide string constants of different kinds.
  3798. You also can't concatenate a wide string constant (of any kind) with a
  3799. UTF-8 string constant.
  3800. @node Type Size
  3801. @chapter Type Size
  3802. @cindex type size
  3803. @cindex size of type
  3804. @findex sizeof
  3805. Each data type has a @dfn{size}, which is the number of bytes
  3806. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3807. a C program, use @code{sizeof}. There are two ways to use it:
  3808. @table @code
  3809. @item sizeof @var{expression}
  3810. This gives the size of @var{expression}, based on its data type. It
  3811. does not calculate the value of @var{expression}, only its size, so if
  3812. @var{expression} includes side effects or function calls, they do not
  3813. happen. Therefore, @code{sizeof} is always a compile-time operation
  3814. that has zero run-time cost.
  3815. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3816. operand of @code{sizeof}.
  3817. For example,
  3818. @example
  3819. double a;
  3820. i = sizeof a + 10;
  3821. @end example
  3822. @noindent
  3823. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3824. Here's how to determine the number of elements in an array
  3825. @code{array}:
  3826. @example
  3827. (sizeof array / sizeof array[0])
  3828. @end example
  3829. @noindent
  3830. The expression @code{sizeof array} gives the size of the array, not
  3831. the size of a pointer to an element. However, if @var{expression} is
  3832. a function parameter that was declared as an array, that
  3833. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3834. the result is the size of that pointer.
  3835. @item sizeof (@var{type})
  3836. This gives the size of @var{type}.
  3837. For example,
  3838. @example
  3839. i = sizeof (double) + 10;
  3840. @end example
  3841. @noindent
  3842. is equivalent to the previous example.
  3843. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3844. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3845. C, which makes adding an integer to a function pointer work as desired
  3846. (@pxref{Pointer Arithmetic}).
  3847. @end table
  3848. @strong{Warning}: When you use @code{sizeof} with a type
  3849. instead of an expression, you must write parentheses around the type.
  3850. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3851. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3852. the cast expression to avoid an ambiguity in the grammar of C@.
  3853. Specifically,
  3854. @example
  3855. sizeof (int) -x
  3856. @end example
  3857. @noindent
  3858. parses as
  3859. @example
  3860. (sizeof (int)) - x
  3861. @end example
  3862. @noindent
  3863. If what you want is
  3864. @example
  3865. sizeof ((int) -x)
  3866. @end example
  3867. @noindent
  3868. you must write it that way, with parentheses.
  3869. The data type of the value of the @code{sizeof} operator is always one
  3870. of the unsigned integer types; which one of those types depends on the
  3871. machine. The header file @code{stddef.h} defines the typedef name
  3872. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3873. Names}.
  3874. @node Pointers
  3875. @chapter Pointers
  3876. @cindex pointers
  3877. Among high-level languages, C is rather low level, close to the
  3878. machine. This is mainly because it has explicit @dfn{pointers}. A
  3879. pointer value is the numeric address of data in memory. The type of
  3880. data to be found at that address is specified by the data type of the
  3881. pointer itself. The unary operator @samp{*} gets the data that a
  3882. pointer points to---this is called @dfn{dereferencing the pointer}.
  3883. C also allows pointers to functions, but since there are some
  3884. differences in how they work, we treat them later. @xref{Function
  3885. Pointers}.
  3886. @menu
  3887. * Address of Data:: Using the ``address-of'' operator.
  3888. * Pointer Types:: For each type, there is a pointer type.
  3889. * Pointer Declarations:: Declaring variables with pointer types.
  3890. * Pointer Type Designators:: Designators for pointer types.
  3891. * Pointer Dereference:: Accessing what a pointer points at.
  3892. * Null Pointers:: Pointers which do not point to any object.
  3893. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3894. * Void Pointers:: Totally generic pointers, can cast to any.
  3895. * Pointer Comparison:: Comparing memory address values.
  3896. * Pointer Arithmetic:: Computing memory address values.
  3897. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3898. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3899. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3900. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3901. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3902. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3903. @end menu
  3904. @node Address of Data
  3905. @section Address of Data
  3906. @cindex address-of operator
  3907. The most basic way to make a pointer is with the ``address-of''
  3908. operator, @samp{&}. Let's suppose we have these variables available:
  3909. @example
  3910. int i;
  3911. double a[5];
  3912. @end example
  3913. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3914. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3915. address of the element 3 of @code{a}. (It is actually the fourth
  3916. element in the array, since the first element has index 0.)
  3917. The address-of operator is unusual because it operates on a place to
  3918. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3919. stored there. (The left argument of a simple assignment is unusual in
  3920. the same way.) You can use it on any lvalue except a bit field
  3921. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3922. Constructors}).
  3923. @node Pointer Types
  3924. @section Pointer Types
  3925. For each data type @var{t}, there is a type for pointers to type
  3926. @var{t}. For these variables,
  3927. @example
  3928. int i;
  3929. double a[5];
  3930. @end example
  3931. @itemize @bullet
  3932. @item
  3933. @code{i} has type @code{int}; we say
  3934. @code{&i} is a ``pointer to @code{int}.''
  3935. @item
  3936. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3937. arrays of five @code{double}s.''
  3938. @item
  3939. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3940. to @code{double}.''
  3941. @end itemize
  3942. @node Pointer Declarations
  3943. @section Pointer-Variable Declarations
  3944. The way to declare that a variable @code{foo} points to type @var{t} is
  3945. @example
  3946. @var{t} *foo;
  3947. @end example
  3948. To remember this syntax, think ``if you dereference @code{foo}, using
  3949. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3950. points to type @var{t}.''
  3951. Thus, we can declare variables that hold pointers to these three
  3952. types, like this:
  3953. @example
  3954. int *ptri; /* @r{Pointer to @code{int}.} */
  3955. double *ptrd; /* @r{Pointer to @code{double}.} */
  3956. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3957. @end example
  3958. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3959. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3960. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3961. @code{double}.'' The parentheses express the point that you would
  3962. dereference it first, then subscript it.
  3963. Contrast the last one with this:
  3964. @example
  3965. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3966. @end example
  3967. @noindent
  3968. Because @samp{*} has higher syntactic precedence than subscripting,
  3969. you would subscript @code{aptrd} then dereference it. Therefore, it
  3970. declares an array of pointers, not a pointer.
  3971. @node Pointer Type Designators
  3972. @section Pointer-Type Designators
  3973. Every type in C has a designator; you make it by deleting the variable
  3974. name and the semicolon from a declaration (@pxref{Type
  3975. Designators}). Here are the designators for the pointer
  3976. types of the example declarations in the previous section:
  3977. @example
  3978. int * /* @r{Pointer to @code{int}.} */
  3979. double * /* @r{Pointer to @code{double}.} */
  3980. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3981. @end example
  3982. Remember, to understand what type a designator stands for, imagine the
  3983. variable name that would be in the declaration, and figure out what
  3984. type it would declare that variable with. @code{double (*)[5]} can
  3985. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3986. which, when dereferenced, gives an array of 5 @code{double}s.
  3987. @node Pointer Dereference
  3988. @section Dereferencing Pointers
  3989. @cindex dereferencing pointers
  3990. @cindex pointer dereferencing
  3991. The main use of a pointer value is to @dfn{dereference it} (access the
  3992. data it points at) with the unary @samp{*} operator. For instance,
  3993. @code{*&i} is the value at @code{i}'s address---which is just
  3994. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3995. valid.
  3996. A pointer-dereference expression whose type is data (not a function)
  3997. is an lvalue.
  3998. Pointers become really useful when we store them somewhere and use
  3999. them later. Here's a simple example to illustrate the practice:
  4000. @example
  4001. @{
  4002. int i;
  4003. int *ptr;
  4004. ptr = &i;
  4005. i = 5;
  4006. @r{@dots{}}
  4007. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  4008. @}
  4009. @end example
  4010. This shows how to declare the variable @code{ptr} as type
  4011. @code{int *} (pointer to @code{int}), store a pointer value into it
  4012. (pointing at @code{i}), and use it later to get the value of the
  4013. object it points at (the value in @code{i}).
  4014. If anyone can provide a useful example which is this basic,
  4015. I would be grateful.
  4016. @node Null Pointers
  4017. @section Null Pointers
  4018. @cindex null pointers
  4019. @cindex pointers, null
  4020. @c ???stdio loads sttddef
  4021. A pointer value can be @dfn{null}, which means it does not point to
  4022. any object. The cleanest way to get a null pointer is by writing
  4023. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4024. also do it by casting 0 to the desired pointer type, as in
  4025. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4026. @xref{Explicit Type Conversion}.)
  4027. You can store a null pointer in any lvalue whose data type
  4028. is a pointer type:
  4029. @example
  4030. char *foo;
  4031. foo = NULL;
  4032. @end example
  4033. These two, if consecutive, can be combined into a declaration with
  4034. initializer,
  4035. @example
  4036. char *foo = NULL;
  4037. @end example
  4038. You can also explicitly cast @code{NULL} to the specific pointer type
  4039. you want---it makes no difference.
  4040. @example
  4041. char *foo;
  4042. foo = (char *) NULL;
  4043. @end example
  4044. To test whether a pointer is null, compare it with zero or
  4045. @code{NULL}, as shown here:
  4046. @example
  4047. if (p != NULL)
  4048. /* @r{@code{p} is not null.} */
  4049. operate (p);
  4050. @end example
  4051. Since testing a pointer for not being null is basic and frequent, all
  4052. but beginners in C will understand the conditional without need for
  4053. @code{!= NULL}:
  4054. @example
  4055. if (p)
  4056. /* @r{@code{p} is not null.} */
  4057. operate (p);
  4058. @end example
  4059. @node Invalid Dereference
  4060. @section Dereferencing Null or Invalid Pointers
  4061. Trying to dereference a null pointer is an error. On most platforms,
  4062. it generally causes a signal, usually @code{SIGSEGV}
  4063. (@pxref{Signals}).
  4064. @example
  4065. char *foo = NULL;
  4066. c = *foo; /* @r{This causes a signal and terminates.} */
  4067. @end example
  4068. @noindent
  4069. Likewise a pointer that has the wrong alignment for the target data type
  4070. (on most types of computer), or points to a part of memory that has
  4071. not been allocated in the process's address space.
  4072. The signal terminates the program, unless the program has arranged to
  4073. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4074. The GNU C Library Reference Manual}).
  4075. However, the signal might not happen if the dereference is optimized
  4076. away. In the example above, if you don't subsequently use the value
  4077. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4078. can prevent such optimization using the @code{volatile} qualifier, as
  4079. shown here:
  4080. @example
  4081. volatile char *p;
  4082. volatile char c;
  4083. c = *p;
  4084. @end example
  4085. You can use this to test whether @code{p} points to unallocated
  4086. memory. Set up a signal handler first, so the signal won't terminate
  4087. the program.
  4088. @node Void Pointers
  4089. @section Void Pointers
  4090. @cindex void pointers
  4091. @cindex pointers, void
  4092. The peculiar type @code{void *}, a pointer whose target type is
  4093. @code{void}, is used often in C@. It represents a pointer to
  4094. we-don't-say-what. Thus,
  4095. @example
  4096. void *numbered_slot_pointer (int);
  4097. @end example
  4098. @noindent
  4099. declares a function @code{numbered_slot_pointer} that takes an
  4100. integer parameter and returns a pointer, but we don't say what type of
  4101. data it points to.
  4102. With type @code{void *}, you can pass the pointer around and test
  4103. whether it is null. However, dereferencing it gives a @code{void}
  4104. value that can't be used (@pxref{The Void Type}). To dereference the
  4105. pointer, first convert it to some other pointer type.
  4106. Assignments convert @code{void *} automatically to any other pointer
  4107. type, if the left operand has a pointer type; for instance,
  4108. @example
  4109. @{
  4110. int *p;
  4111. /* @r{Converts return value to @code{int *}.} */
  4112. p = numbered_slot_pointer (5);
  4113. @r{@dots{}}
  4114. @}
  4115. @end example
  4116. Passing an argument of type @code{void *} for a parameter that has a
  4117. pointer type also converts. For example, supposing the function
  4118. @code{hack} is declared to require type @code{float *} for its
  4119. argument, this will convert the null pointer to that type.
  4120. @example
  4121. /* @r{Declare @code{hack} that way.}
  4122. @r{We assume it is defined somewhere else.} */
  4123. void hack (float *);
  4124. @dots{}
  4125. /* @r{Now call @code{hack}.} */
  4126. @{
  4127. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4128. @r{to @code{float *} to pass it to @code{hack}.} */
  4129. hack (numbered_slot_pointer (5));
  4130. @r{@dots{}}
  4131. @}
  4132. @end example
  4133. You can also convert to another pointer type with an explicit cast
  4134. (@pxref{Explicit Type Conversion}), like this:
  4135. @example
  4136. (int *) numbered_slot_pointer (5)
  4137. @end example
  4138. Here is an example which decides at run time which pointer
  4139. type to convert to:
  4140. @example
  4141. void
  4142. extract_int_or_double (void *ptr, bool its_an_int)
  4143. @{
  4144. if (its_an_int)
  4145. handle_an_int (*(int *)ptr);
  4146. else
  4147. handle_a_double (*(double *)ptr);
  4148. @}
  4149. @end example
  4150. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4151. to type @code{int *}, then dereference it.
  4152. @node Pointer Comparison
  4153. @section Pointer Comparison
  4154. @cindex pointer comparison
  4155. @cindex comparison, pointer
  4156. Two pointer values are equal if they point to the same location, or if
  4157. they are both null. You can test for this with @code{==} and
  4158. @code{!=}. Here's a trivial example:
  4159. @example
  4160. @{
  4161. int i;
  4162. int *p, *q;
  4163. p = &i;
  4164. q = &i;
  4165. if (p == q)
  4166. printf ("This will be printed.\n");
  4167. if (p != q)
  4168. printf ("This won't be printed.\n");
  4169. @}
  4170. @end example
  4171. Ordering comparisons such as @code{>} and @code{>=} operate on
  4172. pointers by converting them to unsigned integers. The C standard says
  4173. the two pointers must point within the same object in memory, but on
  4174. GNU/Linux systems these operations simply compare the numeric values
  4175. of the pointers.
  4176. The pointer values to be compared should in principle have the same type, but
  4177. they are allowed to differ in limited cases. First of all, if the two
  4178. pointers' target types are nearly compatible (@pxref{Compatible
  4179. Types}), the comparison is allowed.
  4180. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4181. the other is another pointer type, the comparison operator converts
  4182. the @code{void *} pointer to the other type so as to compare them.
  4183. (In standard C, this is not allowed if the other type is a function
  4184. pointer type, but that works in GNU C@.)
  4185. Comparison operators also allow comparing the integer 0 with a pointer
  4186. value. Thus works by converting 0 to a null pointer of the same type
  4187. as the other operand.
  4188. @node Pointer Arithmetic
  4189. @section Pointer Arithmetic
  4190. @cindex pointer arithmetic
  4191. @cindex arithmetic, pointer
  4192. Adding an integer (positive or negative) to a pointer is valid in C@.
  4193. It assumes that the pointer points to an element in an array, and
  4194. advances or retracts the pointer across as many array elements as the
  4195. integer specifies. Here is an example, in which adding a positive
  4196. integer advances the pointer to a later element in the same array.
  4197. @example
  4198. void
  4199. incrementing_pointers ()
  4200. @{
  4201. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4202. int elt0, elt1, elt4;
  4203. int *p = &array[0];
  4204. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4205. elt0 = *p;
  4206. ++p;
  4207. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4208. elt1 = *p;
  4209. p += 3;
  4210. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4211. elt4 = *p;
  4212. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4213. elt0, elt1, elt4);
  4214. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4215. @}
  4216. @end example
  4217. Here's an example where adding a negative integer retracts the pointer
  4218. to an earlier element in the same array.
  4219. @example
  4220. void
  4221. decrementing_pointers ()
  4222. @{
  4223. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4224. int elt0, elt3, elt4;
  4225. int *p = &array[4];
  4226. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4227. elt4 = *p;
  4228. --p;
  4229. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4230. elt3 = *p;
  4231. p -= 3;
  4232. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4233. elt0 = *p;
  4234. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4235. elt0, elt3, elt4);
  4236. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4237. @}
  4238. @end example
  4239. If one pointer value was made by adding an integer to another
  4240. pointer value, it should be possible to subtract the pointer values
  4241. and recover that integer. That works too in C@.
  4242. @example
  4243. void
  4244. subtract_pointers ()
  4245. @{
  4246. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4247. int *p0, *p3, *p4;
  4248. int *p = &array[4];
  4249. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4250. p4 = p;
  4251. --p;
  4252. /* @r{Now @code{p} points at element 3. Save the value.} */
  4253. p3 = p;
  4254. p -= 3;
  4255. /* @r{Now @code{p} points at element 0. Save the value.} */
  4256. p0 = p;
  4257. printf ("%d, %d, %d, %d\n",
  4258. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4259. /* @r{Prints 4, 0, 3, -3.} */
  4260. @}
  4261. @end example
  4262. The addition operation does not know where arrays are. All it does is
  4263. add the integer (multiplied by object size) to the value of the
  4264. pointer. When the initial pointer and the result point into a single
  4265. array, the result is well-defined.
  4266. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4267. into different memory objects.
  4268. The difference between two pointers has type @code{int}, or
  4269. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4270. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4271. file @file{stddef.h}.
  4272. This definition of pointer subtraction is consistent with
  4273. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4274. @code{p3}, as in ordinary algebra.
  4275. In standard C, addition and subtraction are not allowed on @code{void
  4276. *}, since the target type's size is not defined in that case.
  4277. Likewise, they are not allowed on pointers to function types.
  4278. However, these operations work in GNU C, and the ``size of the target
  4279. type'' is taken as 1.
  4280. @node Pointers and Arrays
  4281. @section Pointers and Arrays
  4282. @cindex pointers and arrays
  4283. @cindex arrays and pointers
  4284. The clean way to refer to an array element is
  4285. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4286. same job is to get the address of that element as a pointer, then
  4287. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4288. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4289. pointer to element zero, then increments it with @code{+} to point to
  4290. the desired element, then gets the value from there.
  4291. That pointer-arithmetic construct is the @emph{definition} of square
  4292. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4293. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4294. symmetrically, so one must be a pointer and the other an integer; it
  4295. does not matter which comes first.
  4296. Since indexing with square brackets is defined in terms of addition
  4297. and dereference, that too is symmetrical. Thus, you can write
  4298. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4299. would be foolish to write @code{3[array]}, since it has no advantage
  4300. and could confuse people who read the code.
  4301. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4302. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4303. instead. Why is this valid? The name of the array, when used by
  4304. itself as an expression (other than in @code{sizeof}), stands for a
  4305. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4306. converts @code{array} implicitly to @code{&array[0]}, and the result
  4307. is a pointer to element 3, equivalent to @code{&array[3]}.
  4308. Since square brackets are defined in terms of such addition,
  4309. @code{array[3]} first converts @code{array} to a pointer. That's why
  4310. it works to use an array directly in that construct.
  4311. @node Pointer Arithmetic Low Level
  4312. @section Pointer Arithmetic at Low Level
  4313. @cindex pointer arithmetic, low level
  4314. @cindex low level pointer arithmetic
  4315. The behavior of pointer arithmetic is theoretically defined only when
  4316. the pointer values all point within one object allocated in memory.
  4317. But the addition and subtraction operators can't tell whether the
  4318. pointer values are all within one object. They don't know where
  4319. objects start and end. So what do they really do?
  4320. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4321. address, which is in fact an integer---call it @var{pint}. It treats
  4322. @var{i} as a number of elements of the type that @var{p} points to.
  4323. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4324. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4325. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4326. If the starting pointer value @var{p} and the result do not point at
  4327. parts of the same object, the operation is not officially legitimate,
  4328. and C code is not ``supposed'' to do it. But you can do it anyway,
  4329. and it gives precisely the results described by the procedure above.
  4330. In some special situations it can do something useful, but non-wizards
  4331. should avoid it.
  4332. Here's a function to offset a pointer value @emph{as if} it pointed to
  4333. an object of any given size, by explicitly performing that calculation:
  4334. @example
  4335. #include <stdint.h>
  4336. void *
  4337. ptr_add (void *p, int i, int objsize)
  4338. @{
  4339. intptr_t p_address = (long) p;
  4340. intptr_t totalsize = i * objsize;
  4341. intptr_t new_address = p_address + totalsize;
  4342. return (void *) new_address;
  4343. @}
  4344. @end example
  4345. @noindent
  4346. @cindex @code{intptr_t}
  4347. This does the same job as @code{@var{p} + @var{i}} with the proper
  4348. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4349. defined in the header file @file{stdint.h}. (In practice, @code{long
  4350. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4351. @node Pointer Increment/Decrement
  4352. @section Pointer Increment and Decrement
  4353. @cindex pointer increment and decrement
  4354. @cindex incrementing pointers
  4355. @cindex decrementing pointers
  4356. The @samp{++} operator adds 1 to a variable. We have seen it for
  4357. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4358. For instance, suppose we have a series of positive integers,
  4359. terminated by a zero, and we want to add them all up.
  4360. @example
  4361. int
  4362. sum_array_till_0 (int *p)
  4363. @{
  4364. int sum = 0;
  4365. for (;;)
  4366. @{
  4367. /* @r{Fetch the next integer.} */
  4368. int next = *p++;
  4369. /* @r{Exit the loop if it's 0.} */
  4370. if (next == 0)
  4371. break;
  4372. /* @r{Add it into running total.} */
  4373. sum += next;
  4374. @}
  4375. return sum;
  4376. @}
  4377. @end example
  4378. @noindent
  4379. The statement @samp{break;} will be explained further on (@pxref{break
  4380. Statement}). Used in this way, it immediately exits the surrounding
  4381. @code{for} statement.
  4382. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4383. takes precedence over a prefix operator. Therefore, it dereferences
  4384. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4385. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4386. pointer, adding 1 to it advances it by the width of the datum it
  4387. points to---in this case, one @code{int}. Therefore, each iteration
  4388. of the loop picks up the next integer from the series and puts it into
  4389. @code{next}.
  4390. This @code{for}-loop has no initialization expression since @code{p}
  4391. and @code{sum} are already initialized, it has no end-test since the
  4392. @samp{break;} statement will exit it, and needs no expression to
  4393. advance it since that's done within the loop by incrementing @code{p}
  4394. and @code{sum}. Thus, those three expressions after @code{for} are
  4395. left empty.
  4396. Another way to write this function is by keeping the parameter value unchanged
  4397. and using indexing to access the integers in the table.
  4398. @example
  4399. int
  4400. sum_array_till_0_indexing (int *p)
  4401. @{
  4402. int i;
  4403. int sum = 0;
  4404. for (i = 0; ; i++)
  4405. @{
  4406. /* @r{Fetch the next integer.} */
  4407. int next = p[i];
  4408. /* @r{Exit the loop if it's 0.} */
  4409. if (next == 0)
  4410. break;
  4411. /* @r{Add it into running total.} */
  4412. sum += next;
  4413. @}
  4414. return sum;
  4415. @}
  4416. @end example
  4417. In this program, instead of advancing @code{p}, we advance @code{i}
  4418. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4419. i)}.) Either way, it uses the same address to get the next integer.
  4420. It makes no difference in this program whether we write @code{i++} or
  4421. @code{++i}, because the value is not used. All that matters is the
  4422. effect, to increment @code{i}.
  4423. The @samp{--} operator also works on pointers; it can be used
  4424. to scan backwards through an array, like this:
  4425. @example
  4426. int
  4427. after_last_nonzero (int *p, int len)
  4428. @{
  4429. /* @r{Set up @code{q} to point just after the last array element.} */
  4430. int *q = p + len;
  4431. while (q != p)
  4432. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4433. if (*--q != 0)
  4434. /* @r{Return the index of the element after that nonzero.} */
  4435. return q - p + 1;
  4436. return 0;
  4437. @}
  4438. @end example
  4439. That function returns the length of the nonzero part of the
  4440. array specified by its arguments; that is, the index of the
  4441. first zero of the run of zeros at the end.
  4442. @node Pointer Arithmetic Drawbacks
  4443. @section Drawbacks of Pointer Arithmetic
  4444. @cindex drawbacks of pointer arithmetic
  4445. @cindex pointer arithmetic, drawbacks
  4446. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4447. major security flaw in the C language. Theoretically, it is only
  4448. valid to adjust a pointer within one object allocated as a unit in
  4449. memory. However, if you unintentionally adjust a pointer across the
  4450. bounds of the object and into some other object, the system has no way
  4451. to detect this error.
  4452. A bug which does that can easily result in clobbering part of another
  4453. object. For example, with @code{array[-1]} you can read or write the
  4454. nonexistent element before the beginning of an array---probably part
  4455. of some other data.
  4456. Combining pointer arithmetic with casts between pointer types, you can
  4457. create a pointer that fails to be properly aligned for its type. For
  4458. example,
  4459. @example
  4460. int a[2];
  4461. char *pa = (char *)a;
  4462. int *p = (int *)(pa + 1);
  4463. @end example
  4464. @noindent
  4465. gives @code{p} a value pointing to an ``integer'' that includes part
  4466. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4467. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4468. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4469. ``works,'' it may be quite slow. It can also cause aliasing
  4470. confusions (@pxref{Aliasing}).
  4471. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4472. unless it is really necessary.
  4473. @node Pointer-Integer Conversion
  4474. @section Pointer-Integer Conversion
  4475. @cindex pointer-integer conversion
  4476. @cindex conversion between pointers and integers
  4477. @cindex @code{uintptr_t}
  4478. On modern computers, an address is simply a number. It occupies the
  4479. same space as some size of integer. In C, you can convert a pointer
  4480. to the appropriate integer types and vice versa, without losing
  4481. information. The appropriate integer types are @code{uintptr_t} (an
  4482. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4483. in @file{stdint.h}.
  4484. For instance,
  4485. @example
  4486. #include <stdint.h>
  4487. #include <stdio.h>
  4488. void
  4489. print_pointer (void *ptr)
  4490. @{
  4491. uintptr_t converted = (uintptr_t) ptr;
  4492. printf ("Pointer value is 0x%x\n",
  4493. (unsigned int) converted);
  4494. @}
  4495. @end example
  4496. @noindent
  4497. The specification @samp{%x} in the template (the first argument) for
  4498. @code{printf} means to represent this argument using hexadecimal
  4499. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4500. printing treats the number as unsigned, but it won't actually matter:
  4501. all @code{printf} gets to see is the series of bits in the number.
  4502. @strong{Warning:} Converting pointers to integers is risky---don't do
  4503. it unless it is really necessary.
  4504. @node Printing Pointers
  4505. @section Printing Pointers
  4506. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4507. For example:
  4508. @example
  4509. void
  4510. print_pointer (void *ptr)
  4511. @{
  4512. printf ("Pointer value is %p\n", ptr);
  4513. @}
  4514. @end example
  4515. The specification @samp{%p} works with any pointer type. It prints
  4516. @samp{0x} followed by the address in hexadecimal, printed as the
  4517. appropriate unsigned integer type.
  4518. @node Structures
  4519. @chapter Structures
  4520. @cindex structures
  4521. @findex struct
  4522. @cindex fields in structures
  4523. A @dfn{structure} is a user-defined data type that holds various
  4524. @dfn{fields} of data. Each field has a name and a data type specified
  4525. in the structure's definition.
  4526. Here we define a structure suitable for storing a linked list of
  4527. integers. Each list item will hold one integer, plus a pointer
  4528. to the next item.
  4529. @example
  4530. struct intlistlink
  4531. @{
  4532. int datum;
  4533. struct intlistlink *next;
  4534. @};
  4535. @end example
  4536. The structure definition has a @dfn{type tag} so that the code can
  4537. refer to this structure. The type tag here is @code{intlistlink}.
  4538. The definition refers recursively to the same structure through that
  4539. tag.
  4540. You can define a structure without a type tag, but then you can't
  4541. refer to it again. That is useful only in some special contexts, such
  4542. as inside a @code{typedef} or a @code{union}.
  4543. The contents of the structure are specified by the @dfn{field
  4544. declarations} inside the braces. Each field in the structure needs a
  4545. declaration there. The fields in one structure definition must have
  4546. distinct names, but these names do not conflict with any other names
  4547. in the program.
  4548. A field declaration looks just like a variable declaration. You can
  4549. combine field declarations with the same beginning, just as you can
  4550. combine variable declarations.
  4551. This structure has two fields. One, named @code{datum}, has type
  4552. @code{int} and will hold one integer in the list. The other, named
  4553. @code{next}, is a pointer to another @code{struct intlistlink}
  4554. which would be the rest of the list. In the last list item, it would
  4555. be @code{NULL}.
  4556. This structure definition is recursive, since the type of the
  4557. @code{next} field refers to the structure type. Such recursion is not
  4558. a problem; in fact, you can use the type @code{struct intlistlink *}
  4559. before the definition of the type @code{struct intlistlink} itself.
  4560. That works because pointers to all kinds of structures really look the
  4561. same at the machine level.
  4562. After defining the structure, you can declare a variable of type
  4563. @code{struct intlistlink} like this:
  4564. @example
  4565. struct intlistlink foo;
  4566. @end example
  4567. The structure definition itself can serve as the beginning of a
  4568. variable declaration, so you can declare variables immediately after,
  4569. like this:
  4570. @example
  4571. struct intlistlink
  4572. @{
  4573. int datum;
  4574. struct intlistlink *next;
  4575. @} foo;
  4576. @end example
  4577. @noindent
  4578. But that is ugly. It is almost always clearer to separate the
  4579. definition of the structure from its uses.
  4580. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4581. the scope of the structure type name to that block. That means the
  4582. structure type is recognized only within that block. Declaring it in
  4583. a function parameter list, as here,
  4584. @example
  4585. int f (struct foo @{int a, b@} parm);
  4586. @end example
  4587. @noindent
  4588. (assuming that @code{struct foo} is not already defined) limits the
  4589. scope of the structure type @code{struct foo} to that parameter list;
  4590. that is basically useless, so it triggers a warning.
  4591. Standard C requires at least one field in a structure.
  4592. GNU C does not require this.
  4593. @menu
  4594. * Referencing Fields:: Accessing field values in a structure object.
  4595. * Dynamic Memory Allocation:: Allocating space for objects
  4596. while the program is running.
  4597. * Field Offset:: Memory layout of fields within a structure.
  4598. * Structure Layout:: Planning the memory layout of fields.
  4599. * Packed Structures:: Packing structure fields as close as possible.
  4600. * Bit Fields:: Dividing integer fields
  4601. into fields with fewer bits.
  4602. * Bit Field Packing:: How bit fields pack together in integers.
  4603. * const Fields:: Making structure fields immutable.
  4604. * Zero Length:: Zero-length array as a variable-length object.
  4605. * Flexible Array Fields:: Another approach to variable-length objects.
  4606. * Overlaying Structures:: Casting one structure type
  4607. over an object of another structure type.
  4608. * Structure Assignment:: Assigning values to structure objects.
  4609. * Unions:: Viewing the same object in different types.
  4610. * Packing With Unions:: Using a union type to pack various types into
  4611. the same memory space.
  4612. * Cast to Union:: Casting a value one of the union's alternative
  4613. types to the type of the union itself.
  4614. * Structure Constructors:: Building new structure objects.
  4615. * Unnamed Types as Fields:: Fields' types do not always need names.
  4616. * Incomplete Types:: Types which have not been fully defined.
  4617. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4618. * Type Tags:: Scope of structure and union type tags.
  4619. @end menu
  4620. @node Referencing Fields
  4621. @section Referencing Structure Fields
  4622. @cindex referencing structure fields
  4623. @cindex structure fields, referencing
  4624. To make a structure useful, there has to be a way to examine and store
  4625. its fields. The @samp{.} (period) operator does that; its use looks
  4626. like @code{@var{object}.@var{field}}.
  4627. Given this structure and variable,
  4628. @example
  4629. struct intlistlink
  4630. @{
  4631. int datum;
  4632. struct intlistlink *next;
  4633. @};
  4634. struct intlistlink foo;
  4635. @end example
  4636. @noindent
  4637. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4638. fields in the value of @code{foo}. These fields are lvalues, so you
  4639. can store values into them, and read the values out again.
  4640. Most often, structures are dynamically allocated (see the next
  4641. section), and we refer to the objects via pointers.
  4642. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4643. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4644. contains this declaration:
  4645. @example
  4646. struct intlistlink *ptr;
  4647. @end example
  4648. @noindent
  4649. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4650. to the two fields in the object that @code{ptr} points to.
  4651. If a unary operator precedes an expression using @samp{->},
  4652. the @samp{->} nests inside:
  4653. @example
  4654. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4655. @end example
  4656. You can intermix @samp{->} and @samp{.} without parentheses,
  4657. as shown here:
  4658. @example
  4659. struct @{ double d; struct intlistlink l; @} foo;
  4660. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4661. @end example
  4662. @node Dynamic Memory Allocation
  4663. @section Dynamic Memory Allocation
  4664. @cindex dynamic memory allocation
  4665. @cindex memory allocation, dynamic
  4666. @cindex allocating memory dynamically
  4667. To allocate an object dynamically, call the library function
  4668. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4669. Reference Manual}). Here is how to allocate an object of type
  4670. @code{struct intlistlink}. To make this code work, include the file
  4671. @file{stdlib.h}, like this:
  4672. @example
  4673. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4674. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4675. @dots{}
  4676. struct intlistlink *
  4677. alloc_intlistlink ()
  4678. @{
  4679. struct intlistlink *p;
  4680. p = malloc (sizeof (struct intlistlink));
  4681. if (p == NULL)
  4682. fatal ("Ran out of storage");
  4683. /* @r{Initialize the contents.} */
  4684. p->datum = 0;
  4685. p->next = NULL;
  4686. return p;
  4687. @}
  4688. @end example
  4689. @noindent
  4690. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4691. will automatically convert it to type @code{struct intlistlink *}.
  4692. The return value of @code{malloc} is always sufficiently aligned
  4693. (@pxref{Type Alignment}) that it is valid for any data type.
  4694. The test for @code{p == NULL} is necessary because @code{malloc}
  4695. returns a null pointer if it cannot get any storage. We assume that
  4696. the program defines the function @code{fatal} to report a fatal error
  4697. to the user.
  4698. Here's how to add one more integer to the front of such a list:
  4699. @example
  4700. struct intlistlink *my_list = NULL;
  4701. void
  4702. add_to_mylist (int my_int)
  4703. @{
  4704. struct intlistlink *p = alloc_intlistlink ();
  4705. p->datum = my_int;
  4706. p->next = mylist;
  4707. mylist = p;
  4708. @}
  4709. @end example
  4710. The way to free the objects is by calling @code{free}. Here's
  4711. a function to free all the links in one of these lists:
  4712. @example
  4713. void
  4714. free_intlist (struct intlistlink *p)
  4715. @{
  4716. while (p)
  4717. @{
  4718. struct intlistlink *q = p;
  4719. p = p->next;
  4720. free (q);
  4721. @}
  4722. @}
  4723. @end example
  4724. We must extract the @code{next} pointer from the object before freeing
  4725. it, because @code{free} can clobber the data that was in the object.
  4726. For the same reason, the program must not use the list any more after
  4727. freeing its elements. To make sure it won't, it is best to clear out
  4728. the variable where the list was stored, like this:
  4729. @example
  4730. free_intlist (mylist);
  4731. mylist = NULL;
  4732. @end example
  4733. @node Field Offset
  4734. @section Field Offset
  4735. @cindex field offset
  4736. @cindex structure field offset
  4737. @cindex offset of structure fields
  4738. To determine the offset of a given field @var{field} in a structure
  4739. type @var{type}, use the macro @code{offsetof}, which is defined in
  4740. the file @file{stddef.h}. It is used like this:
  4741. @example
  4742. offsetof (@var{type}, @var{field})
  4743. @end example
  4744. Here is an example:
  4745. @example
  4746. struct foo
  4747. @{
  4748. int element;
  4749. struct foo *next;
  4750. @};
  4751. offsetof (struct foo, next)
  4752. /* @r{On most machines that is 4. It may be 8.} */
  4753. @end example
  4754. @node Structure Layout
  4755. @section Structure Layout
  4756. @cindex structure layout
  4757. @cindex layout of structures
  4758. The rest of this chapter covers advanced topics about structures. If
  4759. you are just learning C, you can skip it.
  4760. The precise layout of a @code{struct} type is crucial when using it to
  4761. overlay hardware registers, to access data structures in shared
  4762. memory, or to assemble and disassemble packets for network
  4763. communication. It is also important for avoiding memory waste when
  4764. the program makes many objects of that type. However, the layout
  4765. depends on the target platform. Each platform has conventions for
  4766. structure layout, which compilers need to follow.
  4767. Here are the conventions used on most platforms.
  4768. The structure's fields appear in the structure layout in the order
  4769. they are declared. When possible, consecutive fields occupy
  4770. consecutive bytes within the structure. However, if a field's type
  4771. demands more alignment than it would get that way, C gives it the
  4772. alignment it requires by leaving a gap after the previous field.
  4773. Once all the fields have been laid out, it is possible to determine
  4774. the structure's alignment and size. The structure's alignment is the
  4775. maximum alignment of any of the fields in it. Then the structure's
  4776. size is rounded up to a multiple of its alignment. That may require
  4777. leaving a gap at the end of the structure.
  4778. Here are some examples, where we assume that @code{char} has size and
  4779. alignment 1 (always true), and @code{int} has size and alignment 4
  4780. (true on most kinds of computers):
  4781. @example
  4782. struct foo
  4783. @{
  4784. char a, b;
  4785. int c;
  4786. @};
  4787. @end example
  4788. @noindent
  4789. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4790. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4791. There is a gap of 2 bytes before @code{c}.
  4792. Contrast that with this structure:
  4793. @example
  4794. struct foo
  4795. @{
  4796. char a;
  4797. int c;
  4798. char b;
  4799. @};
  4800. @end example
  4801. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4802. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4803. gaps: three bytes before @code{c}, and three bytes at the end.
  4804. These two structures have the same contents at the C level, but one
  4805. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4806. fields. A reliable way to avoid this sort of wastage is to order the
  4807. fields by size, biggest fields first.
  4808. @node Packed Structures
  4809. @section Packed Structures
  4810. @cindex packed structures
  4811. @cindex @code{__attribute__((packed))}
  4812. In GNU C you can force a structure to be laid out with no gaps by
  4813. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4814. end of the structure type declaration). Here's an example:
  4815. @example
  4816. struct __attribute__((packed)) foo
  4817. @{
  4818. char a;
  4819. int c;
  4820. char b;
  4821. @};
  4822. @end example
  4823. Without @code{__attribute__((packed))}, this structure occupies 12
  4824. bytes (as described in the previous section), assuming 4-byte
  4825. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4826. only 6 bytes long---the sum of the lengths of its fields.
  4827. Use of @code{__attribute__((packed))} often results in fields that
  4828. don't have the normal alignment for their types. Taking the address
  4829. of such a field can result in an invalid pointer because of its
  4830. improper alignment. Dereferencing such a pointer can cause a
  4831. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4832. unaligned pointers.
  4833. @xref{Attributes}.
  4834. @node Bit Fields
  4835. @section Bit Fields
  4836. @cindex bit fields
  4837. A structure field declaration with an integer type can specify the
  4838. number of bits the field should occupy. We call that a @dfn{bit
  4839. field}. These are useful because consecutive bit fields are packed
  4840. into a larger storage unit. For instance,
  4841. @example
  4842. unsigned char opcode: 4;
  4843. @end example
  4844. @noindent
  4845. specifies that this field takes just 4 bits.
  4846. Since it is unsigned, its possible values range
  4847. from 0 to 15. A signed field with 4 bits, such as this,
  4848. @example
  4849. signed char small: 4;
  4850. @end example
  4851. @noindent
  4852. can hold values from -8 to 7.
  4853. You can subdivide a single byte into those two parts by writing
  4854. @example
  4855. unsigned char opcode: 4;
  4856. signed char small: 4;
  4857. @end example
  4858. @noindent
  4859. in the structure. With bit fields, these two numbers fit into
  4860. a single @code{char}.
  4861. Here's how to declare a one-bit field that can hold either 0 or 1:
  4862. @example
  4863. unsigned char special_flag: 1;
  4864. @end example
  4865. You can also use the @code{bool} type for bit fields:
  4866. @example
  4867. bool special_flag: 1;
  4868. @end example
  4869. Except when using @code{bool} (which is always unsigned,
  4870. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4871. for a bit field. There is a default, if that's not specified: the bit
  4872. field is signed if plain @code{char} is signed, except that the option
  4873. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4874. is cleaner not to depend on this default.
  4875. Bit fields are special in that you cannot take their address with
  4876. @samp{&}. They are not stored with the size and alignment appropriate
  4877. for the specified type, so they cannot be addressed through pointers
  4878. to that type.
  4879. @node Bit Field Packing
  4880. @section Bit Field Packing
  4881. Programs to communicate with low-level hardware interfaces need to
  4882. define bit fields laid out to match the hardware data. This section
  4883. explains how to do that.
  4884. Consecutive bit fields are packed together, but each bit field must
  4885. fit within a single object of its specified type. In this example,
  4886. @example
  4887. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4888. @end example
  4889. @noindent
  4890. all five fields fit consecutively into one two-byte @code{short}.
  4891. They need 15 bits, and one @code{short} provides 16. By contrast,
  4892. @example
  4893. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4894. @end example
  4895. @noindent
  4896. needs three bytes. It fits @code{a} and @code{b} into one
  4897. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4898. add up to 9 bits). So @code{c} and @code{d} go into a second
  4899. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4900. Then @code{e} needs a third @code{char}. By contrast,
  4901. @example
  4902. unsigned char a : 3, b : 3;
  4903. unsigned int c : 3;
  4904. unsigned char d : 3, e : 3;
  4905. @end example
  4906. @noindent
  4907. needs only two bytes: the type @code{unsigned int}
  4908. allows @code{c} to straddle bytes that are in the same word.
  4909. You can leave a gap of a specified number of bits by defining a
  4910. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4911. It is allocated space in the structure just as a named bit field would
  4912. be allocated.
  4913. You can force the following bit field to advance to the following
  4914. aligned memory object with @code{@var{type} : 0;}.
  4915. Both of these constructs can syntactically share @var{type} with
  4916. ordinary bit fields. This example illustrates both:
  4917. @example
  4918. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4919. @end example
  4920. @noindent
  4921. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4922. between them. Then @code{: 0} advances to the next @code{int},
  4923. so @code{c} and @code{d} fit into that one.
  4924. These rules for packing bit fields apply to most target platforms,
  4925. including all the usual real computers. A few embedded controllers
  4926. have special layout rules.
  4927. @node const Fields
  4928. @section @code{const} Fields
  4929. @cindex const fields
  4930. @cindex structure fields, constant
  4931. @c ??? Is this a C standard feature?
  4932. A structure field declared @code{const} cannot be assigned to
  4933. (@pxref{const}). For instance, let's define this modified version of
  4934. @code{struct intlistlink}:
  4935. @example
  4936. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4937. @{
  4938. const int datum;
  4939. struct intlistlink *next;
  4940. @};
  4941. @end example
  4942. This structure can be used to prevent part of the code from modifying
  4943. the @code{datum} field:
  4944. @example
  4945. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4946. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4947. struct intlistlink_ro *q
  4948. = (struct intlistlink_ro *) p;
  4949. q->datum = 5; /* @r{Error!} */
  4950. p->datum = 5; /* @r{Valid since @code{*p} is}
  4951. @r{not a @code{struct intlistlink_ro}.} */
  4952. @end example
  4953. A @code{const} field can get a value in two ways: by initialization of
  4954. the whole structure, and by making a pointer-to-structure point to an object
  4955. in which that field already has a value.
  4956. Any @code{const} field in a structure type makes assignment impossible
  4957. for structures of that type (@pxref{Structure Assignment}). That is
  4958. because structure assignment works by assigning the structure's
  4959. fields, one by one.
  4960. @node Zero Length
  4961. @section Arrays of Length Zero
  4962. @cindex array of length zero
  4963. @cindex zero-length arrays
  4964. @cindex length-zero arrays
  4965. GNU C allows zero-length arrays. They are useful as the last element
  4966. of a structure that is really a header for a variable-length object.
  4967. Here's an example, where we construct a variable-size structure
  4968. to hold a line which is @code{this_length} characters long:
  4969. @example
  4970. struct line @{
  4971. int length;
  4972. char contents[0];
  4973. @};
  4974. struct line *thisline
  4975. = ((struct line *)
  4976. malloc (sizeof (struct line)
  4977. + this_length));
  4978. thisline->length = this_length;
  4979. @end example
  4980. In ISO C90, we would have to give @code{contents} a length of 1, which
  4981. means either wasting space or complicating the argument to @code{malloc}.
  4982. @node Flexible Array Fields
  4983. @section Flexible Array Fields
  4984. @cindex flexible array fields
  4985. @cindex array fields, flexible
  4986. The C99 standard adopted a more complex equivalent of zero-length
  4987. array fields. It's called a @dfn{flexible array}, and it's indicated
  4988. by omitting the length, like this:
  4989. @example
  4990. struct line
  4991. @{
  4992. int length;
  4993. char contents[];
  4994. @};
  4995. @end example
  4996. The flexible array has to be the last field in the structure, and there
  4997. must be other fields before it.
  4998. Under the C standard, a structure with a flexible array can't be part
  4999. of another structure, and can't be an element of an array.
  5000. GNU C allows static initialization of flexible array fields. The effect
  5001. is to ``make the array long enough'' for the initializer.
  5002. @example
  5003. struct f1 @{ int x; int y[]; @} f1
  5004. = @{ 1, @{ 2, 3, 4 @} @};
  5005. @end example
  5006. @noindent
  5007. This defines a structure variable named @code{f1}
  5008. whose type is @code{struct f1}. In C, a variable name or function name
  5009. never conflicts with a structure type tag.
  5010. Omitting the flexible array field's size lets the initializer
  5011. determine it. This is allowed only when the flexible array is defined
  5012. in the outermost structure and you declare a variable of that
  5013. structure type. For example:
  5014. @example
  5015. struct foo @{ int x; int y[]; @};
  5016. struct bar @{ struct foo z; @};
  5017. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  5018. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5019. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  5020. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5021. @end example
  5022. @node Overlaying Structures
  5023. @section Overlaying Different Structures
  5024. @cindex overlaying structures
  5025. @cindex structures, overlaying
  5026. Be careful about using different structure types to refer to the same
  5027. memory within one function, because GNU C can optimize code assuming
  5028. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5029. aliasing that can cause the problem:
  5030. @example
  5031. struct a @{ int size; char *data; @};
  5032. struct b @{ int size; char *data; @};
  5033. struct a foo;
  5034. struct b *q = (struct b *) &foo;
  5035. @end example
  5036. Here @code{q} points to the same memory that the variable @code{foo}
  5037. occupies, but they have two different types. The two types
  5038. @code{struct a} and @code{struct b} are defined alike, but they are
  5039. not the same type. Interspersing references using the two types,
  5040. like this,
  5041. @example
  5042. p->size = 0;
  5043. q->size = 1;
  5044. x = p->size;
  5045. @end example
  5046. @noindent
  5047. allows GNU C to assume that @code{p->size} is still zero when it is
  5048. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5049. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5050. Other compilers might also do this optimization. The ISO C standard
  5051. considers such code erroneous, precisely so that this optimization
  5052. will be valid.
  5053. @node Structure Assignment
  5054. @section Structure Assignment
  5055. @cindex structure assignment
  5056. @cindex assigning structures
  5057. Assignment operating on a structure type copies the structure. The
  5058. left and right operands must have the same type. Here is an example:
  5059. @example
  5060. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5061. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5062. @r{@dots{}}
  5063. struct point @{ double x, y; @};
  5064. struct point *
  5065. copy_point (struct point point)
  5066. @{
  5067. struct point *p
  5068. = (struct point *) malloc (sizeof (struct point));
  5069. if (p == NULL)
  5070. fatal ("Out of memory");
  5071. *p = point;
  5072. return p;
  5073. @}
  5074. @end example
  5075. Notionally, assignment on a structure type works by copying each of
  5076. the fields. Thus, if any of the fields has the @code{const}
  5077. qualifier, that structure type does not allow assignment:
  5078. @example
  5079. struct point @{ const double x, y; @};
  5080. struct point a, b;
  5081. a = b; /* @r{Error!} */
  5082. @end example
  5083. @xref{Assignment Expressions}.
  5084. @node Unions
  5085. @section Unions
  5086. @cindex unions
  5087. @findex union
  5088. A @dfn{union type} defines alternative ways of looking at the same
  5089. piece of memory. Each alternative view is defined with a data type,
  5090. and identified by a name. A union definition looks like this:
  5091. @example
  5092. union @var{name}
  5093. @{
  5094. @var{alternative declarations}@r{@dots{}}
  5095. @};
  5096. @end example
  5097. Each alternative declaration looks like a structure field declaration,
  5098. except that it can't be a bit field. For instance,
  5099. @example
  5100. union number
  5101. @{
  5102. long int integer;
  5103. double float;
  5104. @}
  5105. @end example
  5106. @noindent
  5107. lets you store either an integer (type @code{long int}) or a floating
  5108. point number (type @code{double}) in the same place in memory. The
  5109. length and alignment of the union type are the maximum of all the
  5110. alternatives---they do not have to be the same. In this union
  5111. example, @code{double} probably takes more space than @code{long int},
  5112. but that doesn't cause a problem in programs that use the union in the
  5113. normal way.
  5114. The members don't have to be different in data type. Sometimes
  5115. each member pertains to a way the data will be used. For instance,
  5116. @example
  5117. union datum
  5118. @{
  5119. double latitude;
  5120. double longitude;
  5121. double height;
  5122. double weight;
  5123. int continent;
  5124. @}
  5125. @end example
  5126. This union holds one of several kinds of data; most kinds are floating
  5127. points, but the value can also be a code for a continent which is an
  5128. integer. You @emph{could} use one member of type @code{double} to
  5129. access all the values which have that type, but the different member
  5130. names will make the program clearer.
  5131. The alignment of a union type is the maximum of the alignments of the
  5132. alternatives. The size of the union type is the maximum of the sizes
  5133. of the alternatives, rounded up to a multiple of the alignment
  5134. (because every type's size must be a multiple of its alignment).
  5135. All the union alternatives start at the address of the union itself.
  5136. If an alternative is shorter than the union as a whole, it occupies
  5137. the first part of the union's storage, leaving the last part unused
  5138. @emph{for that alternative}.
  5139. @strong{Warning:} if the code stores data using one union alternative
  5140. and accesses it with another, the results depend on the kind of
  5141. computer in use. Only wizards should try to do this. However, when
  5142. you need to do this, a union is a clean way to do it.
  5143. Assignment works on any union type by copying the entire value.
  5144. @node Packing With Unions
  5145. @section Packing With Unions
  5146. Sometimes we design a union with the intention of packing various
  5147. kinds of objects into a certain amount of memory space. For example.
  5148. @example
  5149. union bytes8
  5150. @{
  5151. long long big_int_elt;
  5152. double double_elt;
  5153. struct @{ int first, second; @} two_ints;
  5154. struct @{ void *first, *second; @} two_ptrs;
  5155. @};
  5156. union bytes8 *p;
  5157. @end example
  5158. This union makes it possible to look at 8 bytes of data that @code{p}
  5159. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5160. single floating-point number (@code{p->double_elt}), as a pair of
  5161. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5162. as a pair of pointers (@code{p->two_ptrs.first} and
  5163. @code{p->two_ptrs.second}).
  5164. To pack storage with such a union makes assumptions about the sizes of
  5165. all the types involved. This particular union was written expecting a
  5166. pointer to have the same size as @code{int}. On a machine where one
  5167. pointer takes 8 bytes, the code using this union probably won't work
  5168. as expected. The union, as such, will function correctly---if you
  5169. store two values through @code{two_ints} and extract them through
  5170. @code{two_ints}, you will get the same integers back---but the part of
  5171. the program that expects the union to be 8 bytes long could
  5172. malfunction, or at least use too much space.
  5173. The above example shows one case where a @code{struct} type with no
  5174. tag can be useful. Another way to get effectively the same result
  5175. is with arrays as members of the union:
  5176. @example
  5177. union eight_bytes
  5178. @{
  5179. long long big_int_elt;
  5180. double double_elt;
  5181. int two_ints[2];
  5182. void *two_ptrs[2];
  5183. @};
  5184. @end example
  5185. @node Cast to Union
  5186. @section Cast to a Union Type
  5187. @cindex cast to a union
  5188. @cindex union, casting to a
  5189. In GNU C, you can explicitly cast any of the alternative types to the
  5190. union type; for instance,
  5191. @example
  5192. (union eight_bytes) (long long) 5
  5193. @end example
  5194. @noindent
  5195. makes a value of type @code{union eight_bytes} which gets its contents
  5196. through the alternative named @code{big_int_elt}.
  5197. The value being cast must exactly match the type of the alternative,
  5198. so this is not valid:
  5199. @example
  5200. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5201. @end example
  5202. A cast to union type looks like any other cast, except that the type
  5203. specified is a union type. You can specify the type either with
  5204. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5205. Typedef Names}).
  5206. Using the cast as the right-hand side of an assignment to a variable of
  5207. union type is equivalent to storing in an alternative of the union:
  5208. @example
  5209. union foo u;
  5210. u = (union foo) x @r{means} u.i = x
  5211. u = (union foo) y @r{means} u.d = y
  5212. @end example
  5213. You can also use the union cast as a function argument:
  5214. @example
  5215. void hack (union foo);
  5216. @r{@dots{}}
  5217. hack ((union foo) x);
  5218. @end example
  5219. @node Structure Constructors
  5220. @section Structure Constructors
  5221. @cindex structure constructors
  5222. @cindex constructors, structure
  5223. You can construct a structure value by writing its type in
  5224. parentheses, followed by an initializer that would be valid in a
  5225. declaration for that type. For instance, given this declaration,
  5226. @example
  5227. struct foo @{int a; char b[2];@} structure;
  5228. @end example
  5229. @noindent
  5230. you can create a @code{struct foo} value as follows:
  5231. @example
  5232. ((struct foo) @{x + y, 'a', 0@})
  5233. @end example
  5234. @noindent
  5235. This specifies @code{x + y} for field @code{a},
  5236. the character @samp{a} for field @code{b}'s element 0,
  5237. and the null character for field @code{b}'s element 1.
  5238. The parentheses around that constructor are to necessary, but we
  5239. recommend writing them to make the nesting of the containing
  5240. expression clearer.
  5241. You can also show the nesting of the two by writing it like
  5242. this:
  5243. @example
  5244. ((struct foo) @{x + y, @{'a', 0@} @})
  5245. @end example
  5246. Each of those is equivalent to writing the following statement
  5247. expression (@pxref{Statement Exprs}):
  5248. @example
  5249. (@{
  5250. struct foo temp = @{x + y, 'a', 0@};
  5251. temp;
  5252. @})
  5253. @end example
  5254. You can also create a union value this way, but it is not especially
  5255. useful since that is equivalent to doing a cast:
  5256. @example
  5257. ((union whosis) @{@var{value}@})
  5258. @r{is equivalent to}
  5259. ((union whosis) (@var{value}))
  5260. @end example
  5261. @node Unnamed Types as Fields
  5262. @section Unnamed Types as Fields
  5263. @cindex unnamed structures
  5264. @cindex unnamed unions
  5265. @cindex structures, unnamed
  5266. @cindex unions, unnamed
  5267. A structure or a union can contain, as fields,
  5268. unnamed structures and unions. Here's an example:
  5269. @example
  5270. struct
  5271. @{
  5272. int a;
  5273. union
  5274. @{
  5275. int b;
  5276. float c;
  5277. @};
  5278. int d;
  5279. @} foo;
  5280. @end example
  5281. @noindent
  5282. You can access the fields of the unnamed union within @code{foo} as if they
  5283. were individual fields at the same level as the union definition:
  5284. @example
  5285. foo.a = 42;
  5286. foo.b = 47;
  5287. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5288. foo.d = 314;
  5289. @end example
  5290. Avoid using field names that could cause ambiguity. For example, with
  5291. this definition:
  5292. @example
  5293. struct
  5294. @{
  5295. int a;
  5296. struct
  5297. @{
  5298. int a;
  5299. float b;
  5300. @};
  5301. @} foo;
  5302. @end example
  5303. @noindent
  5304. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5305. an error when a definition is ambiguous in this way.
  5306. @node Incomplete Types
  5307. @section Incomplete Types
  5308. @cindex incomplete types
  5309. @cindex types, incomplete
  5310. A type that has not been fully defined is called an @dfn{incomplete
  5311. type}. Structure and union types are incomplete when the code makes a
  5312. forward reference, such as @code{struct foo}, before defining the
  5313. type. An array type is incomplete when its length is unspecified.
  5314. You can't use an incomplete type to declare a variable or field, or
  5315. use it for a function parameter or return type. The operators
  5316. @code{sizeof} and @code{_Alignof} give errors when used on an
  5317. incomplete type.
  5318. However, you can define a pointer to an incomplete type, and declare a
  5319. variable or field with such a pointer type. In general, you can do
  5320. everything with such pointers except dereference them. For example:
  5321. @example
  5322. extern void bar (struct mysterious_value *);
  5323. void
  5324. foo (struct mysterious_value *arg)
  5325. @{
  5326. bar (arg);
  5327. @}
  5328. @r{@dots{}}
  5329. @{
  5330. struct mysterious_value *p, **q;
  5331. p = *q;
  5332. foo (p);
  5333. @}
  5334. @end example
  5335. @noindent
  5336. These examples are valid because the code doesn't try to understand
  5337. what @code{p} points to; it just passes the pointer around.
  5338. (Presumably @code{bar} is defined in some other file that really does
  5339. have a definition for @code{struct mysterious_value}.) However,
  5340. dereferencing the pointer would get an error; that requires a
  5341. definition for the structure type.
  5342. @node Intertwined Incomplete Types
  5343. @section Intertwined Incomplete Types
  5344. When several structure types contain pointers to each other, you can
  5345. define the types in any order because pointers to types that come
  5346. later are incomplete types. Thus,
  5347. Here is an example.
  5348. @example
  5349. /* @r{An employee record points to a group.} */
  5350. struct employee
  5351. @{
  5352. char *name;
  5353. @r{@dots{}}
  5354. struct group *group; /* @r{incomplete type.} */
  5355. @r{@dots{}}
  5356. @};
  5357. /* @r{An employee list points to employees.} */
  5358. struct employee_list
  5359. @{
  5360. struct employee *this_one;
  5361. struct employee_list *next; /* @r{incomplete type.} */
  5362. @r{@dots{}}
  5363. @};
  5364. /* @r{A group points to one employee_list.} */
  5365. struct group
  5366. @{
  5367. char *name;
  5368. @r{@dots{}}
  5369. struct employee_list *employees;
  5370. @r{@dots{}}
  5371. @};
  5372. @end example
  5373. @node Type Tags
  5374. @section Type Tags
  5375. @cindex type tags
  5376. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5377. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5378. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5379. name or function name; the type tags have a separate @dfn{name space}.
  5380. Thus, there is no name conflict in this code:
  5381. @example
  5382. struct pair @{ int a, b; @};
  5383. int pair = 1;
  5384. @end example
  5385. @noindent
  5386. nor in this one:
  5387. @example
  5388. struct pair @{ int a, b; @} pair;
  5389. @end example
  5390. @noindent
  5391. where @code{pair} is both a structure type tag and a variable name.
  5392. However, @code{struct}, @code{union}, and @code{enum} share the same
  5393. name space of tags, so this is a conflict:
  5394. @example
  5395. struct pair @{ int a, b; @};
  5396. enum pair @{ c, d @};
  5397. @end example
  5398. @noindent
  5399. and so is this:
  5400. @example
  5401. struct pair @{ int a, b; @};
  5402. struct pair @{ int c, d; @};
  5403. @end example
  5404. When the code defines a type tag inside a block, the tag's scope is
  5405. limited to that block (as for local variables). Two definitions for
  5406. one type tag do not conflict if they are in different scopes; rather,
  5407. each is valid in its scope. For example,
  5408. @example
  5409. struct pair @{ int a, b; @};
  5410. void
  5411. pair_up_doubles (int len, double array[])
  5412. @{
  5413. struct pair @{ double a, b; @};
  5414. @r{@dots{}}
  5415. @}
  5416. @end example
  5417. @noindent
  5418. has two definitions for @code{struct pair} which do not conflict. The
  5419. one inside the function applies only within the definition of
  5420. @code{pair_up_doubles}. Within its scope, that definition
  5421. @dfn{shadows} the outer definition.
  5422. If @code{struct pair} appears inside the function body, before the
  5423. inner definition, it refers to the outer definition---the only one
  5424. that has been seen at that point. Thus, in this code,
  5425. @example
  5426. struct pair @{ int a, b; @};
  5427. void
  5428. pair_up_doubles (int len, double array[])
  5429. @{
  5430. struct two_pairs @{ struct pair *p, *q; @};
  5431. struct pair @{ double a, b; @};
  5432. @r{@dots{}}
  5433. @}
  5434. @end example
  5435. @noindent
  5436. the structure @code{two_pairs} has pointers to the outer definition of
  5437. @code{struct pair}, which is probably not desirable.
  5438. To prevent that, you can write @code{struct pair;} inside the function
  5439. body as a variable declaration with no variables. This is a
  5440. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5441. type tag local to the current block, with the details of the type to
  5442. come later. Here's an example:
  5443. @example
  5444. void
  5445. pair_up_doubles (int len, double array[])
  5446. @{
  5447. /* @r{Forward declaration for @code{pair}.} */
  5448. struct pair;
  5449. struct two_pairs @{ struct pair *p, *q; @};
  5450. /* @r{Give the details.} */
  5451. struct pair @{ double a, b; @};
  5452. @r{@dots{}}
  5453. @}
  5454. @end example
  5455. However, the cleanest practice is to avoid shadowing type tags.
  5456. @node Arrays
  5457. @chapter Arrays
  5458. @cindex array
  5459. @cindex elements of arrays
  5460. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5461. all of the same data type. Each element is identified by its numeric
  5462. @var{index} within the array.
  5463. We presented arrays of numbers in the sample programs early in this
  5464. manual (@pxref{Array Example}). However, arrays can have elements of
  5465. any data type, including pointers, structures, unions, and other
  5466. arrays.
  5467. If you know another programming language, you may suppose that you know all
  5468. about arrays, but C arrays have special quirks, so in this chapter we
  5469. collect all the information about arrays in C@.
  5470. The elements of a C array are allocated consecutively in memory,
  5471. with no gaps between them. Each element is aligned as required
  5472. for its data type (@pxref{Type Alignment}).
  5473. @menu
  5474. * Accessing Array Elements:: How to access individual elements of an array.
  5475. * Declaring an Array:: How to name and reserve space for a new array.
  5476. * Strings:: A string in C is a special case of array.
  5477. * Array Type Designators:: Referring to a specific array type.
  5478. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5479. * Limitations of C Arrays:: Arrays are not first-class objects.
  5480. * Multidimensional Arrays:: Arrays of arrays.
  5481. * Constructing Array Values:: Assigning values to an entire array at once.
  5482. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5483. @end menu
  5484. @node Accessing Array Elements
  5485. @section Accessing Array Elements
  5486. @cindex accessing array elements
  5487. @cindex array elements, accessing
  5488. If the variable @code{a} is an array, the @var{n}th element of
  5489. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5490. an element's value or to assign to it:
  5491. @example
  5492. x = a[5];
  5493. a[6] = 1;
  5494. @end example
  5495. @noindent
  5496. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5497. lvalue.
  5498. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5499. valid index is one less than the number of elements.
  5500. The C language does not check whether array indices are in bounds, so
  5501. if the code uses an out-of-range index, it will access memory outside the
  5502. array.
  5503. @strong{Warning:} Using only valid index values in C is the
  5504. programmer's responsibility.
  5505. Array indexing in C is not a primitive operation: it is defined in
  5506. terms of pointer arithmetic and dereferencing. Now that we know
  5507. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5508. its job.
  5509. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5510. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5511. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5512. When an expression with array type (such as @code{a}) appears as part
  5513. of a larger C expression, it is converted automatically to a pointer
  5514. to element zero of that array. For instance, @code{a} in an
  5515. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5516. computed as @code{*(&a[0]+i)}.
  5517. Now we can analyze how that expression gives us the desired element of
  5518. the array. It makes a pointer to element 0 of @code{a}, advances it
  5519. by the value of @code{i}, and dereferences that pointer.
  5520. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5521. @node Declaring an Array
  5522. @section Declaring an Array
  5523. @cindex declaring an array
  5524. @cindex array, declaring
  5525. To make an array declaration, write @code{[@var{length}]} after the
  5526. name being declared. This construct is valid in the declaration of a
  5527. variable, a function parameter, a function value type (the value can't
  5528. be an array, but it can be a pointer to one), a structure field, or a
  5529. union alternative.
  5530. The surrounding declaration specifies the element type of the array;
  5531. that can be any type of data, but not @code{void} or a function type.
  5532. For instance,
  5533. @example
  5534. double a[5];
  5535. @end example
  5536. @noindent
  5537. declares @code{a} as an array of 5 @code{double}s.
  5538. @example
  5539. struct foo bstruct[length];
  5540. @end example
  5541. @noindent
  5542. declares @code{bstruct} as an array of @code{length} objects of type
  5543. @code{struct foo}. A variable array size like this is allowed when
  5544. the array is not file-scope.
  5545. Other declaration constructs can nest within the array declaration
  5546. construct. For instance:
  5547. @example
  5548. struct foo *b[length];
  5549. @end example
  5550. @noindent
  5551. declares @code{b} as an array of @code{length} pointers to
  5552. @code{struct foo}. This shows that the length need not be a constant
  5553. (@pxref{Arrays of Variable Length}).
  5554. @example
  5555. double (*c)[5];
  5556. @end example
  5557. @noindent
  5558. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5559. @example
  5560. char *(*f (int))[5];
  5561. @end example
  5562. @noindent
  5563. declares @code{f} as a function taking an @code{int} argument and
  5564. returning a pointer to an array of 5 strings (pointers to
  5565. @code{char}s).
  5566. @example
  5567. double aa[5][10];
  5568. @end example
  5569. @noindent
  5570. declares @code{aa} as an array of 5 elements, each of which is an
  5571. array of 10 @code{double}s. This shows how to declare a
  5572. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5573. All these declarations specify the array's length, which is needed in
  5574. these cases in order to allocate storage for the array.
  5575. @node Strings
  5576. @section Strings
  5577. @cindex string
  5578. A string in C is a sequence of elements of type @code{char},
  5579. terminated with the null character, the character with code zero.
  5580. Programs often need to use strings with specific, fixed contents. To
  5581. write one in a C program, use a @dfn{string constant} such as
  5582. @code{"Take me to your leader!"}. The data type of a string constant
  5583. is @code{char *}. For the full syntactic details of writing string
  5584. constants, @ref{String Constants}.
  5585. To declare a place to store a non-constant string, declare an array of
  5586. @code{char}. Keep in mind that it must include one extra @code{char}
  5587. for the terminating null. For instance,
  5588. @example
  5589. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5590. @end example
  5591. @noindent
  5592. declares an array named @samp{text} with six elements---five letters
  5593. and the terminating null character. An equivalent way to get the same
  5594. result is this,
  5595. @example
  5596. char text[] = "Hello";
  5597. @end example
  5598. @noindent
  5599. which copies the elements of the string constant, including @emph{its}
  5600. terminating null character.
  5601. @example
  5602. char message[200];
  5603. @end example
  5604. @noindent
  5605. declares an array long enough to hold a string of 199 ASCII characters
  5606. plus the terminating null character.
  5607. When you store a string into @code{message} be sure to check or prove
  5608. that the length does not exceed its size. For example,
  5609. @example
  5610. void
  5611. set_message (char *text)
  5612. @{
  5613. int i;
  5614. for (i = 0; i < sizeof (message); i++)
  5615. @{
  5616. message[i] = text[i];
  5617. if (text[i] == 0)
  5618. return;
  5619. @}
  5620. fatal_error ("Message is too long for `message');
  5621. @}
  5622. @end example
  5623. It's easy to do this with the standard library function
  5624. @code{strncpy}, which fills out the whole destination array (up to a
  5625. specified length) with null characters. Thus, if the last character
  5626. of the destination is not null, the string did not fit. Many system
  5627. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5628. to run faster than an explicit @code{for}-loop.
  5629. Here's what the code looks like:
  5630. @example
  5631. void
  5632. set_message (char *text)
  5633. @{
  5634. strncpy (message, text, sizeof (message));
  5635. if (message[sizeof (message) - 1] != 0)
  5636. fatal_error ("Message is too long for `message');
  5637. @}
  5638. @end example
  5639. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5640. Library Reference Manual}, for more information about the standard
  5641. library functions for operating on strings.
  5642. You can avoid putting a fixed length limit on strings you construct or
  5643. operate on by allocating the space for them dynamically.
  5644. @xref{Dynamic Memory Allocation}.
  5645. @node Array Type Designators
  5646. @section Array Type Designators
  5647. Every C type has a type designator, which you make by deleting the
  5648. variable name and the semicolon from a declaration (@pxref{Type
  5649. Designators}). The designators for array types follow this rule, but
  5650. they may appear surprising.
  5651. @example
  5652. @r{type} int a[5]; @r{designator} int [5]
  5653. @r{type} double a[5][3]; @r{designator} double [5][3]
  5654. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5655. @end example
  5656. @node Incomplete Array Types
  5657. @section Incomplete Array Types
  5658. @cindex incomplete array types
  5659. @cindex array types, incomplete
  5660. An array is equivalent, for most purposes, to a pointer to its zeroth
  5661. element. When that is true, the length of the array is irrelevant.
  5662. The length needs to be known only for allocating space for the array, or
  5663. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5664. contexts C allows
  5665. @itemize @bullet
  5666. @item
  5667. An @code{extern} declaration says how to refer to a variable allocated
  5668. elsewhere. It does not need to allocate space for the variable,
  5669. so if it is an array, you can omit the length. For example,
  5670. @example
  5671. extern int foo[];
  5672. @end example
  5673. @item
  5674. When declaring a function parameter as an array, the argument value
  5675. passed to the function is really a pointer to the array's zeroth
  5676. element. This value does not say how long the array really is, there
  5677. is no need to declare it. For example,
  5678. @example
  5679. int
  5680. func (int foo[])
  5681. @end example
  5682. @end itemize
  5683. These declarations are examples of @dfn{incomplete} array types, types
  5684. that are not fully specified. The incompleteness makes no difference
  5685. for accessing elements of the array, but it matters for some other
  5686. things. For instance, @code{sizeof} is not allowed on an incomplete
  5687. type.
  5688. With multidimensional arrays, only the first dimension can be omitted:
  5689. @example
  5690. extern struct chesspiece *funnyboard foo[][8];
  5691. @end example
  5692. In other words, the code doesn't have to say how many rows there are,
  5693. but it must state how big each row is.
  5694. @node Limitations of C Arrays
  5695. @section Limitations of C Arrays
  5696. @cindex limitations of C arrays
  5697. @cindex first-class object
  5698. Arrays have quirks in C because they are not ``first-class objects'':
  5699. there is no way in C to operate on an array as a unit.
  5700. The other composite objects in C, structures and unions, are
  5701. first-class objects: a C program can copy a structure or union value
  5702. in an assignment, or pass one as an argument to a function, or make a
  5703. function return one. You can't do those things with an array in C@.
  5704. That is because a value you can operate on never has an array type.
  5705. An expression in C can have an array type, but that doesn't produce
  5706. the array as a value. Instead it is converted automatically to a
  5707. pointer to the array's element at index zero. The code can operate
  5708. on the pointer, and through that on individual elements of the array,
  5709. but it can't get and operate on the array as a unit.
  5710. There are three exceptions to this conversion rule, but none of them
  5711. offers a way to operate on the array as a whole.
  5712. First, @samp{&} applied to an expression with array type gives you the
  5713. address of the array, as an array type. However, you can't operate on the
  5714. whole array that way---if you apply @samp{*} to get the array back,
  5715. that expression converts, as usual, to a pointer to its zeroth
  5716. element.
  5717. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5718. @code{typeof} do not convert the array to a pointer; they leave it as
  5719. an array. But they don't operate on the array's data---they only give
  5720. information about its type.
  5721. Third, a string constant used as an initializer for an array is not
  5722. converted to a pointer---rather, the declaration copies the
  5723. @emph{contents} of that string in that one special case.
  5724. You @emph{can} copy the contents of an array, just not with an
  5725. assignment operator. You can do it by calling the library function
  5726. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5727. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5728. when a structure contains just an array, you can copy that structure.
  5729. An array itself is an lvalue if it is a declared variable, or part of
  5730. a structure or union that is an lvalue. When you construct an array
  5731. from elements (@pxref{Constructing Array Values}), that array is not
  5732. an lvalue.
  5733. @node Multidimensional Arrays
  5734. @section Multidimensional Arrays
  5735. @cindex multidimensional arrays
  5736. @cindex array, multidimensional
  5737. Strictly speaking, all arrays in C are unidimensional. However, you
  5738. can create an array of arrays, which is more or less equivalent to a
  5739. multidimensional array. For example,
  5740. @example
  5741. struct chesspiece *board[8][8];
  5742. @end example
  5743. @noindent
  5744. declares an array of 8 arrays of 8 pointers to @code{struct
  5745. chesspiece}. This data type could represent the state of a chess
  5746. game. To access one square's contents requires two array index
  5747. operations, one for each dimension. For instance, you can write
  5748. @code{board[row][column]}, assuming @code{row} and @code{column}
  5749. are variables with integer values in the proper range.
  5750. How does C understand @code{board[row][column]}? First of all,
  5751. @code{board} is converted automatically to a pointer to the zeroth
  5752. element (at index zero) of @code{board}. Adding @code{row} to that
  5753. makes it point to the desired element. Thus, @code{board[row]}'s
  5754. value is an element of @code{board}---an array of 8 pointers.
  5755. However, as an expression with array type, it is converted
  5756. automatically to a pointer to the array's zeroth element. The second
  5757. array index operation, @code{[column]}, accesses the chosen element
  5758. from that array.
  5759. As this shows, pointer-to-array types are meaningful in C@.
  5760. You can declare a variable that points to a row in a chess board
  5761. like this:
  5762. @example
  5763. struct chesspiece *(*rowptr)[8];
  5764. @end example
  5765. @noindent
  5766. This points to an array of 8 pointers to @code{struct chesspiece}.
  5767. You can assign to it as follows:
  5768. @example
  5769. rowptr = &board[5];
  5770. @end example
  5771. The dimensions don't have to be equal in length. Here we declare
  5772. @code{statepop} as an array to hold the population of each state in
  5773. the United States for each year since 1900:
  5774. @example
  5775. #define NSTATES 50
  5776. @{
  5777. int nyears = current_year - 1900 + 1;
  5778. int statepop[NSTATES][nyears];
  5779. @r{@dots{}}
  5780. @}
  5781. @end example
  5782. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5783. each indexed by the year (counting from 1900). Thus, to get the
  5784. element for a particular state and year, we must subscript it first
  5785. by the number that indicates the state, and second by the index for
  5786. the year:
  5787. @example
  5788. statepop[state][year - 1900]
  5789. @end example
  5790. @cindex array, layout in memory
  5791. The subarrays within the multidimensional array are allocated
  5792. consecutively in memory, and within each subarray, its elements are
  5793. allocated consecutively in memory. The most efficient way to process
  5794. all the elements in the array is to scan the last subscript in the
  5795. innermost loop. This means consecutive accesses go to consecutive
  5796. memory locations, which optimizes use of the processor's memory cache.
  5797. For example:
  5798. @example
  5799. int total = 0;
  5800. float average;
  5801. for (int state = 0; state < NSTATES, ++state)
  5802. @{
  5803. for (int year = 0; year < nyears; ++year)
  5804. @{
  5805. total += statepop[state][year];
  5806. @}
  5807. @}
  5808. average = total / nyears;
  5809. @end example
  5810. C's layout for multidimensional arrays is different from Fortran's
  5811. layout. In Fortran, a multidimensional array is not an array of
  5812. arrays; rather, multidimensional arrays are a primitive feature, and
  5813. it is the first index that varies most rapidly between consecutive
  5814. memory locations. Thus, the memory layout of a 50x114 array in C
  5815. matches that of a 114x50 array in Fortran.
  5816. @node Constructing Array Values
  5817. @section Constructing Array Values
  5818. @cindex constructing array values
  5819. @cindex array values, constructing
  5820. You can construct an array from elements by writing them inside
  5821. braces, and preceding all that with the array type's designator in
  5822. parentheses. There is no need to specify the array length, since the
  5823. number of elements determines that. The constructor looks like this:
  5824. @example
  5825. (@var{elttype}[]) @{ @var{elements} @};
  5826. @end example
  5827. Here is an example, which constructs an array of string pointers:
  5828. @example
  5829. (char *[]) @{ "x", "y", "z" @};
  5830. @end example
  5831. That's equivalent in effect to declaring an array with the same
  5832. initializer, like this:
  5833. @example
  5834. char *array[] = @{ "x", "y", "z" @};
  5835. @end example
  5836. and then using the array.
  5837. If all the elements are simple constant expressions, or made up of
  5838. such, then the compound literal can be coerced to a pointer to its
  5839. zeroth element and used to initialize a file-scope variable
  5840. (@pxref{File-Scope Variables}), as shown here:
  5841. @example
  5842. char **foo = (char *[]) @{ "x", "y", "z" @};
  5843. @end example
  5844. @noindent
  5845. The data type of @code{foo} is @code{char **}, which is a pointer
  5846. type, not an array type. The declaration is equivalent to defining
  5847. and then using an array-type variable:
  5848. @example
  5849. char *nameless_array[] = @{ "x", "y", "z" @};
  5850. char **foo = &nameless_array[0];
  5851. @end example
  5852. @node Arrays of Variable Length
  5853. @section Arrays of Variable Length
  5854. @cindex array of variable length
  5855. @cindex variable-length arrays
  5856. In GNU C, you can declare variable-length arrays like any other
  5857. arrays, but with a length that is not a constant expression. The
  5858. storage is allocated at the point of declaration and deallocated when
  5859. the block scope containing the declaration exits. For example:
  5860. @example
  5861. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5862. #include <string.h> /* @r{Declares @code{str}.} */
  5863. FILE *
  5864. concat_fopen (char *s1, char *s2, char *mode)
  5865. @{
  5866. char str[strlen (s1) + strlen (s2) + 1];
  5867. strcpy (str, s1);
  5868. strcat (str, s2);
  5869. return fopen (str, mode);
  5870. @}
  5871. @end example
  5872. @noindent
  5873. (This uses some standard library functions; see @ref{String and Array
  5874. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5875. The length of an array is computed once when the storage is allocated
  5876. and is remembered for the scope of the array in case it is used in
  5877. @code{sizeof}.
  5878. @strong{Warning:} don't allocate a variable-length array if the size
  5879. might be very large (more than 100,000), or in a recursive function,
  5880. because that is likely to cause stack overflow. Allocate the array
  5881. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5882. Jumping or breaking out of the scope of the array name deallocates the
  5883. storage. Jumping into the scope is not allowed; that gives an error
  5884. message.
  5885. You can also use variable-length arrays as arguments to functions:
  5886. @example
  5887. struct entry
  5888. tester (int len, char data[len][len])
  5889. @{
  5890. @r{@dots{}}
  5891. @}
  5892. @end example
  5893. As usual, a function argument declared with an array type
  5894. is really a pointer to an array that already exists.
  5895. Calling the function does not allocate the array, so there's no
  5896. particular danger of stack overflow in using this construct.
  5897. To pass the array first and the length afterward, use a forward
  5898. declaration in the function's parameter list (another GNU extension).
  5899. For example,
  5900. @example
  5901. struct entry
  5902. tester (int len; char data[len][len], int len)
  5903. @{
  5904. @r{@dots{}}
  5905. @}
  5906. @end example
  5907. The @code{int len} before the semicolon is a @dfn{parameter forward
  5908. declaration}, and it serves the purpose of making the name @code{len}
  5909. known when the declaration of @code{data} is parsed.
  5910. You can write any number of such parameter forward declarations in the
  5911. parameter list. They can be separated by commas or semicolons, but
  5912. the last one must end with a semicolon, which is followed by the
  5913. ``real'' parameter declarations. Each forward declaration must match
  5914. a ``real'' declaration in parameter name and data type. ISO C11 does
  5915. not support parameter forward declarations.
  5916. @node Enumeration Types
  5917. @chapter Enumeration Types
  5918. @cindex enumeration types
  5919. @cindex types, enumeration
  5920. @cindex enumerator
  5921. An @dfn{enumeration type} represents a limited set of integer values,
  5922. each with a name. It is effectively equivalent to a primitive integer
  5923. type.
  5924. Suppose we have a list of possible emotional states to store in an
  5925. integer variable. We can give names to these alternative values with
  5926. an enumeration:
  5927. @example
  5928. enum emotion_state @{ neutral, happy, sad, worried,
  5929. calm, nervous @};
  5930. @end example
  5931. @noindent
  5932. (Never mind that this is a simplistic way to classify emotional states;
  5933. it's just a code example.)
  5934. The names inside the enumeration are called @dfn{enumerators}. The
  5935. enumeration type defines them as constants, and their values are
  5936. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5937. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5938. the enumerators explicitly like this:
  5939. @example
  5940. enum emotion_state @{ neutral = 2, happy = 5,
  5941. sad = 20, worried = 10,
  5942. calm = -5, nervous = -300 @};
  5943. @end example
  5944. Each enumerator which does not specify a value gets value zero
  5945. (if it is at the beginning) or the next consecutive integer.
  5946. @example
  5947. /* @r{@code{neutral} is 0 by default,}
  5948. @r{and @code{worried} is 21 by default.} */
  5949. enum emotion_state @{ neutral,
  5950. happy = 5, sad = 20, worried,
  5951. calm = -5, nervous = -300 @};
  5952. @end example
  5953. If an enumerator is obsolete, you can specify that using it should
  5954. cause a warning, by including an attribute in the enumerator's
  5955. declaration. Here is how @code{happy} would look with this
  5956. attribute:
  5957. @example
  5958. happy __attribute__
  5959. ((deprecated
  5960. ("impossible under plutocratic rule")))
  5961. = 5,
  5962. @end example
  5963. @xref{Attributes}.
  5964. You can declare variables with the enumeration type:
  5965. @example
  5966. enum emotion_state feelings_now;
  5967. @end example
  5968. In the C code itself, this is equivalent to declaring the variable
  5969. @code{int}. (If all the enumeration values are positive, it is
  5970. equivalent to @code{unsigned int}.) However, declaring it with the
  5971. enumeration type has an advantage in debugging, because GDB knows it
  5972. should display the current value of the variable using the
  5973. corresponding name. If the variable's type is @code{int}, GDB can
  5974. only show the value as a number.
  5975. The identifier that follows @code{enum} is called a @dfn{type tag}
  5976. since it distinguishes different enumeration types. Type tags are in
  5977. a separate name space and belong to scopes like most other names in C@.
  5978. @xref{Type Tags}, for explanation.
  5979. You can predeclare an @code{enum} type tag like a structure or union
  5980. type tag, like this:
  5981. @example
  5982. enum foo;
  5983. @end example
  5984. @noindent
  5985. The @code{enum} type is incomplete until you finish defining it.
  5986. You can optionally include a trailing comma at the end of a list of
  5987. enumeration values:
  5988. @example
  5989. enum emotion_state @{ neutral, happy, sad, worried,
  5990. calm, nervous, @};
  5991. @end example
  5992. @noindent
  5993. This is useful in some macro definitions, since it enables you to
  5994. assemble the list of enumerators without knowing which one is last.
  5995. The extra comma does not change the meaning of the enumeration in any
  5996. way.
  5997. @node Defining Typedef Names
  5998. @chapter Defining Typedef Names
  5999. @cindex typedef names
  6000. @findex typedef
  6001. You can define a data type keyword as an alias for any type, and then
  6002. use the alias syntactically like a built-in type keyword such as
  6003. @code{int}. You do this using @code{typedef}, so these aliases are
  6004. also called @dfn{typedef names}.
  6005. @code{typedef} is followed by text that looks just like a variable
  6006. declaration, but instead of declaring variables it defines data type
  6007. keywords.
  6008. Here's how to define @code{fooptr} as a typedef alias for the type
  6009. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  6010. with that type:
  6011. @example
  6012. typedef struct foo *fooptr;
  6013. fooptr x, y;
  6014. @end example
  6015. @noindent
  6016. That declaration is equivalent to the following one:
  6017. @example
  6018. struct foo *x, *y;
  6019. @end example
  6020. You can define a typedef alias for any type. For instance, this makes
  6021. @code{frobcount} an alias for type @code{int}:
  6022. @example
  6023. typedef int frobcount;
  6024. @end example
  6025. @noindent
  6026. This doesn't define a new type distinct from @code{int}. Rather,
  6027. @code{frobcount} is another name for the type @code{int}. Once the
  6028. variable is declared, it makes no difference which name the
  6029. declaration used.
  6030. There is a syntactic difference, however, between @code{frobcount} and
  6031. @code{int}: A typedef name cannot be used with
  6032. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6033. to specify the type all by itself. So you can't write this:
  6034. @example
  6035. unsigned frobcount f1; /* @r{Error!} */
  6036. @end example
  6037. But you can write this:
  6038. @example
  6039. typedef unsigned int unsigned_frobcount;
  6040. unsigned_frobcount f1;
  6041. @end example
  6042. In other words, a typedef name is not an alias for @emph{a keyword}
  6043. such as @code{int}. It stands for a @emph{type}, and that could be
  6044. the type @code{int}.
  6045. Typedef names are in the same namespace as functions and variables, so
  6046. you can't use the same name for a typedef and a function, or a typedef
  6047. and a variable. When a typedef is declared inside a code block, it is
  6048. in scope only in that block.
  6049. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6050. because many of these have standard meanings.
  6051. You can redefine a typedef name to the exact same type as its first
  6052. definition, but you cannot redefine a typedef name to a
  6053. different type, even if the two types are compatible. For example, this
  6054. is valid:
  6055. @example
  6056. typedef int frobcount;
  6057. typedef int frotzcount;
  6058. typedef frotzcount frobcount;
  6059. typedef frobcount frotzcount;
  6060. @end example
  6061. @noindent
  6062. because each typedef name is always defined with the same type
  6063. (@code{int}), but this is not valid:
  6064. @example
  6065. enum foo @{f1, f2, f3@};
  6066. typedef enum foo frobcount;
  6067. typedef int frobcount;
  6068. @end example
  6069. @noindent
  6070. Even though the type @code{enum foo} is compatible with @code{int},
  6071. they are not the @emph{same} type.
  6072. @node Statements
  6073. @chapter Statements
  6074. @cindex statements
  6075. A @dfn{statement} specifies computations to be done for effect; it
  6076. does not produce a value, as an expression would. In general a
  6077. statement ends with a semicolon (@samp{;}), but blocks (which are
  6078. statements, more or less) are an exception to that rule.
  6079. @ifnottex
  6080. @xref{Blocks}.
  6081. @end ifnottex
  6082. The places to use statements are inside a block, and inside a
  6083. complex statement. A @dfn{complex statement} contains one or two
  6084. components that are nested statements. Each such component must
  6085. consist of one and only one statement. The way to put multiple
  6086. statements in such a component is to group them into a @dfn{block}
  6087. (@pxref{Blocks}), which counts as one statement.
  6088. The following sections describe the various kinds of statement.
  6089. @menu
  6090. * Expression Statement:: Evaluate an expression, as a statement,
  6091. usually done for a side effect.
  6092. * if Statement:: Basic conditional execution.
  6093. * if-else Statement:: Multiple branches for conditional execution.
  6094. * Blocks:: Grouping multiple statements together.
  6095. * return Statement:: Return a value from a function.
  6096. * Loop Statements:: Repeatedly executing a statement or block.
  6097. * switch Statement:: Multi-way conditional choices.
  6098. * switch Example:: A plausible example of using @code{switch}.
  6099. * Duffs Device:: A special way to use @code{switch}.
  6100. * Case Ranges:: Ranges of values for @code{switch} cases.
  6101. * Null Statement:: A statement that does nothing.
  6102. * goto Statement:: Jump to another point in the source code,
  6103. identified by a label.
  6104. * Local Labels:: Labels with limited scope.
  6105. * Labels as Values:: Getting the address of a label.
  6106. * Statement Exprs:: A series of statements used as an expression.
  6107. @end menu
  6108. @node Expression Statement
  6109. @section Expression Statement
  6110. @cindex expression statement
  6111. @cindex statement, expression
  6112. The most common kind of statement in C is an @dfn{expression statement}.
  6113. It consists of an expression followed by a
  6114. semicolon. The expression's value is discarded, so the expressions
  6115. that are useful are those that have side effects: assignment
  6116. expressions, increment and decrement expressions, and function calls.
  6117. Here are examples of expression statements:
  6118. @smallexample
  6119. x = 5; /* @r{Assignment expression.} */
  6120. p++; /* @r{Increment expression.} */
  6121. printf ("Done\n"); /* @r{Function call expression.} */
  6122. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6123. x + y; /* @r{Useless statement without effect.} */
  6124. @end smallexample
  6125. In very unusual circumstances we use an expression statement
  6126. whose purpose is to get a fault if an address is invalid:
  6127. @smallexample
  6128. volatile char *p;
  6129. @r{@dots{}}
  6130. *p; /* @r{Cause signal if @code{p} is null.} */
  6131. @end smallexample
  6132. If the target of @code{p} is not declared @code{volatile}, the
  6133. compiler might optimize away the memory access, since it knows that
  6134. the value isn't really used. @xref{volatile}.
  6135. @node if Statement
  6136. @section @code{if} Statement
  6137. @cindex @code{if} statement
  6138. @cindex statement, @code{if}
  6139. @findex if
  6140. An @code{if} statement computes an expression to decide
  6141. whether to execute the following statement or not.
  6142. It looks like this:
  6143. @example
  6144. if (@var{condition})
  6145. @var{execute-if-true}
  6146. @end example
  6147. The first thing this does is compute the value of @var{condition}. If
  6148. that is true (nonzero), then it executes the statement
  6149. @var{execute-if-true}. If the value of @var{condition} is false
  6150. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6151. nothing.
  6152. This is a @dfn{complex statement} because it contains a component
  6153. @var{if-true-substatement} that is a nested statement. It must be one
  6154. and only one statement. The way to put multiple statements there is
  6155. to group them into a @dfn{block} (@pxref{Blocks}).
  6156. @node if-else Statement
  6157. @section @code{if-else} Statement
  6158. @cindex @code{if}@dots{}@code{else} statement
  6159. @cindex statement, @code{if}@dots{}@code{else}
  6160. @findex else
  6161. An @code{if}-@code{else} statement computes an expression to decide
  6162. which of two nested statements to execute.
  6163. It looks like this:
  6164. @example
  6165. if (@var{condition})
  6166. @var{if-true-substatement}
  6167. else
  6168. @var{if-false-substatement}
  6169. @end example
  6170. The first thing this does is compute the value of @var{condition}. If
  6171. that is true (nonzero), then it executes the statement
  6172. @var{if-true-substatement}. If the value of @var{condition} is false
  6173. (zero), then it executes the statement @var{if-false-substatement} instead.
  6174. This is a @dfn{complex statement} because it contains components
  6175. @var{if-true-substatement} and @var{if-else-substatement} that are
  6176. nested statements. Each must be one and only one statement. The way
  6177. to put multiple statements in such a component is to group them into a
  6178. @dfn{block} (@pxref{Blocks}).
  6179. @node Blocks
  6180. @section Blocks
  6181. @cindex block
  6182. @cindex compound statement
  6183. A @dfn{block} is a construct that contains multiple statements of any
  6184. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6185. series of statements and declarations in between. Another name for
  6186. blocks is @dfn{compound statements}.
  6187. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6188. normal statement---it does not end with a semicolon. But you can
  6189. @emph{use} it like a statement; anywhere that a statement is required
  6190. or allowed, you can write a block and consider that block a statement.
  6191. So far it seems that a block is a kind of statement with an unusual
  6192. syntax. But that is not entirely true: a function body is also a
  6193. block, and that block is definitely not a statement. The text after a
  6194. function header is not treated as a statement; only a function body is
  6195. allowed there, and nothing else would be meaningful there.
  6196. In a formal grammar we would have to choose---either a block is a kind
  6197. of statement or it is not. But this manual is meant for humans, not
  6198. for parser generators. The clearest answer for humans is, ``a block
  6199. is a statement, in some ways.''
  6200. @cindex nested block
  6201. @cindex internal block
  6202. A block that isn't a function body is called an @dfn{internal block}
  6203. or a @dfn{nested block}. You can put a nested block directly inside
  6204. another block, but more often the nested block is inside some complex
  6205. statement, such as a @code{for} statement or an @code{if} statement.
  6206. There are two uses for nested blocks in C:
  6207. @itemize @bullet
  6208. @item
  6209. To specify the scope for local declarations. For instance, a local
  6210. variable's scope is the rest of the innermost containing block.
  6211. @item
  6212. To write a series of statements where, syntactically, one statement is
  6213. called for. For instance, the @var{execute-if-true} of an @code{if}
  6214. statement is one statement. To put multiple statements there, they
  6215. have to be wrapped in a block, like this:
  6216. @example
  6217. if (x < 0)
  6218. @{
  6219. printf ("x was negative\n");
  6220. x = -x;
  6221. @}
  6222. @end example
  6223. @end itemize
  6224. This example (repeated from above) shows a nested block which serves
  6225. both purposes: it includes two statements (plus a declaration) in the
  6226. body of a @code{while} statement, and it provides the scope for the
  6227. declaration of @code{q}.
  6228. @example
  6229. void
  6230. free_intlist (struct intlistlink *p)
  6231. @{
  6232. while (p)
  6233. @{
  6234. struct intlistlink *q = p;
  6235. p = p->next;
  6236. free (q);
  6237. @}
  6238. @}
  6239. @end example
  6240. @node return Statement
  6241. @section @code{return} Statement
  6242. @cindex @code{return} statement
  6243. @cindex statement, @code{return}
  6244. @findex return
  6245. The @code{return} statement makes the containing function return
  6246. immediately. It has two forms. This one specifies no value to
  6247. return:
  6248. @example
  6249. return;
  6250. @end example
  6251. @noindent
  6252. That form is meant for functions whose return type is @code{void}
  6253. (@pxref{The Void Type}). You can also use it in a function that
  6254. returns nonvoid data, but that's a bad idea, since it makes the
  6255. function return garbage.
  6256. The form that specifies a value looks like this:
  6257. @example
  6258. return @var{value};
  6259. @end example
  6260. @noindent
  6261. which computes the expression @var{value} and makes the function
  6262. return that. If necessary, the value undergoes type conversion to
  6263. the function's declared return value type, which works like
  6264. assigning the value to a variable of that type.
  6265. @node Loop Statements
  6266. @section Loop Statements
  6267. @cindex loop statements
  6268. @cindex statements, loop
  6269. @cindex iteration
  6270. You can use a loop statement when you need to execute a series of
  6271. statements repeatedly, making an @dfn{iteration}. C provides several
  6272. different kinds of loop statements, described in the following
  6273. subsections.
  6274. Every kind of loop statement is a complex statement because contains a
  6275. component, here called @var{body}, which is a nested statement.
  6276. Most often the body is a block.
  6277. @menu
  6278. * while Statement:: Loop as long as a test expression is true.
  6279. * do-while Statement:: Execute a loop once, with further looping
  6280. as long as a test expression is true.
  6281. * break Statement:: End a loop immediately.
  6282. * for Statement:: Iterative looping.
  6283. * Example of for:: An example of iterative looping.
  6284. * Omitted for-Expressions:: for-loop expression options.
  6285. * for-Index Declarations:: for-loop declaration options.
  6286. * continue Statement:: Begin the next cycle of a loop.
  6287. @end menu
  6288. @node while Statement
  6289. @subsection @code{while} Statement
  6290. @cindex @code{while} statement
  6291. @cindex statement, @code{while}
  6292. @findex while
  6293. The @code{while} statement is the simplest loop construct.
  6294. It looks like this:
  6295. @example
  6296. while (@var{test})
  6297. @var{body}
  6298. @end example
  6299. Here, @var{body} is a statement (often a nested block) to repeat, and
  6300. @var{test} is the test expression that controls whether to repeat it again.
  6301. Each iteration of the loop starts by computing @var{test} and, if it
  6302. is true (nonzero), that means the loop should execute @var{body} again
  6303. and then start over.
  6304. Here's an example of advancing to the last structure in a chain of
  6305. structures chained through the @code{next} field:
  6306. @example
  6307. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6308. @r{@dots{}}
  6309. while (chain->next != NULL)
  6310. chain = chain->next;
  6311. @end example
  6312. @noindent
  6313. This code assumes the chain isn't empty to start with; if the chain is
  6314. empty (that is, if @code{chain} is a null pointer), the code gets a
  6315. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6316. @node do-while Statement
  6317. @subsection @code{do-while} Statement
  6318. @cindex @code{do}--@code{while} statement
  6319. @cindex statement, @code{do}--@code{while}
  6320. @findex do
  6321. The @code{do}--@code{while} statement is a simple loop construct that
  6322. performs the test at the end of the iteration.
  6323. @example
  6324. do
  6325. @var{body}
  6326. while (@var{test});
  6327. @end example
  6328. Here, @var{body} is a statement (possibly a block) to repeat, and
  6329. @var{test} is an expression that controls whether to repeat it again.
  6330. Each iteration of the loop starts by executing @var{body}. Then it
  6331. computes @var{test} and, if it is true (nonzero), that means to go
  6332. back and start over with @var{body}. If @var{test} is false (zero),
  6333. then the loop stops repeating and execution moves on past it.
  6334. @node break Statement
  6335. @subsection @code{break} Statement
  6336. @cindex @code{break} statement
  6337. @cindex statement, @code{break}
  6338. @findex break
  6339. The @code{break} statement looks like @samp{break;}. Its effect is to
  6340. exit immediately from the innermost loop construct or @code{switch}
  6341. statement (@pxref{switch Statement}).
  6342. For example, this loop advances @code{p} until the next null
  6343. character or newline.
  6344. @example
  6345. while (*p)
  6346. @{
  6347. /* @r{End loop if we have reached a newline.} */
  6348. if (*p == '\n')
  6349. break;
  6350. p++
  6351. @}
  6352. @end example
  6353. When there are nested loops, the @code{break} statement exits from the
  6354. innermost loop containing it.
  6355. @example
  6356. struct list_if_tuples
  6357. @{
  6358. struct list_if_tuples next;
  6359. int length;
  6360. data *contents;
  6361. @};
  6362. void
  6363. process_all_elements (struct list_if_tuples *list)
  6364. @{
  6365. while (list)
  6366. @{
  6367. /* @r{Process all the elements in this node's vector,}
  6368. @r{stopping when we reach one that is null.} */
  6369. for (i = 0; i < list->length; i++
  6370. @{
  6371. /* @r{Null element terminates this node's vector.} */
  6372. if (list->contents[i] == NULL)
  6373. /* @r{Exit the @code{for} loop.} */
  6374. break;
  6375. /* @r{Operate on the next element.} */
  6376. process_element (list->contents[i]);
  6377. @}
  6378. list = list->next;
  6379. @}
  6380. @}
  6381. @end example
  6382. The only way in C to exit from an outer loop is with
  6383. @code{goto} (@pxref{goto Statement}).
  6384. @node for Statement
  6385. @subsection @code{for} Statement
  6386. @cindex @code{for} statement
  6387. @cindex statement, @code{for}
  6388. @findex for
  6389. A @code{for} statement uses three expressions written inside a
  6390. parenthetical group to define the repetition of the loop. The first
  6391. expression says how to prepare to start the loop. The second says how
  6392. to test, before each iteration, whether to continue looping. The
  6393. third says how to advance, at the end of an iteration, for the next
  6394. iteration. All together, it looks like this:
  6395. @example
  6396. for (@var{start}; @var{continue-test}; @var{advance})
  6397. @var{body}
  6398. @end example
  6399. The first thing the @code{for} statement does is compute @var{start}.
  6400. The next thing it does is compute the expression @var{continue-test}.
  6401. If that expression is false (zero), the @code{for} statement finishes
  6402. immediately, so @var{body} is executed zero times.
  6403. However, if @var{continue-test} is true (nonzero), the @code{for}
  6404. statement executes @var{body}, then @var{advance}. Then it loops back
  6405. to the not-quite-top to test @var{continue-test} again. But it does
  6406. not compute @var{start} again.
  6407. @node Example of for
  6408. @subsection Example of @code{for}
  6409. Here is the @code{for} statement from the iterative Fibonacci
  6410. function:
  6411. @example
  6412. int i;
  6413. for (i = 1; i < n; ++i)
  6414. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6415. /* @r{since @code{i < n} is false the first time.} */
  6416. @{
  6417. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6418. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6419. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6420. int next = prev + last;
  6421. /* @r{Shift the values down.} */
  6422. prev = last;
  6423. last = next;
  6424. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6425. @r{and @var{prev} is @code{fib (@var{i})}.}
  6426. @r{But that won't stay true for long,}
  6427. @r{because we are about to increment @var{i}.} */
  6428. @}
  6429. @end example
  6430. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6431. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6432. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6433. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6434. that contains a declaration and two statements.
  6435. @node Omitted for-Expressions
  6436. @subsection Omitted @code{for}-Expressions
  6437. A fully-fleshed @code{for} statement contains all these parts,
  6438. @example
  6439. for (@var{start}; @var{continue-test}; @var{advance})
  6440. @var{body}
  6441. @end example
  6442. @noindent
  6443. but you can omit any of the three expressions inside the parentheses.
  6444. The parentheses and the two semicolons are required syntactically, but
  6445. the expressions between them may be missing. A missing expression
  6446. means this loop doesn't use that particular feature of the @code{for}
  6447. statement.
  6448. @c ??? You can't do this if START is a declaration.
  6449. Instead of using @var{start}, you can do the loop preparation
  6450. before the @code{for} statement: the effect is the same. So we
  6451. could have written the beginning of the previous example this way:
  6452. @example
  6453. int i = 0;
  6454. for (; i < n; ++i)
  6455. @end example
  6456. @noindent
  6457. instead of this way:
  6458. @example
  6459. int i;
  6460. for (i = 0; i < n; ++i)
  6461. @end example
  6462. Omitting @var{continue-test} means the loop runs forever (or until
  6463. something else causes exit from it). Statements inside the loop can
  6464. test conditions for termination and use @samp{break;} to exit. This
  6465. is more flexible since you can put those tests anywhere in the loop,
  6466. not solely at the beginning.
  6467. Putting an expression in @var{advance} is almost equivalent to writing
  6468. it at the end of the loop body; it does almost the same thing. The
  6469. only difference is for the @code{continue} statement (@pxref{continue
  6470. Statement}). So we could have written this:
  6471. @example
  6472. for (i = 0; i < n;)
  6473. @{
  6474. @r{@dots{}}
  6475. ++i;
  6476. @}
  6477. @end example
  6478. @noindent
  6479. instead of this:
  6480. @example
  6481. for (i = 0; i < n; ++i)
  6482. @{
  6483. @r{@dots{}}
  6484. @}
  6485. @end example
  6486. The choice is mainly a matter of what is more readable for
  6487. programmers. However, there is also a syntactic difference:
  6488. @var{advance} is an expression, not a statement. It can't include
  6489. loops, blocks, declarations, etc.
  6490. @node for-Index Declarations
  6491. @subsection @code{for}-Index Declarations
  6492. You can declare loop-index variables directly in the @var{start}
  6493. portion of the @code{for}-loop, like this:
  6494. @example
  6495. for (int i = 0; i < n; ++i)
  6496. @{
  6497. @r{@dots{}}
  6498. @}
  6499. @end example
  6500. This kind of @var{start} is limited to a single declaration; it can
  6501. declare one or more variables, separated by commas, all of which are
  6502. the same @var{basetype} (@code{int}, in this example):
  6503. @example
  6504. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6505. @{
  6506. @r{@dots{}}
  6507. @}
  6508. @end example
  6509. @noindent
  6510. The scope of these variables is the @code{for} statement as a whole.
  6511. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6512. Variables declared in @code{for} statements should have initializers.
  6513. Omitting the initialization gives the variables unpredictable initial
  6514. values, so this code is erroneous.
  6515. @example
  6516. for (int i; i < n; ++i)
  6517. @{
  6518. @r{@dots{}}
  6519. @}
  6520. @end example
  6521. @node continue Statement
  6522. @subsection @code{continue} Statement
  6523. @cindex @code{continue} statement
  6524. @cindex statement, @code{continue}
  6525. @findex continue
  6526. The @code{continue} statement looks like @samp{continue;}, and its
  6527. effect is to jump immediately to the end of the innermost loop
  6528. construct. If it is a @code{for}-loop, the next thing that happens
  6529. is to execute the loop's @var{advance} expression.
  6530. For example, this loop increments @code{p} until the next null character
  6531. or newline, and operates (in some way not shown) on all the characters
  6532. in the line except for spaces. All it does with spaces is skip them.
  6533. @example
  6534. for (;*p; ++p)
  6535. @{
  6536. /* @r{End loop if we have reached a newline.} */
  6537. if (*p == '\n')
  6538. break;
  6539. /* @r{Pay no attention to spaces.} */
  6540. if (*p == ' ')
  6541. continue;
  6542. /* @r{Operate on the next character.} */
  6543. @r{@dots{}}
  6544. @}
  6545. @end example
  6546. @noindent
  6547. Executing @samp{continue;} skips the loop body but it does not
  6548. skip the @var{advance} expression, @code{p++}.
  6549. We could also write it like this:
  6550. @example
  6551. for (;*p; ++p)
  6552. @{
  6553. /* @r{Exit if we have reached a newline.} */
  6554. if (*p == '\n')
  6555. break;
  6556. /* @r{Pay no attention to spaces.} */
  6557. if (*p != ' ')
  6558. @{
  6559. /* @r{Operate on the next character.} */
  6560. @r{@dots{}}
  6561. @}
  6562. @}
  6563. @end example
  6564. The advantage of using @code{continue} is that it reduces the
  6565. depth of nesting.
  6566. Contrast @code{continue} with the @code{break} statement. @xref{break
  6567. Statement}.
  6568. @node switch Statement
  6569. @section @code{switch} Statement
  6570. @cindex @code{switch} statement
  6571. @cindex statement, @code{switch}
  6572. @findex switch
  6573. @findex case
  6574. @findex default
  6575. The @code{switch} statement selects code to run according to the value
  6576. of an expression. The expression, in parentheses, follows the keyword
  6577. @code{switch}. After that come all the cases to select among,
  6578. inside braces. It looks like this:
  6579. @example
  6580. switch (@var{selector})
  6581. @{
  6582. @var{cases}@r{@dots{}}
  6583. @}
  6584. @end example
  6585. A case can look like this:
  6586. @example
  6587. case @var{value}:
  6588. @var{statements}
  6589. break;
  6590. @end example
  6591. @noindent
  6592. which means ``come here if @var{selector} happens to have the value
  6593. @var{value},'' or like this (a GNU C extension):
  6594. @example
  6595. case @var{rangestart} ... @var{rangeend}:
  6596. @var{statements}
  6597. break;
  6598. @end example
  6599. @noindent
  6600. which means ``come here if @var{selector} happens to have a value
  6601. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6602. Ranges}.
  6603. The values in @code{case} labels must reduce to integer constants.
  6604. They can use arithmetic, and @code{enum} constants, but they cannot
  6605. refer to data in memory, because they have to be computed at compile
  6606. time. It is an error if two @code{case} labels specify the same
  6607. value, or ranges that overlap, or if one is a range and the other is a
  6608. value in that range.
  6609. You can also define a default case to handle ``any other value,'' like
  6610. this:
  6611. @example
  6612. default:
  6613. @var{statements}
  6614. break;
  6615. @end example
  6616. If the @code{switch} statement has no @code{default:} label, then it
  6617. does nothing when the value matches none of the cases.
  6618. The brace-group inside the @code{switch} statement is a block, and you
  6619. can declare variables with that scope just as in any other block
  6620. (@pxref{Blocks}). However, initializers in these declarations won't
  6621. necessarily be executed every time the @code{switch} statement runs,
  6622. so it is best to avoid giving them initializers.
  6623. @code{break;} inside a @code{switch} statement exits immediately from
  6624. the @code{switch} statement. @xref{break Statement}.
  6625. If there is no @code{break;} at the end of the code for a case,
  6626. execution continues into the code for the following case. This
  6627. happens more often by mistake than intentionally, but since this
  6628. feature is used in real code, we cannot eliminate it.
  6629. @strong{Warning:} When one case is intended to fall through to the
  6630. next, write a comment like @samp{falls through} to say it's
  6631. intentional. That way, other programmers won't assume it was an error
  6632. and ``fix'' it erroneously.
  6633. Consecutive @code{case} statements could, pedantically, be considered
  6634. an instance of falling through, but we don't consider or treat them that
  6635. way because they won't confuse anyone.
  6636. @node switch Example
  6637. @section Example of @code{switch}
  6638. Here's an example of using the @code{switch} statement
  6639. to distinguish among characters:
  6640. @cindex counting vowels and punctuation
  6641. @example
  6642. struct vp @{ int vowels, punct; @};
  6643. struct vp
  6644. count_vowels_and_punct (char *string)
  6645. @{
  6646. int c;
  6647. int vowels = 0;
  6648. int punct = 0;
  6649. /* @r{Don't change the parameter itself.} */
  6650. /* @r{That helps in debugging.} */
  6651. char *p = string;
  6652. struct vp value;
  6653. while (c = *p++)
  6654. switch (c)
  6655. @{
  6656. case 'y':
  6657. case 'Y':
  6658. /* @r{We assume @code{y_is_consonant} will check surrounding
  6659. letters to determine whether this y is a vowel.} */
  6660. if (y_is_consonant (p - 1))
  6661. break;
  6662. /* @r{Falls through} */
  6663. case 'a':
  6664. case 'e':
  6665. case 'i':
  6666. case 'o':
  6667. case 'u':
  6668. case 'A':
  6669. case 'E':
  6670. case 'I':
  6671. case 'O':
  6672. case 'U':
  6673. vowels++;
  6674. break;
  6675. case '.':
  6676. case ',':
  6677. case ':':
  6678. case ';':
  6679. case '?':
  6680. case '!':
  6681. case '\"':
  6682. case '\'':
  6683. punct++;
  6684. break;
  6685. @}
  6686. value.vowels = vowels;
  6687. value.punct = punct;
  6688. return value;
  6689. @}
  6690. @end example
  6691. @node Duffs Device
  6692. @section Duff's Device
  6693. @cindex Duff's device
  6694. The cases in a @code{switch} statement can be inside other control
  6695. constructs. For instance, we can use a technique known as @dfn{Duff's
  6696. device} to optimize this simple function,
  6697. @example
  6698. void
  6699. copy (char *to, char *from, int count)
  6700. @{
  6701. while (count > 0)
  6702. *to++ = *from++, count--;
  6703. @}
  6704. @end example
  6705. @noindent
  6706. which copies memory starting at @var{from} to memory starting at
  6707. @var{to}.
  6708. Duff's device involves unrolling the loop so that it copies
  6709. several characters each time around, and using a @code{switch} statement
  6710. to enter the loop body at the proper point:
  6711. @example
  6712. void
  6713. copy (char *to, char *from, int count)
  6714. @{
  6715. if (count <= 0)
  6716. return;
  6717. int n = (count + 7) / 8;
  6718. switch (count % 8)
  6719. @{
  6720. do @{
  6721. case 0: *to++ = *from++;
  6722. case 7: *to++ = *from++;
  6723. case 6: *to++ = *from++;
  6724. case 5: *to++ = *from++;
  6725. case 4: *to++ = *from++;
  6726. case 3: *to++ = *from++;
  6727. case 2: *to++ = *from++;
  6728. case 1: *to++ = *from++;
  6729. @} while (--n > 0);
  6730. @}
  6731. @}
  6732. @end example
  6733. @node Case Ranges
  6734. @section Case Ranges
  6735. @cindex case ranges
  6736. @cindex ranges in case statements
  6737. You can specify a range of consecutive values in a single @code{case} label,
  6738. like this:
  6739. @example
  6740. case @var{low} ... @var{high}:
  6741. @end example
  6742. @noindent
  6743. This has the same effect as the proper number of individual @code{case}
  6744. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6745. This feature is especially useful for ranges of ASCII character codes:
  6746. @example
  6747. case 'A' ... 'Z':
  6748. @end example
  6749. @strong{Be careful:} with integers, write spaces around the @code{...}
  6750. to prevent it from being parsed wrong. For example, write this:
  6751. @example
  6752. case 1 ... 5:
  6753. @end example
  6754. @noindent
  6755. rather than this:
  6756. @example
  6757. case 1...5:
  6758. @end example
  6759. @node Null Statement
  6760. @section Null Statement
  6761. @cindex null statement
  6762. @cindex statement, null
  6763. A @dfn{null statement} is just a semicolon. It does nothing.
  6764. A null statement is a placeholder for use where a statement is
  6765. grammatically required, but there is nothing to be done. For
  6766. instance, sometimes all the work of a @code{for}-loop is done in the
  6767. @code{for}-header itself, leaving no work for the body. Here is an
  6768. example that searches for the first newline in @code{array}:
  6769. @example
  6770. for (p = array; *p != '\n'; p++)
  6771. ;
  6772. @end example
  6773. @node goto Statement
  6774. @section @code{goto} Statement and Labels
  6775. @cindex @code{goto} statement
  6776. @cindex statement, @code{goto}
  6777. @cindex label
  6778. @findex goto
  6779. The @code{goto} statement looks like this:
  6780. @example
  6781. goto @var{label};
  6782. @end example
  6783. @noindent
  6784. Its effect is to transfer control immediately to another part of the
  6785. current function---where the label named @var{label} is defined.
  6786. An ordinary label definition looks like this:
  6787. @example
  6788. @var{label}:
  6789. @end example
  6790. @noindent
  6791. and it can appear before any statement. You can't use @code{default}
  6792. as a label, since that has a special meaning for @code{switch}
  6793. statements.
  6794. An ordinary label doesn't need a separate declaration; defining it is
  6795. enough.
  6796. Here's an example of using @code{goto} to implement a loop
  6797. equivalent to @code{do}--@code{while}:
  6798. @example
  6799. @{
  6800. loop_restart:
  6801. @var{body}
  6802. if (@var{condition})
  6803. goto loop_restart;
  6804. @}
  6805. @end example
  6806. The name space of labels is separate from that of variables and functions.
  6807. Thus, there is no error in using a single name in both ways:
  6808. @example
  6809. @{
  6810. int foo; // @r{Variable @code{foo}.}
  6811. foo: // @r{Label @code{foo}.}
  6812. @var{body}
  6813. if (foo > 0) // @r{Variable @code{foo}.}
  6814. goto foo; // @r{Label @code{foo}.}
  6815. @}
  6816. @end example
  6817. Blocks have no effect on ordinary labels; each label name is defined
  6818. throughout the whole of the function it appears in. It looks strange to
  6819. jump into a block with @code{goto}, but it works. For example,
  6820. @example
  6821. if (x < 0)
  6822. goto negative;
  6823. if (y < 0)
  6824. @{
  6825. negative:
  6826. printf ("Negative\n");
  6827. return;
  6828. @}
  6829. @end example
  6830. If the goto jumps into the scope of a variable, it does not
  6831. initialize the variable. For example, if @code{x} is negative,
  6832. @example
  6833. if (x < 0)
  6834. goto negative;
  6835. if (y < 0)
  6836. @{
  6837. int i = 5;
  6838. negative:
  6839. printf ("Negative, and i is %d\n", i);
  6840. return;
  6841. @}
  6842. @end example
  6843. @noindent
  6844. prints junk because @code{i} was not initialized.
  6845. If the block declares a variable-length automatic array, jumping into
  6846. it gives a compilation error. However, jumping out of the scope of a
  6847. variable-length array works fine, and deallocates its storage.
  6848. A label can't come directly before a declaration, so the code can't
  6849. jump directly to one. For example, this is not allowed:
  6850. @example
  6851. @{
  6852. goto foo;
  6853. foo:
  6854. int x = 5;
  6855. bar(&x);
  6856. @}
  6857. @end example
  6858. @noindent
  6859. The workaround is to add a statement, even an empty statement,
  6860. directly after the label. For example:
  6861. @example
  6862. @{
  6863. goto foo;
  6864. foo:
  6865. ;
  6866. int x = 5;
  6867. bar(&x);
  6868. @}
  6869. @end example
  6870. Likewise, a label can't be the last thing in a block. The workaround
  6871. solution is the same: add a semicolon after the label.
  6872. These unnecessary restrictions on labels make no sense, and ought in
  6873. principle to be removed; but they do only a little harm since labels
  6874. and @code{goto} are rarely the best way to write a program.
  6875. These examples are all artificial; it would be more natural to
  6876. write them in other ways, without @code{goto}. For instance,
  6877. the clean way to write the example that prints @samp{Negative} is this:
  6878. @example
  6879. if (x < 0 || y < 0)
  6880. @{
  6881. printf ("Negative\n");
  6882. return;
  6883. @}
  6884. @end example
  6885. @noindent
  6886. It is hard to construct simple examples where @code{goto} is actually
  6887. the best way to write a program. Its rare good uses tend to be in
  6888. complex code, thus not apt for the purpose of explaining the meaning
  6889. of @code{goto}.
  6890. The only good time to use @code{goto} is when it makes the code
  6891. simpler than any alternative. Jumping backward is rarely desirable,
  6892. because usually the other looping and control constructs give simpler
  6893. code. Using @code{goto} to jump forward is more often desirable, for
  6894. instance when a function needs to do some processing in an error case
  6895. and errors can occur at various different places within the function.
  6896. @node Local Labels
  6897. @section Locally Declared Labels
  6898. @cindex local labels
  6899. @cindex macros, local labels
  6900. @findex __label__
  6901. In GNU C you can declare @dfn{local labels} in any nested block
  6902. scope. A local label is used in a @code{goto} statement just like an
  6903. ordinary label, but you can only reference it within the block in
  6904. which it was declared.
  6905. A local label declaration looks like this:
  6906. @example
  6907. __label__ @var{label};
  6908. @end example
  6909. @noindent
  6910. or
  6911. @example
  6912. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6913. @end example
  6914. Local label declarations must come at the beginning of the block,
  6915. before any ordinary declarations or statements.
  6916. The label declaration declares the label @emph{name}, but does not define
  6917. the label itself. That's done in the usual way, with
  6918. @code{@var{label}:}, before one of the statements in the block.
  6919. The local label feature is useful for complex macros. If a macro
  6920. contains nested loops, a @code{goto} can be useful for breaking out of
  6921. them. However, an ordinary label whose scope is the whole function
  6922. cannot be used: if the macro can be expanded several times in one
  6923. function, the label will be multiply defined in that function. A
  6924. local label avoids this problem. For example:
  6925. @example
  6926. #define SEARCH(value, array, target) \
  6927. do @{ \
  6928. __label__ found; \
  6929. __auto_type _SEARCH_target = (target); \
  6930. __auto_type _SEARCH_array = (array); \
  6931. int i, j; \
  6932. int value; \
  6933. for (i = 0; i < max; i++) \
  6934. for (j = 0; j < max; j++) \
  6935. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6936. @{ (value) = i; goto found; @} \
  6937. (value) = -1; \
  6938. found:; \
  6939. @} while (0)
  6940. @end example
  6941. This could also be written using a statement expression
  6942. (@pxref{Statement Exprs}):
  6943. @example
  6944. #define SEARCH(array, target) \
  6945. (@{ \
  6946. __label__ found; \
  6947. __auto_type _SEARCH_target = (target); \
  6948. __auto_type _SEARCH_array = (array); \
  6949. int i, j; \
  6950. int value; \
  6951. for (i = 0; i < max; i++) \
  6952. for (j = 0; j < max; j++) \
  6953. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6954. @{ value = i; goto found; @} \
  6955. value = -1; \
  6956. found: \
  6957. value; \
  6958. @})
  6959. @end example
  6960. Ordinary labels are visible throughout the function where they are
  6961. defined, and only in that function. However, explicitly declared
  6962. local labels of a block are visible in nested function definitions
  6963. inside that block. @xref{Nested Functions}, for details.
  6964. @xref{goto Statement}.
  6965. @node Labels as Values
  6966. @section Labels as Values
  6967. @cindex labels as values
  6968. @cindex computed gotos
  6969. @cindex goto with computed label
  6970. @cindex address of a label
  6971. In GNU C, you can get the address of a label defined in the current
  6972. function (or a local label defined in the containing function) with
  6973. the unary operator @samp{&&}. The value has type @code{void *}. This
  6974. value is a constant and can be used wherever a constant of that type
  6975. is valid. For example:
  6976. @example
  6977. void *ptr;
  6978. @r{@dots{}}
  6979. ptr = &&foo;
  6980. @end example
  6981. To use these values requires a way to jump to one. This is done
  6982. with the computed goto statement@footnote{The analogous feature in
  6983. Fortran is called an assigned goto, but that name seems inappropriate in
  6984. C, since you can do more with label addresses than store them in special label
  6985. variables.}, @code{goto *@var{exp};}. For example,
  6986. @example
  6987. goto *ptr;
  6988. @end example
  6989. @noindent
  6990. Any expression of type @code{void *} is allowed.
  6991. @xref{goto Statement}.
  6992. @menu
  6993. * Label Value Uses:: Examples of using label values.
  6994. * Label Value Caveats:: Limitations of label values.
  6995. @end menu
  6996. @node Label Value Uses
  6997. @subsection Label Value Uses
  6998. One use for label-valued constants is to initialize a static array to
  6999. serve as a jump table:
  7000. @example
  7001. static void *array[] = @{ &&foo, &&bar, &&hack @};
  7002. @end example
  7003. Then you can select a label with indexing, like this:
  7004. @example
  7005. goto *array[i];
  7006. @end example
  7007. @noindent
  7008. Note that this does not check whether the subscript is in bounds---array
  7009. indexing in C never checks that.
  7010. You can make the table entries offsets instead of addresses
  7011. by subtracting one label from the others. Here is an example:
  7012. @example
  7013. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  7014. &&hack - &&foo @};
  7015. goto *(&&foo + array[i]);
  7016. @end example
  7017. @noindent
  7018. Using offsets is preferable in shared libraries, as it avoids the need
  7019. for dynamic relocation of the array elements; therefore, the array can
  7020. be read-only.
  7021. An array of label values or offsets serves a purpose much like that of
  7022. the @code{switch} statement. The @code{switch} statement is cleaner,
  7023. so use @code{switch} by preference when feasible.
  7024. Another use of label values is in an interpreter for threaded code.
  7025. The labels within the interpreter function can be stored in the
  7026. threaded code for super-fast dispatching.
  7027. @node Label Value Caveats
  7028. @subsection Label Value Caveats
  7029. Jumping to a label defined in another function does not work.
  7030. It can cause unpredictable results.
  7031. The best way to avoid this is to store label values only in
  7032. automatic variables, or static variables whose names are declared
  7033. within the function. Never pass them as arguments.
  7034. @cindex cloning
  7035. An optimization known as @dfn{cloning} generates multiple simplified
  7036. variants of a function's code, for use with specific fixed arguments.
  7037. Using label values in certain ways, such as saving the address in one
  7038. call to the function and using it again in another call, would make cloning
  7039. give incorrect results. These functions must disable cloning.
  7040. Inlining calls to the function would also result in multiple copies of
  7041. the code, each with its own value of the same label. Using the label
  7042. in a computed goto is no problem, because the computed goto inhibits
  7043. inlining. However, using the label value in some other way, such as
  7044. an indication of where an error occurred, would be optimized wrong.
  7045. These functions must disable inlining.
  7046. To prevent inlining or cloning of a function, specify
  7047. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7048. @xref{Attributes}.
  7049. When a function uses a label value in a static variable initializer,
  7050. that automatically prevents inlining or cloning the function.
  7051. @node Statement Exprs
  7052. @section Statements and Declarations in Expressions
  7053. @cindex statements inside expressions
  7054. @cindex declarations inside expressions
  7055. @cindex expressions containing statements
  7056. @c the above section title wrapped and causes an underfull hbox.. i
  7057. @c changed it from "within" to "in". --mew 4feb93
  7058. A block enclosed in parentheses can be used as an expression in GNU
  7059. C@. This provides a way to use local variables, loops and switches within
  7060. an expression. We call it a @dfn{statement expression}.
  7061. Recall that a block is a sequence of statements
  7062. surrounded by braces. In this construct, parentheses go around the
  7063. braces. For example:
  7064. @example
  7065. (@{ int y = foo (); int z;
  7066. if (y > 0) z = y;
  7067. else z = - y;
  7068. z; @})
  7069. @end example
  7070. @noindent
  7071. is a valid (though slightly more complex than necessary) expression
  7072. for the absolute value of @code{foo ()}.
  7073. The last statement in the block should be an expression statement; an
  7074. expression followed by a semicolon, that is. The value of this
  7075. expression serves as the value of statement expression. If the last
  7076. statement is anything else, the statement expression's value is
  7077. @code{void}.
  7078. This feature is mainly useful in making macro definitions compute each
  7079. operand exactly once. @xref{Macros and Auto Type}.
  7080. Statement expressions are not allowed in expressions that must be
  7081. constant, such as the value for an enumerator, the width of a
  7082. bit-field, or the initial value of a static variable.
  7083. Jumping into a statement expression---with @code{goto}, or using a
  7084. @code{switch} statement outside the statement expression---is an
  7085. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7086. compiler can't detect the error, but it still won't work.
  7087. Jumping out of a statement expression is permitted, but since
  7088. subexpressions in C are not computed in a strict order, it is
  7089. unpredictable which other subexpressions will have been computed by
  7090. then. For example,
  7091. @example
  7092. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7093. @end example
  7094. @noindent
  7095. calls @code{foo} and @code{bar1} before it jumps, and never
  7096. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7097. does get called, that occurs after @code{foo} and before @code{bar1}.
  7098. @node Variables
  7099. @chapter Variables
  7100. @cindex variables
  7101. Every variable used in a C program needs to be made known by a
  7102. @dfn{declaration}. It can be used only after it has been declared.
  7103. It is an error to declare a variable name more than once in the same
  7104. scope; an exception is that @code{extern} declarations and tentative
  7105. definitions can coexist with another declaration of the same
  7106. variable.
  7107. Variables can be declared anywhere within a block or file. (Older
  7108. versions of C required that all variable declarations within a block
  7109. occur before any statements.)
  7110. Variables declared within a function or block are @dfn{local} to
  7111. it. This means that the variable name is visible only until the end
  7112. of that function or block, and the memory space is allocated only
  7113. while control is within it.
  7114. Variables declared at the top level in a file are called @dfn{file-scope}.
  7115. They are assigned fixed, distinct memory locations, so they retain
  7116. their values for the whole execution of the program.
  7117. @menu
  7118. * Variable Declarations:: Name a variable and and reserve space for it.
  7119. * Initializers:: Assigning inital values to variables.
  7120. * Designated Inits:: Assigning initial values to array elements
  7121. at particular array indices.
  7122. * Auto Type:: Obtaining the type of a variable.
  7123. * Local Variables:: Variables declared in function definitions.
  7124. * File-Scope Variables:: Variables declared outside of
  7125. function definitions.
  7126. * Static Local Variables:: Variables declared within functions,
  7127. but with permanent storage allocation.
  7128. * Extern Declarations:: Declaring a variable
  7129. which is allocated somewhere else.
  7130. * Allocating File-Scope:: When is space allocated
  7131. for file-scope variables?
  7132. * auto and register:: Historically used storage directions.
  7133. * Omitting Types:: The bad practice of declaring variables
  7134. with implicit type.
  7135. @end menu
  7136. @node Variable Declarations
  7137. @section Variable Declarations
  7138. @cindex variable declarations
  7139. @cindex declaration of variables
  7140. Here's what a variable declaration looks like:
  7141. @example
  7142. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7143. @end example
  7144. The @var{keywords} specify how to handle the scope of the variable
  7145. name and the allocation of its storage. Most declarations have
  7146. no keywords because the defaults are right for them.
  7147. C allows these keywords to come before or after @var{basetype}, or
  7148. even in the middle of it as in @code{unsigned static int}, but don't
  7149. do that---it would surprise other programmers. Always write the
  7150. keywords first.
  7151. The @var{basetype} can be any of the predefined types of C, or a type
  7152. keyword defined with @code{typedef}. It can also be @code{struct
  7153. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7154. addition, it can include type qualifiers such as @code{const} and
  7155. @code{volatile} (@pxref{Type Qualifiers}).
  7156. In the simplest case, @var{decorated-variable} is just the variable
  7157. name. That declares the variable with the type specified by
  7158. @var{basetype}. For instance,
  7159. @example
  7160. int foo;
  7161. @end example
  7162. @noindent
  7163. uses @code{int} as the @var{basetype} and @code{foo} as the
  7164. @var{decorated-variable}. It declares @code{foo} with type
  7165. @code{int}.
  7166. @example
  7167. struct tree_node foo;
  7168. @end example
  7169. @noindent
  7170. declares @code{foo} with type @code{struct tree_node}.
  7171. @menu
  7172. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7173. array and pointer types.
  7174. * Combining Variable Declarations:: More than one variable declaration
  7175. in a single statement.
  7176. @end menu
  7177. @node Declaring Arrays and Pointers
  7178. @subsection Declaring Arrays and Pointers
  7179. @cindex declaring arrays and pointers
  7180. @cindex array, declaring
  7181. @cindex pointers, declaring
  7182. To declare a variable that is an array, write
  7183. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7184. @example
  7185. int foo[5];
  7186. @end example
  7187. To declare a variable that has a pointer type, write
  7188. @code{*@var{variable}} for @var{decorated-variable}:
  7189. @example
  7190. struct list_elt *foo;
  7191. @end example
  7192. These constructs nest. For instance,
  7193. @example
  7194. int foo[3][5];
  7195. @end example
  7196. @noindent
  7197. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7198. @example
  7199. struct list_elt *foo[5];
  7200. @end example
  7201. @noindent
  7202. declares @code{foo} as an array of 5 pointers to structures, and
  7203. @example
  7204. struct list_elt **foo;
  7205. @end example
  7206. @noindent
  7207. declares @code{foo} as a pointer to a pointer to a structure.
  7208. @example
  7209. int **(*foo[30])(int, double);
  7210. @end example
  7211. @noindent
  7212. declares @code{foo} as an array of 30 pointers to functions
  7213. (@pxref{Function Pointers}), each of which must accept two arguments
  7214. (one @code{int} and one @code{double}) and return type @code{int **}.
  7215. @example
  7216. void
  7217. bar (int size)
  7218. @{
  7219. int foo[size];
  7220. @r{@dots{}}
  7221. @}
  7222. @end example
  7223. @noindent
  7224. declares @code{foo} as an array of integers with a size specified at
  7225. run time when the function @code{bar} is called.
  7226. @node Combining Variable Declarations
  7227. @subsection Combining Variable Declarations
  7228. @cindex combining variable declarations
  7229. @cindex variable declarations, combining
  7230. @cindex declarations, combining
  7231. When multiple declarations have the same @var{keywords} and
  7232. @var{basetype}, you can combine them using commas. Thus,
  7233. @example
  7234. @var{keywords} @var{basetype}
  7235. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7236. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7237. @end example
  7238. @noindent
  7239. is equivalent to
  7240. @example
  7241. @var{keywords} @var{basetype}
  7242. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7243. @var{keywords} @var{basetype}
  7244. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7245. @end example
  7246. Here are some simple examples:
  7247. @example
  7248. int a, b;
  7249. int a = 1, b = 2;
  7250. int a, *p, array[5];
  7251. int a = 0, *p = &a, array[5] = @{1, 2@};
  7252. @end example
  7253. @noindent
  7254. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7255. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7256. Since the initializer for @code{array} specifies only two elements,
  7257. the other three elements are initialized to zero.
  7258. @node Initializers
  7259. @section Initializers
  7260. @cindex initializers
  7261. A variable's declaration, unless it is @code{extern}, should also
  7262. specify its initial value. For numeric and pointer-type variables,
  7263. the initializer is an expression for the value. If necessary, it is
  7264. converted to the variable's type, just as in an assignment.
  7265. You can also initialize a local structure-type (@pxref{Structures}) or
  7266. local union-type (@pxref{Unions}) variable this way, from an
  7267. expression whose value has the same type. But you can't initialize an
  7268. array this way (@pxref{Arrays}), since arrays are not first-class
  7269. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7270. assignment.
  7271. You can initialize arrays and structures componentwise,
  7272. with a list of the elements or components. You can initialize
  7273. a union with any one of its alternatives.
  7274. @itemize @bullet
  7275. @item
  7276. A component-wise initializer for an array consists of element values
  7277. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7278. don't cover all the elements in the array, the remaining elements are
  7279. initialized to zero.
  7280. You can omit the size of the array when you declare it, and let
  7281. the initializer specify the size:
  7282. @example
  7283. int array[] = @{ 3, 9, 12 @};
  7284. @end example
  7285. @item
  7286. A component-wise initializer for a structure consists of field values
  7287. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7288. order as the fields are declared in the structure. If the values in
  7289. the initializer don't cover all the fields in the structure, the
  7290. remaining fields are initialized to zero.
  7291. @item
  7292. The initializer for a union-type variable has the form @code{@{
  7293. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7294. in the union definition.
  7295. @end itemize
  7296. For an array of arrays, a structure containing arrays, an array of
  7297. structures, etc., you can nest these constructs. For example,
  7298. @example
  7299. struct point @{ double x, y; @};
  7300. struct point series[]
  7301. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7302. @end example
  7303. You can omit a pair of inner braces if they contain the right
  7304. number of elements for the sub-value they initialize, so that
  7305. no elements or fields need to be filled in with zeros.
  7306. But don't do that very much, as it gets confusing.
  7307. An array of @code{char} can be initialized using a string constant.
  7308. Recall that the string constant includes an implicit null character at
  7309. the end (@pxref{String Constants}). Using a string constant as
  7310. initializer means to use its contents as the initial values of the
  7311. array elements. Here are examples:
  7312. @example
  7313. char text[6] = "text!"; /* @r{Includes the null.} */
  7314. char text[5] = "text!"; /* @r{Excludes the null.} */
  7315. char text[] = "text!"; /* @r{Gets length 6.} */
  7316. char text[]
  7317. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7318. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7319. @end example
  7320. @noindent
  7321. and this kind of initializer can be nested inside braces to initialize
  7322. structures or arrays that contain a @code{char}-array.
  7323. In like manner, you can use a wide string constant to initialize
  7324. an array of @code{wchar_t}.
  7325. @node Designated Inits
  7326. @section Designated Initializers
  7327. @cindex initializers with labeled elements
  7328. @cindex labeled elements in initializers
  7329. @cindex case labels in initializers
  7330. @cindex designated initializers
  7331. In a complex structure or long array, it's useful to indicate
  7332. which field or element we are initializing.
  7333. To designate specific array elements during initialization, include
  7334. the array index in brackets, and an assignment operator, for each
  7335. element:
  7336. @example
  7337. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7338. @end example
  7339. @noindent
  7340. This does the same thing as:
  7341. @example
  7342. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7343. @end example
  7344. The array initialization can include non-designated element values
  7345. alongside designated indices; these follow the expected ordering
  7346. of the array initialization, so that
  7347. @example
  7348. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7349. @end example
  7350. @noindent
  7351. does the same thing as:
  7352. @example
  7353. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7354. @end example
  7355. Note that you can only use constant expressions as array index values,
  7356. not variables.
  7357. If you need to initialize a subsequence of sequential array elements to
  7358. the same value, you can specify a range:
  7359. @example
  7360. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7361. @end example
  7362. @noindent
  7363. Using a range this way is a GNU C extension.
  7364. When subsequence ranges overlap, each element is initialized by the
  7365. last specification that applies to it. Thus, this initialization is
  7366. equivalent to the previous one.
  7367. @example
  7368. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7369. @end example
  7370. @noindent
  7371. as the second overrides the first for elements 0 through 19.
  7372. The value used to initialize a range of elements is evaluated only
  7373. once, for the first element in the range. So for example, this code
  7374. @example
  7375. int random_values[100]
  7376. = @{ [0 ... 99] = get_random_number() @};
  7377. @end example
  7378. @noindent
  7379. would initialize all 100 elements of the array @code{random_values} to
  7380. the same value---probably not what is intended.
  7381. Similarly, you can initialize specific fields of a structure variable
  7382. by specifying the field name prefixed with a dot:
  7383. @example
  7384. struct point @{ int x; int y; @};
  7385. struct point foo = @{ .y = 42; @};
  7386. @end example
  7387. @noindent
  7388. The same syntax works for union variables as well:
  7389. @example
  7390. union int_double @{ int i; double d; @};
  7391. union int_double foo = @{ .d = 34 @};
  7392. @end example
  7393. @noindent
  7394. This casts the integer value 34 to a double and stores it
  7395. in the union variable @code{foo}.
  7396. You can designate both array elements and structure elements in
  7397. the same initialization; for example, here's an array of point
  7398. structures:
  7399. @example
  7400. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7401. @end example
  7402. Along with the capability to specify particular array and structure
  7403. elements to initialize comes the possibility of initializing the same
  7404. element more than once:
  7405. @example
  7406. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7407. @end example
  7408. @noindent
  7409. In such a case, the last initialization value is retained.
  7410. @node Auto Type
  7411. @section Referring to a Type with @code{__auto_type}
  7412. @findex __auto_type
  7413. @findex typeof
  7414. @cindex macros, types of arguments
  7415. You can declare a variable copying the type from
  7416. the initializer by using @code{__auto_type} instead of a particular type.
  7417. Here's an example:
  7418. @example
  7419. #define max(a,b) \
  7420. (@{ __auto_type _a = (a); \
  7421. __auto_type _b = (b); \
  7422. _a > _b ? _a : _b @})
  7423. @end example
  7424. This defines @code{_a} to be of the same type as @code{a}, and
  7425. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7426. to do in a macro that ought to be able to handle any type of data
  7427. (@pxref{Macros and Auto Type}).
  7428. The original GNU C method for obtaining the type of a value is to use
  7429. @code{typeof}, which takes as an argument either a value or the name of
  7430. a type. The previous example could also be written as:
  7431. @example
  7432. #define max(a,b) \
  7433. (@{ typeof(a) _a = (a); \
  7434. typeof(b) _b = (b); \
  7435. _a > _b ? _a : _b @})
  7436. @end example
  7437. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7438. principal use case for @code{typeof} is in variable declarations with
  7439. initialization, which is exactly what @code{__auto_type} handles.
  7440. @node Local Variables
  7441. @section Local Variables
  7442. @cindex local variables
  7443. @cindex variables, local
  7444. Declaring a variable inside a function definition (@pxref{Function
  7445. Definitions}) makes the variable name @dfn{local} to the containing
  7446. block---that is, the containing pair of braces. More precisely, the
  7447. variable's name is visible starting just after where it appears in the
  7448. declaration, and its visibility continues until the end of the block.
  7449. Local variables in C are generally @dfn{automatic} variables: each
  7450. variable's storage exists only from the declaration to the end of the
  7451. block. Execution of the declaration allocates the storage, computes
  7452. the initial value, and stores it in the variable. The end of the
  7453. block deallocates the storage.@footnote{Due to compiler optimizations,
  7454. allocation and deallocation don't necessarily really happen at
  7455. those times.}
  7456. @strong{Warning:} Two declarations for the same local variable
  7457. in the same scope are an error.
  7458. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7459. The total space for the program's stack may be limited; therefore,
  7460. in using very large arrays, it may be necessary to allocate
  7461. them in some other way to stop the program from crashing.
  7462. @strong{Warning:} If the declaration of an automatic variable does not
  7463. specify an initial value, the variable starts out containing garbage.
  7464. In this example, the value printed could be anything at all:
  7465. @example
  7466. @{
  7467. int i;
  7468. printf ("Print junk %d\n", i);
  7469. @}
  7470. @end example
  7471. In a simple test program, that statement is likely to print 0, simply
  7472. because every process starts with memory zeroed. But don't rely on it
  7473. to be zero---that is erroneous.
  7474. @strong{Note:} Make sure to store a value into each local variable (by
  7475. assignment, or by initialization) before referring to its value.
  7476. @node File-Scope Variables
  7477. @section File-Scope Variables
  7478. @cindex file-scope variables
  7479. @cindex global variables
  7480. @cindex variables, file-scope
  7481. @cindex variables, global
  7482. A variable declaration at the top level in a file (not inside a
  7483. function definition) declares a @dfn{file-scope variable}. Loading a
  7484. program allocates the storage for all the file-scope variables in it,
  7485. and initializes them too.
  7486. Each file-scope variable is either @dfn{static} (limited to one
  7487. compilation module) or @dfn{global} (shared with all compilation
  7488. modules in the program). To make the variable static, write the
  7489. keyword @code{static} at the start of the declaration. Omitting
  7490. @code{static} makes the variable global.
  7491. The initial value for a file-scope variable can't depend on the
  7492. contents of storage, and can't call any functions.
  7493. @example
  7494. int foo = 5; /* @r{Valid.} */
  7495. int bar = foo; /* @r{Invalid!} */
  7496. int bar = sin (1.0); /* @r{Invalid!} */
  7497. @end example
  7498. But it can use the address of another file-scope variable:
  7499. @example
  7500. int foo;
  7501. int *bar = &foo; /* @r{Valid.} */
  7502. int arr[5];
  7503. int *bar3 = &arr[3]; /* @r{Valid.} */
  7504. int *bar4 = arr + 4; /* @r{Valid.} */
  7505. @end example
  7506. It is valid for a module to have multiple declarations for a
  7507. file-scope variable, as long as they are all global or all static, but
  7508. at most one declaration can specify an initial value for it.
  7509. @node Static Local Variables
  7510. @section Static Local Variables
  7511. @cindex static local variables
  7512. @cindex variables, static local
  7513. @findex static
  7514. The keyword @code{static} in a local variable declaration says to
  7515. allocate the storage for the variable permanently, just like a
  7516. file-scope variable, even if the declaration is within a function.
  7517. Here's an example:
  7518. @example
  7519. int
  7520. increment_counter ()
  7521. @{
  7522. static int counter = 0;
  7523. return ++counter;
  7524. @}
  7525. @end example
  7526. The scope of the name @code{counter} runs from the declaration to the
  7527. end of the containing block, just like an automatic local variable,
  7528. but its storage is permanent, so the value persists from one call to
  7529. the next. As a result, each call to @code{increment_counter}
  7530. returns a different, unique value.
  7531. The initial value of a static local variable has the same limitations
  7532. as for file-scope variables: it can't depend on the contents of
  7533. storage or call any functions. It can use the address of a file-scope
  7534. variable or a static local variable, because those addresses are
  7535. determined before the program runs.
  7536. @node Extern Declarations
  7537. @section @code{extern} Declarations
  7538. @cindex @code{extern} declarations
  7539. @cindex declarations, @code{extern}
  7540. @findex extern
  7541. An @code{extern} declaration is used to refer to a global variable
  7542. whose principal declaration comes elsewhere---in the same module, or in
  7543. another compilation module. It looks like this:
  7544. @example
  7545. extern @var{basetype} @var{decorated-variable};
  7546. @end example
  7547. Its meaning is that, in the current scope, the variable name refers to
  7548. the file-scope variable of that name---which needs to be declared in a
  7549. non-@code{extern}, non-@code{static} way somewhere else.
  7550. For instance, if one compilation module has this global variable
  7551. declaration
  7552. @example
  7553. int error_count = 0;
  7554. @end example
  7555. @noindent
  7556. then other compilation modules can specify this
  7557. @example
  7558. extern int error_count;
  7559. @end example
  7560. @noindent
  7561. to allow reference to the same variable.
  7562. The usual place to write an @code{extern} declaration is at top level
  7563. in a source file, but you can write an @code{extern} declaration
  7564. inside a block to make a global or static file-scope variable
  7565. accessible in that block.
  7566. Since an @code{extern} declaration does not allocate space for the
  7567. variable, it can omit the size of an array:
  7568. @example
  7569. extern int array[];
  7570. @end example
  7571. You can use @code{array} normally in all contexts where it is
  7572. converted automatically to a pointer. However, to use it as the
  7573. operand of @code{sizeof} is an error, since the size is unknown.
  7574. It is valid to have multiple @code{extern} declarations for the same
  7575. variable, even in the same scope, if they give the same type. They do
  7576. not conflict---they agree. For an array, it is legitimate for some
  7577. @code{extern} declarations can specify the size while others omit it.
  7578. However, if two declarations give different sizes, that is an error.
  7579. Likewise, you can use @code{extern} declarations at file scope
  7580. (@pxref{File-Scope Variables}) followed by an ordinary global
  7581. (non-static) declaration of the same variable. They do not conflict,
  7582. because they say compatible things about the same meaning of the variable.
  7583. @node Allocating File-Scope
  7584. @section Allocating File-Scope Variables
  7585. @cindex allocation file-scope variables
  7586. @cindex file-scope variables, allocating
  7587. Some file-scope declarations allocate space for the variable, and some
  7588. don't.
  7589. A file-scope declaration with an initial value @emph{must} allocate
  7590. space for the variable; if there are two of such declarations for the
  7591. same variable, even in different compilation modules, they conflict.
  7592. An @code{extern} declaration @emph{never} allocates space for the variable.
  7593. If all the top-level declarations of a certain variable are
  7594. @code{extern}, the variable never gets memory space. If that variable
  7595. is used anywhere in the program, the use will be reported as an error,
  7596. saying that the variable is not defined.
  7597. @cindex tentative definition
  7598. A file-scope declaration without an initial value is called a
  7599. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7600. allocate space for the variable, but does not insist. So it causes no
  7601. conflict, no error, if the variable has another declaration that
  7602. allocates space for it, perhaps in another compilation module. But if
  7603. nothing else allocates space for the variable, the tentative
  7604. definition will do it. Any number of compilation modules can declare
  7605. the same variable in this way, and that is sufficient for all of them
  7606. to use the variable.
  7607. @c @opindex -fno-common
  7608. @c @opindex --warn_common
  7609. In programs that are very large or have many contributors, it may be
  7610. wise to adopt the convention of never using tentative definitions.
  7611. You can use the compilation option @option{-fno-common} to make them
  7612. an error, or @option{--warn-common} to warn about them.
  7613. If a file-scope variable gets its space through a tentative
  7614. definition, it starts out containing all zeros.
  7615. @node auto and register
  7616. @section @code{auto} and @code{register}
  7617. @cindex @code{auto} declarations
  7618. @cindex @code{register} declarations
  7619. @findex auto
  7620. @findex register
  7621. For historical reasons, you can write @code{auto} or @code{register}
  7622. before a local variable declaration. @code{auto} merely emphasizes
  7623. that the variable isn't static; it changes nothing.
  7624. @code{register} suggests to the compiler storing this variable in a
  7625. register. However, GNU C ignores this suggestion, since it can
  7626. choose the best variables to store in registers without any hints.
  7627. It is an error to take the address of a variable declared
  7628. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7629. If the variable is an array, you can't use it at all (other than as
  7630. the operand of @code{sizeof}), which makes it rather useless.
  7631. @node Omitting Types
  7632. @section Omitting Types in Declarations
  7633. @cindex omitting types in declarations
  7634. The syntax of C traditionally allows omitting the data type in a
  7635. declaration if it specifies a storage class, a type qualifier (see the
  7636. next chapter), or @code{auto} or @code{register}. Then the type
  7637. defaults to @code{int}. For example:
  7638. @example
  7639. auto foo = 42;
  7640. @end example
  7641. This is bad practice; if you see it, fix it.
  7642. @node Type Qualifiers
  7643. @chapter Type Qualifiers
  7644. A declaration can include type qualifiers to advise the compiler
  7645. about how the variable will be used. There are three different
  7646. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7647. pertain to different issues, so you can use more than one together.
  7648. For instance, @code{const volatile} describes a value that the
  7649. program is not allowed to change, but might have a different value
  7650. each time the program examines it. (This might perhaps be a special
  7651. hardware register, or part of shared memory.)
  7652. If you are just learning C, you can skip this chapter.
  7653. @menu
  7654. * const:: Variables whose values don't change.
  7655. * volatile:: Variables whose values may be accessed
  7656. or changed outside of the control of
  7657. this program.
  7658. * restrict Pointers:: Restricted pointers for code optimization.
  7659. * restrict Pointer Example:: Example of how that works.
  7660. @end menu
  7661. @node const
  7662. @section @code{const} Variables and Fields
  7663. @cindex @code{const} variables and fields
  7664. @cindex variables, @code{const}
  7665. @findex const
  7666. You can mark a variable as ``constant'' by writing @code{const} in
  7667. front of the declaration. This says to treat any assignment to that
  7668. variable as an error. It may also permit some compiler
  7669. optimizations---for instance, to fetch the value only once to satisfy
  7670. multiple references to it. The construct looks like this:
  7671. @example
  7672. const double pi = 3.14159;
  7673. @end example
  7674. After this definition, the code can use the variable @code{pi}
  7675. but cannot assign a different value to it.
  7676. @example
  7677. pi = 3.0; /* @r{Error!} */
  7678. @end example
  7679. Simple variables that are constant can be used for the same purposes
  7680. as enumeration constants, and they are not limited to integers. The
  7681. constantness of the variable propagates into pointers, too.
  7682. A pointer type can specify that the @emph{target} is constant. For
  7683. example, the pointer type @code{const double *} stands for a pointer
  7684. to a constant @code{double}. That's the type that results from taking
  7685. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7686. left side of an assignment.
  7687. @example
  7688. *(&pi) = 3.0; /* @r{Error!} */
  7689. @end example
  7690. Nonconstant pointers can be converted automatically to constant
  7691. pointers, but not vice versa. For instance,
  7692. @example
  7693. const double *cptr;
  7694. double *ptr;
  7695. cptr = &pi; /* @r{Valid.} */
  7696. cptr = ptr; /* @r{Valid.} */
  7697. ptr = cptr; /* @r{Error!} */
  7698. ptr = &pi; /* @r{Error!} */
  7699. @end example
  7700. This is not an ironclad protection against modifying the value. You
  7701. can always cast the constant pointer to a nonconstant pointer type:
  7702. @example
  7703. ptr = (double *)cptr; /* @r{Valid.} */
  7704. ptr = (double *)&pi; /* @r{Valid.} */
  7705. @end example
  7706. However, @code{const} provides a way to show that a certain function
  7707. won't modify the data structure whose address is passed to it. Here's
  7708. an example:
  7709. @example
  7710. int
  7711. string_length (const char *string)
  7712. @{
  7713. int count = 0;
  7714. while (*string++)
  7715. count++;
  7716. return count;
  7717. @}
  7718. @end example
  7719. @noindent
  7720. Using @code{const char *} for the parameter is a way of saying this
  7721. function never modifies the memory of the string itself.
  7722. In calling @code{string_length}, you can specify an ordinary
  7723. @code{char *} since that can be converted automatically to @code{const
  7724. char *}.
  7725. @node volatile
  7726. @section @code{volatile} Variables and Fields
  7727. @cindex @code{volatile} variables and fields
  7728. @cindex variables, @code{volatile}
  7729. @findex volatile
  7730. The GNU C compiler often performs optimizations that eliminate the
  7731. need to write or read a variable. For instance,
  7732. @example
  7733. int foo;
  7734. foo = 1;
  7735. foo++;
  7736. @end example
  7737. @noindent
  7738. might simply store the value 2 into @code{foo}, without ever storing 1.
  7739. These optimizations can also apply to structure fields in some cases.
  7740. If the memory containing @code{foo} is shared with another program,
  7741. or if it is examined asynchronously by hardware, such optimizations
  7742. could confuse the communication. Using @code{volatile} is one way
  7743. to prevent them.
  7744. Writing @code{volatile} with the type in a variable or field declaration
  7745. says that the value may be examined or changed for reasons outside the
  7746. control of the program at any moment. Therefore, the program must
  7747. execute in a careful way to assure correct interaction with those
  7748. accesses, whenever they may occur.
  7749. The simplest use looks like this:
  7750. @example
  7751. volatile int lock;
  7752. @end example
  7753. This directs the compiler not to do certain common optimizations on
  7754. use of the variable @code{lock}. All the reads and writes for a volatile
  7755. variable or field are really done, and done in the order specified
  7756. by the source code. Thus, this code:
  7757. @example
  7758. lock = 1;
  7759. list = list->next;
  7760. if (lock)
  7761. lock_broken (&lock);
  7762. lock = 0;
  7763. @end example
  7764. @noindent
  7765. really stores the value 1 in @code{lock}, even though there is no
  7766. sign it is really used, and the @code{if} statement reads and
  7767. checks the value of @code{lock}, rather than assuming it is still 1.
  7768. A limited amount of optimization can be done, in principle, on
  7769. @code{volatile} variables and fields: multiple references between two
  7770. sequence points (@pxref{Sequence Points}) can be simplified together.
  7771. Use of @code{volatile} does not eliminate the flexibility in ordering
  7772. the computation of the operands of most operators. For instance, in
  7773. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7774. @code{foo} is not specified, so they may be done in either order; the
  7775. fact that @code{lock} is @code{volatile} has no effect on that.
  7776. @node restrict Pointers
  7777. @section @code{restrict}-Qualified Pointers
  7778. @cindex @code{restrict} pointers
  7779. @cindex pointers, @code{restrict}-qualified
  7780. @findex restrict
  7781. You can declare a pointer as ``restricted'' using the @code{restrict}
  7782. type qualifier, like this:
  7783. @example
  7784. int *restrict p = x;
  7785. @end example
  7786. @noindent
  7787. This enables better optimization of code that uses the pointer.
  7788. If @code{p} is declared with @code{restrict}, and then the code
  7789. references the object that @code{p} points to (using @code{*p} or
  7790. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7791. code will not access that object in any other way---only through
  7792. @code{p}.
  7793. For instance, it means the code must not use another pointer
  7794. to access the same space, as shown here:
  7795. @example
  7796. int *restrict p = @var{whatever};
  7797. int *q = p;
  7798. foo (*p, *q);
  7799. @end example
  7800. @noindent
  7801. That contradicts the @code{restrict} promise by accessing the object
  7802. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7803. Likewise, it must not do this:
  7804. @example
  7805. int *restrict p = @var{whatever};
  7806. struct @{ int *a, *b; @} s;
  7807. s.a = p;
  7808. foo (*p, *s.a);
  7809. @end example
  7810. @noindent
  7811. This example uses a structure field instead of the variable @code{q}
  7812. to hold the other pointer, and that contradicts the promise just the
  7813. same.
  7814. The keyword @code{restrict} also promises that @code{p} won't point to
  7815. the allocated space of any automatic or static variable. So the code
  7816. must not do this:
  7817. @example
  7818. int a;
  7819. int *restrict p = &a;
  7820. foo (*p, a);
  7821. @end example
  7822. @noindent
  7823. because that does direct access to the object (@code{a}) that @code{p}
  7824. points to, which bypasses @code{p}.
  7825. If the code makes such promises with @code{restrict} then breaks them,
  7826. execution is unpredictable.
  7827. @node restrict Pointer Example
  7828. @section @code{restrict} Pointer Example
  7829. Here are examples where @code{restrict} enables real optimization.
  7830. In this example, @code{restrict} assures GCC that the array @code{out}
  7831. points to does not overlap with the array @code{in} points to.
  7832. @example
  7833. void
  7834. process_data (const char *in,
  7835. char * restrict out,
  7836. size_t size)
  7837. @{
  7838. for (i = 0; i < size; i++)
  7839. out[i] = in[i] + in[i + 1];
  7840. @}
  7841. @end example
  7842. Here's a simple tree structure, where each tree node holds data of
  7843. type @code{PAYLOAD} plus two subtrees.
  7844. @example
  7845. struct foo
  7846. @{
  7847. PAYLOAD payload;
  7848. struct foo *left;
  7849. struct foo *right;
  7850. @};
  7851. @end example
  7852. Now here's a function to null out both pointers in the @code{left}
  7853. subtree.
  7854. @example
  7855. void
  7856. null_left (struct foo *a)
  7857. @{
  7858. a->left->left = NULL;
  7859. a->left->right = NULL;
  7860. @}
  7861. @end example
  7862. Since @code{*a} and @code{*a->left} have the same data type,
  7863. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7864. the compiled code for @code{null_left} must read @code{a->left}
  7865. again from memory when executing the second assignment statement.
  7866. We can enable optimization, so that it does not need to read
  7867. @code{a->left} again, by writing @code{null_left} in a less
  7868. obvious way.
  7869. @example
  7870. void
  7871. null_left (struct foo *a)
  7872. @{
  7873. struct foo *b = a->left;
  7874. b->left = NULL;
  7875. b->right = NULL;
  7876. @}
  7877. @end example
  7878. A more elegant way to fix this is with @code{restrict}.
  7879. @example
  7880. void
  7881. null_left (struct foo *restrict a)
  7882. @{
  7883. a->left->left = NULL;
  7884. a->left->right = NULL;
  7885. @}
  7886. @end example
  7887. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7888. as @code{a->left} will not point to the same memory space as @code{a}.
  7889. Therefore, the memory location @code{a->left->left} cannot be the same
  7890. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7891. reloading @code{a->left} for the second statement.
  7892. @node Functions
  7893. @chapter Functions
  7894. @cindex functions
  7895. We have already presented many examples of functions, so if you've
  7896. read this far, you basically understand the concept of a function. It
  7897. is vital, nonetheless, to have a chapter in the manual that collects
  7898. all the information about functions.
  7899. @menu
  7900. * Function Definitions:: Writing the body of a function.
  7901. * Function Declarations:: Declaring the interface of a function.
  7902. * Function Calls:: Using functions.
  7903. * Function Call Semantics:: Call-by-value argument passing.
  7904. * Function Pointers:: Using references to functions.
  7905. * The main Function:: Where execution of a GNU C program begins.
  7906. * Advanced Definitions:: Advanced features of function definitions.
  7907. * Obsolete Definitions:: Obsolete features still used
  7908. in function definitions in old code.
  7909. @end menu
  7910. @node Function Definitions
  7911. @section Function Definitions
  7912. @cindex function definitions
  7913. @cindex defining functions
  7914. We have already presented many examples of function definitions. To
  7915. summarize the rules, a function definition looks like this:
  7916. @example
  7917. @var{returntype}
  7918. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7919. @{
  7920. @var{body}
  7921. @}
  7922. @end example
  7923. The part before the open-brace is called the @dfn{function header}.
  7924. Write @code{void} as the @var{returntype} if the function does
  7925. not return a value.
  7926. @menu
  7927. * Function Parameter Variables:: Syntax and semantics
  7928. of function parameters.
  7929. * Forward Function Declarations:: Functions can only be called after
  7930. they have been defined or declared.
  7931. * Static Functions:: Limiting visibility of a function.
  7932. * Arrays as Parameters:: Functions that accept array arguments.
  7933. * Structs as Parameters:: Functions that accept structure arguments.
  7934. @end menu
  7935. @node Function Parameter Variables
  7936. @subsection Function Parameter Variables
  7937. @cindex function parameter variables
  7938. @cindex parameter variables in functions
  7939. @cindex parameter list
  7940. A function parameter variable is a local variable (@pxref{Local
  7941. Variables}) used within the function to store the value passed as an
  7942. argument in a call to the function. Usually we say ``function
  7943. parameter'' or ``parameter'' for short, not mentioning the fact that
  7944. it's a variable.
  7945. We declare these variables in the beginning of the function
  7946. definition, in the @dfn{parameter list}. For example,
  7947. @example
  7948. fib (int n)
  7949. @end example
  7950. @noindent
  7951. has a parameter list with one function parameter @code{n}, which has
  7952. type @code{int}.
  7953. Function parameter declarations differ from ordinary variable
  7954. declarations in several ways:
  7955. @itemize @bullet
  7956. @item
  7957. Inside the function definition header, commas separate parameter
  7958. declarations, and each parameter needs a complete declaration
  7959. including the type. For instance, if a function @code{foo} has two
  7960. @code{int} parameters, write this:
  7961. @example
  7962. foo (int a, int b)
  7963. @end example
  7964. You can't share the common @code{int} between the two declarations:
  7965. @example
  7966. foo (int a, b) /* @r{Invalid!} */
  7967. @end example
  7968. @item
  7969. A function parameter variable is initialized to whatever value is
  7970. passed in the function call, so its declaration cannot specify an
  7971. initial value.
  7972. @item
  7973. Writing an array type in a function parameter declaration has the
  7974. effect of declaring it as a pointer. The size specified for the array
  7975. has no effect at all, and we normally omit the size. Thus,
  7976. @example
  7977. foo (int a[5])
  7978. foo (int a[])
  7979. foo (int *a)
  7980. @end example
  7981. @noindent
  7982. are equivalent.
  7983. @item
  7984. The scope of the parameter variables is the entire function body,
  7985. notwithstanding the fact that they are written in the function header,
  7986. which is just outside the function body.
  7987. @end itemize
  7988. If a function has no parameters, it would be most natural for the
  7989. list of parameters in its definition to be empty. But that, in C, has
  7990. a special meaning for historical reasons: ``Do not check that calls to
  7991. this function have the right number of arguments.'' Thus,
  7992. @example
  7993. int
  7994. foo ()
  7995. @{
  7996. return 5;
  7997. @}
  7998. int
  7999. bar (int x)
  8000. @{
  8001. return foo (x);
  8002. @}
  8003. @end example
  8004. @noindent
  8005. would not report a compilation error in passing @code{x} as an
  8006. argument to @code{foo}. By contrast,
  8007. @example
  8008. int
  8009. foo (void)
  8010. @{
  8011. return 5;
  8012. @}
  8013. int
  8014. bar (int x)
  8015. @{
  8016. return foo (x);
  8017. @}
  8018. @end example
  8019. @noindent
  8020. would report an error because @code{foo} is supposed to receive
  8021. no arguments.
  8022. @node Forward Function Declarations
  8023. @subsection Forward Function Declarations
  8024. @cindex forward function declarations
  8025. @cindex function declarations, forward
  8026. The order of the function definitions in the source code makes no
  8027. difference, except that each function needs to be defined or declared
  8028. before code uses it.
  8029. The definition of a function also declares its name for the rest of
  8030. the containing scope. But what if you want to call the function
  8031. before its definition? To permit that, write a compatible declaration
  8032. of the same function, before the first call. A declaration that
  8033. prefigures a subsequent definition in this way is called a
  8034. @dfn{forward declaration}. The function declaration can be at top
  8035. @c ??? file scope
  8036. level or within a block, and it applies until the end of the containing
  8037. scope.
  8038. @xref{Function Declarations}, for more information about these
  8039. declarations.
  8040. @node Static Functions
  8041. @subsection Static Functions
  8042. @cindex static functions
  8043. @cindex functions, static
  8044. @findex static
  8045. The keyword @code{static} in a function definition limits the
  8046. visibility of the name to the current compilation module. (That's the
  8047. same thing @code{static} does in variable declarations;
  8048. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8049. contains this code:
  8050. @example
  8051. static int
  8052. foo (void)
  8053. @{
  8054. @r{@dots{}}
  8055. @}
  8056. @end example
  8057. @noindent
  8058. then the code of that compilation module can call @code{foo} anywhere
  8059. after the definition, but other compilation modules cannot refer to it
  8060. at all.
  8061. @cindex forward declaration
  8062. @cindex static function, declaration
  8063. To call @code{foo} before its definition, it needs a forward
  8064. declaration, which should use @code{static} since the function
  8065. definition does. For this function, it looks like this:
  8066. @example
  8067. static int foo (void);
  8068. @end example
  8069. It is generally wise to use @code{static} on the definitions of
  8070. functions that won't be called from outside the same compilation
  8071. module. This makes sure that calls are not added in other modules.
  8072. If programmers decide to change the function's calling convention, or
  8073. understand all the consequences of its use, they will only have to
  8074. check for calls in the same compilation module.
  8075. @node Arrays as Parameters
  8076. @subsection Arrays as Parameters
  8077. @cindex array as parameters
  8078. @cindex functions with array parameters
  8079. Arrays in C are not first-class objects: it is impossible to copy
  8080. them. So they cannot be passed as arguments like other values.
  8081. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8082. a special way.
  8083. @menu
  8084. * Array Parm Pointer::
  8085. * Passing Array Args::
  8086. * Array Parm Qualifiers::
  8087. @end menu
  8088. @node Array Parm Pointer
  8089. @subsubsection Array parameters are pointers
  8090. Declaring a function parameter variable as an array really gives it a
  8091. pointer type. C does this because an expression with array type, if
  8092. used as an argument in a function call, is converted automatically to
  8093. a pointer (to the zeroth element of the array). If you declare the
  8094. corresponding parameter as an ``array'', it will work correctly with
  8095. the pointer value that really gets passed.
  8096. This relates to the fact that C does not check array bounds in access
  8097. to elements of the array (@pxref{Accessing Array Elements}).
  8098. For example, in this function,
  8099. @example
  8100. void
  8101. clobber4 (int array[20])
  8102. @{
  8103. array[4] = 0;
  8104. @}
  8105. @end example
  8106. @noindent
  8107. the parameter @code{array}'s real type is @code{int *}; the specified
  8108. length, 20, has no effect on the program. You can leave out the length
  8109. and write this:
  8110. @example
  8111. void
  8112. clobber4 (int array[])
  8113. @{
  8114. array[4] = 0;
  8115. @}
  8116. @end example
  8117. @noindent
  8118. or write the parameter declaration explicitly as a pointer:
  8119. @example
  8120. void
  8121. clobber4 (int *array)
  8122. @{
  8123. array[4] = 0;
  8124. @}
  8125. @end example
  8126. They are all equivalent.
  8127. @node Passing Array Args
  8128. @subsubsection Passing array arguments
  8129. The function call passes this pointer by
  8130. value, like all argument values in C@. However, the result is
  8131. paradoxical in that the array itself is passed by reference: its
  8132. contents are treated as shared memory---shared between the caller and
  8133. the called function, that is. When @code{clobber4} assigns to element
  8134. 4 of @code{array}, the effect is to alter element 4 of the array
  8135. specified in the call.
  8136. @example
  8137. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8138. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8139. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8140. int
  8141. main (void)
  8142. @{
  8143. int data[] = @{1, 2, 3, 4, 5, 6@};
  8144. int i;
  8145. /* @r{Show the initial value of element 4.} */
  8146. for (i = 0; i < 6; i++)
  8147. printf ("data[%d] = %d\n", i, data[i]);
  8148. printf ("\n");
  8149. clobber4 (data);
  8150. /* @r{Show that element 4 has been changed.} */
  8151. for (i = 0; i < 6; i++)
  8152. printf ("data[%d] = %d\n", i, data[i]);
  8153. printf ("\n");
  8154. return EXIT_SUCCESS;
  8155. @}
  8156. @end example
  8157. @noindent
  8158. shows that @code{data[4]} has become zero after the call to
  8159. @code{clobber4}.
  8160. The array @code{data} has 6 elements, but passing it to a function
  8161. whose argument type is written as @code{int [20]} is not an error,
  8162. because that really stands for @code{int *}. The pointer that is the
  8163. real argument carries no indication of the length of the array it
  8164. points into. It is not required to point to the beginning of the
  8165. array, either. For instance,
  8166. @example
  8167. clobber4 (data+1);
  8168. @end example
  8169. @noindent
  8170. passes an ``array'' that starts at element 1 of @code{data}, and the
  8171. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8172. If all calls to the function will provide an array of a particular
  8173. size, you can specify the size of the array to be @code{static}:
  8174. @example
  8175. void
  8176. clobber4 (int array[static 20])
  8177. @r{@dots{}}
  8178. @end example
  8179. @noindent
  8180. This is a promise to the compiler that the function will always be
  8181. called with an array of 20 elements, so that the compiler can optimize
  8182. code accordingly. If the code breaks this promise and calls the
  8183. function with, for example, a shorter array, unpredictable things may
  8184. happen.
  8185. @node Array Parm Qualifiers
  8186. @subsubsection Type qualifiers on array parameters
  8187. You can use the type qualifiers @code{const}, @code{restrict}, and
  8188. @code{volatile} with array parameters; for example:
  8189. @example
  8190. void
  8191. clobber4 (volatile int array[20])
  8192. @r{@dots{}}
  8193. @end example
  8194. @noindent
  8195. denotes that @code{array} is equivalent to a pointer to a volatile
  8196. @code{int}. Alternatively:
  8197. @example
  8198. void
  8199. clobber4 (int array[const 20])
  8200. @r{@dots{}}
  8201. @end example
  8202. @noindent
  8203. makes the array parameter equivalent to a constant pointer to an
  8204. @code{int}. If we want the @code{clobber4} function to succeed, it
  8205. would not make sense to write
  8206. @example
  8207. void
  8208. clobber4 (const int array[20])
  8209. @r{@dots{}}
  8210. @end example
  8211. @noindent
  8212. as this would tell the compiler that the parameter should point to an
  8213. array of constant @code{int} values, and then we would not be able to
  8214. store zeros in them.
  8215. In a function with multiple array parameters, you can use @code{restrict}
  8216. to tell the compiler that each array parameter passed in will be distinct:
  8217. @example
  8218. void
  8219. foo (int array1[restrict 10], int array2[restrict 10])
  8220. @r{@dots{}}
  8221. @end example
  8222. @noindent
  8223. Using @code{restrict} promises the compiler that callers will
  8224. not pass in the same array for more than one @code{restrict} array
  8225. parameter. Knowing this enables the compiler to perform better code
  8226. optimization. This is the same effect as using @code{restrict}
  8227. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8228. the code that an array of a specific size is expected.
  8229. @node Structs as Parameters
  8230. @subsection Functions That Accept Structure Arguments
  8231. Structures in GNU C are first-class objects, so using them as function
  8232. parameters and arguments works in the natural way. This function
  8233. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8234. and returns a structure of the same type but with the fields
  8235. exchanged.
  8236. @example
  8237. struct foo @{ int a, b; @};
  8238. struct foo x;
  8239. struct foo
  8240. swapfoo (struct foo inval)
  8241. @{
  8242. struct foo outval;
  8243. outval.a = inval.b;
  8244. outval.b = inval.a;
  8245. return outval;
  8246. @}
  8247. @end example
  8248. This simpler definition of @code{swapfoo} avoids using a local
  8249. variable to hold the result about to be return, by using a structure
  8250. constructor (@pxref{Structure Constructors}), like this:
  8251. @example
  8252. struct foo
  8253. swapfoo (struct foo inval)
  8254. @{
  8255. return (struct foo) @{ inval.b, inval.a @};
  8256. @}
  8257. @end example
  8258. It is valid to define a structure type in a function's parameter list,
  8259. as in
  8260. @example
  8261. int
  8262. frob_bar (struct bar @{ int a, b; @} inval)
  8263. @{
  8264. @var{body}
  8265. @}
  8266. @end example
  8267. @noindent
  8268. and @var{body} can access the fields of @var{inval} since the
  8269. structure type @code{struct bar} is defined for the whole function
  8270. body. However, there is no way to create a @code{struct bar} argument
  8271. to pass to @code{frob_bar}, except with kludges. As a result,
  8272. defining a structure type in a parameter list is useless in practice.
  8273. @node Function Declarations
  8274. @section Function Declarations
  8275. @cindex function declarations
  8276. @cindex declararing functions
  8277. To call a function, or use its name as a pointer, a @dfn{function
  8278. declaration} for the function name must be in effect at that point in
  8279. the code. The function's definition serves as a declaration of that
  8280. function for the rest of the containing scope, but to use the function
  8281. in code before the definition, or from another compilation module, a
  8282. separate function declaration must precede the use.
  8283. A function declaration looks like the start of a function definition.
  8284. It begins with the return value type (@code{void} if none) and the
  8285. function name, followed by argument declarations in parentheses
  8286. (though these can sometimes be omitted). But that's as far as the
  8287. similarity goes: instead of the function body, the declaration uses a
  8288. semicolon.
  8289. @cindex function prototype
  8290. @cindex prototype of a function
  8291. A declaration that specifies argument types is called a @dfn{function
  8292. prototype}. You can include the argument names or omit them. The
  8293. names, if included in the declaration, have no effect, but they may
  8294. serve as documentation.
  8295. This form of prototype specifies fixed argument types:
  8296. @example
  8297. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8298. @end example
  8299. @noindent
  8300. This form says the function takes no arguments:
  8301. @example
  8302. @var{rettype} @var{function} (void);
  8303. @end example
  8304. @noindent
  8305. This form declares types for some arguments, and allows additional
  8306. arguments whose types are not specified:
  8307. @example
  8308. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8309. @end example
  8310. For a parameter that's an array of variable length, you can write
  8311. its declaration with @samp{*} where the ``length'' of the array would
  8312. normally go; for example, these are all equivalent.
  8313. @example
  8314. double maximum (int n, int m, double a[n][m]);
  8315. double maximum (int n, int m, double a[*][*]);
  8316. double maximum (int n, int m, double a[ ][*]);
  8317. double maximum (int n, int m, double a[ ][m]);
  8318. @end example
  8319. @noindent
  8320. The old-fashioned form of declaration, which is not a prototype, says
  8321. nothing about the types of arguments or how many they should be:
  8322. @example
  8323. @var{rettype} @var{function} ();
  8324. @end example
  8325. @strong{Warning:} Arguments passed to a function declared without a
  8326. prototype are converted with the default argument promotions
  8327. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8328. types are unspecified.
  8329. Function declarations are usually written at the top level in a source file,
  8330. but you can also put them inside code blocks. Then the function name
  8331. is visible for the rest of the containing scope. For example:
  8332. @example
  8333. void
  8334. foo (char *file_name)
  8335. @{
  8336. void save_file (char *);
  8337. save_file (file_name);
  8338. @}
  8339. @end example
  8340. If another part of the code tries to call the function
  8341. @code{save_file}, this declaration won't be in effect there. So the
  8342. function will get an implicit declaration of the form @code{extern int
  8343. save_file ();}. That conflicts with the explicit declaration
  8344. here, and the discrepancy generates a warning.
  8345. The syntax of C traditionally allows omitting the data type in a
  8346. function declaration if it specifies a storage class or a qualifier.
  8347. Then the type defaults to @code{int}. For example:
  8348. @example
  8349. static foo (double x);
  8350. @end example
  8351. @noindent
  8352. defaults the return type to @code{int}.
  8353. This is bad practice; if you see it, fix it.
  8354. Calling a function that is undeclared has the effect of an creating
  8355. @dfn{implicit} declaration in the innermost containing scope,
  8356. equivalent to this:
  8357. @example
  8358. extern int @dfn{function} ();
  8359. @end example
  8360. @noindent
  8361. This declaration says that the function returns @code{int} but leaves
  8362. its argument types unspecified. If that does not accurately fit the
  8363. function, then the program @strong{needs} an explicit declaration of
  8364. the function with argument types in order to call it correctly.
  8365. Implicit declarations are deprecated, and a function call that creates one
  8366. causes a warning.
  8367. @node Function Calls
  8368. @section Function Calls
  8369. @cindex function calls
  8370. @cindex calling functions
  8371. Starting a program automatically calls the function named @code{main}
  8372. (@pxref{The main Function}). Aside from that, a function does nothing
  8373. except when it is @dfn{called}. That occurs during the execution of a
  8374. function-call expression specifying that function.
  8375. A function-call expression looks like this:
  8376. @example
  8377. @var{function} (@var{arguments}@r{@dots{}})
  8378. @end example
  8379. Most of the time, @var{function} is a function name. However, it can
  8380. also be an expression with a function pointer value; that way, the
  8381. program can determine at run time which function to call.
  8382. The @var{arguments} are a series of expressions separated by commas.
  8383. Each expression specifies one argument to pass to the function.
  8384. The list of arguments in a function call looks just like use of the
  8385. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8386. the parentheses of a function call gives it a different meaning.
  8387. Here's an example of a function call, taken from an example near the
  8388. beginning (@pxref{Complete Program}).
  8389. @example
  8390. printf ("Fibonacci series item %d is %d\n",
  8391. 19, fib (19));
  8392. @end example
  8393. The three arguments given to @code{printf} are a constant string, the
  8394. integer 19, and the integer returned by @code{fib (19)}.
  8395. @node Function Call Semantics
  8396. @section Function Call Semantics
  8397. @cindex function call semantics
  8398. @cindex semantics of function calls
  8399. @cindex call-by-value
  8400. The meaning of a function call is to compute the specified argument
  8401. expressions, convert their values according to the function's
  8402. declaration, then run the function giving it copies of the converted
  8403. values. (This method of argument passing is known as
  8404. @dfn{call-by-value}.) When the function finishes, the value it
  8405. returns becomes the value of the function-call expression.
  8406. Call-by-value implies that an assignment to the function argument
  8407. variable has no direct effect on the caller. For instance,
  8408. @example
  8409. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8410. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8411. void
  8412. subroutine (int x)
  8413. @{
  8414. x = 5;
  8415. @}
  8416. void
  8417. main (void)
  8418. @{
  8419. int y = 20;
  8420. subroutine (y);
  8421. printf ("y is %d\n", y);
  8422. return EXIT_SUCCESS;
  8423. @}
  8424. @end example
  8425. @noindent
  8426. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8427. from the value of @code{y}, but this does not establish any other
  8428. relationship between the two variables. Thus, the assignment to
  8429. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8430. If an argument's type is specified by the function's declaration, the
  8431. function call converts the argument expression to that type if
  8432. possible. If the conversion is impossible, that is an error.
  8433. If the function's declaration doesn't specify the type of that
  8434. argument, then the @emph{default argument promotions} apply.
  8435. @xref{Argument Promotions}.
  8436. @node Function Pointers
  8437. @section Function Pointers
  8438. @cindex function pointers
  8439. @cindex pointers to functions
  8440. A function name refers to a fixed function. Sometimes it is useful to
  8441. call a function to be determined at run time; to do this, you can use
  8442. a @dfn{function pointer value} that points to the chosen function
  8443. (@pxref{Pointers}).
  8444. Pointer-to-function types can be used to declare variables and other
  8445. data, including array elements, structure fields, and union
  8446. alternatives. They can also be used for function arguments and return
  8447. values. These types have the peculiarity that they are never
  8448. converted automatically to @code{void *} or vice versa. However, you
  8449. can do that conversion with a cast.
  8450. @menu
  8451. * Declaring Function Pointers:: How to declare a pointer to a function.
  8452. * Assigning Function Pointers:: How to assign values to function pointers.
  8453. * Calling Function Pointers:: How to call functions through pointers.
  8454. @end menu
  8455. @node Declaring Function Pointers
  8456. @subsection Declaring Function Pointers
  8457. @cindex declaring function pointers
  8458. @cindex function pointers, declaring
  8459. The declaration of a function pointer variable (or structure field)
  8460. looks almost like a function declaration, except it has an additional
  8461. @samp{*} just before the variable name. Proper nesting requires a
  8462. pair of parentheses around the two of them. For instance, @code{int
  8463. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8464. an @code{int}-returning function.''
  8465. Contrast these three declarations:
  8466. @example
  8467. /* @r{Declare a function returning @code{char *}.} */
  8468. char *a (char *);
  8469. /* @r{Declare a pointer to a function returning @code{char}.} */
  8470. char (*a) (char *);
  8471. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8472. char *(*a) (char *);
  8473. @end example
  8474. The possible argument types of the function pointed to are the same
  8475. as in a function declaration. You can write a prototype
  8476. that specifies all the argument types:
  8477. @example
  8478. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8479. @end example
  8480. @noindent
  8481. or one that specifies some and leaves the rest unspecified:
  8482. @example
  8483. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8484. @end example
  8485. @noindent
  8486. or one that says there are no arguments:
  8487. @example
  8488. @var{rettype} (*@var{function}) (void);
  8489. @end example
  8490. You can also write a non-prototype declaration that says
  8491. nothing about the argument types:
  8492. @example
  8493. @var{rettype} (*@var{function}) ();
  8494. @end example
  8495. For example, here's a declaration for a variable that should
  8496. point to some arithmetic function that operates on two @code{double}s:
  8497. @example
  8498. double (*binary_op) (double, double);
  8499. @end example
  8500. Structure fields, union alternatives, and array elements can be
  8501. function pointers; so can parameter variables. The function pointer
  8502. declaration construct can also be combined with other operators
  8503. allowed in declarations. For instance,
  8504. @example
  8505. int **(*foo)();
  8506. @end example
  8507. @noindent
  8508. declares @code{foo} as a pointer to a function that returns
  8509. type @code{int **}, and
  8510. @example
  8511. int **(*foo[30])();
  8512. @end example
  8513. @noindent
  8514. declares @code{foo} as an array of 30 pointers to functions that
  8515. return type @code{int **}.
  8516. @example
  8517. int **(**foo)();
  8518. @end example
  8519. @noindent
  8520. declares @code{foo} as a pointer to a pointer to a function that
  8521. returns type @code{int **}.
  8522. @node Assigning Function Pointers
  8523. @subsection Assigning Function Pointers
  8524. @cindex assigning function pointers
  8525. @cindex function pointers, assigning
  8526. Assuming we have declared the variable @code{binary_op} as in the
  8527. previous section, giving it a value requires a suitable function to
  8528. use. So let's define a function suitable for the variable to point
  8529. to. Here's one:
  8530. @example
  8531. double
  8532. double_add (double a, double b)
  8533. @{
  8534. return a+b;
  8535. @}
  8536. @end example
  8537. Now we can give it a value:
  8538. @example
  8539. binary_op = double_add;
  8540. @end example
  8541. The target type of the function pointer must be upward compatible with
  8542. the type of the function (@pxref{Compatible Types}).
  8543. There is no need for @samp{&} in front of @code{double_add}.
  8544. Using a function name such as @code{double_add} as an expression
  8545. automatically converts it to the function's address, with the
  8546. appropriate function pointer type. However, it is ok to use
  8547. @samp{&} if you feel that is clearer:
  8548. @example
  8549. binary_op = &double_add;
  8550. @end example
  8551. @node Calling Function Pointers
  8552. @subsection Calling Function Pointers
  8553. @cindex calling function pointers
  8554. @cindex function pointers, calling
  8555. To call the function specified by a function pointer, just write the
  8556. function pointer value in a function call. For instance, here's a
  8557. call to the function @code{binary_op} points to:
  8558. @example
  8559. binary_op (x, 5)
  8560. @end example
  8561. Since the data type of @code{binary_op} explicitly specifies type
  8562. @code{double} for the arguments, the call converts @code{x} and 5 to
  8563. @code{double}.
  8564. The call conceptually dereferences the pointer @code{binary_op} to
  8565. ``get'' the function it points to, and calls that function. If you
  8566. wish, you can explicitly represent the derefence by writing the
  8567. @code{*} operator:
  8568. @example
  8569. (*binary_op) (x, 5)
  8570. @end example
  8571. The @samp{*} reminds people reading the code that @code{binary_op} is
  8572. a function pointer rather than the name of a specific function.
  8573. @node The main Function
  8574. @section The @code{main} Function
  8575. @cindex @code{main} function
  8576. @findex main
  8577. Every complete executable program requires at least one function,
  8578. called @code{main}, which is where execution begins. You do not have
  8579. to explicitly declare @code{main}, though GNU C permits you to do so.
  8580. Conventionally, @code{main} should be defined to follow one of these
  8581. calling conventions:
  8582. @example
  8583. int main (void) @{@r{@dots{}}@}
  8584. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8585. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8586. @end example
  8587. @noindent
  8588. Using @code{void} as the parameter list means that @code{main} does
  8589. not use the arguments. You can write @code{char **argv} instead of
  8590. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8591. constructs are equivalent.
  8592. @ignore @c Not so at present
  8593. Defining @code{main} in any other way generates a warning. Your
  8594. program will still compile, but you may get unexpected results when
  8595. executing it.
  8596. @end ignore
  8597. You can call @code{main} from C code, as you can call any other
  8598. function, though that is an unusual thing to do. When you do that,
  8599. you must write the call to pass arguments that match the parameters in
  8600. the definition of @code{main}.
  8601. The @code{main} function is not actually the first code that runs when
  8602. a program starts. In fact, the first code that runs is system code
  8603. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8604. code, but in GNU we replaced it with C code. Its job is to find
  8605. the arguments for @code{main} and call that.
  8606. @menu
  8607. * Values from main:: Returning values from the main function.
  8608. * Command-line Parameters:: Accessing command-line parameters
  8609. provided to the program.
  8610. * Environment Variables:: Accessing system environment variables.
  8611. @end menu
  8612. @node Values from main
  8613. @subsection Returning Values from @code{main}
  8614. @cindex returning values from @code{main}
  8615. @cindex success
  8616. @cindex failure
  8617. @cindex exit status
  8618. When @code{main} returns, the process terminates. Whatever value
  8619. @code{main} returns becomes the exit status which is reported to the
  8620. parent process. While nominally the return value is of type
  8621. @code{int}, in fact the exit status gets truncated to eight bits; if
  8622. @code{main} returns the value 256, the exit status is 0.
  8623. Normally, programs return only one of two values: 0 for success,
  8624. and 1 for failure. For maximum portability, use the macro
  8625. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8626. @code{stdlib.h}. Here's an example:
  8627. @cindex @code{EXIT_FAILURE}
  8628. @cindex @code{EXIT_SUCCESS}
  8629. @example
  8630. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8631. /* @r{and @code{EXIT_FAILURE}.} */
  8632. int
  8633. main (void)
  8634. @{
  8635. @r{@dots{}}
  8636. if (foo)
  8637. return EXIT_SUCCESS;
  8638. else
  8639. return EXIT_FAILURE;
  8640. @}
  8641. @end example
  8642. Some types of programs maintain special conventions for various return
  8643. values; for example, comparison programs including @code{cmp} and
  8644. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8645. the comparison couldn't be performed.
  8646. @node Command-line Parameters
  8647. @subsection Accessing Command-line Parameters
  8648. @cindex command-line parameters
  8649. @cindex parameters, command-line
  8650. If the program was invoked with any command-line arguments, it can
  8651. access them through the arguments of @code{main}, @code{argc} and
  8652. @code{argv}. (You can give these arguments any names, but the names
  8653. @code{argc} and @code{argv} are customary.)
  8654. The value of @code{argv} is an array containing all of the
  8655. command-line arguments as strings, with the name of the command
  8656. invoked as the first string. @code{argc} is an integer that says how
  8657. many strings @code{argv} contains. Here is an example of accessing
  8658. the command-line parameters, retrieving the program's name and
  8659. checking for the standard @option{--version} and @option{--help} options:
  8660. @example
  8661. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8662. int
  8663. main (int argc, char *argv[])
  8664. @{
  8665. char *program_name = argv[0];
  8666. for (int i = 1; i < argc; i++)
  8667. @{
  8668. if (!strcmp (argv[i], "--version"))
  8669. @{
  8670. /* @r{Print version information and exit.} */
  8671. @r{@dots{}}
  8672. @}
  8673. else if (!strcmp (argv[i], "--help"))
  8674. @{
  8675. /* @r{Print help information and exit.} */
  8676. @r{@dots{}}
  8677. @}
  8678. @}
  8679. @r{@dots{}}
  8680. @}
  8681. @end example
  8682. @node Environment Variables
  8683. @subsection Accessing Environment Variables
  8684. @cindex environment variables
  8685. You can optionally include a third parameter to @code{main}, another
  8686. array of strings, to capture the environment variables available to
  8687. the program. Unlike what happens with @code{argv}, there is no
  8688. additional parameter for the count of environment variables; rather,
  8689. the array of environment variables concludes with a null pointer.
  8690. @example
  8691. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8692. int
  8693. main (int argc, char *argv[], char *envp[])
  8694. @{
  8695. /* @r{Print out all environment variables.} */
  8696. int i = 0;
  8697. while (envp[i])
  8698. @{
  8699. printf ("%s\n", envp[i]);
  8700. i++;
  8701. @}
  8702. @}
  8703. @end example
  8704. Another method of retrieving environment variables is to use the
  8705. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8706. Using @code{getenv} does not require defining @code{main} to accept the
  8707. @code{envp} pointer. For example, here is a program that fetches and prints
  8708. the user's home directory (if defined):
  8709. @example
  8710. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8711. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8712. int
  8713. main (void)
  8714. @{
  8715. char *home_directory = getenv ("HOME");
  8716. if (home_directory)
  8717. printf ("My home directory is: %s\n", home_directory);
  8718. else
  8719. printf ("My home directory is not defined!\n");
  8720. @}
  8721. @end example
  8722. @node Advanced Definitions
  8723. @section Advanced Function Features
  8724. This section describes some advanced or obscure features for GNU C
  8725. function definitions. If you are just learning C, you can skip the
  8726. rest of this chapter.
  8727. @menu
  8728. * Variable-Length Array Parameters:: Functions that accept arrays
  8729. of variable length.
  8730. * Variable Number of Arguments:: Variadic functions.
  8731. * Nested Functions:: Defining functions within functions.
  8732. * Inline Function Definitions:: A function call optimization technique.
  8733. @end menu
  8734. @node Variable-Length Array Parameters
  8735. @subsection Variable-Length Array Parameters
  8736. @cindex variable-length array parameters
  8737. @cindex array parameters, variable-length
  8738. @cindex functions that accept variable-length arrays
  8739. An array parameter can have variable length: simply declare the array
  8740. type with a size that isn't constant. In a nested function, the
  8741. length can refer to a variable defined in a containing scope. In any
  8742. function, it can refer to a previous parameter, like this:
  8743. @example
  8744. struct entry
  8745. tester (int len, char data[len][len])
  8746. @{
  8747. @r{@dots{}}
  8748. @}
  8749. @end example
  8750. Alternatively, in function declarations (but not in function
  8751. definitions), you can use @code{[*]} to denote that the array
  8752. parameter is of a variable length, such that these two declarations
  8753. mean the same thing:
  8754. @example
  8755. struct entry
  8756. tester (int len, char data[len][len]);
  8757. @end example
  8758. @example
  8759. struct entry
  8760. tester (int len, char data[*][*]);
  8761. @end example
  8762. @noindent
  8763. The two forms of input are equivalent in GNU C, but emphasizing that
  8764. the array parameter is variable-length may be helpful to those
  8765. studying the code.
  8766. You can also omit the length parameter, and instead use some other
  8767. in-scope variable for the length in the function definition:
  8768. @example
  8769. struct entry
  8770. tester (char data[*][*]);
  8771. @r{@dots{}}
  8772. int dataLength = 20;
  8773. @r{@dots{}}
  8774. struct entry
  8775. tester (char data[dataLength][dataLength])
  8776. @{
  8777. @r{@dots{}}
  8778. @}
  8779. @end example
  8780. @c ??? check text above
  8781. @cindex parameter forward declaration
  8782. In GNU C, to pass the array first and the length afterward, you can
  8783. use a @dfn{parameter forward declaration}, like this:
  8784. @example
  8785. struct entry
  8786. tester (int len; char data[len][len], int len)
  8787. @{
  8788. @r{@dots{}}
  8789. @}
  8790. @end example
  8791. The @samp{int len} before the semicolon is the parameter forward
  8792. declaration; it serves the purpose of making the name @code{len} known
  8793. when the declaration of @code{data} is parsed.
  8794. You can write any number of such parameter forward declarations in the
  8795. parameter list. They can be separated by commas or semicolons, but
  8796. the last one must end with a semicolon, which is followed by the
  8797. ``real'' parameter declarations. Each forward declaration must match
  8798. a subsequent ``real'' declaration in parameter name and data type.
  8799. Standard C does not support parameter forward declarations.
  8800. @node Variable Number of Arguments
  8801. @subsection Variable-Length Parameter Lists
  8802. @cindex variable-length parameter lists
  8803. @cindex parameters lists, variable length
  8804. @cindex function parameter lists, variable length
  8805. @cindex variadic function
  8806. A function that takes a variable number of arguments is called a
  8807. @dfn{variadic function}. In C, a variadic function must specify at
  8808. least one fixed argument with an explicitly declared data type.
  8809. Additional arguments can follow, and can vary in both quantity and
  8810. data type.
  8811. In the function header, declare the fixed parameters in the normal
  8812. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8813. example of a variadic function header:
  8814. @example
  8815. int add_multiple_values (int number, ...)
  8816. @end example
  8817. @cindex @code{va_list}
  8818. @cindex @code{va_start}
  8819. @cindex @code{va_end}
  8820. The function body can refer to fixed arguments by their parameter
  8821. names, but the additional arguments have no names. Accessing them in
  8822. the function body uses certain standard macros. They are defined in
  8823. the library header file @file{stdarg.h}, so the code must
  8824. @code{#include} that file.
  8825. In the body, write
  8826. @example
  8827. va_list ap;
  8828. va_start (ap, @var{last_fixed_parameter});
  8829. @end example
  8830. @noindent
  8831. This declares the variable @code{ap} (you can use any name for it)
  8832. and then sets it up to point before the first additional argument.
  8833. Then, to fetch the next consecutive additional argument, write this:
  8834. @example
  8835. va_arg (ap, @var{type})
  8836. @end example
  8837. After fetching all the additional arguments (or as many as need to be
  8838. used), write this:
  8839. @example
  8840. va_end (ap);
  8841. @end example
  8842. Here's an example of a variadic function definition that adds any
  8843. number of @code{int} arguments. The first (fixed) argument says how
  8844. many more arguments follow.
  8845. @example
  8846. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8847. @r{@dots{}}
  8848. int
  8849. add_multiple_values (int argcount, ...)
  8850. @{
  8851. int counter, total = 0;
  8852. /* @r{Declare a variable of type @code{va_list}.} */
  8853. va_list argptr;
  8854. /* @r{Initialize that variable..} */
  8855. va_start (argptr, argcount);
  8856. for (counter = 0; counter < argcount; counter++)
  8857. @{
  8858. /* @r{Get the next additional argument.} */
  8859. total += va_arg (argptr, int);
  8860. @}
  8861. /* @r{End use of the @code{argptr} variable.} */
  8862. va_end (argptr);
  8863. return total;
  8864. @}
  8865. @end example
  8866. With GNU C, @code{va_end} is superfluous, but some other compilers
  8867. might make @code{va_start} allocate memory so that calling
  8868. @code{va_end} is necessary to avoid a memory leak. Before doing
  8869. @code{va_start} again with the same variable, do @code{va_end}
  8870. first.
  8871. @cindex @code{va_copy}
  8872. Because of this possible memory allocation, it is risky (in principle)
  8873. to copy one @code{va_list} variable to another with assignment.
  8874. Instead, use @code{va_copy}, which copies the substance but allocates
  8875. separate memory in the variable you copy to. The call looks like
  8876. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8877. @var{from} should be variables of type @code{va_list}. In principle,
  8878. do @code{va_end} on each of these variables before its scope ends.
  8879. Since the additional arguments' types are not specified in the
  8880. function's definition, the default argument promotions
  8881. (@pxref{Argument Promotions}) apply to them in function calls. The
  8882. function definition must take account of this; thus, if an argument
  8883. was passed as @code{short}, the function should get it as @code{int}.
  8884. If an argument was passed as @code{float}, the function should get it
  8885. as @code{double}.
  8886. C has no mechanism to tell the variadic function how many arguments
  8887. were passed to it, so its calling convention must give it a way to
  8888. determine this. That's why @code{add_multiple_values} takes a fixed
  8889. argument that says how many more arguments follow. Thus, you can
  8890. call the function like this:
  8891. @example
  8892. sum = add_multiple_values (3, 12, 34, 190);
  8893. /* @r{Value is 12+34+190.} */
  8894. @end example
  8895. In GNU C, there is no actual need to use the @code{va_end} function.
  8896. In fact, it does nothing. It's used for compatibility with other
  8897. compilers, when that matters.
  8898. It is a mistake to access variables declared as @code{va_list} except
  8899. in the specific ways described here. Just what that type consists of
  8900. is an implementation detail, which could vary from one platform to
  8901. another.
  8902. @node Nested Functions
  8903. @subsection Nested Functions
  8904. @cindex nested functions
  8905. @cindex functions, nested
  8906. @cindex downward funargs
  8907. @cindex thunks
  8908. A @dfn{nested function} is a function defined inside another function.
  8909. (The ability to do this indispensable for automatic translation of
  8910. certain programming languages into C.) The nested function's name is
  8911. local to the block where it is defined. For example, here we define a
  8912. nested function named @code{square}, then call it twice:
  8913. @example
  8914. @group
  8915. foo (double a, double b)
  8916. @{
  8917. double square (double z) @{ return z * z; @}
  8918. return square (a) + square (b);
  8919. @}
  8920. @end group
  8921. @end example
  8922. The nested function definition can access all the variables of the containing
  8923. function that are visible at the point of its definition. This is
  8924. called @dfn{lexical scoping}. For example, here we show a nested
  8925. function that uses an inherited variable named @code{offset}:
  8926. @example
  8927. @group
  8928. bar (int *array, int offset, int size)
  8929. @{
  8930. int access (int *array, int index)
  8931. @{ return array[index + offset]; @}
  8932. int i;
  8933. @r{@dots{}}
  8934. for (i = 0; i < size; i++)
  8935. @r{@dots{}} access (array, i) @r{@dots{}}
  8936. @}
  8937. @end group
  8938. @end example
  8939. Nested function definitions can appear wherever automatic variable
  8940. declarations are allowed; that is, in any block, interspersed with the
  8941. other declarations and statements in the block.
  8942. The nested function's name is visible only within the parent block;
  8943. the name's scope starts from its definition and continues to the end
  8944. of the containing block. If the nested function's name
  8945. is the same as the parent function's name, there wil be
  8946. no way to refer to the parent function inside the scope of the
  8947. name of the nested function.
  8948. Using @code{extern} or @code{static} on a nested function definition
  8949. is an error.
  8950. It is possible to call the nested function from outside the scope of its
  8951. name by storing its address or passing the address to another function.
  8952. You can do this safely, but you must be careful:
  8953. @example
  8954. @group
  8955. hack (int *array, int size, int addition)
  8956. @{
  8957. void store (int index, int value)
  8958. @{ array[index] = value + addition; @}
  8959. intermediate (store, size);
  8960. @}
  8961. @end group
  8962. @end example
  8963. Here, the function @code{intermediate} receives the address of
  8964. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8965. the arguments given to @code{store} are used to store into @code{array}.
  8966. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8967. It is safe for @code{intermediate} to call @code{store} because
  8968. @code{hack}'s stack frame, with its arguments and local variables,
  8969. continues to exist during the call to @code{intermediate}.
  8970. Calling the nested function through its address after the containing
  8971. function has exited is asking for trouble. If it is called after a
  8972. containing scope level has exited, and if it refers to some of the
  8973. variables that are no longer in scope, it will refer to memory
  8974. containing junk or other data. It's not wise to take the risk.
  8975. The GNU C Compiler implements taking the address of a nested function
  8976. using a technique called @dfn{trampolines}. This technique was
  8977. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8978. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8979. A nested function can jump to a label inherited from a containing
  8980. function, provided the label was explicitly declared in the containing
  8981. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8982. containing function, exiting the nested function that did the
  8983. @code{goto} and any intermediate function invocations as well. Here
  8984. is an example:
  8985. @example
  8986. @group
  8987. bar (int *array, int offset, int size)
  8988. @{
  8989. /* @r{Explicitly declare the label @code{failure}.} */
  8990. __label__ failure;
  8991. int access (int *array, int index)
  8992. @{
  8993. if (index > size)
  8994. /* @r{Exit this function,}
  8995. @r{and return to @code{bar}.} */
  8996. goto failure;
  8997. return array[index + offset];
  8998. @}
  8999. @end group
  9000. @group
  9001. int i;
  9002. @r{@dots{}}
  9003. for (i = 0; i < size; i++)
  9004. @r{@dots{}} access (array, i) @r{@dots{}}
  9005. @r{@dots{}}
  9006. return 0;
  9007. /* @r{Control comes here from @code{access}
  9008. if it does the @code{goto}.} */
  9009. failure:
  9010. return -1;
  9011. @}
  9012. @end group
  9013. @end example
  9014. To declare the nested function before its definition, use
  9015. @code{auto} (which is otherwise meaningless for function declarations;
  9016. @pxref{auto and register}). For example,
  9017. @example
  9018. bar (int *array, int offset, int size)
  9019. @{
  9020. auto int access (int *, int);
  9021. @r{@dots{}}
  9022. @r{@dots{}} access (array, i) @r{@dots{}}
  9023. @r{@dots{}}
  9024. int access (int *array, int index)
  9025. @{
  9026. @r{@dots{}}
  9027. @}
  9028. @r{@dots{}}
  9029. @}
  9030. @end example
  9031. @node Inline Function Definitions
  9032. @subsection Inline Function Definitions
  9033. @cindex inline function definitions
  9034. @cindex function definitions, inline
  9035. @findex inline
  9036. To declare a function inline, use the @code{inline} keyword in its
  9037. definition. Here's a simple function that takes a pointer-to-@code{int}
  9038. and increments the integer stored there---declared inline.
  9039. @example
  9040. struct list
  9041. @{
  9042. struct list *first, *second;
  9043. @};
  9044. inline struct list *
  9045. list_first (struct list *p)
  9046. @{
  9047. return p->first;
  9048. @}
  9049. inline struct list *
  9050. list_second (struct list *p)
  9051. @{
  9052. return p->second;
  9053. @}
  9054. @end example
  9055. optimized compilation can substitute the inline function's body for
  9056. any call to it. This is called @emph{inlining} the function. It
  9057. makes the code that contains the call run faster, significantly so if
  9058. the inline function is small.
  9059. Here's a function that uses @code{pair_second}:
  9060. @example
  9061. int
  9062. pairlist_length (struct list *l)
  9063. @{
  9064. int length = 0;
  9065. while (l)
  9066. @{
  9067. length++;
  9068. l = pair_second (l);
  9069. @}
  9070. return length;
  9071. @}
  9072. @end example
  9073. Substituting the code of @code{pair_second} into the definition of
  9074. @code{pairlist_length} results in this code, in effect:
  9075. @example
  9076. int
  9077. pairlist_length (struct list *l)
  9078. @{
  9079. int length = 0;
  9080. while (l)
  9081. @{
  9082. length++;
  9083. l = l->second;
  9084. @}
  9085. return length;
  9086. @}
  9087. @end example
  9088. Since the definition of @code{pair_second} does not say @code{extern}
  9089. or @code{static}, that definition is used only for inlining. It
  9090. doesn't generate code that can be called at run time. If not all the
  9091. calls to the function are inlined, there must be a definition of the
  9092. same function name in another module for them to call.
  9093. @cindex inline functions, omission of
  9094. @c @opindex fkeep-inline-functions
  9095. Adding @code{static} to an inline function definition means the
  9096. function definition is limited to this compilation module. Also, it
  9097. generates run-time code if necessary for the sake of any calls that
  9098. were not inlined. If all calls are inlined then the function
  9099. definition does not generate run-time code, but you can force
  9100. generation of run-time code with the option
  9101. @option{-fkeep-inline-functions}.
  9102. @cindex extern inline function
  9103. Specifying @code{extern} along with @code{inline} means the function is
  9104. external and generates run-time code to be called from other
  9105. separately compiled modules, as well as inlined. You can define the
  9106. function as @code{inline} without @code{extern} in other modules so as
  9107. to inline calls to the same function in those modules.
  9108. Why are some calls not inlined? First of all, inlining is an
  9109. optimization, so non-optimized compilation does not inline.
  9110. Some calls cannot be inlined for technical reasons. Also, certain
  9111. usages in a function definition can make it unsuitable for inline
  9112. substitution. Among these usages are: variadic functions, use of
  9113. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9114. use of nonlocal goto. The option @option{-Winline} requests a warning
  9115. when a function marked @code{inline} is unsuitable to be inlined. The
  9116. warning explains what obstacle makes it unsuitable.
  9117. Just because a call @emph{can} be inlined does not mean it
  9118. @emph{should} be inlined. The GNU C compiler weighs costs and
  9119. benefits to decide whether inlining a particular call is advantageous.
  9120. You can force inlining of all calls to a given function that can be
  9121. inlined, even in a non-optimized compilation. by specifying the
  9122. @samp{always_inline} attribute for the function, like this:
  9123. @example
  9124. /* @r{Prototype.} */
  9125. inline void foo (const char) __attribute__((always_inline));
  9126. @end example
  9127. @noindent
  9128. This is a GNU C extension. @xref{Attributes}.
  9129. A function call may be inlined even if not declared @code{inline} in
  9130. special cases where the compiler can determine this is correct and
  9131. desirable. For instance, when a static function is called only once,
  9132. it will very likely be inlined. With @option{-flto}, link-time
  9133. optimization, any function might be inlined. To absolutely prevent
  9134. inlining of a specific function, specify
  9135. @code{__attribute__((__noinline__))} in the function's definition.
  9136. @node Obsolete Definitions
  9137. @section Obsolete Function Features
  9138. These features of function definitions are still used in old
  9139. programs, but you shouldn't write code this way today.
  9140. If you are just learning C, you can skip this section.
  9141. @menu
  9142. * Old GNU Inlining:: An older inlining technique.
  9143. * Old-Style Function Definitions:: Original K&R style functions.
  9144. @end menu
  9145. @node Old GNU Inlining
  9146. @subsection Older GNU C Inlining
  9147. The GNU C spec for inline functions, before GCC version 5, defined
  9148. @code{extern inline} on a function definition to mean to inline calls
  9149. to it but @emph{not} generate code for the function that could be
  9150. called at run time. By contrast, @code{inline} without @code{extern}
  9151. specified to generate run-time code for the function. In effect, ISO
  9152. incompatibly flipped the meanings of these two cases. We changed GCC
  9153. in version 5 to adopt the ISO specification.
  9154. Many programs still use these cases with the previous GNU C meanings.
  9155. You can specify use of those meanings with the option
  9156. @option{-fgnu89-inline}. You can also specify this for a single
  9157. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9158. @example
  9159. inline __attribute__ ((gnu_inline))
  9160. int
  9161. inc (int *a)
  9162. @{
  9163. (*a)++;
  9164. @}
  9165. @end example
  9166. @node Old-Style Function Definitions
  9167. @subsection Old-Style Function Definitions
  9168. @cindex old-style function definitions
  9169. @cindex function definitions, old-style
  9170. @cindex K&R-style function definitions
  9171. The syntax of C traditionally allows omitting the data type in a
  9172. function declaration if it specifies a storage class or a qualifier.
  9173. Then the type defaults to @code{int}. For example:
  9174. @example
  9175. static foo (double x);
  9176. @end example
  9177. @noindent
  9178. defaults the return type to @code{int}. This is bad practice; if you
  9179. see it, fix it.
  9180. An @dfn{old-style} (or ``K&R'') function definition is the way
  9181. function definitions were written in the 1980s. It looks like this:
  9182. @example
  9183. @var{rettype}
  9184. @var{function} (@var{parmnames})
  9185. @var{parm_declarations}
  9186. @{
  9187. @var{body}
  9188. @}
  9189. @end example
  9190. In @var{parmnames}, only the parameter names are listed, separated by
  9191. commas. Then @var{parm_declarations} declares their data types; these
  9192. declarations look just like variable declarations. If a parameter is
  9193. listed in @var{parmnames} but has no declaration, it is implicitly
  9194. declared @code{int}.
  9195. There is no reason to write a definition this way nowadays, but they
  9196. can still be seen in older GNU programs.
  9197. An old-style variadic function definition looks like this:
  9198. @example
  9199. #include <varargs.h>
  9200. int
  9201. add_multiple_values (va_alist)
  9202. va_dcl
  9203. @{
  9204. int argcount;
  9205. int counter, total = 0;
  9206. /* @r{Declare a variable of type @code{va_list}.} */
  9207. va_list argptr;
  9208. /* @r{Initialize that variable.} */
  9209. va_start (argptr);
  9210. /* @r{Get the first argument (fixed).} */
  9211. argcount = va_arg (int);
  9212. for (counter = 0; counter < argcount; counter++)
  9213. @{
  9214. /* @r{Get the next additional argument.} */
  9215. total += va_arg (argptr, int);
  9216. @}
  9217. /* @r{End use of the @code{argptr} variable.} */
  9218. va_end (argptr);
  9219. return total;
  9220. @}
  9221. @end example
  9222. Note that the old-style variadic function definition has no fixed
  9223. parameter variables; all arguments must be obtained with
  9224. @code{va_arg}.
  9225. @node Compatible Types
  9226. @chapter Compatible Types
  9227. @cindex compatible types
  9228. @cindex types, compatible
  9229. Declaring a function or variable twice is valid in C only if the two
  9230. declarations specify @dfn{compatible} types. In addition, some
  9231. operations on pointers require operands to have compatible target
  9232. types.
  9233. In C, two different primitive types are never compatible. Likewise for
  9234. the defined types @code{struct}, @code{union} and @code{enum}: two
  9235. separately defined types are incompatible unless they are defined
  9236. exactly the same way.
  9237. However, there are a few cases where different types can be
  9238. compatible:
  9239. @itemize @bullet
  9240. @item
  9241. Every enumeration type is compatible with some integer type. In GNU
  9242. C, the choice of integer type depends on the largest enumeration
  9243. value.
  9244. @c ??? Which one, in GCC?
  9245. @c ??? ... it varies, depending on the enum values. Testing on
  9246. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9247. @c ??? then moves on to an 8-byte signed integer. These details
  9248. @c ??? might be platform-dependent, as the C standard says that even
  9249. @c ??? char could be used as an enum type, but it's at least true
  9250. @c ??? that GCC chooses a type that is at least large enough to
  9251. @c ??? hold the largest enum value.
  9252. @item
  9253. Array types are compatible if the element types are compatible
  9254. and the sizes (when specified) match.
  9255. @item
  9256. Pointer types are compatible if the pointer target types are
  9257. compatible.
  9258. @item
  9259. Function types that specify argument types are compatible if the
  9260. return types are compatible and the argument types are compatible,
  9261. argument by argument. In addition, they must all agree in whether
  9262. they use @code{...} to allow additional arguments.
  9263. @item
  9264. Function types that don't specify argument types are compatible if the
  9265. return types are.
  9266. @item
  9267. Function types that specify the argument types are compatible with
  9268. function types that omit them, if the return types are compatible and
  9269. the specified argument types are unaltered by the argument promotions
  9270. (@pxref{Argument Promotions}).
  9271. @end itemize
  9272. In order for types to be compatible, they must agree in their type
  9273. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9274. It follows that @code{const int *} and @code{int *} are incompatible
  9275. too (they are pointers to types that are not compatible).
  9276. If two types are compatible ignoring the qualifiers, we call them
  9277. @dfn{nearly compatible}. (If they are array types, we ignore
  9278. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9279. Comparison of pointers is valid if the pointers' target types are
  9280. nearly compatible. Likewise, the two branches of a conditional
  9281. expression may be pointers to nearly compatible target types.
  9282. If two types are compatible ignoring the qualifiers, and the first
  9283. type has all the qualifiers of the second type, we say the first is
  9284. @dfn{upward compatible} with the second. Assignment of pointers
  9285. requires the assigned pointer's target type to be upward compatible
  9286. with the right operand (the new value)'s target type.
  9287. @node Type Conversions
  9288. @chapter Type Conversions
  9289. @cindex type conversions
  9290. @cindex conversions, type
  9291. C converts between data types automatically when that seems clearly
  9292. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9293. @menu
  9294. * Explicit Type Conversion:: Casting a value from one type to another.
  9295. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9296. * Argument Promotions:: Automatic conversion of function parameters.
  9297. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9298. * Common Type:: When operand types differ, which one is used?
  9299. @end menu
  9300. @node Explicit Type Conversion
  9301. @section Explicit Type Conversion
  9302. @cindex cast
  9303. @cindex explicit type conversion
  9304. You can do explicit conversions using the unary @dfn{cast} operator,
  9305. which is written as a type designator (@pxref{Type Designators}) in
  9306. parentheses. For example, @code{(int)} is the operator to cast to
  9307. type @code{int}. Here's an example of using it:
  9308. @example
  9309. @{
  9310. double d = 5.5;
  9311. printf ("Floating point value: %f\n", d);
  9312. printf ("Rounded to integer: %d\n", (int) d);
  9313. @}
  9314. @end example
  9315. Using @code{(int) d} passes an @code{int} value as argument to
  9316. @code{printf}, so you can print it with @samp{%d}. Using just
  9317. @code{d} without the cast would pass the value as @code{double}.
  9318. That won't work at all with @samp{%d}; the results would be gibberish.
  9319. To divide one integer by another without rounding,
  9320. cast either of the integers to @code{double} first:
  9321. @example
  9322. (double) @var{dividend} / @var{divisor}
  9323. @var{dividend} / (double) @var{divisor}
  9324. @end example
  9325. It is enough to cast one of them, because that forces the common type
  9326. to @code{double} so the other will be converted automatically.
  9327. The valid cast conversions are:
  9328. @itemize @bullet
  9329. @item
  9330. One numerical type to another.
  9331. @item
  9332. One pointer type to another.
  9333. (Converting between pointers that point to functions
  9334. and pointers that point to data is not standard C.)
  9335. @item
  9336. A pointer type to an integer type.
  9337. @item
  9338. An integer type to a pointer type.
  9339. @item
  9340. To a union type, from the type of any alternative in the union
  9341. (@pxref{Unions}). (This is a GNU extension.)
  9342. @item
  9343. Anything, to @code{void}.
  9344. @end itemize
  9345. @node Assignment Type Conversions
  9346. @section Assignment Type Conversions
  9347. @cindex assignment type conversions
  9348. Certain type conversions occur automatically in assignments
  9349. and certain other contexts. These are the conversions
  9350. assignments can do:
  9351. @itemize @bullet
  9352. @item
  9353. Converting any numeric type to any other numeric type.
  9354. @item
  9355. Converting @code{void *} to any other pointer type
  9356. (except pointer-to-function types).
  9357. @item
  9358. Converting any other pointer type to @code{void *}.
  9359. (except pointer-to-function types).
  9360. @item
  9361. Converting 0 (a null pointer constant) to any pointer type.
  9362. @item
  9363. Converting any pointer type to @code{bool}. (The result is
  9364. 1 if the pointer is not null.)
  9365. @item
  9366. Converting between pointer types when the left-hand target type is
  9367. upward compatible with the right-hand target type. @xref{Compatible
  9368. Types}.
  9369. @end itemize
  9370. These type conversions occur automatically in certain contexts,
  9371. which are:
  9372. @itemize @bullet
  9373. @item
  9374. An assignment converts the type of the right-hand expression
  9375. to the type wanted by the left-hand expression. For example,
  9376. @example
  9377. double i;
  9378. i = 5;
  9379. @end example
  9380. @noindent
  9381. converts 5 to @code{double}.
  9382. @item
  9383. A function call, when the function specifies the type for that
  9384. argument, converts the argument value to that type. For example,
  9385. @example
  9386. void foo (double);
  9387. foo (5);
  9388. @end example
  9389. @noindent
  9390. converts 5 to @code{double}.
  9391. @item
  9392. A @code{return} statement converts the specified value to the type
  9393. that the function is declared to return. For example,
  9394. @example
  9395. double
  9396. foo ()
  9397. @{
  9398. return 5;
  9399. @}
  9400. @end example
  9401. @noindent
  9402. also converts 5 to @code{double}.
  9403. @end itemize
  9404. In all three contexts, if the conversion is impossible, that
  9405. constitutes an error.
  9406. @node Argument Promotions
  9407. @section Argument Promotions
  9408. @cindex argument promotions
  9409. @cindex promotion of arguments
  9410. When a function's definition or declaration does not specify the type
  9411. of an argument, that argument is passed without conversion in whatever
  9412. type it has, with these exceptions:
  9413. @itemize @bullet
  9414. @item
  9415. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9416. expression is a narrow integer, such as @code{char} or @code{short},
  9417. the call converts it automatically to @code{int} (@pxref{Integer
  9418. Types}).@footnote{On an embedded controller where @code{char}
  9419. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9420. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9421. never occurs in GNU C on real computers.}
  9422. In this example, the expression @code{c} is passed as an @code{int}:
  9423. @example
  9424. char c = '$';
  9425. printf ("Character c is '%c'\n", c);
  9426. @end example
  9427. @item
  9428. If the expression
  9429. has type @code{float}, the call converts it automatically to
  9430. @code{double}.
  9431. @item
  9432. An array as argument is converted to a pointer to its zeroth element.
  9433. @item
  9434. A function name as argument is converted to a pointer to that function.
  9435. @end itemize
  9436. @node Operand Promotions
  9437. @section Operand Promotions
  9438. @cindex operand promotions
  9439. The operands in arithmetic operations undergo type conversion automatically.
  9440. These @dfn{operand promotions} are the same as the argument promotions
  9441. except without converting @code{float} to @code{double}. In other words,
  9442. the operand promotions convert
  9443. @itemize @bullet
  9444. @item
  9445. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9446. @item
  9447. an array to a pointer to its zeroth element, and
  9448. @item
  9449. a function name to a pointer to that function.
  9450. @end itemize
  9451. @node Common Type
  9452. @section Common Type
  9453. @cindex common type
  9454. Arithmetic binary operators (except the shift operators) convert their
  9455. operands to the @dfn{common type} before operating on them.
  9456. Conditional expressions also convert the two possible results to their
  9457. common type. Here are the rules for determining the common type.
  9458. If one of the numbers has a floating-point type and the other is an
  9459. integer, the common type is that floating-point type. For instance,
  9460. @example
  9461. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9462. @end example
  9463. If both are floating point, the type with the larger range is the
  9464. common type.
  9465. If both are integers but of different widths, the common type
  9466. is the wider of the two.
  9467. If they are integer types of the same width, the common type is
  9468. unsigned if either operand is unsigned, and it's @code{long} if either
  9469. operand is @code{long}. It's @code{long long} if either operand is
  9470. @code{long long}.
  9471. These rules apply to addition, subtraction, multiplication, division,
  9472. remainder, comparisons, and bitwise operations. They also apply to
  9473. the two branches of a conditional expression, and to the arithmetic
  9474. done in a modifying assignment operation.
  9475. @node Scope
  9476. @chapter Scope
  9477. @cindex scope
  9478. @cindex block scope
  9479. @cindex function scope
  9480. @cindex function prototype scope
  9481. Each definition or declaration of an identifier is visible
  9482. in certain parts of the program, which is typically less than the whole
  9483. of the program. The parts where it is visible are called its @dfn{scope}.
  9484. Normally, declarations made at the top-level in the source -- that is,
  9485. not within any blocks and function definitions -- are visible for the
  9486. entire contents of the source file after that point. This is called
  9487. @dfn{file scope} (@pxref{File-Scope Variables}).
  9488. Declarations made within blocks of code, including within function
  9489. definitions, are visible only within those blocks. This is called
  9490. @dfn{block scope}. Here is an example:
  9491. @example
  9492. @group
  9493. void
  9494. foo (void)
  9495. @{
  9496. int x = 42;
  9497. @}
  9498. @end group
  9499. @end example
  9500. @noindent
  9501. In this example, the variable @code{x} has block scope; it is visible
  9502. only within the @code{foo} function definition block. Thus, other
  9503. blocks could have their own variables, also named @code{x}, without
  9504. any conflict between those variables.
  9505. A variable declared inside a subblock has a scope limited to
  9506. that subblock,
  9507. @example
  9508. @group
  9509. void
  9510. foo (void)
  9511. @{
  9512. @{
  9513. int x = 42;
  9514. @}
  9515. // @r{@code{x} is out of scope here.}
  9516. @}
  9517. @end group
  9518. @end example
  9519. If a variable declared within a block has the same name as a variable
  9520. declared outside of that block, the definition within the block
  9521. takes precedence during its scope:
  9522. @example
  9523. @group
  9524. int x = 42;
  9525. void
  9526. foo (void)
  9527. @{
  9528. int x = 17;
  9529. printf ("%d\n", x);
  9530. @}
  9531. @end group
  9532. @end example
  9533. @noindent
  9534. This prints 17, the value of the variable @code{x} declared in the
  9535. function body block, rather than the value of the variable @code{x} at
  9536. file scope. We say that the inner declaration of @code{x}
  9537. @dfn{shadows} the outer declaration, for the extent of the inner
  9538. declaration's scope.
  9539. A declaration with block scope can be shadowed by another declaration
  9540. with the same name in a subblock.
  9541. @example
  9542. @group
  9543. void
  9544. foo (void)
  9545. @{
  9546. char *x = "foo";
  9547. @{
  9548. int x = 42;
  9549. @r{@dots{}}
  9550. exit (x / 6);
  9551. @}
  9552. @}
  9553. @end group
  9554. @end example
  9555. A function parameter's scope is the entire function body, but it can
  9556. be shadowed. For example:
  9557. @example
  9558. @group
  9559. int x = 42;
  9560. void
  9561. foo (int x)
  9562. @{
  9563. printf ("%d\n", x);
  9564. @}
  9565. @end group
  9566. @end example
  9567. @noindent
  9568. This prints the value of @code{x} the function parameter, rather than
  9569. the value of the file-scope variable @code{x}. However,
  9570. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9571. is visible for the whole of the containing function body, both before
  9572. and after the label declaration:
  9573. @example
  9574. @group
  9575. void
  9576. foo (void)
  9577. @{
  9578. @r{@dots{}}
  9579. goto bar;
  9580. @r{@dots{}}
  9581. @{ // @r{Subblock does not affect labels.}
  9582. bar:
  9583. @r{@dots{}}
  9584. @}
  9585. goto bar;
  9586. @}
  9587. @end group
  9588. @end example
  9589. Except for labels, a declared identifier is not
  9590. visible to code before its declaration. For example:
  9591. @example
  9592. @group
  9593. int x = 5;
  9594. int y = x + 10;
  9595. @end group
  9596. @end example
  9597. @noindent
  9598. will work, but:
  9599. @example
  9600. @group
  9601. int x = y + 10;
  9602. int y = 5;
  9603. @end group
  9604. @end example
  9605. @noindent
  9606. cannot refer to the variable @code{y} before its declaration.
  9607. @include cpp.texi
  9608. @node Integers in Depth
  9609. @chapter Integers in Depth
  9610. This chapter explains the machine-level details of integer types: how
  9611. they are represented as bits in memory, and the range of possible
  9612. values for each integer type.
  9613. @menu
  9614. * Integer Representations:: How integer values appear in memory.
  9615. * Maximum and Minimum Values:: Value ranges of integer types.
  9616. @end menu
  9617. @node Integer Representations
  9618. @section Integer Representations
  9619. @cindex integer representations
  9620. @cindex representation of integers
  9621. Modern computers store integer values as binary (base-2) numbers that
  9622. occupy a single unit of storage, typically either as an 8-bit
  9623. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9624. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9625. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9626. any of these types could have some other size, bit it's not worth even
  9627. a minute to cater to that possibility. It never happens on
  9628. GNU/Linux.}
  9629. @cindex @code{CHAR_BIT}
  9630. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9631. of bits in type @code{char}. On any real operating system, the value
  9632. is 8.
  9633. The fixed sizes of numeric types necessarily limits their @dfn{range
  9634. of values}, and the particular encoding of integers decides what that
  9635. range is.
  9636. @cindex two's-complement representation
  9637. For unsigned integers, the entire space is used to represent a
  9638. nonnegative value. Signed integers are stored using
  9639. @dfn{two's-complement representation}: a signed integer with @var{n}
  9640. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9641. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9642. high-order, bit is called the @dfn{sign bit}.
  9643. @c ??? Needs correcting
  9644. There is only one value that means zero, and the most negative number
  9645. lacks a positive counterpart. As a result, negating that number
  9646. causes overflow; in practice, its result is that number back again.
  9647. For example, a two's-complement signed 8-bit integer can represent all
  9648. decimal numbers from @minus{}128 to +127. We will revisit that
  9649. peculiarity shortly.
  9650. Decades ago, there were computers that didn't use two's-complement
  9651. representation for integers (@pxref{Integers in Depth}), but they are
  9652. long gone and not worth any effort to support.
  9653. @c ??? Is this duplicate?
  9654. When an arithmetic operation produces a value that is too big to
  9655. represent, the operation is said to @dfn{overflow}. In C, integer
  9656. overflow does not interrupt the control flow or signal an error.
  9657. What it does depends on signedness.
  9658. For unsigned arithmetic, the result of an operation that overflows is
  9659. the @var{n} low-order bits of the correct value. If the correct value
  9660. is representable in @var{n} bits, that is always the result;
  9661. thus we often say that ``integer arithmetic is exact,'' omitting the
  9662. crucial qualifying phrase ``as long as the exact result is
  9663. representable.''
  9664. In principle, a C program should be written so that overflow never
  9665. occurs for signed integers, but in GNU C you can specify various ways
  9666. of handling such overflow (@pxref{Integer Overflow}).
  9667. Integer representations are best understood by looking at a table for
  9668. a tiny integer size; here are the possible values for an integer with
  9669. three bits:
  9670. @multitable @columnfractions .25 .25 .25 .25
  9671. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9672. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9673. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9674. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9675. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9676. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9677. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9678. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9679. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9680. @end multitable
  9681. The parenthesized decimal numbers in the last column represent the
  9682. signed meanings of the two's-complement of the line's value. Recall
  9683. that, in two's-complement encoding, the high-order bit is 0 when
  9684. the number is nonnegative.
  9685. We can now understand the peculiar behavior of negation of the
  9686. most negative two's-complement integer: start with 0b100,
  9687. invert the bits to get 0b011, and add 1: we get
  9688. 0b100, the value we started with.
  9689. We can also see overflow behavior in two's-complement:
  9690. @example
  9691. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9692. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9693. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9694. @end example
  9695. @noindent
  9696. A sum of two nonnegative signed values that overflows has a 1 in the
  9697. sign bit, so the exact positive result is truncated to a negative
  9698. value.
  9699. @c =====================================================================
  9700. @node Maximum and Minimum Values
  9701. @section Maximum and Minimum Values
  9702. @cindex maximum integer values
  9703. @cindex minimum integer values
  9704. @cindex integer ranges
  9705. @cindex ranges of integer types
  9706. @findex INT_MAX
  9707. @findex UINT_MAX
  9708. @findex SHRT_MAX
  9709. @findex LONG_MAX
  9710. @findex LLONG_MAX
  9711. @findex USHRT_MAX
  9712. @findex ULONG_MAX
  9713. @findex ULLONG_MAX
  9714. @findex CHAR_MAX
  9715. @findex SCHAR_MAX
  9716. @findex UCHAR_MAX
  9717. For each primitive integer type, there is a standard macro defined in
  9718. @file{limits.h} that gives the largest value that type can hold. For
  9719. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9720. On a 32-bit computer, that is equal to 2,147,483,647. The
  9721. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9722. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9723. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9724. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9725. @code{ULLONG_MAX}.
  9726. Since there are three ways to specify a @code{char} type, there are
  9727. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9728. @code{UCHAR_MAX}.
  9729. For each type that is or might be signed, there is another symbol that
  9730. gives the minimum value it can hold. (Just replace @code{MAX} with
  9731. @code{MIN} in the names listed above.) There is no minimum limit
  9732. symbol for types specified with @code{unsigned} because the
  9733. minimum for them is universally zero.
  9734. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9735. two's-complement representation, the most negative number is 1 less
  9736. than the negative of the most positive number. Thus, @code{INT_MIN}
  9737. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9738. actually write the value that way in C, since it would overflow.
  9739. That's a good reason to use @code{INT_MIN} to specify
  9740. that value. Its definition is written to avoid overflow.
  9741. @include fp.texi
  9742. @node Compilation
  9743. @chapter Compilation
  9744. @cindex object file
  9745. @cindex compilation module
  9746. @cindex make rules
  9747. @cindex link
  9748. Early in the manual we explained how to compile a simple C program
  9749. that consists of a single source file (@pxref{Compile Example}).
  9750. However, we handle only short programs that way. A typical C program
  9751. consists of many source files, each of which is usually a separate
  9752. @dfn{compilation module}---meaning that it has to be compiled
  9753. separately. (The source files that are not separate compilation
  9754. modules are those that are used via @code{#include}; see @ref{Header
  9755. Files}.)
  9756. To compile a multi-module program, you compile each of the program's
  9757. compilation modules, making an @dfn{object file} for that module. The
  9758. last step is to @dfn{link} the many object files together into a
  9759. single executable for the whole program.
  9760. The full details of how to compile C programs (and other programs)
  9761. with GCC are documented in xxxx.
  9762. @c ??? ref
  9763. Here we give only a simple introduction.
  9764. These commands compile two compilation modules, @file{foo.c} and
  9765. @file{bar.c}, running the compiler for each module:
  9766. @example
  9767. gcc -c -O -g foo.c
  9768. gcc -c -O -g bar.c
  9769. @end example
  9770. @noindent
  9771. In these commands, @option{-g} says to generate debugging information,
  9772. @option{-O} says to do some optimization, and @option{-c} says to put
  9773. the compiled code for that module into a corresponding object file and
  9774. go no further. The object file for @file{foo.c} is automatically
  9775. called @file{foo.o}, and so on.
  9776. If you wish, you can specify the additional compilation options. For
  9777. instance, @option{-Wformat -Wparenthesis -Wstrict-prototypes} request
  9778. additional warnings.
  9779. @cindex linking object files
  9780. After you compile all the program's modules, you link the object files
  9781. into a combined executable, like this:
  9782. @example
  9783. gcc -o foo foo.o bar.o
  9784. @end example
  9785. @noindent
  9786. In this command, @option{-o foo} species the file name for the
  9787. executable file, and the other arguments are the object files to link.
  9788. Always specify the executable file name in a command that generates
  9789. one.
  9790. One reason to divide a large program into multiple compilation modules
  9791. is to control how each module can access the internals of the others.
  9792. When a module declares a function or variable @code{extern}, other
  9793. modules can access it. The other functions and variables defined in a
  9794. module can't be accessed from outside that module.
  9795. The other reason for using multiple modules is so that changing one
  9796. source file does not require recompiling all of them in order to try
  9797. the modified program. It is sufficient to recompile the source file
  9798. that you changed, then link them all again. Dividing a large program
  9799. into many substantial modules in this way typically makes
  9800. recompilation much faster.
  9801. Normally we don't run any of these commands directly. Instead we
  9802. write a set of @dfn{make rules} for the program, then use the
  9803. @command{make} program to recompile only the source files that need to
  9804. be recompiled, by following those rules. @xref{Top, The GNU Make
  9805. Mamual, , Make, The GNU Make Manual}.
  9806. @node Directing Compilation
  9807. @chapter Directing Compilation
  9808. This chapter describes C constructs that don't alter the program's
  9809. meaning @emph{as such}, but rather direct the compiler how to treat
  9810. some aspects of the program.
  9811. @menu
  9812. * Pragmas:: Controling compilation of some constructs.
  9813. * Static Assertions:: Compile-time tests for conditions.
  9814. @end menu
  9815. @node Pragmas
  9816. @section Pragmas
  9817. A @dfn{pragma} is an annotation in a program that gives direction to
  9818. the compiler.
  9819. @menu
  9820. * Pragma Basics:: Pragma syntax and usage.
  9821. * Severity Pragmas:: Settings for compile-time pragma output.
  9822. * Optimization Pragmas:: Controlling optimizations.
  9823. @end menu
  9824. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9825. @node Pragma Basics
  9826. @subsection Pragma Basics
  9827. C defines two syntactical forms for pragmas, the line form and the
  9828. token form. You can write any pragma in either form, with the same
  9829. meaning.
  9830. The line form is a line in the source code, like this:
  9831. @example
  9832. #pragma @var{line}
  9833. @end example
  9834. @noindent
  9835. The line pragma has no effect on the parsing of the lines around it.
  9836. This form has the drawback that it can't be generated by a macro expansion.
  9837. The token form is a series of tokens; it can appear anywhere in the
  9838. program between the other tokens.
  9839. @example
  9840. _Pragma (@var{stringconstant})
  9841. @end example
  9842. @noindent
  9843. The pragma has no effect on the syntax of the tokens that surround it;
  9844. thus, here's a pragma in the middle of an @code{if} statement:
  9845. @example
  9846. if _Pragma ("hello") (x > 1)
  9847. @end example
  9848. @noindent
  9849. However, that's an unclear thing to do; for the sake of
  9850. understandability, it is better to put a pragma on a line by itself
  9851. and not embedded in the middle of another construct.
  9852. Both forms of pragma have a textual argument. In a line pragma, the
  9853. text is the rest of the line. The textual argument to @code{_Pragma}
  9854. uses the same syntax as a C string constant: surround the text with
  9855. two @samp{"} characters, and add a backslash before each @samp{"} or
  9856. @samp{\} character in it.
  9857. With either syntax, the textual argument specifies what to do.
  9858. It begins with one or several words that specify the operation.
  9859. If the compiler does not recognize them, it ignores the pragma.
  9860. Here are the pragma operations supported in GNU C@.
  9861. @c ??? Verify font for []
  9862. @table @code
  9863. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9864. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9865. Declares that the current source file depends on @var{file}, so GNU C
  9866. compares the file times and gives a warning if @var{file} is newer
  9867. than the current source file.
  9868. This directive searches for @var{file} the way @code{#include}
  9869. searches for a non-system header file.
  9870. If @var{message} is given, the warning message includes that text.
  9871. Examples:
  9872. @example
  9873. #pragma GCC dependency "parse.y"
  9874. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9875. rerun fixincludes")
  9876. @end example
  9877. @item #pragma GCC poison @var{identifiers}
  9878. @itemx _Pragma ("GCC poison @var{identifiers}")
  9879. Poisons the identifiers listed in @var{identifiers}.
  9880. This is useful to make sure all mention of @var{identifiers} has been
  9881. deleted from the program and that no reference to them creeps back in.
  9882. If any of those identifiers appears anywhere in the source after the
  9883. directive, it causes a compilation error. For example,
  9884. @example
  9885. #pragma GCC poison printf sprintf fprintf
  9886. sprintf(some_string, "hello");
  9887. @end example
  9888. @noindent
  9889. generates an error.
  9890. If a poisoned identifier appears as part of the expansion of a macro
  9891. that was defined before the identifier was poisoned, it will @emph{not}
  9892. cause an error. Thus, system headers that define macros that use
  9893. the identifier will not cause errors.
  9894. For example,
  9895. @example
  9896. #define strrchr rindex
  9897. _Pragma ("GCC poison rindex")
  9898. strrchr(some_string, 'h');
  9899. @end example
  9900. @noindent
  9901. does not cause a compilation error.
  9902. @item #pragma GCC system_header
  9903. @itemx _Pragma ("GCC system_header")
  9904. Specify treating the rest of the current source file as if it came
  9905. from a system header file. @xref{System Headers, System Headers,
  9906. System Headers, gcc, Using the GNU Compiler Collection}.
  9907. @item #pragma GCC warning @var{message}
  9908. @itemx _Pragma ("GCC warning @var{message}")
  9909. Equivalent to @code{#warning}. Its advantage is that the
  9910. @code{_Pragma} form can be included in a macro definition.
  9911. @item #pragma GCC error @var{message}
  9912. @itemx _Pragma ("GCC error @var{message}")
  9913. Equivalent to @code{#error}. Its advantage is that the
  9914. @code{_Pragma} form can be included in a macro definition.
  9915. @item #pragma GCC message @var{message}
  9916. @itemx _Pragma ("GCC message @var{message}")
  9917. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9918. informational message, and could be used to include additional warning
  9919. or error text without triggering more warnings or errors. (Note that
  9920. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9921. @samp{GCC} as part of the pragma.)
  9922. @end table
  9923. @node Severity Pragmas
  9924. @subsection Severity Pragmas
  9925. These pragmas control the severity of classes of diagnostics.
  9926. You can specify the class of diagnostic with the GCC option that causes
  9927. those diagnostics to be generated.
  9928. @table @code
  9929. @item #pragma GCC diagnostic error @var{option}
  9930. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9931. For code following this pragma, treat diagnostics of the variety
  9932. specified by @var{option} as errors. For example:
  9933. @example
  9934. _Pragma ("GCC diagnostic error -Wformat")
  9935. @end example
  9936. @noindent
  9937. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9938. as errors rather than warnings.
  9939. @item #pragma GCC diagnostic warning @var{option}
  9940. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9941. For code following this pragma, treat diagnostics of the variety
  9942. specified by @var{option} as warnings. This overrides the
  9943. @var{-Werror} option which says to treat warnings as errors.
  9944. @item #pragma GCC diagnostic ignore @var{option}
  9945. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9946. For code following this pragma, refrain from reporting any diagnostics
  9947. of the variety specified by @var{option}.
  9948. @item #pragma GCC diagnostic push
  9949. @itemx _Pragma ("GCC diagnostic push")
  9950. @itemx #pragma GCC diagnostic pop
  9951. @itemx _Pragma ("GCC diagnostic pop")
  9952. These pragmas maintain a stack of states for severity settings.
  9953. @samp{GCC diagnostic push} saves the current settings on the stack,
  9954. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9955. the current settings from that.
  9956. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9957. restores the settings to what they were at the start of compilation.
  9958. Here is an example:
  9959. @example
  9960. _Pragma ("GCC diagnostic error -Wformat")
  9961. /* @r{@option{-Wformat} messages treated as errors. } */
  9962. _Pragma ("GCC diagnostic push")
  9963. _Pragma ("GCC diagnostic warning -Wformat")
  9964. /* @r{@option{-Wformat} messages treated as warnings. } */
  9965. _Pragma ("GCC diagnostic push")
  9966. _Pragma ("GCC diagnostic ignored -Wformat")
  9967. /* @r{@option{-Wformat} messages suppressed. } */
  9968. _Pragma ("GCC diagnostic pop")
  9969. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9970. _Pragma ("GCC diagnostic pop")
  9971. /* @r{@option{-Wformat} messages treated as errors again. } */
  9972. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9973. _Pragma ("GCC diagnostic pop")
  9974. /* @r{@option{-Wformat} messages treated once again}
  9975. @r{as specified by the GCC command-line options.} */
  9976. @end example
  9977. @end table
  9978. @node Optimization Pragmas
  9979. @subsection Optimization Pragmas
  9980. These pragmas enable a particular optimization for specific function
  9981. definitions. The settings take effect at the end of a function
  9982. definition, so the clean place to use these pragmas is between
  9983. function definitions.
  9984. @table @code
  9985. @item #pragma GCC optimize @var{optimization}
  9986. @itemx _Pragma ("GCC optimize @var{optimization}")
  9987. These pragmas enable the optimization @var{optimization} for the
  9988. following functions. For example,
  9989. @example
  9990. _Pragma ("GCC optimize -fforward-propagate")
  9991. @end example
  9992. @noindent
  9993. says to apply the @samp{forward-propagate} optimization to all
  9994. following function definitions. Specifying optimizations for
  9995. individual functions, rather than for the entire program, is rare but
  9996. can be useful for getting around a bug in the compiler.
  9997. If @var{optimization} does not correspond to a defined optimization
  9998. option, the pragma is erroneous. To turn off an optimization, use the
  9999. corresponding @samp{-fno-} option, such as
  10000. @samp{-fno-forward-propagate}.
  10001. @item #pragma GCC target @var{optimizations}
  10002. @itemx _Pragma ("GCC target @var{optimizations}")
  10003. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  10004. used for platform-specific optimizations. Thus,
  10005. @example
  10006. _Pragma ("GCC target popcnt")
  10007. @end example
  10008. @noindent
  10009. activates the optimization @samp{popcnt} for all
  10010. following function definitions. This optimization is supported
  10011. on a few common targets but not on others.
  10012. @item #pragma GCC push_options
  10013. @itemx _Pragma ("GCC push_options")
  10014. The @samp{push_options} pragma saves on a stack the current settings
  10015. specified with the @samp{target} and @samp{optimize} pragmas.
  10016. @item #pragma GCC pop_options
  10017. @itemx _Pragma ("GCC pop_options")
  10018. The @samp{pop_options} pragma pops saved settings from that stack.
  10019. Here's an example of using this stack.
  10020. @example
  10021. _Pragma ("GCC push_options")
  10022. _Pragma ("GCC optimize forward-propagate")
  10023. /* @r{Functions to compile}
  10024. @r{with the @code{forward-propagate} optimization.} */
  10025. _Pragma ("GCC pop_options")
  10026. /* @r{Ends enablement of @code{forward-propagate}.} */
  10027. @end example
  10028. @item #pragma GCC reset_options
  10029. @itemx _Pragma ("GCC reset_options")
  10030. Clears all pragma-defined @samp{target} and @samp{optimize}
  10031. optimization settings.
  10032. @end table
  10033. @node Static Assertions
  10034. @section Static Assertions
  10035. @cindex static assertions
  10036. @findex _Static_assert
  10037. You can add compiler-time tests for necessary conditions into your
  10038. code using @code{_Static_assert}. This can be useful, for example, to
  10039. check that the compilation target platform supports the type sizes
  10040. that the code expects. For example,
  10041. @example
  10042. _Static_assert ((sizeof (long int) >= 8),
  10043. "long int needs to be at least 8 bytes");
  10044. @end example
  10045. @noindent
  10046. reports a compile-time error if compiled on a system with long
  10047. integers smaller than 8 bytes, with @samp{long int needs to be at
  10048. least 8 bytes} as the error message.
  10049. Since calls @code{_Static_assert} are processed at compile time, the
  10050. expression must be computable at compile time and the error message
  10051. must be a literal string. The expression can refer to the sizes of
  10052. variables, but can't refer to their values. For example, the
  10053. following static assertion is invalid for two reasons:
  10054. @example
  10055. char *error_message
  10056. = "long int needs to be at least 8 bytes";
  10057. int size_of_long_int = sizeof (long int);
  10058. _Static_assert (size_of_long_int == 8, error_message);
  10059. @end example
  10060. @noindent
  10061. The expression @code{size_of_long_int == 8} isn't computable at
  10062. compile time, and the error message isn't a literal string.
  10063. You can, though, use preprocessor definition values with
  10064. @code{_Static_assert}:
  10065. @example
  10066. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10067. at least 8 bytes"
  10068. _Static_assert ((sizeof (long int) == 8),
  10069. LONG_INT_ERROR_MESSAGE);
  10070. @end example
  10071. Static assertions are permitted wherever a statement or declaration is
  10072. permitted, including at top level in the file, and also inside the
  10073. definition of a type.
  10074. @example
  10075. union y
  10076. @{
  10077. int i;
  10078. int *ptr;
  10079. _Static_assert (sizeof (int *) == sizeof (int),
  10080. "Pointer and int not same size");
  10081. @};
  10082. @end example
  10083. @node Type Alignment
  10084. @appendix Type Alignment
  10085. @cindex type alignment
  10086. @cindex alignment of type
  10087. @findex _Alignof
  10088. @findex __alignof__
  10089. Code for device drivers and other communication with low-level
  10090. hardware sometimes needs to be concerned with the alignment of
  10091. data objects in memory.
  10092. Each data type has a required @dfn{alignment}, always a power of 2,
  10093. that says at which memory addresses an object of that type can validly
  10094. start. A valid address for the type must be a multiple of its
  10095. alignment. If a type's alignment is 1, that means it can validly
  10096. start at any address. If a type's alignment is 2, that means it can
  10097. only start at an even address. If a type's alignment is 4, that means
  10098. it can only start at an address that is a multiple of 4.
  10099. The alignment of a type (except @code{char}) can vary depending on the
  10100. kind of computer in use. To refer to the alignment of a type in a C
  10101. program, use @code{_Alignof}, whose syntax parallels that of
  10102. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10103. operation, and it doesn't compute the value of the expression used
  10104. as its argument.
  10105. Nominally, each integer and floating-point type has an alignment equal to
  10106. the largest power of 2 that divides its size. Thus, @code{int} with
  10107. size 4 has a nominal alignment of 4, and @code{long long int} with
  10108. size 8 has a nominal alignment of 8.
  10109. However, each kind of computer generally has a maximum alignment, and
  10110. no type needs more alignment than that. If the computer's maximum
  10111. alignment is 4 (which is common), then no type's alignment is more
  10112. than 4.
  10113. The size of any type is always a multiple of its alignment; that way,
  10114. in an array whose elements have that type, all the elements are
  10115. properly aligned if the first one is.
  10116. These rules apply to all real computers today, but some embedded
  10117. controllers have odd exceptions. We don't have references to cite for
  10118. them.
  10119. @c We can't cite a nonfree manual as documentation.
  10120. Ordinary C code guarantees that every object of a given type is in
  10121. fact aligned as that type requires.
  10122. If the operand of @code{_Alignof} is a structure field, the value
  10123. is the alignment it requires. It may have a greater alignment by
  10124. coincidence, due to the other fields, but @code{_Alignof} is not
  10125. concerned about that. @xref{Structures}.
  10126. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10127. but now that the feature has been standardized, it is better
  10128. to use the standard keyword @code{_Alignof}.
  10129. @findex _Alignas
  10130. @findex __aligned__
  10131. You can explicitly specify an alignment requirement for a particular
  10132. variable or structure field by adding @code{_Alignas
  10133. (@var{alignment})} to the declaration, where @var{alignment} is a
  10134. power of 2 or a type name. For instance:
  10135. @example
  10136. char _Alignas (8) x;
  10137. @end example
  10138. @noindent
  10139. or
  10140. @example
  10141. char _Alignas (double) x;
  10142. @end example
  10143. @noindent
  10144. specifies that @code{x} must start on an address that is a multiple of
  10145. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10146. machine, that maximum is how much alignment @code{x} will get.
  10147. The older GNU C syntax for this feature looked like
  10148. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10149. declaration, and was added after the variable. For instance:
  10150. @example
  10151. char x __attribute__ ((__aligned__ 8));
  10152. @end example
  10153. @xref{Attributes}.
  10154. @node Aliasing
  10155. @appendix Aliasing
  10156. @cindex aliasing (of storage)
  10157. @cindex pointer type conversion
  10158. @cindex type conversion, pointer
  10159. We have already presented examples of casting a @code{void *} pointer
  10160. to another pointer type, and casting another pointer type to
  10161. @code{void *}.
  10162. One common kind of pointer cast is guaranteed safe: casting the value
  10163. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10164. Allocation}). It is safe because these functions do not save the
  10165. pointer anywhere else; the only way the program will access the newly
  10166. allocated memory is via the pointer just returned.
  10167. In fact, C allows casting any pointer type to any other pointer type.
  10168. Using this to access the same place in memory using two
  10169. different data types is called @dfn{aliasing}.
  10170. Aliasing is necessary in some programs that do sophisticated memory
  10171. management, such as GNU Emacs, but most C programs don't need to do
  10172. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10173. aliasing correctly requires following the rules stated below.
  10174. Otherwise, the aliasing may result in malfunctions when the program
  10175. runs.
  10176. The rest of this appendix explains the pitfalls and rules of aliasing.
  10177. @menu
  10178. * Aliasing Alignment:: Memory alignment considerations for
  10179. casting between pointer types.
  10180. * Aliasing Length:: Type size considerations for
  10181. casting between pointer types.
  10182. * Aliasing Type Rules:: Even when type alignment and size matches,
  10183. aliasing can still have surprising results.
  10184. @end menu
  10185. @node Aliasing Alignment
  10186. @appendixsection Aliasing and Alignment
  10187. In order for a type-converted pointer to be valid, it must have the
  10188. alignment that the new pointer type requires. For instance, on most
  10189. computers, @code{int} has alignment 4; the address of an @code{int}
  10190. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10191. address of a @code{char} is usually not a multiple of 4. Taking the
  10192. address of such a @code{char} and casting it to @code{int *} probably
  10193. results in an invalid pointer. Trying to dereference it may cause a
  10194. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10195. @example
  10196. foo ()
  10197. @{
  10198. char i[4];
  10199. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10200. return *p; /* @r{Crash!} */
  10201. @}
  10202. @end example
  10203. This requirement is never a problem when casting the return value
  10204. of @code{malloc} because that function always returns a pointer
  10205. with as much alignment as any type can require.
  10206. @node Aliasing Length
  10207. @appendixsection Aliasing and Length
  10208. When converting a pointer to a different pointer type, make sure the
  10209. object it really points to is at least as long as the target of the
  10210. converted pointer. For instance, suppose @code{p} has type @code{int
  10211. *} and it's cast as follows:
  10212. @example
  10213. int *p;
  10214. struct
  10215. @{
  10216. double d, e, f;
  10217. @} foo;
  10218. struct foo *q = (struct foo *)p;
  10219. q->f = 5.14159;
  10220. @end example
  10221. @noindent
  10222. the value @code{q->f} will run past the end of the @code{int} that
  10223. @code{p} points to. If @code{p} was initialized to the start of an
  10224. array of type @code{int[6]}, the object is long enough for three
  10225. @code{double}s. But if @code{p} points to something shorter,
  10226. @code{q->f} will run on beyond the end of that, overlaying some other
  10227. data. Storing that will garble that other data. Or it could extend
  10228. past the end of memory space and cause a @code{SIGSEGV} signal
  10229. (@pxref{Signals}).
  10230. @node Aliasing Type Rules
  10231. @appendixsection Type Rules for Aliasing
  10232. C code that converts a pointer to a different pointer type can use the
  10233. pointers to access the same memory locations with two different data
  10234. types. If the same address is accessed with different types in a
  10235. single control thread, optimization can make the code do surprising
  10236. things (in effect, make it malfunction).
  10237. Here's a concrete example where aliasing that can change the code's
  10238. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10239. long, like @code{int}, and so is every pointer. Thus, the structures
  10240. @code{struct a} and @code{struct b} are both 8 bytes.
  10241. @example
  10242. #include <stdio.h>
  10243. struct a @{ int size; char *data; @};
  10244. struct b @{ float size; char *data; @};
  10245. void sub (struct a *p, struct b *q)
  10246. @{
  10247.   int x;
  10248.   p->size = 0;
  10249.   q->size = 1;
  10250.   x = p->size;
  10251.   printf("x       =%d\n", x);
  10252.   printf("p->size =%d\n", (int)p->size);
  10253.   printf("q->size =%d\n", (int)q->size);
  10254. @}
  10255. int main(void)
  10256. @{
  10257.   struct a foo;
  10258.   struct a *p = &foo;
  10259.   struct b *q = (struct b *) &foo;
  10260.   sub (p, q);
  10261. @}
  10262. @end example
  10263. This code works as intended when compiled without optimization. All
  10264. the operations are carried out sequentially as written. The code
  10265. sets @code{x} to @code{p->size}, but what it actually gets is the
  10266. bits of the floating point number 1, as type @code{int}.
  10267. However, when optimizing, the compiler is allowed to assume
  10268. (mistakenly, here) that @code{q} does not point to the same storage as
  10269. @code{p}, because their data types are not allowed to alias.
  10270. From this assumption, the compiler can deduce (falsely, here) that the
  10271. assignment into @code{q->size} has no effect on the value of
  10272. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10273. be set to 0.
  10274. GNU C, following the C standard, @emph{defines} this optimization as
  10275. legitimate. Code that misbehaves when optimized following these rules
  10276. is, by definition, incorrect C code.
  10277. The rules for storage aliasing in C are based on the two data types:
  10278. the type of the object, and the type it is accessed through. The
  10279. rules permit accessing part of a storage object of type @var{t} using
  10280. only these types:
  10281. @itemize @bullet
  10282. @item
  10283. @var{t}.
  10284. @item
  10285. A type compatible with @var{t}. @xref{Compatible Types}.
  10286. @item
  10287. A signed or unsigned version of one of the above.
  10288. @item
  10289. A qualifed version of one of the above.
  10290. @xref{Type Qualifiers}.
  10291. @item
  10292. An array, structure (@pxref{Structures}), or union type
  10293. (@code{Unions}) that contains one of the above, either directly as a
  10294. field or through multiple levels of fields. If @var{t} is
  10295. @code{double}, this would include @code{struct s @{ union @{ double
  10296. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10297. inside it somewhere.
  10298. @item
  10299. A character type.
  10300. @end itemize
  10301. What do these rules say about the example in this subsection?
  10302. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10303. @code{int}. The type @code{float} is not allowed as an aliasing type
  10304. by those rules, so @code{b->size} is not supposed to alias with
  10305. elements of @code{j}. Based on that assumption, GNU C makes a
  10306. permitted optimization that was not, in this case, consistent with
  10307. what the programmer intended the program to do.
  10308. Whether GCC actually performs type-based aliasing analysis depends on
  10309. the details of the code. GCC has other ways to determine (in some cases)
  10310. whether objects alias, and if it gets a reliable answer that way, it won't
  10311. fall back on type-based heuristics.
  10312. @c @opindex -fno-strict-aliasing
  10313. The importance of knowing the type-based aliasing rules is not so as
  10314. to ensure that the optimization is done where it would be safe, but so
  10315. as to ensure it is @emph{not} done in a way that would break the
  10316. program. You can turn off type-based aliasing analysis by giving GCC
  10317. the option @option{-fno-strict-aliasing}.
  10318. @node Digraphs
  10319. @appendix Digraphs
  10320. @cindex digraphs
  10321. C accepts aliases for certain characters. Apparently in the 1990s
  10322. some computer systems had trouble inputting these characters, or
  10323. trouble displaying them. These digraphs almost never appear in C
  10324. programs nowadays, but we mention them for completeness.
  10325. @table @samp
  10326. @item <:
  10327. An alias for @samp{[}.
  10328. @item :>
  10329. An alias for @samp{]}.
  10330. @item <%
  10331. An alias for @samp{@{}.
  10332. @item %>
  10333. An alias for @samp{@}}.
  10334. @item %:
  10335. An alias for @samp{#},
  10336. used for preprocessing directives (@pxref{Directives}) and
  10337. macros (@pxref{Macros}).
  10338. @end table
  10339. @node Attributes
  10340. @appendix Attributes in Declarations
  10341. @cindex attributes
  10342. @findex __attribute__
  10343. You can specify certain additional requirements in a declaration, to
  10344. get fine-grained control over code generation, and helpful
  10345. informational messages during compilation. We use a few attributes in
  10346. code examples throughout this manual, including
  10347. @table @code
  10348. @item aligned
  10349. The @code{aligned} attribute specifies a minimum alignment for a
  10350. variable or structure field, measured in bytes:
  10351. @example
  10352. int foo __attribute__ ((aligned (8))) = 0;
  10353. @end example
  10354. @noindent
  10355. This directs GNU C to allocate @code{foo} at an address that is a
  10356. multiple of 8 bytes. However, you can't force an alignment bigger
  10357. than the computer's maximum meaningful alignment.
  10358. @item packed
  10359. The @code{packed} attribute specifies to compact the fields of a
  10360. structure by not leaving gaps between fields. For example,
  10361. @example
  10362. struct __attribute__ ((packed)) bar
  10363. @{
  10364. char a;
  10365. int b;
  10366. @};
  10367. @end example
  10368. @noindent
  10369. allocates the integer field @code{b} at byte 1 in the structure,
  10370. immediately after the character field @code{a}. The packed structure
  10371. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10372. alignment is 1, that of @code{char}.
  10373. @item deprecated
  10374. Applicable to both variables and functions, the @code{deprecated}
  10375. attribute tells the compiler to issue a warning if the variable or
  10376. function is ever used in the source file.
  10377. @example
  10378. int old_foo __attribute__ ((deprecated));
  10379. int old_quux () __attribute__ ((deprecated));
  10380. @end example
  10381. @item __noinline__
  10382. The @code{__noinline__} attribute, in a function's declaration or
  10383. definition, specifies never to inline calls to that function. All
  10384. calls to that function, in a compilation unit where it has this
  10385. attribute, will be compiled to invoke the separately compiled
  10386. function. @xref{Inline Function Definitions}.
  10387. @item __noclone__
  10388. The @code{__noclone__} attribute, in a function's declaration or
  10389. definition, specifies never to clone that function. Thus, there will
  10390. be only one compiled version of the function. @xref{Label Value
  10391. Caveats}, for more information about cloning.
  10392. @item always_inline
  10393. The @code{always_inline} attribute, in a function's declaration or
  10394. definition, specifies to inline all calls to that function (unless
  10395. something about the function makes inlining impossible). This applies
  10396. to all calls to that function in a compilation unit where it has this
  10397. attribute. @xref{Inline Function Definitions}.
  10398. @item gnu_inline
  10399. The @code{gnu_inline} attribute, in a function's declaration or
  10400. definition, specifies to handle the @code{inline} keyword the way GNU
  10401. C originally implemented it, many years before ISO C said anything
  10402. about inlining. @xref{Inline Function Definitions}.
  10403. @end table
  10404. For full documentation of attributes, see the GCC manual.
  10405. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10406. the GNU Compiler Collection}.
  10407. @node Signals
  10408. @appendix Signals
  10409. @cindex signal
  10410. @cindex handler (for signal)
  10411. @cindex @code{SIGSEGV}
  10412. @cindex @code{SIGFPE}
  10413. @cindex @code{SIGBUS}
  10414. Some program operations bring about an error condition called a
  10415. @dfn{signal}. These signals terminate the program, by default.
  10416. There are various different kinds of signals, each with a name. We
  10417. have seen several such error conditions through this manual:
  10418. @table @code
  10419. @item SIGSEGV
  10420. This signal is generated when a program tries to read or write outside
  10421. the memory that is allocated for it, or to write memory that can only
  10422. be read. The name is an abbreviation for ``segmentation violation''.
  10423. @item SIGFPE
  10424. This signal indicates a fatal arithmetic error. The name is an
  10425. abbreviation for ``floating-point exception'', but covers all types of
  10426. arithmetic errors, including division by zero and overflow.
  10427. @item SIGBUS
  10428. This signal is generated when an invalid pointer is dereferenced,
  10429. typically the result of dereferencing an uninintalized pointer. It is
  10430. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10431. invalid access to valid memory, while @code{SIGBUS} indicates an
  10432. attempt to access an invalid address.
  10433. @end table
  10434. These kinds of signal allow the program to specify a function as a
  10435. @dfn{signal handler}. When a signal has a handler, it doesn't
  10436. terminate the program; instead it calls the handler.
  10437. There are many other kinds of signal; here we list only those that
  10438. come from run-time errors in C operations. The rest have to do with
  10439. the functioning of the operating system. The GNU C Library Reference
  10440. Manual gives more explanation about signals (@pxref{Program Signal
  10441. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10442. Manual}).
  10443. @node GNU Free Documentation License
  10444. @appendix GNU Free Documentation License
  10445. @include fdl.texi
  10446. @node Symbol Index
  10447. @unnumbered Index of Symbols and Keywords
  10448. @printindex fn
  10449. @node Concept Index
  10450. @unnumbered Concept Index
  10451. @printindex cp
  10452. @bye