c.texi 426 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174
  1. \input texinfo
  2. @c Copyright (C) 2022 Richard Stallman and Free Software Foundation, Inc.
  3. @c (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. @c licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @c Merge variable index into the function index.
  10. @synindex vr fn
  11. @copying
  12. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  13. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  14. licensed to the FSF.)
  15. @quotation
  16. Permission is granted to copy, distribute and/or modify this document
  17. under the terms of the GNU Free Documentation License, Version 1.3 or
  18. any later version published by the Free Software Foundation; with the
  19. Invariant Sections being ``GNU General Public License,'' with the
  20. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  21. Texts as in (a) below. A copy of the license is included in the
  22. section entitled ``GNU Free Documentation License.''
  23. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  24. modify this GNU manual.''
  25. @end quotation
  26. @end copying
  27. @dircategory Programming
  28. @direntry
  29. * C: (c). GNU C Language Intro and Reference Manual
  30. @end direntry
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Introduction}
  34. @center @titlefont{and Reference Manual}
  35. @sp 4
  36. @c @center @value{EDITION} Edition
  37. @sp 5
  38. @center Richard Stallman
  39. @center and
  40. @center Trevis Rothwell
  41. @center plus Nelson Beebe
  42. @center on floating point
  43. @page
  44. @vskip 0pt plus 1filll
  45. @insertcopying
  46. @sp 2
  47. @ignore
  48. WILL BE Published by the Free Software Foundation @*
  49. 51 Franklin Street, Fifth Floor @*
  50. Boston, MA 02110-1301 USA @*
  51. ISBN ?-??????-??-?
  52. @end ignore
  53. @ignore
  54. @sp 1
  55. Cover art by J. Random Artist
  56. @end ignore
  57. @end titlepage
  58. @summarycontents
  59. @contents
  60. @node Top
  61. @ifnottex
  62. @top GNU C Manual
  63. @end ifnottex
  64. @iftex
  65. @top Preface
  66. @end iftex
  67. This manual explains the C language for use with the GNU Compiler
  68. Collection (GCC) on the GNU/Linux system and other systems. We refer
  69. to this dialect as GNU C. If you already know C, you can use this as
  70. a reference manual.
  71. If you understand basic concepts of programming but know nothing about
  72. C, you can read this manual sequentially from the beginning to learn
  73. the C language.
  74. If you are a beginner in programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are provided by
  112. functions defined in the standard library, which is automatically
  113. available in every C program. @xref{Top, The GNU C Library, , libc,
  114. The GNU C Library Reference Manual}.
  115. GNU/Linux systems use the GNU C Library to do this job. It is itself
  116. a C program, so once you know C you can read its source code and see
  117. how its library functions do their jobs. Some fraction of the
  118. functions are implemented as @dfn{system calls}, which means they
  119. contain a special instruction that asks the system kernel (Linux) to
  120. do a specific task. To understand how those are implemented, you'd
  121. need to read Linux source code instead. Whether a library function is
  122. a system call is an internal implementation detail that makes no
  123. difference for how to call the function.
  124. This manual incorporates the former GNU C Preprocessor Manual, which
  125. was among the earliest GNU manuals. It also uses some text from the
  126. earlier GNU C Manual that was written by Trevis Rothwell and James
  127. Youngman.
  128. GNU C has many obscure features, each one either for historical
  129. compatibility or meant for very special situations. We have left them
  130. to a companion manual, the GNU C Obscurities Manual, which will be
  131. published digitally later.
  132. Please report errors and suggestions to c-manual@@gnu.org.
  133. @menu
  134. * The First Example:: Getting started with basic C code.
  135. * Complete Program:: A whole example program
  136. that can be compiled and run.
  137. * Storage:: Basic layout of storage; bytes.
  138. * Beyond Integers:: Exploring different numeric types.
  139. * Lexical Syntax:: The various lexical components of C programs.
  140. * Arithmetic:: Numeric computations.
  141. * Assignment Expressions:: Storing values in variables.
  142. * Execution Control Expressions:: Expressions combining values in various ways.
  143. * Binary Operator Grammar:: An overview of operator precedence.
  144. * Order of Execution:: The order of program execution.
  145. * Primitive Types:: More details about primitive data types.
  146. * Constants:: Explicit constant values:
  147. details and examples.
  148. * Type Size:: The memory space occupied by a type.
  149. * Pointers:: Creating and manipulating memory pointers.
  150. * Structures:: Compound data types built
  151. by grouping other types.
  152. * Arrays:: Creating and manipulating arrays.
  153. * Enumeration Types:: Sets of integers with named values.
  154. * Defining Typedef Names:: Using @code{typedef} to define type names.
  155. * Statements:: Controlling program flow.
  156. * Variables:: Details about declaring, initializing,
  157. and using variables.
  158. * Type Qualifiers:: Mark variables for certain intended uses.
  159. * Functions:: Declaring, defining, and calling functions.
  160. * Compatible Types:: How to tell if two types are compatible
  161. with each other.
  162. * Type Conversions:: Converting between types.
  163. * Scope:: Different categories of identifier scope.
  164. * Preprocessing:: Using the GNU C preprocessor.
  165. * Integers in Depth:: How integer numbers are represented.
  166. * Floating Point in Depth:: How floating-point numbers are represented.
  167. * Compilation:: How to compile multi-file programs.
  168. * Directing Compilation:: Operations that affect compilation
  169. but don't change the program.
  170. Appendices
  171. * Type Alignment:: Where in memory a type can validly start.
  172. * Aliasing:: Accessing the same data in two types.
  173. * Digraphs:: Two-character aliases for some characters.
  174. * Attributes:: Specifying additional information
  175. in a declaration.
  176. * Signals:: Fatal errors triggered in various scenarios.
  177. * GNU Free Documentation License:: The license for this manual.
  178. * Symbol Index:: Keyword and symbol index.
  179. * Concept Index:: Detailed topical index.
  180. @detailmenu
  181. --- The Detailed Node Listing ---
  182. * Recursive Fibonacci:: Writing a simple function recursively.
  183. * Stack:: Each function call uses space in the stack.
  184. * Iterative Fibonacci:: Writing the same function iteratively.
  185. * Complete Example:: Turn the simple function into a full program.
  186. * Complete Explanation:: Explanation of each part of the example.
  187. * Complete Line-by-Line:: Explaining each line of the example.
  188. * Compile Example:: Using GCC to compile the example.
  189. * Float Example:: A function that uses floating-point numbers.
  190. * Array Example:: A function that works with arrays.
  191. * Array Example Call:: How to call that function.
  192. * Array Example Variations:: Different ways to write the call example.
  193. Lexical Syntax
  194. * English:: Write programs in English!
  195. * Characters:: The characters allowed in C programs.
  196. * Whitespace:: The particulars of whitespace characters.
  197. * Comments:: How to include comments in C code.
  198. * Identifiers:: How to form identifiers (names).
  199. * Operators/Punctuation:: Characters used as operators or punctuation.
  200. * Line Continuation:: Splitting one line into multiple lines.
  201. * Digraphs:: Two-character substitutes for some characters.
  202. Arithmetic
  203. * Basic Arithmetic:: Addition, subtraction, multiplication,
  204. and division.
  205. * Integer Arithmetic:: How C performs arithmetic with integer values.
  206. * Integer Overflow:: When an integer value exceeds the range
  207. of its type.
  208. * Mixed Mode:: Calculating with both integer values
  209. and floating-point values.
  210. * Division and Remainder:: How integer division works.
  211. * Numeric Comparisons:: Comparing numeric values for
  212. equality or order.
  213. * Shift Operations:: Shift integer bits left or right.
  214. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  215. Assignment Expressions
  216. * Simple Assignment:: The basics of storing a value.
  217. * Lvalues:: Expressions into which a value can be stored.
  218. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  219. * Increment/Decrement:: Shorthand for incrementing and decrementing
  220. an lvalue's contents.
  221. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  222. * Assignment in Subexpressions:: How to avoid ambiguity.
  223. * Write Assignments Separately:: Write assignments as separate statements.
  224. Execution Control Expressions
  225. * Logical Operators:: Logical conjunction, disjunction, negation.
  226. * Logicals and Comparison:: Logical operators with comparison operators.
  227. * Logicals and Assignments:: Assignments with logical operators.
  228. * Conditional Expression:: An if/else construct inside expressions.
  229. * Comma Operator:: Build a sequence of subexpressions.
  230. Order of Execution
  231. * Reordering of Operands:: Operations in C are not necessarily computed
  232. in the order they are written.
  233. * Associativity and Ordering:: Some associative operations are performed
  234. in a particular order; others are not.
  235. * Sequence Points:: Some guarantees about the order of operations.
  236. * Postincrement and Ordering:: Ambiguous execution order with postincrement.
  237. * Ordering of Operands:: Evaluation order of operands
  238. and function arguments.
  239. * Optimization and Ordering:: Compiler optimizations can reorder operations
  240. only if it has no impact on program results.
  241. Primitive Data Types
  242. * Integer Types:: Description of integer types.
  243. * Floating-Point Data Types:: Description of floating-point types.
  244. * Complex Data Types:: Description of complex number types.
  245. * The Void Type:: A type indicating no value at all.
  246. * Other Data Types:: A brief summary of other types.
  247. Constants
  248. * Integer Constants:: Literal integer values.
  249. * Integer Const Type:: Types of literal integer values.
  250. * Floating Constants:: Literal floating-point values.
  251. * Imaginary Constants:: Literal imaginary number values.
  252. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  253. * Character Constants:: Literal character values.
  254. * Unicode Character Codes:: Unicode characters represented
  255. in either UTF-16 or UTF-32.
  256. * Wide Character Constants:: Literal characters values larger than 8 bits.
  257. * String Constants:: Literal string values.
  258. * UTF-8 String Constants:: Literal UTF-8 string values.
  259. * Wide String Constants:: Literal string values made up of
  260. 16- or 32-bit characters.
  261. Pointers
  262. * Address of Data:: Using the ``address-of'' operator.
  263. * Pointer Types:: For each type, there is a pointer type.
  264. * Pointer Declarations:: Declaring variables with pointer types.
  265. * Pointer Type Designators:: Designators for pointer types.
  266. * Pointer Dereference:: Accessing what a pointer points at.
  267. * Null Pointers:: Pointers which do not point to any object.
  268. * Invalid Dereference:: Dereferencing null or invalid pointers.
  269. * Void Pointers:: Totally generic pointers, can cast to any.
  270. * Pointer Comparison:: Comparing memory address values.
  271. * Pointer Arithmetic:: Computing memory address values.
  272. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  273. * Low-Level Pointer Arithmetic:: More about computing memory address values.
  274. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  275. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  276. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  277. * Printing Pointers:: Using @code{printf} for a pointer's value.
  278. Structures
  279. * Referencing Fields:: Accessing field values in a structure object.
  280. * Arrays as Fields:: Accessing field values in a structure object.
  281. * Dynamic Memory Allocation:: Allocating space for objects
  282. while the program is running.
  283. * Field Offset:: Memory layout of fields within a structure.
  284. * Structure Layout:: Planning the memory layout of fields.
  285. * Packed Structures:: Packing structure fields as close as possible.
  286. * Bit Fields:: Dividing integer fields
  287. into fields with fewer bits.
  288. * Bit Field Packing:: How bit fields pack together in integers.
  289. * const Fields:: Making structure fields immutable.
  290. * Zero Length:: Zero-length array as a variable-length object.
  291. * Flexible Array Fields:: Another approach to variable-length objects.
  292. * Overlaying Structures:: Casting one structure type
  293. over an object of another structure type.
  294. * Structure Assignment:: Assigning values to structure objects.
  295. * Unions:: Viewing the same object in different types.
  296. * Packing With Unions:: Using a union type to pack various types into
  297. the same memory space.
  298. * Cast to Union:: Casting a value one of the union's alternative
  299. types to the type of the union itself.
  300. * Structure Constructors:: Building new structure objects.
  301. * Unnamed Types as Fields:: Fields' types do not always need names.
  302. * Incomplete Types:: Types which have not been fully defined.
  303. * Intertwined Incomplete Types:: Defining mutually-recursive structure types.
  304. * Type Tags:: Scope of structure and union type tags.
  305. Arrays
  306. * Accessing Array Elements:: How to access individual elements of an array.
  307. * Declaring an Array:: How to name and reserve space for a new array.
  308. * Strings:: A string in C is a special case of array.
  309. * Incomplete Array Types:: Naming, but not allocating, a new array.
  310. * Limitations of C Arrays:: Arrays are not first-class objects.
  311. * Multidimensional Arrays:: Arrays of arrays.
  312. * Constructing Array Values:: Assigning values to an entire array at once.
  313. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  314. Statements
  315. * Expression Statement:: Evaluate an expression, as a statement,
  316. usually done for a side effect.
  317. * if Statement:: Basic conditional execution.
  318. * if-else Statement:: Multiple branches for conditional execution.
  319. * Blocks:: Grouping multiple statements together.
  320. * return Statement:: Return a value from a function.
  321. * Loop Statements:: Repeatedly executing a statement or block.
  322. * switch Statement:: Multi-way conditional choices.
  323. * switch Example:: A plausible example of using @code{switch}.
  324. * Duffs Device:: A special way to use @code{switch}.
  325. * Case Ranges:: Ranges of values for @code{switch} cases.
  326. * Null Statement:: A statement that does nothing.
  327. * goto Statement:: Jump to another point in the source code,
  328. identified by a label.
  329. * Local Labels:: Labels with limited scope.
  330. * Labels as Values:: Getting the address of a label.
  331. * Statement Exprs:: A series of statements used as an expression.
  332. Variables
  333. * Variable Declarations:: Name a variable and and reserve space for it.
  334. * Initializers:: Assigning initial values to variables.
  335. * Designated Inits:: Assigning initial values to array elements
  336. at particular array indices.
  337. * Auto Type:: Obtaining the type of a variable.
  338. * Local Variables:: Variables declared in function definitions.
  339. * File-Scope Variables:: Variables declared outside of
  340. function definitions.
  341. * Static Local Variables:: Variables declared within functions,
  342. but with permanent storage allocation.
  343. * Extern Declarations:: Declaring a variable
  344. which is allocated somewhere else.
  345. * Allocating File-Scope:: When is space allocated
  346. for file-scope variables?
  347. * auto and register:: Historically used storage directions.
  348. * Omitting Types:: The bad practice of declaring variables
  349. with implicit type.
  350. Type Qualifiers
  351. * const:: Variables whose values don't change.
  352. * volatile:: Variables whose values may be accessed
  353. or changed outside of the control of
  354. this program.
  355. * restrict Pointers:: Restricted pointers for code optimization.
  356. * restrict Pointer Example:: Example of how that works.
  357. Functions
  358. * Function Definitions:: Writing the body of a function.
  359. * Function Declarations:: Declaring the interface of a function.
  360. * Function Calls:: Using functions.
  361. * Function Call Semantics:: Call-by-value argument passing.
  362. * Function Pointers:: Using references to functions.
  363. * The main Function:: Where execution of a GNU C program begins.
  364. Type Conversions
  365. * Explicit Type Conversion:: Casting a value from one type to another.
  366. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  367. * Argument Promotions:: Automatic conversion of function parameters.
  368. * Operand Promotions:: Automatic conversion of arithmetic operands.
  369. * Common Type:: When operand types differ, which one is used?
  370. Scope
  371. * Scope:: Different categories of identifier scope.
  372. Preprocessing
  373. * Preproc Overview:: Introduction to the C preprocessor.
  374. * Directives:: The form of preprocessor directives.
  375. * Preprocessing Tokens:: The lexical elements of preprocessing.
  376. * Header Files:: Including one source file in another.
  377. * Macros:: Macro expansion by the preprocessor.
  378. * Conditionals:: Controlling whether to compile some lines
  379. or ignore them.
  380. * Diagnostics:: Reporting warnings and errors.
  381. * Line Control:: Reporting source line numbers.
  382. * Null Directive:: A preprocessing no-op.
  383. Integers in Depth
  384. * Integer Representations:: How integer values appear in memory.
  385. * Maximum and Minimum Values:: Value ranges of integer types.
  386. Floating Point in Depth
  387. * Floating Representations:: How floating-point values appear in memory.
  388. * Floating Type Specs:: Precise details of memory representations.
  389. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  390. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  391. * Exception Flags:: Handling certain conditions in floating point.
  392. * Exact Floating-Point:: Not all floating calculations lose precision.
  393. * Rounding:: When a floating result can't be represented
  394. exactly in the floating-point type in use.
  395. * Rounding Issues:: Avoid magnifying rounding errors.
  396. * Significance Loss:: Subtracting numbers that are almost equal.
  397. * Fused Multiply-Add:: Taking advantage of a special floating-point
  398. instruction for faster execution.
  399. * Error Recovery:: Determining rounding errors.
  400. * Exact Floating Constants:: Precisely specified floating-point numbers.
  401. * Handling Infinity:: When floating calculation is out of range.
  402. * Handling NaN:: What floating calculation is undefined.
  403. * Signed Zeros:: Positive zero vs. negative zero.
  404. * Scaling by the Base:: A useful exact floating-point operation.
  405. * Rounding Control:: Specifying some rounding behaviors.
  406. * Machine Epsilon:: The smallest number you can add to 1.0
  407. and get a sum which is larger than 1.0.
  408. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  409. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  410. * Further Reading:: References for floating-point numbers.
  411. Directing Compilation
  412. * Pragmas:: Controlling compilation of some constructs.
  413. * Static Assertions:: Compile-time tests for conditions.
  414. @end detailmenu
  415. @end menu
  416. @node The First Example
  417. @chapter The First Example
  418. This chapter presents the source code for a very simple C program and
  419. uses it to explain a few features of the language. If you already
  420. know the basic points of C presented in this chapter, you can skim it
  421. or skip it.
  422. We present examples of C source code (other than comments) using a
  423. fixed-width typeface, since that's the way they look when you edit
  424. them in an editor such as GNU Emacs.
  425. @menu
  426. * Recursive Fibonacci:: Writing a simple function recursively.
  427. * Stack:: Each function call uses space in the stack.
  428. * Iterative Fibonacci:: Writing the same function iteratively.
  429. @end menu
  430. @node Recursive Fibonacci
  431. @section Example: Recursive Fibonacci
  432. @cindex recursive Fibonacci function
  433. @cindex Fibonacci function, recursive
  434. To introduce the most basic features of C, let's look at code for a
  435. simple mathematical function that does calculations on integers. This
  436. function calculates the @var{n}th number in the Fibonacci series, in
  437. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  438. 13, 21, 34, 55, @dots{}.
  439. @example
  440. int
  441. fib (int n)
  442. @{
  443. if (n <= 2) /* @r{This avoids infinite recursion.} */
  444. return 1;
  445. else
  446. return fib (n - 1) + fib (n - 2);
  447. @}
  448. @end example
  449. This very simple program illustrates several features of C:
  450. @itemize @bullet
  451. @item
  452. A function definition, whose first two lines constitute the function
  453. header. @xref{Function Definitions}.
  454. @item
  455. A function parameter @code{n}, referred to as the variable @code{n}
  456. inside the function body. @xref{Function Parameter Variables}.
  457. A function definition uses parameters to refer to the argument
  458. values provided in a call to that function.
  459. @item
  460. Arithmetic. C programs add with @samp{+} and subtract with
  461. @samp{-}. @xref{Arithmetic}.
  462. @item
  463. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  464. equal.'' @xref{Numeric Comparisons}.
  465. @item
  466. Integer constants written in base 10.
  467. @xref{Integer Constants}.
  468. @item
  469. A function call. The function call @code{fib (n - 1)} calls the
  470. function @code{fib}, passing as its argument the value @code{n - 1}.
  471. @xref{Function Calls}.
  472. @item
  473. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  474. comment has no effect on the execution of the program. Its purpose is
  475. to provide explanations to people reading the source code. Including
  476. comments in the code is tremendously important---they provide
  477. background information so others can understand the code more quickly.
  478. @xref{Comments}.
  479. In this manual, we present comment text in the variable-width typeface
  480. used for the text of the chapters, not in the fixed-width typeface
  481. used for the rest of the code. That is to make comments easier to
  482. read. This distinction of typeface does not exist in a real file of C
  483. source code.
  484. @item
  485. Two kinds of statements, the @code{return} statement and the
  486. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  487. @item
  488. Recursion. The function @code{fib} calls itself; that is called a
  489. @dfn{recursive call}. These are valid in C, and quite common.
  490. The @code{fib} function would not be useful if it didn't return.
  491. Thus, recursive definitions, to be of any use, must avoid
  492. @dfn{infinite recursion}.
  493. This function definition prevents infinite recursion by specially
  494. handling the case where @code{n} is two or less. Thus the maximum
  495. depth of recursive calls is less than @code{n}.
  496. @end itemize
  497. @menu
  498. * Function Header:: The function's name and how it is called.
  499. * Function Body:: Declarations and statements that implement the function.
  500. @end menu
  501. @node Function Header
  502. @subsection Function Header
  503. @cindex function header
  504. In our example, the first two lines of the function definition are the
  505. @dfn{header}. Its purpose is to state the function's name and say how
  506. it is called:
  507. @example
  508. int
  509. fib (int n)
  510. @end example
  511. @noindent
  512. says that the function returns an integer (type @code{int}), its name is
  513. @code{fib}, and it takes one argument named @code{n} which is also an
  514. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  515. @node Function Body
  516. @subsection Function Body
  517. @cindex function body
  518. @cindex recursion
  519. The rest of the function definition is called the @dfn{function body}.
  520. Like every function body, this one starts with @samp{@{}, ends with
  521. @samp{@}}, and contains zero or more @dfn{statements} and
  522. @dfn{declarations}. Statements specify actions to take, whereas
  523. declarations define names of variables, functions, and so on. Each
  524. statement and each declaration ends with a semicolon (@samp{;}).
  525. Statements and declarations often contain @dfn{expressions}; an
  526. expression is a construct whose execution produces a @dfn{value} of
  527. some data type, but may also take actions through ``side effects''
  528. that alter subsequent execution. A statement, by contrast, does not
  529. have a value; it affects further execution of the program only through
  530. the actions it takes.
  531. This function body contains no declarations, and just one statement,
  532. but that one is a complex statement in that it contains nested
  533. statements. This function uses two kinds of statements:
  534. @table @code
  535. @item return
  536. The @code{return} statement makes the function return immediately.
  537. It looks like this:
  538. @example
  539. return @var{value};
  540. @end example
  541. Its meaning is to compute the expression @var{value} and exit the
  542. function, making it return whatever value that expression produced.
  543. For instance,
  544. @example
  545. return 1;
  546. @end example
  547. @noindent
  548. returns the integer 1 from the function, and
  549. @example
  550. return fib (n - 1) + fib (n - 2);
  551. @end example
  552. @noindent
  553. returns a value computed by performing two function calls
  554. as specified and adding their results.
  555. @item @code{if}@dots{}@code{else}
  556. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  557. Each time it executes, it chooses one of its two substatements to execute
  558. and ignores the other. It looks like this:
  559. @example
  560. if (@var{condition})
  561. @var{if-true-statement}
  562. else
  563. @var{if-false-statement}
  564. @end example
  565. Its meaning is to compute the expression @var{condition} and, if it's
  566. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  567. @var{if-false-statement}. @xref{if-else Statement}.
  568. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  569. simply an expression. It's considered ``true'' if its value is
  570. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  571. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  572. Comparisons}.) Thus,
  573. @example
  574. if (n <= 2)
  575. return 1;
  576. else
  577. return fib (n - 1) + fib (n - 2);
  578. @end example
  579. @noindent
  580. first tests whether the value of @code{n} is less than or equal to 2.
  581. If so, the expression @code{n <= 2} has the value 1. So execution
  582. continues with the statement
  583. @example
  584. return 1;
  585. @end example
  586. @noindent
  587. Otherwise, execution continues with this statement:
  588. @example
  589. return fib (n - 1) + fib (n - 2);
  590. @end example
  591. Each of these statements ends the execution of the function and
  592. provides a value for it to return. @xref{return Statement}.
  593. @end table
  594. Calculating @code{fib} using ordinary integers in C works only for
  595. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  596. in type @code{int}. The addition operation that tries to add
  597. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  598. This occurrence is called @dfn{integer overflow}.
  599. Overflow can manifest itself in various ways, but one thing that can't
  600. possibly happen is to produce the correct value, since that can't fit
  601. in the space for the value. @xref{Integer Overflow}.
  602. @xref{Functions}, for a full explanation about functions.
  603. @node Stack
  604. @section The Stack, And Stack Overflow
  605. @cindex stack
  606. @cindex stack frame
  607. @cindex stack overflow
  608. @cindex recursion, drawbacks of
  609. @cindex stack frame
  610. Recursion has a drawback: there are limits to how many nested levels of
  611. function calls a program can make. In C, each function call allocates a block
  612. of memory which it uses until the call returns. C allocates these
  613. blocks consecutively within a large area of memory known as the
  614. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  615. The size of the stack is limited; if the program tries to use too
  616. much, that causes the program to fail because the stack is full. This
  617. is called @dfn{stack overflow}.
  618. @cindex crash
  619. @cindex segmentation fault
  620. Stack overflow on GNU/Linux typically manifests itself as the
  621. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  622. fault.'' By default, this signal terminates the program immediately,
  623. rather than letting the program try to recover, or reach an expected
  624. ending point. (We commonly say in this case that the program
  625. ``crashes''). @xref{Signals}.
  626. It is inconvenient to observe a crash by passing too large
  627. an argument to recursive Fibonacci, because the program would run a
  628. long time before it crashes. This algorithm is simple but
  629. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  630. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  631. the final result.
  632. However, you can observe stack overflow very quickly if you use
  633. this function instead:
  634. @example
  635. int
  636. fill_stack (int n)
  637. @{
  638. if (n <= 1) /* @r{This limits the depth of recursion.} */
  639. return 1;
  640. else
  641. return fill_stack (n - 1);
  642. @}
  643. @end example
  644. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  645. and using the default configuration, an experiment showed there is
  646. enough stack space to do 261906 nested calls to that function. One
  647. more, and the stack overflows and the program crashes. On another
  648. platform, with a different configuration, or with a different
  649. function, the limit might be bigger or smaller.
  650. @node Iterative Fibonacci
  651. @section Example: Iterative Fibonacci
  652. @cindex iterative Fibonacci function
  653. @cindex Fibonacci function, iterative
  654. Here's a much faster algorithm for computing the same Fibonacci
  655. series. It is faster for two reasons. First, it uses @dfn{iteration}
  656. (that is, repetition or looping) rather than recursion, so it doesn't
  657. take time for a large number of function calls. But mainly, it is
  658. faster because the number of repetitions is small---only @code{@var{n}}.
  659. @c If you change this, change the duplicate in node Example of for.
  660. @example
  661. int
  662. fib (int n)
  663. @{
  664. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  665. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  666. int i;
  667. for (i = 1; i < n; ++i)
  668. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  669. /* @r{since @code{i < n} is false the first time.} */
  670. @{
  671. /* @r{Now @code{last} is @code{fib (@code{i})}}
  672. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  673. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  674. int next = prev + last;
  675. /* @r{Shift the values down.} */
  676. prev = last;
  677. last = next;
  678. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  679. @r{and @code{prev} is @code{fib (@code{i})}.}
  680. @r{But that won't stay true for long,}
  681. @r{because we are about to increment @code{i}.} */
  682. @}
  683. return last;
  684. @}
  685. @end example
  686. This definition computes @code{fib (@var{n})} in a time proportional
  687. to @code{@var{n}}. The comments in the definition explain how it works: it
  688. advances through the series, always keeps the last two values in
  689. @code{last} and @code{prev}, and adds them to get the next value.
  690. Here are the additional C features that this definition uses:
  691. @table @asis
  692. @item Internal blocks
  693. Within a function, wherever a statement is called for, you can write a
  694. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  695. more statements and declarations. (You can also use additional
  696. blocks as statements in a block.)
  697. The function body also counts as a block, which is why it can contain
  698. statements and declarations.
  699. @xref{Blocks}.
  700. @item Declarations of local variables
  701. This function body contains declarations as well as statements. There
  702. are three declarations directly in the function body, as well as a
  703. fourth declaration in an internal block. Each starts with @code{int}
  704. because it declares a variable whose type is integer. One declaration
  705. can declare several variables, but each of these declarations is
  706. simple and declares just one variable.
  707. Variables declared inside a block (either a function body or an
  708. internal block) are @dfn{local variables}. These variables exist only
  709. within that block; their names are not defined outside the block, and
  710. exiting the block deallocates their storage. This example declares
  711. four local variables: @code{last}, @code{prev}, @code{i}, and
  712. @code{next}.
  713. The most basic local variable declaration looks like this:
  714. @example
  715. @var{type} @var{variablename};
  716. @end example
  717. For instance,
  718. @example
  719. int i;
  720. @end example
  721. @noindent
  722. declares the local variable @code{i} as an integer.
  723. @xref{Variable Declarations}.
  724. @item Initializers
  725. When you declare a variable, you can also specify its initial value,
  726. like this:
  727. @example
  728. @var{type} @var{variablename} = @var{value};
  729. @end example
  730. For instance,
  731. @example
  732. int last = 1;
  733. @end example
  734. @noindent
  735. declares the local variable @code{last} as an integer (type
  736. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  737. @item Assignment
  738. Assignment: a specific kind of expression, written with the @samp{=}
  739. operator, that stores a new value in a variable or other place. Thus,
  740. @example
  741. @var{variable} = @var{value}
  742. @end example
  743. @noindent
  744. is an expression that computes @code{@var{value}} and stores the value in
  745. @code{@var{variable}}. @xref{Assignment Expressions}.
  746. @item Expression statements
  747. An expression statement is an expression followed by a semicolon.
  748. That computes the value of the expression, then ignores the value.
  749. An expression statement is useful when the expression changes some
  750. data or has other side effects---for instance, with function calls, or
  751. with assignments as in this example. @xref{Expression Statement}.
  752. Using an expression with no side effects in an expression statement is
  753. pointless except in very special cases. For instance, the expression
  754. statement @code{x;} would examine the value of @code{x} and ignore it.
  755. That is not useful.
  756. @item Increment operator
  757. The increment operator is @samp{++}. @code{++i} is an
  758. expression that is short for @code{i = i + 1}.
  759. @xref{Increment/Decrement}.
  760. @item @code{for} statements
  761. A @code{for} statement is a clean way of executing a statement
  762. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  763. @example
  764. for (i = 1; i < n; ++i)
  765. @var{body}
  766. @end example
  767. @noindent
  768. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  769. for the loop. The loop itself consists of
  770. @itemize @bullet
  771. @item
  772. Testing @code{i < n} and exiting the loop if that's false.
  773. @item
  774. Executing @var{body}.
  775. @item
  776. Advancing the loop (executing @code{++i}, which increments @code{i}).
  777. @end itemize
  778. The net result is to execute @var{body} with 1 in @code{i},
  779. then with 2 in @code{i}, and so on, stopping just before the repetition
  780. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  781. the loop will execute the body zero times.
  782. The body of the @code{for} statement must be one and only one
  783. statement. You can't write two statements in a row there; if you try
  784. to, only the first of them will be treated as part of the loop.
  785. The way to put multiple statements in such a place is to group them
  786. with a block, and that's what we do in this example.
  787. @end table
  788. @node Complete Program
  789. @chapter A Complete Program
  790. @cindex complete example program
  791. @cindex example program, complete
  792. It's all very well to write a Fibonacci function, but you cannot run
  793. it by itself. It is a useful program, but it is not a complete
  794. program.
  795. In this chapter we present a complete program that contains the
  796. @code{fib} function. This example shows how to make the program
  797. start, how to make it finish, how to do computation, and how to print
  798. a result.
  799. @menu
  800. * Complete Example:: Turn the simple function into a full program.
  801. * Complete Explanation:: Explanation of each part of the example.
  802. * Complete Line-by-Line:: Explaining each line of the example.
  803. * Compile Example:: Using GCC to compile the example.
  804. @end menu
  805. @node Complete Example
  806. @section Complete Program Example
  807. Here is the complete program that uses the simple, recursive version
  808. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  809. @example
  810. #include <stdio.h>
  811. int
  812. fib (int n)
  813. @{
  814. if (n <= 2) /* @r{This avoids infinite recursion.} */
  815. return 1;
  816. else
  817. return fib (n - 1) + fib (n - 2);
  818. @}
  819. int
  820. main (void)
  821. @{
  822. printf ("Fibonacci series item %d is %d\n",
  823. 20, fib (20));
  824. return 0;
  825. @}
  826. @end example
  827. @noindent
  828. This program prints a message that shows the value of @code{fib (20)}.
  829. Now for an explanation of what that code means.
  830. @node Complete Explanation
  831. @section Complete Program Explanation
  832. @ifnottex
  833. Here's the explanation of the code of the example in the
  834. previous section.
  835. @end ifnottex
  836. This sample program prints a message that shows the value of @code{fib
  837. (20)}, and exits with code 0 (which stands for successful execution).
  838. Every C program is started by running the function named @code{main}.
  839. Therefore, the example program defines a function named @code{main} to
  840. provide a way to start it. Whatever that function does is what the
  841. program does. @xref{The main Function}.
  842. The @code{main} function is the first one called when the program
  843. runs, but it doesn't come first in the example code. The order of the
  844. function definitions in the source code makes no difference to the
  845. program's meaning.
  846. The initial call to @code{main} always passes certain arguments, but
  847. @code{main} does not have to pay attention to them. To ignore those
  848. arguments, define @code{main} with @code{void} as the parameter list.
  849. (@code{void} as a function's parameter list normally means ``call with
  850. no arguments,'' but @code{main} is a special case.)
  851. The function @code{main} returns 0 because that is
  852. the conventional way for @code{main} to indicate successful execution.
  853. It could instead return a positive integer to indicate failure, and
  854. some utility programs have specific conventions for the meaning of
  855. certain numeric @dfn{failure codes}. @xref{Values from main}.
  856. @cindex @code{printf}
  857. The simplest way to print text in C is by calling the @code{printf}
  858. function, so here we explain very briefly what that function does.
  859. For a full explanation of @code{printf} and the other standard I/O
  860. functions, see @ref{I/O on Streams, The GNU C Library, , libc, The GNU
  861. C Library Reference Manual}.
  862. @cindex standard output
  863. The first argument to @code{printf} is a @dfn{string constant}
  864. (@pxref{String Constants}) that is a template for output. The
  865. function @code{printf} copies most of that string directly as output,
  866. including the newline character at the end of the string, which is
  867. written as @samp{\n}. The output goes to the program's @dfn{standard
  868. output} destination, which in the usual case is the terminal.
  869. @samp{%} in the template introduces a code that substitutes other text
  870. into the output. Specifically, @samp{%d} means to take the next
  871. argument to @code{printf} and substitute it into the text as a decimal
  872. number. (The argument for @samp{%d} must be of type @code{int}; if it
  873. isn't, @code{printf} will malfunction.) So the output is a line that
  874. looks like this:
  875. @example
  876. Fibonacci series item 20 is 6765
  877. @end example
  878. This program does not contain a definition for @code{printf} because
  879. it is defined by the C library, which makes it available in all C
  880. programs. However, each program does need to @dfn{declare}
  881. @code{printf} so it will be called correctly. The @code{#include}
  882. line takes care of that; it includes a @dfn{header file} called
  883. @file{stdio.h} into the program's code. That file is provided by the
  884. operating system and it contains declarations for the many standard
  885. input/output functions in the C library, one of which is
  886. @code{printf}.
  887. Don't worry about header files for now; we'll explain them later in
  888. @ref{Header Files}.
  889. The first argument of @code{printf} does not have to be a string
  890. constant; it can be any string (@pxref{Strings}). However, using a
  891. constant is the most common case.
  892. @node Complete Line-by-Line
  893. @section Complete Program, Line by Line
  894. Here's the same example, explained line by line.
  895. @strong{Beginners, do you find this helpful or not?
  896. Would you prefer a different layout for the example?
  897. Please tell rms@@gnu.org.}
  898. @example
  899. #include <stdio.h> /* @r{Include declaration of usual} */
  900. /* @r{I/O functions such as @code{printf}.} */
  901. /* @r{Most programs need these.} */
  902. int /* @r{This function returns an @code{int}.} */
  903. fib (int n) /* @r{Its name is @code{fib};} */
  904. /* @r{its argument is called @code{n}.} */
  905. @{ /* @r{Start of function body.} */
  906. /* @r{This stops the recursion from being infinite.} */
  907. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  908. return 1; /* @r{make @code{fib} return 1.} */
  909. else /* @r{otherwise, add the two previous} */
  910. /* @r{Fibonacci numbers.} */
  911. return fib (n - 1) + fib (n - 2);
  912. @}
  913. int /* @r{This function returns an @code{int}.} */
  914. main (void) /* @r{Start here; ignore arguments.} */
  915. @{ /* @r{Print message with numbers in it.} */
  916. printf ("Fibonacci series item %d is %d\n",
  917. 20, fib (20));
  918. return 0; /* @r{Terminate program, report success.} */
  919. @}
  920. @end example
  921. @node Compile Example
  922. @section Compiling the Example Program
  923. @cindex compiling
  924. @cindex executable file
  925. To run a C program requires converting the source code into an
  926. @dfn{executable file}. This is called @dfn{compiling} the program,
  927. and the command to do that using GNU C is @command{gcc}.
  928. This example program consists of a single source file. If we
  929. call that file @file{fib1.c}, the complete command to compile it is
  930. this:
  931. @example
  932. gcc -g -O -o fib1 fib1.c
  933. @end example
  934. @noindent
  935. Here, @option{-g} says to generate debugging information, @option{-O}
  936. says to optimize at the basic level, and @option{-o fib1} says to put
  937. the executable program in the file @file{fib1}.
  938. To run the program, use its file name as a shell command.
  939. For instance,
  940. @example
  941. ./fib1
  942. @end example
  943. @noindent
  944. However, unless you are sure the program is correct, you should
  945. expect to need to debug it. So use this command,
  946. @example
  947. gdb fib1
  948. @end example
  949. @noindent
  950. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  951. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  952. debug the executable program @code{fib1}.
  953. Richard Stallman's advice, from personal experience, is to turn to the
  954. debugger as soon as you can reproduce the problem. Don't try to avoid
  955. it by using other methods instead---occasionally they are shortcuts,
  956. but usually they waste an unbounded amount of time. With the
  957. debugger, you will surely find the bug in a reasonable time; overall,
  958. you will get your work done faster. The sooner you get serious and
  959. start the debugger, the sooner you are likely to find the bug.
  960. @xref{Compilation}, for an introduction to compiling more complex
  961. programs which consist of more than one source file.
  962. @node Storage
  963. @chapter Storage and Data
  964. @cindex bytes
  965. @cindex storage organization
  966. @cindex memory organization
  967. Storage in C programs is made up of units called @dfn{bytes}. On
  968. nearly all computers, a byte consists of 8 bits, but there are a few
  969. peculiar computers (mostly ``embedded controllers'' for very small
  970. systems) where a byte is longer than that. This manual does not try
  971. to explain the peculiarity of those computers; we assume that a byte
  972. is 8 bits.
  973. Every C data type is made up of a certain number of bytes; that number
  974. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  975. types @code{signed char} and @code{unsigned char} are one byte long;
  976. use those types to operate on data byte by byte. @xref{Signed and
  977. Unsigned Types}. You can refer to a series of consecutive bytes as an
  978. array of @code{char} elements; that's what an ASCII string looks like
  979. in memory. @xref{String Constants}.
  980. @node Beyond Integers
  981. @chapter Beyond Integers
  982. So far we've presented programs that operate on integers. In this
  983. chapter we'll present examples of handling non-integral numbers and
  984. arrays of numbers.
  985. @menu
  986. * Float Example:: A function that uses floating-point numbers.
  987. * Array Example:: A function that works with arrays.
  988. * Array Example Call:: How to call that function.
  989. * Array Example Variations:: Different ways to write the call example.
  990. @end menu
  991. @node Float Example
  992. @section An Example with Non-Integer Numbers
  993. @cindex floating point example
  994. Here's a function that operates on and returns @dfn{floating point}
  995. numbers that don't have to be integers. Floating point represents a
  996. number as a fraction together with a power of 2. (For more detail,
  997. @pxref{Floating-Point Data Types}.) This example calculates the
  998. average of three floating point numbers that are passed to it as
  999. arguments:
  1000. @example
  1001. double
  1002. average_of_three (double a, double b, double c)
  1003. @{
  1004. return (a + b + c) / 3;
  1005. @}
  1006. @end example
  1007. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  1008. integers, and even when they happen to be integers, most likely their
  1009. average is not an integer.
  1010. @code{double} is the usual data type in C for calculations on
  1011. floating-point numbers.
  1012. To print a @code{double} with @code{printf}, we must use @samp{%f}
  1013. instead of @samp{%d}:
  1014. @example
  1015. printf ("Average is %f\n",
  1016. average_of_three (1.1, 9.8, 3.62));
  1017. @end example
  1018. The code that calls @code{printf} must pass a @code{double} for
  1019. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  1020. If the argument has the wrong type, @code{printf} will produce garbage
  1021. output.
  1022. Here's a complete program that computes the average of three
  1023. specific numbers and prints the result:
  1024. @example
  1025. double
  1026. average_of_three (double a, double b, double c)
  1027. @{
  1028. return (a + b + c) / 3;
  1029. @}
  1030. int
  1031. main (void)
  1032. @{
  1033. printf ("Average is %f\n",
  1034. average_of_three (1.1, 9.8, 3.62));
  1035. return 0;
  1036. @}
  1037. @end example
  1038. From now on we will not present examples of calls to @code{main}.
  1039. Instead we encourage you to write them for yourself when you want
  1040. to test executing some code.
  1041. @node Array Example
  1042. @section An Example with Arrays
  1043. @cindex array example
  1044. A function to take the average of three numbers is very specific and
  1045. limited. A more general function would take the average of any number
  1046. of numbers. That requires passing the numbers in an array. An array
  1047. is an object in memory that contains a series of values of the same
  1048. data type. This chapter presents the basic concepts and use of arrays
  1049. through an example; for the full explanation, see @ref{Arrays}.
  1050. Here's a function definition to take the average of several
  1051. floating-point numbers, passed as type @code{double}. The first
  1052. parameter, @code{length}, specifies how many numbers are passed. The
  1053. second parameter, @code{input_data}, is an array that holds those
  1054. numbers.
  1055. @example
  1056. double
  1057. avg_of_double (int length, double input_data[])
  1058. @{
  1059. double sum = 0;
  1060. int i;
  1061. for (i = 0; i < length; i++)
  1062. sum = sum + input_data[i];
  1063. return sum / length;
  1064. @}
  1065. @end example
  1066. This introduces the expression to refer to an element of an array:
  1067. @code{input_data[i]} means the element at index @code{i} in
  1068. @code{input_data}. The index of the element can be any expression
  1069. with an integer value; in this case, the expression is @code{i}.
  1070. @xref{Accessing Array Elements}.
  1071. @cindex zero-origin indexing
  1072. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1073. valid index is one less than the number of elements. (This is known
  1074. as @dfn{zero-origin indexing}.)
  1075. This example also introduces the way to declare that a function
  1076. parameter is an array. Such declarations are modeled after the syntax
  1077. for an element of the array. Just as @code{double foo} declares that
  1078. @code{foo} is of type @code{double}, @code{double input_data[]}
  1079. declares that each element of @code{input_data} is of type
  1080. @code{double}. Therefore, @code{input_data} itself has type ``array
  1081. of @code{double}.''
  1082. When declaring an array parameter, it's not necessary to say how long
  1083. the array is. In this case, the parameter @code{input_data} has no
  1084. length information. That's why the function needs another parameter,
  1085. @code{length}, for the caller to provide that information to the
  1086. function @code{avg_of_double}.
  1087. @node Array Example Call
  1088. @section Calling the Array Example
  1089. To call the function @code{avg_of_double} requires making an
  1090. array and then passing it as an argument. Here is an example.
  1091. @example
  1092. @{
  1093. /* @r{The array of values to average.} */
  1094. double nums_to_average[5];
  1095. /* @r{The average, once we compute it.} */
  1096. double average;
  1097. /* @r{Fill in elements of @code{nums_to_average}.} */
  1098. nums_to_average[0] = 58.7;
  1099. nums_to_average[1] = 5.1;
  1100. nums_to_average[2] = 7.7;
  1101. nums_to_average[3] = 105.2;
  1102. nums_to_average[4] = -3.14159;
  1103. average = avg_of_double (5, nums_to_average);
  1104. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1105. @}
  1106. @end example
  1107. This shows an array subscripting expression again, this time
  1108. on the left side of an assignment, storing a value into an
  1109. element of an array.
  1110. It also shows how to declare a local variable that is an array:
  1111. @code{double nums_to_average[5];}. Since this declaration allocates the
  1112. space for the array, it needs to know the array's length. You can
  1113. specify the length with any expression whose value is an integer, but
  1114. in this declaration the length is a constant, the integer 5.
  1115. The name of the array, when used by itself as an expression, stands
  1116. for the address of the array's data, and that's what gets passed to
  1117. the function @code{avg_of_double} in @code{avg_of_double (5,
  1118. nums_to_average)}.
  1119. We can make the code easier to maintain by avoiding the need to write
  1120. 5, the array length, when calling @code{avg_of_double}. That way, if
  1121. we change the array to include more elements, we won't have to change
  1122. that call. One way to do this is with the @code{sizeof} operator:
  1123. @example
  1124. average = avg_of_double ((sizeof (nums_to_average)
  1125. / sizeof (nums_to_average[0])),
  1126. nums_to_average);
  1127. @end example
  1128. This computes the number of elements in @code{nums_to_average} by dividing
  1129. its total size by the size of one element. @xref{Type Size}, for more
  1130. details of using @code{sizeof}.
  1131. We don't show in this example what happens after storing the result of
  1132. @code{avg_of_double} in the variable @code{average}. Presumably
  1133. more code would follow that uses that result somehow. (Why compute
  1134. the average and not use it?) But that isn't part of this topic.
  1135. @node Array Example Variations
  1136. @section Variations for Array Example
  1137. The code to call @code{avg_of_double} has two declarations that
  1138. start with the same data type:
  1139. @example
  1140. /* @r{The array of values to average.} */
  1141. double nums_to_average[5];
  1142. /* @r{The average, once we compute it.} */
  1143. double average;
  1144. @end example
  1145. In C, you can combine the two, like this:
  1146. @example
  1147. double nums_to_average[5], average;
  1148. @end example
  1149. This declares @code{nums_to_average} so each of its elements is a
  1150. @code{double}, and @code{average} so that it simply is a
  1151. @code{double}.
  1152. However, while you @emph{can} combine them, that doesn't mean you
  1153. @emph{should}. If it is useful to write comments about the variables,
  1154. and usually it is, then it's clearer to keep the declarations separate
  1155. so you can put a comment on each one.
  1156. We set all of the elements of the array @code{nums_to_average} with
  1157. assignments, but it is more convenient to use an initializer in the
  1158. declaration:
  1159. @example
  1160. @{
  1161. /* @r{The array of values to average.} */
  1162. double nums_to_average[]
  1163. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1164. /* @r{The average, once we compute it.} */
  1165. average = avg_of_double ((sizeof (nums_to_average)
  1166. / sizeof (nums_to_average[0])),
  1167. nums_to_average);
  1168. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1169. @}
  1170. @end example
  1171. The array initializer is a comma-separated list of values, delimited
  1172. by braces. @xref{Initializers}.
  1173. Note that the declaration does not specify a size for
  1174. @code{nums_to_average}, so the size is determined from the
  1175. initializer. There are five values in the initializer, so
  1176. @code{nums_to_average} gets length 5. If we add another element to
  1177. the initializer, @code{nums_to_average} will have six elements.
  1178. Because the code computes the number of elements from the size of
  1179. the array, using @code{sizeof}, the program will operate on all the
  1180. elements in the initializer, regardless of how many those are.
  1181. @node Lexical Syntax
  1182. @chapter Lexical Syntax
  1183. @cindex lexical syntax
  1184. @cindex token
  1185. To start the full description of the C language, we explain the
  1186. lexical syntax and lexical units of C code. The lexical units of a
  1187. programming language are known as @dfn{tokens}. This chapter covers
  1188. all the tokens of C except for constants, which are covered in a later
  1189. chapter (@pxref{Constants}). One vital kind of token is the
  1190. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1191. kind.
  1192. @menu
  1193. * English:: Write programs in English!
  1194. * Characters:: The characters allowed in C programs.
  1195. * Whitespace:: The particulars of whitespace characters.
  1196. * Comments:: How to include comments in C code.
  1197. * Identifiers:: How to form identifiers (names).
  1198. * Operators/Punctuation:: Characters used as operators or punctuation.
  1199. * Line Continuation:: Splitting one line into multiple lines.
  1200. @end menu
  1201. @node English
  1202. @section Write Programs in English!
  1203. In principle, you can write the function and variable names in a
  1204. program, and the comments, in any human language. C allows any kinds
  1205. of characters in comments, and you can put non-ASCII characters into
  1206. identifiers with a special prefix. However, to enable programmers in
  1207. all countries to understand and develop the program, it is best given
  1208. today's circumstances to write identifiers and comments in
  1209. English.
  1210. English is the one language that programmers in all countries
  1211. generally study. If a program's names are in English, most
  1212. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1213. understand them. Most programmers in those countries can speak
  1214. English, or at least read it, but they do not read each other's
  1215. languages at all. In India, with so many languages, two programmers
  1216. may have no common language other than English.
  1217. If you don't feel confident in writing English, do the best you can,
  1218. and follow each English comment with a version in a language you
  1219. write better; add a note asking others to translate that to English.
  1220. Someone will eventually do that.
  1221. The program's user interface is a different matter. We don't need to
  1222. choose one language for that; it is easy to support multiple languages
  1223. and let each user choose the language to use. This requires writing
  1224. the program to support localization of its interface. (The
  1225. @code{gettext} package exists to support this; @pxref{Message
  1226. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1227. Manual}.) Then a community-based translation effort can provide
  1228. support for all the languages users want to use.
  1229. @node Characters
  1230. @section Characters
  1231. @cindex character set
  1232. @cindex Unicode
  1233. @c ??? How to express ¶?
  1234. GNU C source files are usually written in the
  1235. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1236. was defined in the 1960s for English. However, they can also include
  1237. Unicode characters represented in the
  1238. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1239. This makes it possible to represent accented letters such as @samp{á},
  1240. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1241. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1242. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1243. manual.}
  1244. In C source code, non-ASCII characters are valid in comments, in wide
  1245. character constants (@pxref{Wide Character Constants}), and in string
  1246. constants (@pxref{String Constants}).
  1247. @c ??? valid in identifiers?
  1248. Another way to specify non-ASCII characters in constants (character or
  1249. string) and identifiers is with an escape sequence starting with
  1250. backslash, specifying the intended Unicode character. (@xref{Unicode
  1251. Character Codes}.) This specifies non-ASCII characters without
  1252. putting a real non-ASCII character in the source file itself.
  1253. C accepts two-character aliases called @dfn{digraphs} for certain
  1254. characters. @xref{Digraphs}.
  1255. @node Whitespace
  1256. @section Whitespace
  1257. @cindex whitespace characters in source files
  1258. @cindex space character in source
  1259. @cindex tab character in source
  1260. @cindex formfeed in source
  1261. @cindex linefeed in source
  1262. @cindex newline in source
  1263. @cindex carriage return in source
  1264. @cindex vertical tab in source
  1265. Whitespace means characters that exist in a file but appear blank in a
  1266. printed listing of a file (or traditionally did appear blank, several
  1267. decades ago). The C language requires whitespace in order to separate
  1268. two consecutive identifiers, or to separate an identifier from a
  1269. numeric constant. Other than that, and a few special situations
  1270. described later, whitespace is optional; you can put it in when you
  1271. wish, to make the code easier to read.
  1272. Space and tab in C code are treated as whitespace characters. So are
  1273. line breaks. You can represent a line break with the newline
  1274. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1275. the CRLF sequence (two characters: carriage return followed by a
  1276. newline character).
  1277. The @dfn{formfeed} character, Control-L, was traditionally used to
  1278. divide a file into pages. It is still used this way in source code,
  1279. and the tools that generate nice printouts of source code still start
  1280. a new page after each ``formfeed'' character. Dividing code into
  1281. pages separated by formfeed characters is a good way to break it up
  1282. into comprehensible pieces and show other programmers where they start
  1283. and end.
  1284. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1285. make printing advance down to the next section of a page. We know of
  1286. no particular reason to use it in source code, but it is still
  1287. accepted as whitespace in C.
  1288. Comments are also syntactically equivalent to whitespace.
  1289. @ifinfo
  1290. @xref{Comments}.
  1291. @end ifinfo
  1292. @node Comments
  1293. @section Comments
  1294. @cindex comments
  1295. A comment encapsulates text that has no effect on the program's
  1296. execution or meaning.
  1297. The purpose of comments is to explain the code to people that read it.
  1298. Writing good comments for your code is tremendously important---they
  1299. should provide background information that helps programmers
  1300. understand the reasons why the code is written the way it is. You,
  1301. returning to the code six months from now, will need the help of these
  1302. comments to remember why you wrote it this way.
  1303. Outdated comments that become incorrect are counterproductive, so part
  1304. of the software developer's responsibility is to update comments as
  1305. needed to correspond with changes to the program code.
  1306. C allows two kinds of comment syntax, the traditional style and the
  1307. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1308. with @samp{*/}. For instance,
  1309. @example
  1310. /* @r{This is a comment in traditional C syntax.} */
  1311. @end example
  1312. A traditional comment can contain @samp{/*}, but these delimiters do
  1313. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1314. whether it contains @samp{/*} sequences.
  1315. @example
  1316. /* @r{This} /* @r{is a comment} */ But this is not! */
  1317. @end example
  1318. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1319. For instance,
  1320. @example
  1321. // @r{This is a comment in C@t{++} style.}
  1322. @end example
  1323. Line comments do nest, in effect, because @samp{//} inside a line
  1324. comment is part of that comment:
  1325. @example
  1326. // @r{this whole line is} // @r{one comment}
  1327. This is code, not comment.
  1328. @end example
  1329. It is safe to put line comments inside block comments, or vice versa.
  1330. @example
  1331. @group
  1332. /* @r{traditional comment}
  1333. // @r{contains line comment}
  1334. @r{more traditional comment}
  1335. */ text here is not a comment
  1336. // @r{line comment} /* @r{contains traditional comment} */
  1337. @end group
  1338. @end example
  1339. But beware of commenting out one end of a traditional comment with a line
  1340. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1341. inside an already-started comment.
  1342. @example
  1343. @group
  1344. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1345. Oops! The line comment has ended;
  1346. this isn't a comment any more. */
  1347. @end group
  1348. @end example
  1349. Comments are not recognized within string constants. @t{@w{"/* blah
  1350. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1351. string.
  1352. In this manual we show the text in comments in a variable-width font,
  1353. for readability, but this font distinction does not exist in source
  1354. files.
  1355. A comment is syntactically equivalent to whitespace, so it always
  1356. separates tokens. Thus,
  1357. @example
  1358. @group
  1359. int/* @r{comment} */foo;
  1360. @r{is equivalent to}
  1361. int foo;
  1362. @end group
  1363. @end example
  1364. @noindent
  1365. but clean code always uses real whitespace to separate the comment
  1366. visually from surrounding code.
  1367. @node Identifiers
  1368. @section Identifiers
  1369. @cindex identifiers
  1370. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1371. as well as @samp{_}, that does not start with a digit. Most compilers
  1372. also allow @samp{$}. An identifier can be as long as you like; for
  1373. example,
  1374. @example
  1375. int anti_dis_establishment_arian_ism;
  1376. @end example
  1377. @cindex case of letters in identifiers
  1378. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1379. and @code{A} are two different identifiers.
  1380. @cindex keyword
  1381. @cindex reserved words
  1382. Identifiers in C are used as variable names, function names, typedef
  1383. names, enumeration constants, type tags, field names, and labels.
  1384. Certain identifiers in C are @dfn{keywords}, which means they have
  1385. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1386. meaning you cannot use them in any other way. For instance, you can't
  1387. define a variable or function named @code{return} or @code{if}.
  1388. You can also include other characters, even non-ASCII characters, in
  1389. identifiers by writing their Unicode character names, which start with
  1390. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1391. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1392. characters in identifiers, and when they are written in English, they
  1393. never need non-ASCII characters. @xref{English}.
  1394. Whitespace is required to separate two consecutive identifiers, or to
  1395. separate an identifier from a preceding or following numeric
  1396. constant.
  1397. @node Operators/Punctuation
  1398. @section Operators and Punctuation
  1399. @cindex operators
  1400. @cindex punctuation
  1401. Here we describe the lexical syntax of operators and punctuation in C.
  1402. The specific operators of C and their meanings are presented in
  1403. subsequent chapters.
  1404. Most operators in C consist of one or two characters that can't be
  1405. used in identifiers. The characters used for operators in C are
  1406. @samp{!~^&|*/%+-=<>,.?:}.
  1407. Some operators are a single character. For instance, @samp{-} is the
  1408. operator for negation (with one operand) and the operator for
  1409. subtraction (with two operands).
  1410. Some operators are two characters. For example, @samp{++} is the
  1411. increment operator. Recognition of multicharacter operators works by
  1412. grouping together as many consecutive characters as can constitute one
  1413. operator.
  1414. For instance, the character sequence @samp{++} is always interpreted
  1415. as the increment operator; therefore, if we want to write two
  1416. consecutive instances of the operator @samp{+}, we must separate them
  1417. with a space so that they do not combine as one token. Applying the
  1418. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1419. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1420. of a valid C program and the former could not (since @code{a++}
  1421. is not an lvalue and thus can't be the operand of @code{++}).
  1422. A few C operators are keywords rather than special characters. They
  1423. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1424. (@pxref{Type Alignment}).
  1425. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1426. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1427. @samp{@}}) begin and end a block at the statement level
  1428. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1429. for a variable with multiple elements or components (such as arrays or
  1430. structures).
  1431. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1432. @code{array[5]}.
  1433. Parentheses are used in expressions for explicit nesting of
  1434. expressions (@pxref{Basic Arithmetic}), around the parameter
  1435. declarations in a function declaration or definition, and around the
  1436. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1437. (@pxref{Function Calls}). Several kinds of statements also use
  1438. parentheses as part of their syntax---for instance, @code{if}
  1439. statements, @code{for} statements, @code{while} statements, and
  1440. @code{switch} statements. @xref{if Statement}, and following
  1441. sections.
  1442. Parentheses are also required around the operand of the operator
  1443. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1444. type rather than a value. @xref{Type Size}.
  1445. @node Line Continuation
  1446. @section Line Continuation
  1447. @cindex line continuation
  1448. @cindex continuation of lines
  1449. The sequence of a backslash and a newline is ignored absolutely
  1450. anywhere in a C program. This makes it possible to split a single
  1451. source line into multiple lines in the source file. GNU C tolerates
  1452. and ignores other whitespace between the backslash and the newline.
  1453. In particular, it always ignores a CR (carriage return) character
  1454. there, in case some text editor decided to end the line with the CRLF
  1455. sequence.
  1456. The main use of line continuation in C is for macro definitions that
  1457. would be inconveniently long for a single line (@pxref{Macros}).
  1458. It is possible to continue a line comment onto another line with
  1459. backslash-newline. You can put backslash-newline in the middle of an
  1460. identifier, even a keyword, or an operator. You can even split
  1461. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1462. backslash-newline. Here's an ugly example:
  1463. @example
  1464. @group
  1465. /\
  1466. *
  1467. */ fo\
  1468. o +\
  1469. = 1\
  1470. 0;
  1471. @end group
  1472. @end example
  1473. @noindent
  1474. That's equivalent to @samp{/* */ foo += 10;}.
  1475. Don't do those things in real programs, since they make code hard to
  1476. read.
  1477. @strong{Note:} For the sake of using certain tools on the source code, it is
  1478. wise to end every source file with a newline character which is not
  1479. preceded by a backslash, so that it really ends the last line.
  1480. @node Arithmetic
  1481. @chapter Arithmetic
  1482. @cindex arithmetic operators
  1483. @cindex operators, arithmetic
  1484. @c ??? Duplication with other sections -- get rid of that?
  1485. Arithmetic operators in C attempt to be as similar as possible to the
  1486. abstract arithmetic operations, but it is impossible to do this
  1487. perfectly. Numbers in a computer have a finite range of possible
  1488. values, and non-integer values have a limit on their possible
  1489. accuracy. Nonetheless, except when results are out of range, you will
  1490. encounter no surprises in using @samp{+} for addition, @samp{-} for
  1491. subtraction, and @samp{*} for multiplication.
  1492. Each C operator has a @dfn{precedence}, which is its rank in the
  1493. grammatical order of the various operators. The operators with the
  1494. highest precedence grab adjoining operands first; these expressions
  1495. then become operands for operators of lower precedence. We give some
  1496. information about precedence of operators in this chapter where we
  1497. describe the operators; for the full explanation, see @ref{Binary
  1498. Operator Grammar}.
  1499. The arithmetic operators always @dfn{promote} their operands before
  1500. operating on them. This means converting narrow integer data types to
  1501. a wider data type (@pxref{Operand Promotions}). If you are just
  1502. learning C, don't worry about this yet.
  1503. Given two operands that have different types, most arithmetic
  1504. operations convert them both to their @dfn{common type}. For
  1505. instance, if one is @code{int} and the other is @code{double}, the
  1506. common type is @code{double}. (That's because @code{double} can
  1507. represent all the values that an @code{int} can hold, but not vice
  1508. versa.) For the full details, see @ref{Common Type}.
  1509. @menu
  1510. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1511. and division.
  1512. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1513. * Integer Overflow:: When an integer value exceeds the range
  1514. of its type.
  1515. * Mixed Mode:: Calculating with both integer values
  1516. and floating-point values.
  1517. * Division and Remainder:: How integer division works.
  1518. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1519. * Shift Operations:: Shift integer bits left or right.
  1520. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1521. @end menu
  1522. @node Basic Arithmetic
  1523. @section Basic Arithmetic
  1524. @cindex addition operator
  1525. @cindex subtraction operator
  1526. @cindex multiplication operator
  1527. @cindex division operator
  1528. @cindex negation operator
  1529. @cindex operator, addition
  1530. @cindex operator, subtraction
  1531. @cindex operator, multiplication
  1532. @cindex operator, division
  1533. @cindex operator, negation
  1534. Basic arithmetic in C is done with the usual binary operators of
  1535. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1536. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1537. used to change the sign of a number. The unary @code{+} operator also
  1538. exists; it yields its operand unaltered.
  1539. @samp{/} is the division operator, but dividing integers may not give
  1540. the result you expect. Its value is an integer, which is not equal to
  1541. the mathematical quotient when that is a fraction. Use @samp{%} to
  1542. get the corresponding integer remainder when necessary.
  1543. @xref{Division and Remainder}. Floating point division yields value
  1544. as close as possible to the mathematical quotient.
  1545. These operators use algebraic syntax with the usual algebraic
  1546. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1547. and division are done before addition and subtraction, but you can use
  1548. parentheses to explicitly specify how the operators nest. They are
  1549. left-associative (@pxref{Associativity and Ordering}). Thus,
  1550. @example
  1551. -a + b - c + d * e / f
  1552. @end example
  1553. @noindent
  1554. is equivalent to
  1555. @example
  1556. (((-a) + b) - c) + ((d * e) / f)
  1557. @end example
  1558. @node Integer Arithmetic
  1559. @section Integer Arithmetic
  1560. @cindex integer arithmetic
  1561. Each of the basic arithmetic operations in C has two variants for
  1562. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1563. by the data types of their operands.
  1564. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1565. A signed type can hold a range of positive and negative numbers, with
  1566. zero near the middle of the range. An unsigned type can hold only
  1567. nonnegative numbers; its range starts with zero and runs upward.
  1568. The most basic integer types are @code{int}, which normally can hold
  1569. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1570. int}, which normally can hold numbers from 0 to 4,294,967,295. (This
  1571. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1572. computers but not always on embedded controllers.) @xref{Integer
  1573. Types}, for full information about integer types.
  1574. When a basic arithmetic operation is given two signed operands, it
  1575. does signed arithmetic. Given two unsigned operands, it does
  1576. unsigned arithmetic.
  1577. If one operand is @code{unsigned int} and the other is @code{int}, the
  1578. operator treats them both as unsigned. More generally, the common
  1579. type of the operands determines whether the operation is signed or
  1580. not. @xref{Common Type}.
  1581. Printing the results of unsigned arithmetic with @code{printf} using
  1582. @samp{%d} can produce surprising results for values far away from
  1583. zero. Even though the rules above say that the computation was done
  1584. with unsigned arithmetic, the printed result may appear to be signed!
  1585. The explanation is that the bit pattern resulting from addition,
  1586. subtraction or multiplication is actually the same for signed and
  1587. unsigned operations. The difference is only in the data type of the
  1588. result, which affects the @emph{interpretation} of the result bit pattern,
  1589. and whether the arithmetic operation can overflow (see the next section).
  1590. But @samp{%d} doesn't know its argument's data type. It sees only the
  1591. value's bit pattern, and it is defined to interpret that as
  1592. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1593. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1594. libc, The GNU C Library Reference Manual}.
  1595. Arithmetic in C never operates directly on narrow integer types (those
  1596. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1597. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1598. @node Integer Overflow
  1599. @section Integer Overflow
  1600. @cindex integer overflow
  1601. @cindex overflow, integer
  1602. When the mathematical value of an arithmetic operation doesn't fit in
  1603. the range of the data type in use, that's called @dfn{overflow}.
  1604. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1605. Integer overflow happens only in arithmetic operations. Type conversion
  1606. operations, by definition, do not cause overflow, not even when the
  1607. result can't fit in its new type. @xref{Integer Conversion}.
  1608. Signed numbers use two's-complement representation, in which the most
  1609. negative number lacks a positive counterpart (@pxref{Integers in
  1610. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1611. overflow.
  1612. @menu
  1613. * Unsigned Overflow:: Overflow in unsigned integer arithmetic.
  1614. * Signed Overflow:: Overflow in signed integer arithmetic.
  1615. @end menu
  1616. @node Unsigned Overflow
  1617. @subsection Overflow with Unsigned Integers
  1618. Unsigned arithmetic in C ignores overflow; it produces the true result
  1619. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1620. in the data type. We say it ``truncates'' the true result to the
  1621. lowest @var{n} bits.
  1622. A true result that is negative, when taken modulo the @var{n}th power
  1623. of 2, yields a positive number. For instance,
  1624. @example
  1625. unsigned int x = 1;
  1626. unsigned int y;
  1627. y = -x;
  1628. @end example
  1629. @noindent
  1630. causes overflow because the negative number @minus{}1 can't be stored
  1631. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1632. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1633. is the largest value that the unsigned data type can store. For a
  1634. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1635. and Minimum Values}.
  1636. Adding that number to itself, as here,
  1637. @example
  1638. unsigned int z;
  1639. z = y + y;
  1640. @end example
  1641. @noindent
  1642. ought to yield 8,489,934,590; however, that is again too large to fit,
  1643. so overflow truncates the value to 4,294,967,294. If that were a
  1644. signed integer, it would mean @minus{}2, which (not by coincidence)
  1645. equals @minus{}1 + @minus{}1.
  1646. @node Signed Overflow
  1647. @subsection Overflow with Signed Integers
  1648. @cindex compiler options for integer overflow
  1649. @cindex integer overflow, compiler options
  1650. @cindex overflow, compiler options
  1651. For signed integers, the result of overflow in C is @emph{in
  1652. principle} undefined, meaning that anything whatsoever could happen.
  1653. Therefore, C compilers can do optimizations that treat the overflow
  1654. case with total unconcern. (Since the result of overflow is undefined
  1655. in principle, one cannot claim that these optimizations are
  1656. erroneous.)
  1657. @strong{Watch out:} These optimizations can do surprising things. For
  1658. instance,
  1659. @example
  1660. int i;
  1661. @r{@dots{}}
  1662. if (i < i + 1)
  1663. x = 5;
  1664. @end example
  1665. @noindent
  1666. could be optimized to do the assignment unconditionally, because the
  1667. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1668. GCC offers compiler options to control handling signed integer
  1669. overflow. These options operate per module; that is, each module
  1670. behaves according to the options it was compiled with.
  1671. These two options specify particular ways to handle signed integer
  1672. overflow, other than the default way:
  1673. @table @option
  1674. @item -fwrapv
  1675. Make signed integer operations well-defined, like unsigned integer
  1676. operations: they produce the @var{n} low-order bits of the true
  1677. result. The highest of those @var{n} bits is the sign bit of the
  1678. result. With @option{-fwrapv}, these out-of-range operations are not
  1679. considered overflow, so (strictly speaking) integer overflow never
  1680. happens.
  1681. The option @option{-fwrapv} enables some optimizations based on the
  1682. defined values of out-of-range results. In GCC 8, it disables
  1683. optimizations that are based on assuming signed integer operations
  1684. will not overflow.
  1685. @item -ftrapv
  1686. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1687. This terminates the program unless the program handles the signal.
  1688. @xref{Signals}.
  1689. @end table
  1690. One other option is useful for finding where overflow occurs:
  1691. @ignore
  1692. @item -fno-strict-overflow
  1693. Disable optimizations that are based on assuming signed integer
  1694. operations will not overflow.
  1695. @end ignore
  1696. @table @option
  1697. @item -fsanitize=signed-integer-overflow
  1698. Output a warning message at run time when signed integer overflow
  1699. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1700. This takes priority over @option{-ftrapv}.
  1701. @end table
  1702. @node Mixed Mode
  1703. @section Mixed-Mode Arithmetic
  1704. Mixing integers and floating-point numbers in a basic arithmetic
  1705. operation converts the integers automatically to floating point.
  1706. In most cases, this gives exactly the desired results.
  1707. But sometimes it matters precisely where the conversion occurs.
  1708. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1709. as an integer, then converts the sum to floating point for the
  1710. multiplication. If the addition causes an overflow, that is not
  1711. equivalent to converting each integer to floating point and then
  1712. adding the two floating point numbers. You can get the latter result
  1713. by explicitly converting the integers, as in @code{((double) i +
  1714. (double) j) * 2.0}. @xref{Explicit Type Conversion}.
  1715. @c Eggert's report
  1716. Adding or multiplying several values, including some integers and some
  1717. floating point, performs the operations left to right. Thus, @code{3.0 +
  1718. i + j} converts @code{i} to floating point, then adds 3.0, then
  1719. converts @code{j} to floating point and adds that. You can specify a
  1720. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1721. and @code{j} first and then adds that sum (converted to floating
  1722. point) to 3.0. In this respect, C differs from other languages, such
  1723. as Fortran.
  1724. @node Division and Remainder
  1725. @section Division and Remainder
  1726. @cindex remainder operator
  1727. @cindex modulus
  1728. @cindex operator, remainder
  1729. Division of integers in C rounds the result to an integer. The result
  1730. is always rounded towards zero.
  1731. @example
  1732. 16 / 3 @result{} 5
  1733. -16 / 3 @result{} -5
  1734. 16 / -3 @result{} -5
  1735. -16 / -3 @result{} 5
  1736. @end example
  1737. @noindent
  1738. To get the corresponding remainder, use the @samp{%} operator:
  1739. @example
  1740. 16 % 3 @result{} 1
  1741. -16 % 3 @result{} -1
  1742. 16 % -3 @result{} 1
  1743. -16 % -3 @result{} -1
  1744. @end example
  1745. @noindent
  1746. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1747. From the rounded quotient and the remainder, you can reconstruct
  1748. the dividend, like this:
  1749. @example
  1750. int
  1751. original_dividend (int divisor, int quotient, int remainder)
  1752. @{
  1753. return divisor * quotient + remainder;
  1754. @}
  1755. @end example
  1756. To do unrounded division, use floating point. If only one operand is
  1757. floating point, @samp{/} converts the other operand to floating
  1758. point.
  1759. @example
  1760. 16.0 / 3 @result{} 5.333333333333333
  1761. 16 / 3.0 @result{} 5.333333333333333
  1762. 16.0 / 3.0 @result{} 5.333333333333333
  1763. 16 / 3 @result{} 5
  1764. @end example
  1765. The remainder operator @samp{%} is not allowed for floating-point
  1766. operands, because it is not needed. The concept of remainder makes
  1767. sense for integers because the result of division of integers has to
  1768. be an integer. For floating point, the result of division is a
  1769. floating-point number, in other words a fraction, which will differ
  1770. from the exact result only by a very small amount.
  1771. There are functions in the standard C library to calculate remainders
  1772. from integral-values division of floating-point numbers.
  1773. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1774. Reference Manual}.
  1775. Integer division overflows in one specific case: dividing the smallest
  1776. negative value for the data type (@pxref{Maximum and Minimum Values})
  1777. by @minus{}1. That's because the correct result, which is the
  1778. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1779. in the same number of bits. On some computers now in use, this always
  1780. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1781. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1782. Division by zero leads to unpredictable results---depending on the
  1783. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1784. produce a numeric result.
  1785. @cindex division by zero
  1786. @cindex zero, division by
  1787. @strong{Watch out:} Make sure the program does not divide by zero. If
  1788. you can't prove that the divisor is not zero, test whether it is zero,
  1789. and skip the division if so.
  1790. @node Numeric Comparisons
  1791. @section Numeric Comparisons
  1792. @cindex numeric comparisons
  1793. @cindex comparisons
  1794. @cindex operators, comparison
  1795. @cindex equal operator
  1796. @cindex not-equal operator
  1797. @cindex less-than operator
  1798. @cindex greater-than operator
  1799. @cindex less-or-equal operator
  1800. @cindex greater-or-equal operator
  1801. @cindex operator, equal
  1802. @cindex operator, not-equal
  1803. @cindex operator, less-than
  1804. @cindex operator, greater-than
  1805. @cindex operator, less-or-equal
  1806. @cindex operator, greater-or-equal
  1807. @cindex truth value
  1808. There are two kinds of comparison operators: @dfn{equality} and
  1809. @dfn{ordering}. Equality comparisons test whether two expressions
  1810. have the same value. The result is a @dfn{truth value}: a number that
  1811. is 1 for ``true'' and 0 for ``false.''
  1812. @example
  1813. a == b /* @r{Test for equal.} */
  1814. a != b /* @r{Test for not equal.} */
  1815. @end example
  1816. The equality comparison is written @code{==} because plain @code{=}
  1817. is the assignment operator.
  1818. Ordering comparisons test which operand is greater or less. Their
  1819. results are truth values. These are the ordering comparisons of C:
  1820. @example
  1821. a < b /* @r{Test for less-than.} */
  1822. a > b /* @r{Test for greater-than.} */
  1823. a <= b /* @r{Test for less-than-or-equal.} */
  1824. a >= b /* @r{Test for greater-than-or-equal.} */
  1825. @end example
  1826. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1827. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1828. mathematics. However, if @code{a} and @code{b} are special floating
  1829. point values (not ordinary numbers), all three can be false.
  1830. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1831. @node Shift Operations
  1832. @section Shift Operations
  1833. @cindex shift operators
  1834. @cindex operators, shift
  1835. @cindex operators, shift
  1836. @cindex shift count
  1837. @dfn{Shifting} an integer means moving the bit values to the left or
  1838. right within the bits of the data type. Shifting is defined only for
  1839. integers. Here's the way to write it:
  1840. @example
  1841. /* @r{Left shift.} */
  1842. 5 << 2 @result{} 20
  1843. /* @r{Right shift.} */
  1844. 5 >> 2 @result{} 1
  1845. @end example
  1846. @noindent
  1847. The left operand is the value to be shifted, and the right operand
  1848. says how many bits to shift it (the @dfn{shift count}). The left
  1849. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1850. operates on a narrow integer type; it's always either @code{int} or
  1851. wider. The result of the shift operation has the same type as the
  1852. promoted left operand.
  1853. @menu
  1854. * Bits Shifted In:: How shifting makes new bits to shift in.
  1855. * Shift Caveats:: Caveats of shift operations.
  1856. * Shift Hacks:: Clever tricks with shift operations.
  1857. @end menu
  1858. @node Bits Shifted In
  1859. @subsection Shifting Makes New Bits
  1860. A shift operation shifts towards one end of the number and has to
  1861. generate new bits at the other end.
  1862. Shifting left one bit must generate a new least significant bit. It
  1863. always brings in zero there. It is equivalent to multiplying by the
  1864. appropriate power of 2. For example,
  1865. @example
  1866. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1867. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1868. @end example
  1869. The meaning of shifting right depends on whether the data type is
  1870. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1871. data type, it performs ``arithmetic shift,'' which keeps the number's
  1872. sign unchanged by duplicating the sign bit. For an unsigned data
  1873. type, it performs ``logical shift,'' which always shifts in zeros at
  1874. the most significant bit.
  1875. In both cases, shifting right one bit is division by two, rounding
  1876. towards negative infinity. For example,
  1877. @example
  1878. (unsigned) 19 >> 2 @result{} 4
  1879. (unsigned) 20 >> 2 @result{} 5
  1880. (unsigned) 21 >> 2 @result{} 5
  1881. @end example
  1882. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1883. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1884. zero.
  1885. The shift count must be zero or greater. Shifting by a negative
  1886. number of bits gives machine-dependent results.
  1887. @node Shift Caveats
  1888. @subsection Caveats for Shift Operations
  1889. @strong{Warning:} If the shift count is greater than or equal to the
  1890. width in bits of the promoted first operand, the results are
  1891. machine-dependent. Logically speaking, the ``correct'' value would be
  1892. either @minus{}1 (for right shift of a negative number) or 0 (in all other
  1893. cases), but the actual result is whatever the machine's shift
  1894. instruction does in that case. So unless you can prove that the
  1895. second operand is not too large, write code to check it at run time.
  1896. @strong{Warning:} Never rely on how the shift operators relate in
  1897. precedence to other arithmetic binary operators. Programmers don't
  1898. remember these precedences, and won't understand the code. Always use
  1899. parentheses to explicitly specify the nesting, like this:
  1900. @example
  1901. a + (b << 5) /* @r{Shift first, then add.} */
  1902. (a + b) << 5 /* @r{Add first, then shift.} */
  1903. @end example
  1904. Note: according to the C standard, shifting of signed values isn't
  1905. guaranteed to work properly when the value shifted is negative, or
  1906. becomes negative during the operation of shifting left. However, only
  1907. pedants have a reason to be concerned about this; only computers with
  1908. strange shift instructions could plausibly do this wrong. In GNU C,
  1909. the operation always works as expected,
  1910. @node Shift Hacks
  1911. @subsection Shift Hacks
  1912. You can use the shift operators for various useful hacks. For
  1913. example, given a date specified by day of the month @code{d}, month
  1914. @code{m}, and year @code{y}, you can store the entire date in a single
  1915. integer @code{date}:
  1916. @example
  1917. unsigned int d = 12;
  1918. unsigned int m = 6;
  1919. unsigned int y = 1983;
  1920. unsigned int date = ((y << 4) + m) << 5) + d;
  1921. @end example
  1922. @noindent
  1923. To extract the original day, month, and year out of
  1924. @code{date}, use a combination of shift and remainder.
  1925. @example
  1926. d = date % 32;
  1927. m = (date >> 5) % 16;
  1928. y = date >> 9;
  1929. @end example
  1930. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1931. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1932. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1933. multiplication, since negating a value is equivalent to multiplying it
  1934. by @minus{}1.
  1935. @node Bitwise Operations
  1936. @section Bitwise Operations
  1937. @cindex bitwise operators
  1938. @cindex operators, bitwise
  1939. @cindex negation, bitwise
  1940. @cindex conjunction, bitwise
  1941. @cindex disjunction, bitwise
  1942. Bitwise operators operate on integers, treating each bit independently.
  1943. They are not allowed for floating-point types.
  1944. The examples in this section use binary constants, starting with
  1945. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1946. of type @code{int}.
  1947. @table @code
  1948. @item ~@code{a}
  1949. Unary operator for bitwise negation; this changes each bit of
  1950. @code{a} from 1 to 0 or from 0 to 1.
  1951. @example
  1952. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1953. ~0 @result{} 0b11111111111111111111111111111111
  1954. ~0b11111111111111111111111111111111 @result{} 0
  1955. ~ (-1) @result{} 0
  1956. @end example
  1957. It is useful to remember that @code{~@var{x} + 1} equals
  1958. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1959. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1960. as @var{x}.
  1961. @item @code{a} & @code{b}
  1962. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1963. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1964. @example
  1965. 0b10101010 & 0b11001100 @result{} 0b10001000
  1966. @end example
  1967. @item @code{a} | @code{b}
  1968. Binary operator for bitwise ``or'' (``inclusive or'' or
  1969. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1970. either @code{a} or @code{b}.
  1971. @example
  1972. 0b10101010 | 0b11001100 @result{} 0b11101110
  1973. @end example
  1974. @item @code{a} ^ @code{b}
  1975. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1976. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1977. @example
  1978. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1979. @end example
  1980. @end table
  1981. To understand the effect of these operators on signed integers, keep
  1982. in mind that all modern computers use two's-complement representation
  1983. (@pxref{Integer Representations}) for negative integers. This means
  1984. that the highest bit of the number indicates the sign; it is 1 for a
  1985. negative number and 0 for a positive number. In a negative number,
  1986. the value in the other bits @emph{increases} as the number gets closer
  1987. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1988. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1989. @strong{Warning:} C defines a precedence ordering for the bitwise
  1990. binary operators, but you should never rely on it. You should
  1991. never rely on how bitwise binary operators relate in precedence to the
  1992. arithmetic and shift binary operators. Other programmers don't
  1993. remember this precedence ordering, so always use parentheses to
  1994. explicitly specify the nesting.
  1995. For example, suppose @code{offset} is an integer that specifies
  1996. the offset within shared memory of a table, except that its bottom few
  1997. bits (@code{LOWBITS} says how many) are special flags. Here's
  1998. how to get just that offset and add it to the base address.
  1999. @example
  2000. shared_mem_base + (offset & (-1 << LOWBITS))
  2001. @end example
  2002. Thanks to the outer set of parentheses, we don't need to know whether
  2003. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  2004. set, we don't need to know whether @samp{&} has higher precedence than
  2005. @samp{<<}. But we can rely on all unary operators to have higher
  2006. precedence than any binary operator, so we don't need parentheses
  2007. around the left operand of @samp{<<}.
  2008. @node Assignment Expressions
  2009. @chapter Assignment Expressions
  2010. @cindex assignment expressions
  2011. @cindex operators, assignment
  2012. As a general concept in programming, an @dfn{assignment} is a
  2013. construct that stores a new value into a place where values can be
  2014. stored---for instance, in a variable. Such places are called
  2015. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  2016. An assignment in C is an expression because it has a value; we call
  2017. it an @dfn{assignment expression}. A simple assignment looks like
  2018. @example
  2019. @var{lvalue} = @var{value-to-store}
  2020. @end example
  2021. @noindent
  2022. We say it assigns the value of the expression @var{value-to-store} to
  2023. the location @var{lvalue}, or that it stores @var{value-to-store}
  2024. there. You can think of the ``l'' in ``lvalue'' as standing for
  2025. ``left,'' since that's what you put on the left side of the assignment
  2026. operator.
  2027. However, that's not the only way to use an lvalue, and not all lvalues
  2028. can be assigned to. To use the lvalue in the left side of an
  2029. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2030. not declared with the type qualifier @code{const} (@pxref{const}).
  2031. The value of the assignment expression is that of @var{lvalue} after
  2032. the new value is stored in it. This means you can use an assignment
  2033. inside other expressions. Assignment operators are right-associative
  2034. so that
  2035. @example
  2036. x = y = z = 0;
  2037. @end example
  2038. @noindent
  2039. is equivalent to
  2040. @example
  2041. x = (y = (z = 0));
  2042. @end example
  2043. This is the only useful way for them to associate;
  2044. the other way,
  2045. @example
  2046. ((x = y) = z) = 0;
  2047. @end example
  2048. @noindent
  2049. would be invalid since an assignment expression such as @code{x = y}
  2050. is not valid as an lvalue.
  2051. @strong{Warning:} Write parentheses around an assignment if you nest
  2052. it inside another expression, unless that is a conditional expression,
  2053. or comma-separated series, or another assignment.
  2054. @menu
  2055. * Simple Assignment:: The basics of storing a value.
  2056. * Lvalues:: Expressions into which a value can be stored.
  2057. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2058. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2059. an lvalue's contents.
  2060. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2061. * Assignment in Subexpressions:: How to avoid ambiguity.
  2062. * Write Assignments Separately:: Write assignments as separate statements.
  2063. @end menu
  2064. @node Simple Assignment
  2065. @section Simple Assignment
  2066. @cindex simple assignment
  2067. @cindex assignment, simple
  2068. A @dfn{simple assignment expression} computes the value of the right
  2069. operand and stores it into the lvalue on the left. Here is a simple
  2070. assignment expression that stores 5 in @code{i}:
  2071. @example
  2072. i = 5
  2073. @end example
  2074. @noindent
  2075. We say that this is an @dfn{assignment to} the variable @code{i} and
  2076. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2077. because it is an expression (so it has a value). Adding a semicolon
  2078. at the end would make it a statement (@pxref{Expression Statement}).
  2079. Here is another example of a simple assignment expression. Its
  2080. operands are not simple, but the kind of assignment done here is
  2081. simple assignment.
  2082. @example
  2083. x[foo ()] = y + 6
  2084. @end example
  2085. A simple assignment with two different numeric data types converts the
  2086. right operand value to the lvalue's type, if possible. It can convert
  2087. any numeric type to any other numeric type.
  2088. Simple assignment is also allowed on some non-numeric types: pointers
  2089. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2090. unions (@pxref{Unions}).
  2091. @strong{Warning:} Assignment is not allowed on arrays because
  2092. there are no array values in C; C variables can be arrays, but these
  2093. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2094. Arrays}.
  2095. @xref{Assignment Type Conversions}, for the complete rules about data
  2096. types used in assignments.
  2097. @node Lvalues
  2098. @section Lvalues
  2099. @cindex lvalues
  2100. An expression that identifies a memory space that holds a value is
  2101. called an @dfn{lvalue}, because it is a location that can hold a value.
  2102. The standard kinds of lvalues are:
  2103. @itemize @bullet
  2104. @item
  2105. A variable.
  2106. @item
  2107. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2108. unary @samp{*}.
  2109. @item
  2110. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2111. the structure value is an lvalue.
  2112. @item
  2113. A structure field reference using @samp{->}. This is always an lvalue
  2114. since @samp{->} implies pointer dereference.
  2115. @item
  2116. A union alternative reference (@pxref{Unions}), on the same conditions
  2117. as for structure fields.
  2118. @item
  2119. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2120. is an lvalue.
  2121. @end itemize
  2122. If an expression's outermost operation is any other operator, that
  2123. expression is not an lvalue. Thus, the variable @code{x} is an
  2124. lvalue, but @code{x + 0} is not, even though these two expressions
  2125. compute the same value (assuming @code{x} is a number).
  2126. An array can be an lvalue (the rules above determine whether it is
  2127. one), but using the array in an expression converts it automatically
  2128. to a pointer to the first element. The result of this conversion is
  2129. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2130. use @code{a} by itself as the left operand of an assignment. But you
  2131. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2132. lvalue since @code{a} is an lvalue.
  2133. @node Modifying Assignment
  2134. @section Modifying Assignment
  2135. @cindex modifying assignment
  2136. @cindex assignment, modifying
  2137. You can abbreviate the common construct
  2138. @example
  2139. @var{lvalue} = @var{lvalue} + @var{expression}
  2140. @end example
  2141. @noindent
  2142. as
  2143. @example
  2144. @var{lvalue} += @var{expression}
  2145. @end example
  2146. This is known as a @dfn{modifying assignment}. For instance,
  2147. @example
  2148. i = i + 5;
  2149. i += 5;
  2150. @end example
  2151. @noindent
  2152. shows two statements that are equivalent. The first uses
  2153. simple assignment; the second uses modifying assignment.
  2154. Modifying assignment works with any binary arithmetic operator. For
  2155. instance, you can subtract something from an lvalue like this,
  2156. @example
  2157. @var{lvalue} -= @var{expression}
  2158. @end example
  2159. @noindent
  2160. or multiply it by a certain amount like this,
  2161. @example
  2162. @var{lvalue} *= @var{expression}
  2163. @end example
  2164. @noindent
  2165. or shift it by a certain amount like this.
  2166. @example
  2167. @var{lvalue} <<= @var{expression}
  2168. @var{lvalue} >>= @var{expression}
  2169. @end example
  2170. In most cases, this feature adds no power to the language, but it
  2171. provides substantial convenience. Also, when @var{lvalue} contains
  2172. code that has side effects, the simple assignment performs those side
  2173. effects twice, while the modifying assignment performs them once. For
  2174. instance,
  2175. @example
  2176. x[foo ()] = x[foo ()] + 5;
  2177. @end example
  2178. @noindent
  2179. calls @code{foo} twice, and it could return different values each
  2180. time. If @code{foo ()} returns 1 the first time and 3 the second
  2181. time, then the effect could be to add @code{x[3]} and 5 and store the
  2182. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2183. result in @code{x[3]}. We don't know which of the two it will do,
  2184. because C does not specify which call to @code{foo} is computed first.
  2185. Such a statement is not well defined, and shouldn't be used.
  2186. By contrast,
  2187. @example
  2188. x[foo ()] += 5;
  2189. @end example
  2190. @noindent
  2191. is well defined: it calls @code{foo} only once to determine which
  2192. element of @code{x} to adjust, and it adjusts that element by adding 5
  2193. to it.
  2194. @node Increment/Decrement
  2195. @section Increment and Decrement Operators
  2196. @cindex increment operator
  2197. @cindex decrement operator
  2198. @cindex operator, increment
  2199. @cindex operator, decrement
  2200. @cindex preincrement expression
  2201. @cindex predecrement expression
  2202. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2203. @dfn{decrement} operators. When used on a numeric value, they add or
  2204. subtract 1. We don't consider them assignments, but they are
  2205. equivalent to assignments.
  2206. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2207. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2208. and the result becomes the expression's value. For instance,
  2209. @example
  2210. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2211. int
  2212. main (void)
  2213. @{
  2214. int i = 5;
  2215. printf ("%d\n", i);
  2216. printf ("%d\n", ++i);
  2217. printf ("%d\n", i);
  2218. return 0;
  2219. @}
  2220. @end example
  2221. @noindent
  2222. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2223. increments @code{i} from 5 to 6, and has the value 6, so the output
  2224. from @code{printf} on that line says @samp{6}.
  2225. Using @samp{--} instead, for predecrement,
  2226. @example
  2227. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2228. int
  2229. main (void)
  2230. @{
  2231. int i = 5;
  2232. printf ("%d\n", i);
  2233. printf ("%d\n", --i);
  2234. printf ("%d\n", i);
  2235. return 0;
  2236. @}
  2237. @end example
  2238. @noindent
  2239. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2240. again @samp{4}.
  2241. @node Postincrement/Postdecrement
  2242. @section Postincrement and Postdecrement
  2243. @cindex postincrement expression
  2244. @cindex postdecrement expression
  2245. @cindex operator, postincrement
  2246. @cindex operator, postdecrement
  2247. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2248. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2249. increments or decrements it. Thus, the value of @code{i++} is the same
  2250. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2251. little later.'' This is called @dfn{postincrement} or
  2252. @dfn{postdecrement}.
  2253. For example,
  2254. @example
  2255. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2256. int
  2257. main (void)
  2258. @{
  2259. int i = 5;
  2260. printf ("%d\n", i);
  2261. printf ("%d\n", i++);
  2262. printf ("%d\n", i);
  2263. return 0;
  2264. @}
  2265. @end example
  2266. @noindent
  2267. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2268. has the value 5, which is the value of @code{i} at the time,
  2269. but it increments @code{i} from 5 to 6 just a little later.
  2270. How much later is ``just a little later''? That is flexible. The
  2271. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2272. that means by the end of the statement. @xref{Sequence Points}.
  2273. If a unary operator precedes a postincrement or postincrement expression,
  2274. the increment nests inside:
  2275. @example
  2276. -a++ @r{is equivalent to} -(a++)
  2277. @end example
  2278. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2279. it can't be incremented.
  2280. The most common use of postincrement is with arrays. Here's
  2281. an example of using postincrement to access one element of an
  2282. array and advance the index for the next access. Compare
  2283. this with the example @code{avg_of_double}, which is almost
  2284. the same but doesn't use postincrement (@pxref{Array Example}).
  2285. @example
  2286. double
  2287. avg_of_double_alt (int length, double input_data[])
  2288. @{
  2289. double sum = 0;
  2290. int i;
  2291. /* @r{Fetch each element and add it into @code{sum}.} */
  2292. for (i = 0; i < length;)
  2293. /* @r{Use the index @code{i}, then increment it.} */
  2294. sum += input_data[i++];
  2295. return sum / length;
  2296. @}
  2297. @end example
  2298. @node Assignment in Subexpressions
  2299. @section Pitfall: Assignment in Subexpressions
  2300. @cindex assignment in subexpressions
  2301. @cindex subexpressions, assignment in
  2302. In C, the order of computing parts of an expression is not fixed.
  2303. Aside from a few special cases, the operations can be computed in any
  2304. order. If one part of the expression has an assignment to @code{x}
  2305. and another part of the expression uses @code{x}, the result is
  2306. unpredictable because that use might be computed before or after the
  2307. assignment.
  2308. Here's an example of ambiguous code:
  2309. @example
  2310. x = 20;
  2311. printf ("%d %d\n", x, x = 4);
  2312. @end example
  2313. @noindent
  2314. If the second argument, @code{x}, is computed before the third argument,
  2315. @code{x = 4}, the second argument's value will be 20. If they are
  2316. computed in the other order, the second argument's value will be 4.
  2317. Here's one way to make that code unambiguous:
  2318. @example
  2319. y = 20;
  2320. printf ("%d %d\n", y, x = 4);
  2321. @end example
  2322. Here's another way, with the other meaning:
  2323. @example
  2324. x = 4;
  2325. printf ("%d %d\n", x, x);
  2326. @end example
  2327. This issue applies to all kinds of assignments, and to the increment
  2328. and decrement operators, which are equivalent to assignments.
  2329. @xref{Order of Execution}, for more information about this.
  2330. However, it can be useful to write assignments inside an
  2331. @code{if}-condition or @code{while}-test along with logical operators.
  2332. @xref{Logicals and Assignments}.
  2333. @node Write Assignments Separately
  2334. @section Write Assignments in Separate Statements
  2335. It is often convenient to write an assignment inside an
  2336. @code{if}-condition, but that can reduce the readability of the
  2337. program. Here's an example of what to avoid:
  2338. @example
  2339. if (x = advance (x))
  2340. @r{@dots{}}
  2341. @end example
  2342. The idea here is to advance @code{x} and test if the value is nonzero.
  2343. However, readers might miss the fact that it uses @samp{=} and not
  2344. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2345. inside a condition is a common error, so GNU C can give warnings when
  2346. @samp{=} appears in a way that suggests it's an error.
  2347. It is much clearer to write the assignment as a separate statement, like this:
  2348. @example
  2349. x = advance (x);
  2350. if (x != 0)
  2351. @r{@dots{}}
  2352. @end example
  2353. @noindent
  2354. This makes it unmistakably clear that @code{x} is assigned a new value.
  2355. Another method is to use the comma operator (@pxref{Comma Operator}),
  2356. like this:
  2357. @example
  2358. if (x = advance (x), x != 0)
  2359. @r{@dots{}}
  2360. @end example
  2361. @noindent
  2362. However, putting the assignment in a separate statement is usually clearer
  2363. unless the assignment is very short, because it reduces nesting.
  2364. @node Execution Control Expressions
  2365. @chapter Execution Control Expressions
  2366. @cindex execution control expressions
  2367. @cindex expressions, execution control
  2368. This chapter describes the C operators that combine expressions to
  2369. control which of those expressions execute, or in which order.
  2370. @menu
  2371. * Logical Operators:: Logical conjunction, disjunction, negation.
  2372. * Logicals and Comparison:: Logical operators with comparison operators.
  2373. * Logicals and Assignments:: Assignments with logical operators.
  2374. * Conditional Expression:: An if/else construct inside expressions.
  2375. * Comma Operator:: Build a sequence of subexpressions.
  2376. @end menu
  2377. @node Logical Operators
  2378. @section Logical Operators
  2379. @cindex logical operators
  2380. @cindex operators, logical
  2381. @cindex conjunction operator
  2382. @cindex disjunction operator
  2383. @cindex negation operator, logical
  2384. The @dfn{logical operators} combine truth values, which are normally
  2385. represented in C as numbers. Any expression with a numeric value is a
  2386. valid truth value: zero means false, and any other value means true.
  2387. A pointer type is also meaningful as a truth value; a null pointer
  2388. (which is zero) means false, and a non-null pointer means true
  2389. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2390. or 0 and has type @code{int} (@pxref{Integer Types}).
  2391. The logical operators are used mainly in the condition of an @code{if}
  2392. statement, or in the end test in a @code{for} statement or
  2393. @code{while} statement (@pxref{Statements}). However, they are valid
  2394. in any context where an integer-valued expression is allowed.
  2395. @table @samp
  2396. @item ! @var{exp}
  2397. Unary operator for logical ``not.'' The value is 1 (true) if
  2398. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2399. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2400. function call, you should write parentheses around it.
  2401. @item @var{left} && @var{right}
  2402. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2403. @var{right}. If both of the operands are true, the @samp{&&} expression
  2404. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2405. gives the value 0 (false). If @var{left} yields a false value,
  2406. that determines the overall result, so @var{right} is not computed.
  2407. @item @var{left} || @var{right}
  2408. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2409. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2410. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2411. gives the value 0 (false). If @var{left} yields a true value,
  2412. that determines the overall result, so @var{right} is not computed.
  2413. @end table
  2414. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2415. and @samp{||}. When you use them together, always use parentheses to
  2416. specify explicitly how they nest, as shown here:
  2417. @example
  2418. if ((r != 0 && x % r == 0)
  2419. ||
  2420. (s != 0 && x % s == 0))
  2421. @end example
  2422. @node Logicals and Comparison
  2423. @section Logical Operators and Comparisons
  2424. The most common thing to use inside the logical operators is a
  2425. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2426. precedence than comparison operators and arithmetic operators, so we
  2427. can write expressions like this without parentheses and get the
  2428. nesting that is natural: two comparison operations that must both be
  2429. true.
  2430. @example
  2431. if (r != 0 && x % r == 0)
  2432. @end example
  2433. @noindent
  2434. This example also shows how it is useful that @samp{&&} guarantees to
  2435. skip the right operand if the left one turns out false. Because of
  2436. that, this code never tries to divide by zero.
  2437. This is equivalent:
  2438. @example
  2439. if (r && x % r == 0)
  2440. @end example
  2441. @noindent
  2442. A truth value is simply a number, so using @code{r} as a truth value
  2443. tests whether it is nonzero. But @code{r}'s meaning as en expression
  2444. is not a truth value---it is a number to divide by. So it is better
  2445. style to write the explicit @code{!= 0}.
  2446. Here's another equivalent way to write it:
  2447. @example
  2448. if (!(r == 0) && x % r == 0)
  2449. @end example
  2450. @noindent
  2451. This illustrates the unary @samp{!} operator, and the need to
  2452. write parentheses around its operand.
  2453. @node Logicals and Assignments
  2454. @section Logical Operators and Assignments
  2455. There are cases where assignments nested inside the condition can
  2456. actually make a program @emph{easier} to read. Here is an example
  2457. using a hypothetical type @code{list} which represents a list; it
  2458. tests whether the list has at least two links, using hypothetical
  2459. functions, @code{nonempty} which is true if the argument is a nonempty
  2460. list, and @code{list_next} which advances from one list link to the
  2461. next. We assume that a list is never a null pointer, so that the
  2462. assignment expressions are always ``true.''
  2463. @example
  2464. if (nonempty (list)
  2465. && (temp1 = list_next (list))
  2466. && nonempty (temp1)
  2467. && (temp2 = list_next (temp1)))
  2468. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2469. @end example
  2470. @noindent
  2471. Here we take advantage of the @samp{&&} operator to avoid executing
  2472. the rest of the code if a call to @code{nonempty} returns ``false.'' The
  2473. only natural place to put the assignments is among those calls.
  2474. It would be possible to rewrite this as several statements, but that
  2475. could make it much more cumbersome. On the other hand, when the test
  2476. is even more complex than this one, splitting it into multiple
  2477. statements might be necessary for clarity.
  2478. If an empty list is a null pointer, we can dispense with calling
  2479. @code{nonempty}:
  2480. @example
  2481. if ((temp1 = list_next (list))
  2482. && (temp2 = list_next (temp1)))
  2483. @r{@dots{}}
  2484. @end example
  2485. @node Conditional Expression
  2486. @section Conditional Expression
  2487. @cindex conditional expression
  2488. @cindex expression, conditional
  2489. C has a conditional expression that selects one of two expressions
  2490. to compute and get the value from. It looks like this:
  2491. @example
  2492. @var{condition} ? @var{iftrue} : @var{iffalse}
  2493. @end example
  2494. @menu
  2495. * Conditional Rules:: Rules for the conditional operator.
  2496. * Conditional Branches:: About the two branches in a conditional.
  2497. @end menu
  2498. @node Conditional Rules
  2499. @subsection Rules for the Conditional Operator
  2500. The first operand, @var{condition}, should be a value that can be
  2501. compared with zero---a number or a pointer. If it is true (nonzero),
  2502. then the conditional expression computes @var{iftrue} and its value
  2503. becomes the value of the conditional expression. Otherwise the
  2504. conditional expression computes @var{iffalse} and its value becomes
  2505. the value of the conditional expression. The conditional expression
  2506. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2507. of them.
  2508. Here's an example: the absolute value of a number @code{x}
  2509. can be written as @code{(x >= 0 ? x : -x)}.
  2510. @strong{Warning:} The conditional expression operators have rather low
  2511. syntactic precedence. Except when the conditional expression is used
  2512. as an argument in a function call, write parentheses around it. For
  2513. clarity, always write parentheses around it if it extends across more
  2514. than one line.
  2515. Assignment operators and the comma operator (@pxref{Comma Operator})
  2516. have lower precedence than conditional expression operators, so write
  2517. parentheses around those when they appear inside a conditional
  2518. expression. @xref{Order of Execution}.
  2519. @node Conditional Branches
  2520. @subsection Conditional Operator Branches
  2521. @cindex branches of conditional expression
  2522. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2523. conditional.
  2524. The two branches should normally have the same type, but a few
  2525. exceptions are allowed. If they are both numeric types, the
  2526. conditional converts both to their common type (@pxref{Common Type}).
  2527. With pointers (@pxref{Pointers}), the two values can be pointers to
  2528. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2529. result type is a similar pointer whose target type combines all the
  2530. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2531. If one branch has type @code{void *} and the other is a pointer to an
  2532. object (not to a function), the conditional converts the @code{void *}
  2533. branch to the type of the other.
  2534. If one branch is an integer constant with value zero and the other is
  2535. a pointer, the conditional converts zero to the pointer's type.
  2536. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2537. that case, if @var{condition} is nonzero, its value becomes the value of
  2538. the conditional expression, after conversion to the common type.
  2539. Thus,
  2540. @example
  2541. x ? : y
  2542. @end example
  2543. @noindent
  2544. has the value of @code{x} if that is nonzero; otherwise, the value of
  2545. @code{y}.
  2546. @cindex side effect in ?:
  2547. @cindex ?: side effect
  2548. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2549. In that case, writing that expression twice would carry out the side
  2550. effects twice, but writing it once does them just once. For example,
  2551. if we suppose that the function @code{next_element} advances a pointer
  2552. variable to point to the next element in a list and returns the new
  2553. pointer,
  2554. @example
  2555. next_element () ? : default_pointer
  2556. @end example
  2557. @noindent
  2558. is a way to advance the pointer and use its new value if it isn't
  2559. null, but use @code{default_pointer} if that is null. We cannot do
  2560. it this way,
  2561. @example
  2562. next_element () ? next_element () : default_pointer
  2563. @end example
  2564. @noindent
  2565. because that would advance the pointer a second time.
  2566. @node Comma Operator
  2567. @section Comma Operator
  2568. @cindex comma operator
  2569. @cindex operator, comma
  2570. The comma operator stands for sequential execution of expressions.
  2571. The value of the comma expression comes from the last expression in
  2572. the sequence; the previous expressions are computed only for their
  2573. side effects. It looks like this:
  2574. @example
  2575. @var{exp1}, @var{exp2} @r{@dots{}}
  2576. @end example
  2577. @noindent
  2578. You can bundle any number of expressions together this way, by putting
  2579. commas between them.
  2580. @menu
  2581. * Uses of Comma:: When to use the comma operator.
  2582. * Clean Comma:: Clean use of the comma operator.
  2583. * Avoid Comma:: When to not use the comma operator.
  2584. @end menu
  2585. @node Uses of Comma
  2586. @subsection The Uses of the Comma Operator
  2587. With commas, you can put several expressions into a place that
  2588. requires just one expression---for example, in the header of a
  2589. @code{for} statement. This statement
  2590. @example
  2591. for (i = 0, j = 10, k = 20; i < n; i++)
  2592. @end example
  2593. @noindent
  2594. contains three assignment expressions, to initialize @code{i}, @code{j}
  2595. and @code{k}. The syntax of @code{for} requires just one expression
  2596. for initialization; to include three assignments, we use commas to
  2597. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2598. 20}. This technique is also useful in the loop-advance expression,
  2599. the last of the three inside the @code{for} parentheses.
  2600. In the @code{for} statement and the @code{while} statement
  2601. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2602. effect before the loop-exit test. For example,
  2603. @example
  2604. while (printf ("At the test, x = %d\n", x), x != 0)
  2605. @end example
  2606. @node Clean Comma
  2607. @subsection Clean Use of the Comma Operator
  2608. Always write parentheses around a series of comma operators, except
  2609. when it is at top level in an expression statement, or within the
  2610. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2611. statement (@pxref{Statements}). For instance, in
  2612. @example
  2613. for (i = 0, j = 10, k = 20; i < n; i++)
  2614. @end example
  2615. @noindent
  2616. the commas between the assignments are clear because they are between
  2617. a parenthesis and a semicolon.
  2618. The arguments in a function call are also separated by commas, but that is
  2619. not an instance of the comma operator. Note the difference between
  2620. @example
  2621. foo (4, 5, 6)
  2622. @end example
  2623. @noindent
  2624. which passes three arguments to @code{foo} and
  2625. @example
  2626. foo ((4, 5, 6))
  2627. @end example
  2628. @noindent
  2629. which uses the comma operator and passes just one argument
  2630. (with value 6).
  2631. @strong{Warning:} don't use the comma operator around an argument
  2632. of a function unless it makes the code more readable. When you do so,
  2633. don't put part of another argument on the same line. Instead, add a
  2634. line break to make the parentheses around the comma operator easier to
  2635. see, like this.
  2636. @example
  2637. foo ((mumble (x, y), frob (z)),
  2638. *p)
  2639. @end example
  2640. @node Avoid Comma
  2641. @subsection When Not to Use the Comma Operator
  2642. You can use a comma in any subexpression, but in most cases it only
  2643. makes the code confusing, and it is clearer to raise all but the last
  2644. of the comma-separated expressions to a higher level. Thus, instead
  2645. of this:
  2646. @example
  2647. x = (y += 4, 8);
  2648. @end example
  2649. @noindent
  2650. it is much clearer to write this:
  2651. @example
  2652. y += 4, x = 8;
  2653. @end example
  2654. @noindent
  2655. or this:
  2656. @example
  2657. y += 4;
  2658. x = 8;
  2659. @end example
  2660. Use commas only in the cases where there is no clearer alternative
  2661. involving multiple statements.
  2662. By contrast, don't hesitate to use commas in the expansion in a macro
  2663. definition. The trade-offs of code clarity are different in that
  2664. case, because the @emph{use} of the macro may improve overall clarity
  2665. so much that the ugliness of the macro's @emph{definition} is a small
  2666. price to pay. @xref{Macros}.
  2667. @node Binary Operator Grammar
  2668. @chapter Binary Operator Grammar
  2669. @cindex binary operator grammar
  2670. @cindex grammar, binary operator
  2671. @cindex operator precedence
  2672. @cindex precedence, operator
  2673. @cindex left-associative
  2674. @dfn{Binary operators} are those that take two operands, one
  2675. on the left and one on the right.
  2676. All the binary operators in C are syntactically left-associative.
  2677. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2678. @var{op} b) @var{op} c}}. However, the only operators you should
  2679. repeat in this way without parentheses are @samp{+}, @samp{-},
  2680. @samp{*} and @samp{/}, because those cases are clear from algebra. So
  2681. it is OK to write @code{a + b + c} or @code{a - b - c}, but never
  2682. @code{a == b == c} or @code{a % b % c}. For those operators, use
  2683. explicit parentheses to show how the operations nest.
  2684. Each C operator has a @dfn{precedence}, which is its rank in the
  2685. grammatical order of the various operators. The operators with the
  2686. highest precedence grab adjoining operands first; these expressions
  2687. then become operands for operators of lower precedence.
  2688. The precedence order of operators in C is fully specified, so any
  2689. combination of operations leads to a well-defined nesting. We state
  2690. only part of the full precedence ordering here because it is bad
  2691. practice for C code to depend on the other cases. For cases not
  2692. specified in this chapter, always use parentheses to make the nesting
  2693. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2694. remembering anything about the C precedence order beyond what's stated
  2695. here. I studied the full precedence table to write the parser, and
  2696. promptly forgot it again. If you need to look up the full precedence order
  2697. to understand some C code, fix the code with parentheses so nobody else
  2698. needs to do that.}
  2699. You can depend on this subsequence of the precedence ordering
  2700. (stated from highest precedence to lowest):
  2701. @enumerate
  2702. @item
  2703. Component access (@samp{.} and @samp{->}).
  2704. @item
  2705. Unary prefix operators.
  2706. @item
  2707. Unary postfix operators.
  2708. @item
  2709. Multiplication, division, and remainder (they have the same precedence).
  2710. @item
  2711. Addition and subtraction (they have the same precedence).
  2712. @item
  2713. Comparisons---but watch out!
  2714. @item
  2715. Logical operators @samp{&&} and @samp{||}---but watch out!
  2716. @item
  2717. Conditional expression with @samp{?} and @samp{:}.
  2718. @item
  2719. Assignments.
  2720. @item
  2721. Sequential execution (the comma operator, @samp{,}).
  2722. @end enumerate
  2723. Two of the lines in the above list say ``but watch out!'' That means
  2724. that the line covers operators with subtly different precedence.
  2725. Never depend on the grammar of C to decide how two comparisons nest;
  2726. instead, always use parentheses to specify their nesting.
  2727. You can let several @samp{&&} operators associate, or several
  2728. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2729. and @samp{||} nest with each other. @xref{Logical Operators}.
  2730. There is one other precedence ordering that code can depend on:
  2731. @enumerate
  2732. @item
  2733. Unary postfix operators.
  2734. @item
  2735. Bitwise and shift operators---but watch out!
  2736. @item
  2737. Conditional expression with @samp{?} and @samp{:}.
  2738. @end enumerate
  2739. The caveat for bitwise and shift operators is like that for logical
  2740. operators: you can let multiple uses of one bitwise operator
  2741. associate, but always use parentheses to control nesting of dissimilar
  2742. operators.
  2743. These lists do not specify any precedence ordering between the bitwise
  2744. and shift operators of the second list and the binary operators above
  2745. conditional expressions in the first list. When they come together,
  2746. parenthesize them. @xref{Bitwise Operations}.
  2747. @node Order of Execution
  2748. @chapter Order of Execution
  2749. @cindex order of execution
  2750. The order of execution of a C program is not always obvious, and not
  2751. necessarily predictable. This chapter describes what you can count on.
  2752. @menu
  2753. * Reordering of Operands:: Operations in C are not necessarily computed
  2754. in the order they are written.
  2755. * Associativity and Ordering:: Some associative operations are performed
  2756. in a particular order; others are not.
  2757. * Sequence Points:: Some guarantees about the order of operations.
  2758. * Postincrement and Ordering:: Ambiguous execution order with postincrement.
  2759. * Ordering of Operands:: Evaluation order of operands
  2760. and function arguments.
  2761. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2762. only if it has no impact on program results.
  2763. @end menu
  2764. @node Reordering of Operands
  2765. @section Reordering of Operands
  2766. @cindex ordering of operands
  2767. @cindex reordering of operands
  2768. @cindex operand execution ordering
  2769. The C language does not necessarily carry out operations within an
  2770. expression in the order they appear in the code. For instance, in
  2771. this expression,
  2772. @example
  2773. foo () + bar ()
  2774. @end example
  2775. @noindent
  2776. @code{foo} might be called first or @code{bar} might be called first.
  2777. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2778. results can be unpredictable.
  2779. The unpredictable order of computation of subexpressions also makes a
  2780. difference when one of them contains an assignment. We already saw
  2781. this example of bad code,
  2782. @example
  2783. x = 20;
  2784. printf ("%d %d\n", x, x = 4);
  2785. @end example
  2786. @noindent
  2787. in which the second argument, @code{x}, has a different value
  2788. depending on whether it is computed before or after the assignment in
  2789. the third argument.
  2790. @node Associativity and Ordering
  2791. @section Associativity and Ordering
  2792. @cindex associativity and ordering
  2793. An associative binary operator, such as @code{+}, when used repeatedly
  2794. can combine any number of operands. The operands' values may be
  2795. computed in any order.
  2796. If the values are integers and overflow can be ignored, they may be
  2797. combined in any order. Thus, given four functions that return
  2798. @code{unsigned int}, calling them and adding their results as here
  2799. @example
  2800. (foo () + bar ()) + (baz () + quux ())
  2801. @end example
  2802. @noindent
  2803. may add up the results in any order.
  2804. By contrast, arithmetic on signed integers, in which overflow is significant,
  2805. is not always associative (@pxref{Integer Overflow}). Thus, the
  2806. additions must be done in the order specified, obeying parentheses and
  2807. left-association. That means computing @code{(foo () + bar ())} and
  2808. @code{(baz () + quux ())} first (in either order), then adding the
  2809. two.
  2810. The same applies to arithmetic on floating-point values, since that
  2811. too is not really associative. However, the GCC option
  2812. @option{-funsafe-math-optimizations} allows the compiler to change the
  2813. order of calculation when an associative operation (associative in
  2814. exact mathematics) combines several operands. The option takes effect
  2815. when compiling a module (@pxref{Compilation}). Changing the order
  2816. of association can enable the program to pipeline the floating point
  2817. operations.
  2818. In all these cases, the four function calls can be done in any order.
  2819. There is no right or wrong about that.
  2820. @node Sequence Points
  2821. @section Sequence Points
  2822. @cindex sequence points
  2823. @cindex full expression
  2824. There are some points in the code where C makes limited guarantees
  2825. about the order of operations. These are called @dfn{sequence
  2826. points}. Here is where they occur:
  2827. @itemize @bullet
  2828. @item
  2829. At the end of a @dfn{full expression}; that is to say, an expression
  2830. that is not part of a larger expression. All side effects specified
  2831. by that expression are carried out before execution moves
  2832. on to subsequent code.
  2833. @item
  2834. At the end of the first operand of certain operators: @samp{,},
  2835. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2836. that expression are carried out before any execution of the
  2837. next operand.
  2838. The commas that separate arguments in a function call are @emph{not}
  2839. comma operators, and they do not create sequence points. The rule
  2840. for function arguments and the rule for operands are different
  2841. (@pxref{Ordering of Operands}).
  2842. @item
  2843. Just before calling a function. All side effects specified by the
  2844. argument expressions are carried out before calling the function.
  2845. If the function to be called is not constant---that is, if it is
  2846. computed by an expression---all side effects in that expression are
  2847. carried out before calling the function.
  2848. @end itemize
  2849. The ordering imposed by a sequence point applies locally to a limited
  2850. range of code, as stated above in each case. For instance, the
  2851. ordering imposed by the comma operator does not apply to code outside
  2852. the operands of that comma operator. Thus, in this code,
  2853. @example
  2854. (x = 5, foo (x)) + x * x
  2855. @end example
  2856. @noindent
  2857. the sequence point of the comma operator orders @code{x = 5} before
  2858. @code{foo (x)}, but @code{x * x} could be computed before or after
  2859. them.
  2860. @node Postincrement and Ordering
  2861. @section Postincrement and Ordering
  2862. @cindex postincrement and ordering
  2863. @cindex ordering and postincrement
  2864. The ordering requirements for the postincrement and postdecrement
  2865. operations (@pxref{Postincrement/Postdecrement}) are loose: those side
  2866. effects must happen ``a little later,'' before the next sequence
  2867. point. That still leaves room for various orders that give different
  2868. results. In this expression,
  2869. @example
  2870. z = x++ - foo ()
  2871. @end example
  2872. @noindent
  2873. it's unpredictable whether @code{x} gets incremented before or after
  2874. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2875. it might see the old value or it might see the incremented value.
  2876. In this perverse expression,
  2877. @example
  2878. x = x++
  2879. @end example
  2880. @noindent
  2881. @code{x} will certainly be incremented but the incremented value may
  2882. be replaced with the old value. That's because the incrementation and
  2883. the assignment may occur in either oder. If the incrementation of
  2884. @code{x} occurs after the assignment to @code{x}, the incremented
  2885. value will remain in place. But if the incrementation happens first,
  2886. the assignment will put the not-yet-incremented value back into
  2887. @code{x}, so the expression as a whole will leave @code{x} unchanged.
  2888. The conclusion: @strong{avoid such expressions}. Take care, when you
  2889. use postincrement and postdecrement, that the specific expression you
  2890. use is not ambiguous as to order of execution.
  2891. @node Ordering of Operands
  2892. @section Ordering of Operands
  2893. @cindex ordering of operands
  2894. @cindex operand ordering
  2895. Operands and arguments can be computed in any order, but there are limits to
  2896. this intermixing in GNU C:
  2897. @itemize @bullet
  2898. @item
  2899. The operands of a binary arithmetic operator can be computed in either
  2900. order, but they can't be intermixed: one of them has to come first,
  2901. followed by the other. Any side effects in the operand that's computed
  2902. first are executed before the other operand is computed.
  2903. @item
  2904. That applies to assignment operators too, except that, in simple assignment,
  2905. the previous value of the left operand is unused.
  2906. @item
  2907. The arguments in a function call can be computed in any order, but
  2908. they can't be intermixed. Thus, one argument is fully computed, then
  2909. another, and so on until they have all been done. Any side effects in
  2910. one argument are executed before computation of another argument
  2911. begins.
  2912. @end itemize
  2913. These rules don't cover side effects caused by postincrement and
  2914. postdecrement operators---those can be deferred up to the next
  2915. sequence point.
  2916. If you want to get pedantic, the fact is that GCC can reorder the
  2917. computations in many other ways provided that it doesn't alter the result
  2918. of running the program. However, because it doesn't alter the result
  2919. of running the program, it is negligible, unless you are concerned
  2920. with the values in certain variables at various times as seen by other
  2921. processes. In those cases, you should use @code{volatile} to prevent
  2922. optimizations that would make them behave strangely. @xref{volatile}.
  2923. @node Optimization and Ordering
  2924. @section Optimization and Ordering
  2925. @cindex optimization and ordering
  2926. @cindex ordering and optimization
  2927. Sequence points limit the compiler's freedom to reorder operations
  2928. arbitrarily, but optimizations can still reorder them if the compiler
  2929. concludes that this won't alter the results. Thus, in this code,
  2930. @example
  2931. x++;
  2932. y = z;
  2933. x++;
  2934. @end example
  2935. @noindent
  2936. there is a sequence point after each statement, so the code is
  2937. supposed to increment @code{x} once before the assignment to @code{y}
  2938. and once after. However, incrementing @code{x} has no effect on
  2939. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2940. the code could be optimized into this:
  2941. @example
  2942. y = z;
  2943. x += 2;
  2944. @end example
  2945. Normally that has no effect except to make the program faster. But
  2946. there are special situations where it can cause trouble due to things
  2947. that the compiler cannot know about, such as shared memory. To limit
  2948. optimization in those places, use the @code{volatile} type qualifier
  2949. (@pxref{volatile}).
  2950. @node Primitive Types
  2951. @chapter Primitive Data Types
  2952. @cindex primitive types
  2953. @cindex types, primitive
  2954. This chapter describes all the primitive data types of C---that is,
  2955. all the data types that aren't built up from other types. They
  2956. include the types @code{int} and @code{double} that we've already covered.
  2957. @menu
  2958. * Integer Types:: Description of integer types.
  2959. * Floating-Point Data Types:: Description of floating-point types.
  2960. * Complex Data Types:: Description of complex number types.
  2961. * The Void Type:: A type indicating no value at all.
  2962. * Other Data Types:: A brief summary of other types.
  2963. * Type Designators:: Referring to a data type abstractly.
  2964. @end menu
  2965. These types are all made up of bytes (@pxref{Storage}).
  2966. @node Integer Types
  2967. @section Integer Data Types
  2968. @cindex integer types
  2969. @cindex types, integer
  2970. Here we describe all the integer types and their basic
  2971. characteristics. @xref{Integers in Depth}, for more information about
  2972. the bit-level integer data representations and arithmetic.
  2973. @menu
  2974. * Basic Integers:: Overview of the various kinds of integers.
  2975. * Signed and Unsigned Types:: Integers can either hold both negative and
  2976. non-negative values, or only non-negative.
  2977. * Narrow Integers:: When to use smaller integer types.
  2978. * Integer Conversion:: Casting a value from one integer type
  2979. to another.
  2980. * Boolean Type:: An integer type for boolean values.
  2981. * Integer Variations:: Sizes of integer types can vary
  2982. across platforms.
  2983. @end menu
  2984. @node Basic Integers
  2985. @subsection Basic Integers
  2986. @findex char
  2987. @findex int
  2988. @findex short int
  2989. @findex long int
  2990. @findex long long int
  2991. Integer data types in C can be signed or unsigned. An unsigned type
  2992. can represent only positive numbers and zero. A signed type can
  2993. represent both positive and negative numbers, in a range spread almost
  2994. equally on both sides of zero.
  2995. Aside from signedness, the integer data types vary in size: how many
  2996. bytes long they are. The size determines the range of integer values
  2997. the type can hold.
  2998. Here's a list of the signed integer data types, with the sizes they
  2999. have on most computers. Each has a corresponding unsigned type; see
  3000. @ref{Signed and Unsigned Types}.
  3001. @table @code
  3002. @item signed char
  3003. One byte (8 bits). This integer type is used mainly for integers that
  3004. represent characters, usually as elements of arrays or fields of other
  3005. data structures.
  3006. @item short
  3007. @itemx short int
  3008. Two bytes (16 bits).
  3009. @item int
  3010. Four bytes (32 bits).
  3011. @item long
  3012. @itemx long int
  3013. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  3014. platform. Typically it is 32 bits on 32-bit computers
  3015. and 64 bits on 64-bit computers, but there are exceptions.
  3016. @item long long
  3017. @itemx long long int
  3018. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  3019. incorporated into standard C as of ISO C99.
  3020. @end table
  3021. You can omit @code{int} when you use @code{long} or @code{short}.
  3022. This is harmless and customary.
  3023. @node Signed and Unsigned Types
  3024. @subsection Signed and Unsigned Types
  3025. @cindex signed types
  3026. @cindex unsigned types
  3027. @cindex types, signed
  3028. @cindex types, unsigned
  3029. @findex signed
  3030. @findex unsigned
  3031. An unsigned integer type can represent only positive numbers and zero.
  3032. A signed type can represent both positive and negative number, in a
  3033. range spread almost equally on both sides of zero. For instance,
  3034. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  3035. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  3036. these types holds 256 different possible values, since they are both 8
  3037. bits wide.
  3038. Write @code{signed} or @code{unsigned} before the type keyword to
  3039. specify a signed or an unsigned type. However, the integer types
  3040. other than @code{char} are signed by default; with them, @code{signed}
  3041. is a no-op.
  3042. Plain @code{char} may be signed or unsigned; this depends on the
  3043. compiler, the machine in use, and its operating system.
  3044. In many programs, it makes no difference whether @code{char} is
  3045. signed. When it does matter, don't leave it to chance; write
  3046. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  3047. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  3048. Arctic Char. When my meal arrived, I noted that the chef had not
  3049. signed it. So I complained, ``This char is unsigned---I wanted a
  3050. signed char!'' Or rather, I would have said this if I had thought of
  3051. it fast enough.}
  3052. @node Narrow Integers
  3053. @subsection Narrow Integers
  3054. The types that are narrower than @code{int} are rarely used for
  3055. ordinary variables---we declare them @code{int} instead. This is
  3056. because C converts those narrower types to @code{int} for any
  3057. arithmetic. There is literally no reason to declare a local variable
  3058. @code{char}, for instance.
  3059. In particular, if the value is really a character, you should declare
  3060. the variable @code{int}. Not @code{char}! Using that narrow type can
  3061. force the compiler to truncate values for conversion, which is a
  3062. waste. Furthermore, some functions return either a character value,
  3063. or @minus{}1 for ``no character.'' Using @code{int} makes it possible
  3064. to distinguish @minus{}1 from a character by sign.
  3065. The narrow integer types are useful as parts of other objects, such as
  3066. arrays and structures. Compare these array declarations, whose sizes
  3067. on 32-bit processors are shown:
  3068. @example
  3069. signed char ac[1000]; /* @r{1000 bytes} */
  3070. short as[1000]; /* @r{2000 bytes} */
  3071. int ai[1000]; /* @r{4000 bytes} */
  3072. long long all[1000]; /* @r{8000 bytes} */
  3073. @end example
  3074. In addition, character strings must be made up of @code{char}s,
  3075. because that's what all the standard library string functions expect.
  3076. Thus, array @code{ac} could be used as a character string, but the
  3077. others could not be.
  3078. @node Integer Conversion
  3079. @subsection Conversion among Integer Types
  3080. C converts between integer types implicitly in many situations. It
  3081. converts the narrow integer types, @code{char} and @code{short}, to
  3082. @code{int} whenever they are used in arithmetic. Assigning a new
  3083. value to an integer variable (or other lvalue) converts the value to
  3084. the variable's type.
  3085. You can also convert one integer type to another explicitly with a
  3086. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3087. The process of conversion to a wider type is straightforward: the
  3088. value is unchanged. The only exception is when converting a negative
  3089. value (in a signed type, obviously) to a wider unsigned type. In that
  3090. case, the result is a positive value with the same bits
  3091. (@pxref{Integers in Depth}).
  3092. @cindex truncation
  3093. Converting to a narrower type, also called @dfn{truncation}, involves
  3094. discarding some of the value's bits. This is not considered overflow
  3095. (@pxref{Integer Overflow}) because loss of significant bits is a
  3096. normal consequence of truncation. Likewise for conversion between
  3097. signed and unsigned types of the same width.
  3098. More information about conversion for assignment is in
  3099. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3100. see @ref{Argument Promotions}.
  3101. @node Boolean Type
  3102. @subsection Boolean Type
  3103. @cindex boolean type
  3104. @cindex type, boolean
  3105. @findex bool
  3106. The unsigned integer type @code{bool} holds truth values: its possible
  3107. values are 0 and 1. Converting any nonzero value to @code{bool}
  3108. results in 1. For example:
  3109. @example
  3110. bool a = 0;
  3111. bool b = 1;
  3112. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3113. @end example
  3114. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3115. the header file @file{stdbool.h}.
  3116. @node Integer Variations
  3117. @subsection Integer Variations
  3118. The integer types of C have standard @emph{names}, but what they
  3119. @emph{mean} varies depending on the kind of platform in use:
  3120. which kind of computer, which operating system, and which compiler.
  3121. It may even depend on the compiler options used.
  3122. Plain @code{char} may be signed or unsigned; this depends on the
  3123. platform, too. Even for GNU C, there is no general rule.
  3124. In theory, all of the integer types' sizes can vary. @code{char} is
  3125. always considered one ``byte'' for C, but it is not necessarily an
  3126. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3127. specifies only that none of these types is narrower than the ones
  3128. above it in the list in @ref{Basic Integers}, and that @code{short}
  3129. has at least 16 bits.
  3130. It is possible that in the future GNU C will support platforms where
  3131. @code{int} is 64 bits long. In practice, however, on today's real
  3132. computers, there is little variation; you can rely on the table
  3133. given previously (@pxref{Basic Integers}).
  3134. To be completely sure of the size of an integer type,
  3135. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3136. Their corresponding unsigned types add @samp{u} at the front:
  3137. @code{uint16_t}, @code{uint32_t} and @code{uint64_t}.
  3138. To define all these types, include the header file @file{stdint.h}.
  3139. The GNU C Compiler can compile for some embedded controllers that use two
  3140. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3141. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3142. 32 bits. These processors can't support an ordinary operating system
  3143. (they may have their own specialized operating systems), and most C
  3144. programs do not try to support them.
  3145. @node Floating-Point Data Types
  3146. @section Floating-Point Data Types
  3147. @cindex floating-point types
  3148. @cindex types, floating-point
  3149. @findex double
  3150. @findex float
  3151. @findex long double
  3152. @dfn{Floating point} is the binary analogue of scientific notation:
  3153. internally it represents a number as a fraction and a binary exponent;
  3154. the value is that fraction multiplied by the specified power of 2.
  3155. (The C standard nominally permits other bases, but in GNU C the base
  3156. is always 2.)
  3157. @c ???
  3158. For instance, to represent 6, the fraction would be 0.75 and the
  3159. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3160. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3161. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3162. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3163. @minus{}1 as the exponent.
  3164. These binary exponents are used by machine instructions. You can
  3165. write a floating-point constant this way if you wish, using
  3166. hexadecimal; but normally we write floating-point numbers in decimal (base 10).
  3167. @xref{Floating Constants}.
  3168. C has three floating-point data types:
  3169. @table @code
  3170. @item double
  3171. ``Double-precision'' floating point, which uses 64 bits. This is the
  3172. normal floating-point type, and modern computers normally do
  3173. their floating-point computations in this type, or some wider type.
  3174. Except when there is a special reason to do otherwise, this is the
  3175. type to use for floating-point values.
  3176. @item float
  3177. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3178. for floating-point values stored in structures and arrays, to save
  3179. space when the full precision of @code{double} is not needed. In
  3180. addition, single-precision arithmetic is faster on some computers, and
  3181. occasionally that is useful. But not often---most programs don't use
  3182. the type @code{float}.
  3183. C would be cleaner if @code{float} were the name of the type we
  3184. use for most floating-point values; however, for historical reasons,
  3185. that's not so.
  3186. @item long double
  3187. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3188. precision, depending on the machine in use. On some machines, which
  3189. have no floating-point format wider than @code{double}, this is
  3190. equivalent to @code{double}.
  3191. @end table
  3192. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3193. Point in Depth}, for more information.
  3194. @node Complex Data Types
  3195. @section Complex Data Types
  3196. @cindex complex numbers
  3197. @cindex types, complex
  3198. @cindex @code{_Complex} keyword
  3199. @cindex @code{__complex__} keyword
  3200. @findex _Complex
  3201. @findex __complex__
  3202. Complex numbers can include both a real part and an imaginary part.
  3203. The numeric constants covered above have real-numbered values. An
  3204. imaginary-valued constant is an ordinary real-valued constant followed
  3205. by @samp{i}.
  3206. To declare numeric variables as complex, use the @code{_Complex}
  3207. keyword.@footnote{For compatibility with older versions of GNU C, the
  3208. keyword @code{__complex__} is also allowed. Going forward, however,
  3209. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3210. standard C complex data types are floating point,
  3211. @example
  3212. _Complex float foo;
  3213. _Complex double bar;
  3214. _Complex long double quux;
  3215. @end example
  3216. @noindent
  3217. but GNU C supports integer complex types as well.
  3218. Since @code{_Complex} is a keyword just like @code{float} and
  3219. @code{double} and @code{long}, the keywords can appear in any order,
  3220. but the order shown above seems most logical.
  3221. GNU C supports constants for complex values; for instance, @code{4.0 +
  3222. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3223. @xref{Imaginary Constants}.
  3224. To pull the real and imaginary parts of the number back out, GNU C
  3225. provides the keywords @code{__real__} and @code{__imag__}:
  3226. @example
  3227. _Complex double foo = 4.0 + 3.0i;
  3228. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3229. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3230. @end example
  3231. @noindent
  3232. Standard C does not include these keywords, and instead relies on
  3233. functions defined in @code{complex.h} for accessing the real and
  3234. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3235. @code{creall} extract the real part of a float, double, or long double
  3236. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3237. @code{cimagl} extract the imaginary part.
  3238. @cindex complex conjugation
  3239. GNU C also defines @samp{~} as an operator for complex conjugation,
  3240. which means negating the imaginary part of a complex number:
  3241. @example
  3242. _Complex double foo = 4.0 + 3.0i;
  3243. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3244. @end example
  3245. @noindent
  3246. For standard C compatibility, you can use the appropriate library
  3247. function: @code{conjf}, @code{conj}, or @code{confl}.
  3248. @node The Void Type
  3249. @section The Void Type
  3250. @cindex void type
  3251. @cindex type, void
  3252. @findex void
  3253. The data type @code{void} is a dummy---it allows no operations. It
  3254. really means ``no value at all.'' When a function is meant to return
  3255. no value, we write @code{void} for its return type. Then
  3256. @code{return} statements in that function should not specify a value
  3257. (@pxref{return Statement}). Here's an example:
  3258. @example
  3259. void
  3260. print_if_positive (double x, double y)
  3261. @{
  3262. if (x <= 0)
  3263. return;
  3264. if (y <= 0)
  3265. return;
  3266. printf ("Next point is (%f,%f)\n", x, y);
  3267. @}
  3268. @end example
  3269. A @code{void}-returning function is comparable to what some other
  3270. languages (for instance, Fortran and Pascal) call a ``procedure''
  3271. instead of a ``function.''
  3272. @c ??? Already presented
  3273. @c @samp{%f} in an output template specifies to format a @code{double} value
  3274. @c as a decimal number, using a decimal point if needed.
  3275. @node Other Data Types
  3276. @section Other Data Types
  3277. Beyond the primitive types, C provides several ways to construct new
  3278. data types. For instance, you can define @dfn{pointers}, values that
  3279. represent the addresses of other data (@pxref{Pointers}). You can
  3280. define @dfn{structures}, as in many other languages
  3281. (@pxref{Structures}), and @dfn{unions}, which define multiple ways to
  3282. interpret the contents of the same memory space (@pxref{Unions}).
  3283. @dfn{Enumerations} are collections of named integer codes
  3284. (@pxref{Enumeration Types}).
  3285. @dfn{Array types} in C are used for allocating space for objects,
  3286. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3287. @node Type Designators
  3288. @section Type Designators
  3289. @cindex type designator
  3290. Some C constructs require a way to designate a specific data type
  3291. independent of any particular variable or expression which has that
  3292. type. The way to do this is with a @dfn{type designator}. The
  3293. constructs that need one include casts (@pxref{Explicit Type
  3294. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3295. We also use type designators to talk about the type of a value in C,
  3296. so you will see many type designators in this manual. When we say,
  3297. ``The value has type @code{int},'' @code{int} is a type designator.
  3298. To make the designator for any type, imagine a variable declaration
  3299. for a variable of that type and delete the variable name and the final
  3300. semicolon.
  3301. For example, to designate the type of full-word integers, we start
  3302. with the declaration for a variable @code{foo} with that type,
  3303. which is this:
  3304. @example
  3305. int foo;
  3306. @end example
  3307. @noindent
  3308. Then we delete the variable name @code{foo} and the semicolon, leaving
  3309. @code{int}---exactly the keyword used in such a declaration.
  3310. Therefore, the type designator for this type is @code{int}.
  3311. What about long unsigned integers? From the declaration
  3312. @example
  3313. unsigned long int foo;
  3314. @end example
  3315. @noindent
  3316. we determine that the designator is @code{unsigned long int}.
  3317. Following this procedure, the designator for any primitive type is
  3318. simply the set of keywords which specifies that type in a declaration.
  3319. The same is true for compound types such as structures, unions, and
  3320. enumerations.
  3321. Designators for pointer types do follow the rule of deleting the
  3322. variable name and semicolon, but the result is not so simple.
  3323. @xref{Pointer Type Designators}, as part of the chapter about
  3324. pointers. @xref{Array Type Designators}), for designators for array
  3325. types.
  3326. To understand what type a designator stands for, imagine a variable
  3327. name inserted into the right place in the designator to make a valid
  3328. declaration. What type would that variable be declared as? That is the
  3329. type the designator designates.
  3330. @node Constants
  3331. @chapter Constants
  3332. @cindex constants
  3333. A @dfn{constant} is an expression that stands for a specific value by
  3334. explicitly representing the desired value. C allows constants for
  3335. numbers, characters, and strings. We have already seen numeric and
  3336. string constants in the examples.
  3337. @menu
  3338. * Integer Constants:: Literal integer values.
  3339. * Integer Const Type:: Types of literal integer values.
  3340. * Floating Constants:: Literal floating-point values.
  3341. * Imaginary Constants:: Literal imaginary number values.
  3342. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3343. * Character Constants:: Literal character values.
  3344. * String Constants:: Literal string values.
  3345. * UTF-8 String Constants:: Literal UTF-8 string values.
  3346. * Unicode Character Codes:: Unicode characters represented
  3347. in either UTF-16 or UTF-32.
  3348. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3349. * Wide String Constants:: Literal string values made up of
  3350. 16- or 32-bit characters.
  3351. @end menu
  3352. @node Integer Constants
  3353. @section Integer Constants
  3354. @cindex integer constants
  3355. @cindex constants, integer
  3356. An integer constant consists of a number to specify the value,
  3357. followed optionally by suffix letters to specify the data type.
  3358. The simplest integer constants are numbers written in base 10
  3359. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3360. constant cannot start with the character @samp{0} (zero) because
  3361. that makes the constant octal.
  3362. You can get the effect of a negative integer constant by putting a
  3363. minus sign at the beginning. In grammatical terms, that is an
  3364. arithmetic expression rather than a constant, but it behaves just like
  3365. a true constant.
  3366. Integer constants can also be written in octal (base 8), hexadecimal
  3367. (base 16), or binary (base 2). An octal constant starts with the
  3368. character @samp{0} (zero), followed by any number of octal digits
  3369. (@samp{0} to @samp{7}):
  3370. @example
  3371. 0 // @r{zero}
  3372. 077 // @r{63}
  3373. 0403 // @r{259}
  3374. @end example
  3375. @noindent
  3376. Pedantically speaking, the constant @code{0} is an octal constant, but
  3377. we can think of it as decimal; it has the same value either way.
  3378. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3379. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3380. through @samp{f} in upper or lower case):
  3381. @example
  3382. 0xff // @r{255}
  3383. 0XA0 // @r{160}
  3384. 0xffFF // @r{65535}
  3385. @end example
  3386. @cindex binary integer constants
  3387. A binary constant starts with @samp{0b} (upper or lower case) followed
  3388. by bits (each represented by the characters @samp{0} or @samp{1}):
  3389. @example
  3390. 0b101 // @r{5}
  3391. @end example
  3392. @noindent
  3393. Binary constants are a GNU C extension, not part of the C standard.
  3394. Sometimes a space is needed after an integer constant to avoid
  3395. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3396. @node Integer Const Type
  3397. @section Integer Constant Data Types
  3398. @cindex integer constant data types
  3399. @cindex constant data types, integer
  3400. @cindex types of integer constants
  3401. The type of an integer constant is normally @code{int}, if the value
  3402. fits in that type, but here are the complete rules. The type
  3403. of an integer constant is the first one in this sequence that can
  3404. properly represent the value,
  3405. @enumerate
  3406. @item
  3407. @code{int}
  3408. @item
  3409. @code{unsigned int}
  3410. @item
  3411. @code{long int}
  3412. @item
  3413. @code{unsigned long int}
  3414. @item
  3415. @code{long long int}
  3416. @item
  3417. @code{unsigned long long int}
  3418. @end enumerate
  3419. @noindent
  3420. and that isn't excluded by the following rules.
  3421. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3422. first two types (non-@code{long}).
  3423. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3424. first four types (non-@code{long long}).
  3425. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3426. the signed types.
  3427. Otherwise, if the constant is decimal (not binary, octal, or
  3428. hexadecimal), that excludes the unsigned types.
  3429. @c ### This said @code{unsigned int} is excluded.
  3430. @c ### See 17 April 2016
  3431. Here are some examples of the suffixes.
  3432. @example
  3433. 3000000000u // @r{three billion as @code{unsigned int}.}
  3434. 0LL // @r{zero as a @code{long long int}.}
  3435. 0403l // @r{259 as a @code{long int}.}
  3436. @end example
  3437. Suffixes in integer constants are rarely used. When the precise type
  3438. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3439. Type Conversion}).
  3440. @xref{Integer Types}.
  3441. @node Floating Constants
  3442. @section Floating-Point Constants
  3443. @cindex floating-point constants
  3444. @cindex constants, floating-point
  3445. A floating-point constant must have either a decimal point, an
  3446. exponent-of-ten, or both; they distinguish it from an integer
  3447. constant.
  3448. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3449. value follows. It is always written as a decimal number; it can
  3450. optionally start with a sign. The exponent @var{n} means to multiply
  3451. the constant's value by ten to the @var{n}th power.
  3452. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3453. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3454. writing a floating-point number whose value is 1500. They are all
  3455. equivalent.
  3456. Here are more examples with decimal points:
  3457. @example
  3458. 1.0
  3459. 1000.
  3460. 3.14159
  3461. .05
  3462. .0005
  3463. @end example
  3464. For each of them, here are some equivalent constants written with
  3465. exponents:
  3466. @example
  3467. 1e0, 1.0000e0
  3468. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3469. 3.14159e0
  3470. 5e-2, .0005e+2, 5E-2, .0005E2
  3471. .05e-2
  3472. @end example
  3473. A floating-point constant normally has type @code{double}. You can
  3474. force it to type @code{float} by adding @samp{f} or @samp{F}
  3475. at the end. For example,
  3476. @example
  3477. 3.14159f
  3478. 3.14159e0f
  3479. 1000.f
  3480. 100E1F
  3481. .0005f
  3482. .05e-2f
  3483. @end example
  3484. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3485. to type @code{long double}.
  3486. You can use exponents in hexadecimal floating constants, but since
  3487. @samp{e} would be interpreted as a hexadecimal digit, the character
  3488. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3489. The exponent in a hexadecimal floating constant is an optionally signed
  3490. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3491. multiply into the number.
  3492. Here are some examples:
  3493. @example
  3494. @group
  3495. 0xAp2 // @r{40 in decimal}
  3496. 0xAp-1 // @r{5 in decimal}
  3497. 0x2.0Bp4 // @r{16.75 decimal}
  3498. 0xE.2p3 // @r{121 decimal}
  3499. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3500. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3501. 0x100p-8 // @r{1}
  3502. 0x10p-4 // @r{1}
  3503. 0x1p+4 // @r{16}
  3504. 0x1p+8 // @r{256}
  3505. @end group
  3506. @end example
  3507. @xref{Floating-Point Data Types}.
  3508. @node Imaginary Constants
  3509. @section Imaginary Constants
  3510. @cindex imaginary constants
  3511. @cindex complex constants
  3512. @cindex constants, imaginary
  3513. A complex number consists of a real part plus an imaginary part. (You
  3514. may omit one part if it is zero.) This section explains how to write
  3515. numeric constants with imaginary values. By adding these to ordinary
  3516. real-valued numeric constants, we can make constants with complex
  3517. values.
  3518. The simple way to write an imaginary-number constant is to attach the
  3519. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3520. floating-point constant. For example, @code{2.5fi} has type
  3521. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3522. The four alternative suffix letters are all equivalent.
  3523. @cindex _Complex_I
  3524. The other way to write an imaginary constant is to multiply a real
  3525. constant by @code{_Complex_I}, which represents the imaginary number
  3526. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3527. this clunky method is needed.
  3528. To write a complex constant with a nonzero real part and a nonzero
  3529. imaginary part, write the two separately and add them, like this:
  3530. @example
  3531. 4.0 + 3.0i
  3532. @end example
  3533. @noindent
  3534. That gives the value 4 + 3i, with type @code{_Complex double}.
  3535. Such a sum can include multiple real constants, or none. Likewise, it
  3536. can include multiple imaginary constants, or none. For example:
  3537. @example
  3538. _Complex double foo, bar, quux;
  3539. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3540. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3541. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3542. @end example
  3543. @xref{Complex Data Types}.
  3544. @node Invalid Numbers
  3545. @section Invalid Numbers
  3546. Some number-like constructs which are not really valid as numeric
  3547. constants are treated as numbers in preprocessing directives. If
  3548. these constructs appear outside of preprocessing, they are erroneous.
  3549. @xref{Preprocessing Tokens}.
  3550. Sometimes we need to insert spaces to separate tokens so that they
  3551. won't be combined into a single number-like construct. For example,
  3552. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3553. constant, so it is a syntax error. If what we want is the three
  3554. tokens @code{@w{0xE + 12}}, we have to insert two spaces as separators.
  3555. @node Character Constants
  3556. @section Character Constants
  3557. @cindex character constants
  3558. @cindex constants, character
  3559. @cindex escape sequence
  3560. A @dfn{character constant} is written with single quotes, as in
  3561. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3562. character that the constant should represent. The constant has type
  3563. @code{int}, and its value is the character code of that character.
  3564. For instance, @code{'a'} represents the character code for the letter
  3565. @samp{a}: 97, that is.
  3566. To put the @samp{'} character (single quote) in the character
  3567. constant, @dfn{escape} it with a backslash (@samp{\}). This character
  3568. constant looks like @code{'\''}. The backslash character here
  3569. functions as an @dfn{escape character}, and such a sequence,
  3570. starting with @samp{\}, is called an @dfn{escape sequence}.
  3571. To put the @samp{\} character (backslash) in the character constant,
  3572. escape it with @samp{\} (another backslash). This character
  3573. constant looks like @code{'\\'}.
  3574. @cindex bell character
  3575. @cindex @samp{\a}
  3576. @cindex backspace
  3577. @cindex @samp{\b}
  3578. @cindex tab (ASCII character)
  3579. @cindex @samp{\t}
  3580. @cindex vertical tab
  3581. @cindex @samp{\v}
  3582. @cindex formfeed
  3583. @cindex @samp{\f}
  3584. @cindex newline
  3585. @cindex @samp{\n}
  3586. @cindex return (ASCII character)
  3587. @cindex @samp{\r}
  3588. @cindex escape (ASCII character)
  3589. @cindex @samp{\e}
  3590. Here are all the escape sequences that represent specific
  3591. characters in a character constant. The numeric values shown are
  3592. the corresponding ASCII character codes, as decimal numbers.
  3593. @example
  3594. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3595. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3596. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3597. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3598. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3599. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3600. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3601. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3602. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3603. '\'' @result{} 39 /* @r{single quote character, @kbd{'}} */
  3604. '\"' @result{} 34 /* @r{double quote character, @kbd{"}} */
  3605. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3606. @end example
  3607. @samp{\e} is a GNU C extension; to stick to standard C, write
  3608. @samp{\33}. (The number after @samp{backslash} is octal.) To specify
  3609. a character constant using decimal, use a cast; for instance,
  3610. @code{(unsigned char) 27}.
  3611. You can also write octal and hex character codes as
  3612. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3613. option here, so octal codes do not need to start with @samp{0}.
  3614. The character constant's value has type @code{int}. However, the
  3615. character code is treated initially as a @code{char} value, which is
  3616. then converted to @code{int}. If the character code is greater than
  3617. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3618. on a platform where the type @code{char} is 8 bits long and signed.
  3619. @node String Constants
  3620. @section String Constants
  3621. @cindex string constants
  3622. @cindex constants, string
  3623. A @dfn{string constant} represents a series of characters. It starts
  3624. with @samp{"} and ends with @samp{"}; in between are the contents of
  3625. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3626. newline in the contents works in string constants as in character
  3627. constants. In a string constant, @samp{'} does not need to be quoted.
  3628. A string constant defines an array of characters which contains the
  3629. specified characters followed by the null character (code 0). Using
  3630. the string constant is equivalent to using the name of an array with
  3631. those contents. In simple cases, where there are no backslash escape
  3632. sequences, the length in bytes of the string constant is one greater
  3633. than the number of characters written in it.
  3634. As with any array in C, using the string constant in an expression
  3635. converts the array to a pointer (@pxref{Pointers}) to the array's
  3636. first element (@pxref{Accessing Array Elements}). This pointer will
  3637. have type @code{char *} because it points to an element of type
  3638. @code{char}. @code{char *} is an example of a type designator for a
  3639. pointer type (@pxref{Pointer Type Designators}). That type is used
  3640. for strings generally, not just the strings expressed as constants
  3641. in a program.
  3642. Thus, the string constant @code{"Foo!"} is almost
  3643. equivalent to declaring an array like this
  3644. @example
  3645. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3646. @end example
  3647. @noindent
  3648. and then using @code{string_array_1} in the program. There
  3649. are two differences, however:
  3650. @itemize @bullet
  3651. @item
  3652. The string constant doesn't define a name for the array.
  3653. @item
  3654. The string constant is probably stored in a read-only area of memory.
  3655. @end itemize
  3656. Newlines are not allowed in the text of a string constant. The motive
  3657. for this prohibition is to catch the error of omitting the closing
  3658. @samp{"}. To put a newline in a constant string, write it as
  3659. @samp{\n} in the string constant.
  3660. A real null character in the source code inside a string constant
  3661. causes a warning. To put a null character in the middle of a string
  3662. constant, write @samp{\0} or @samp{\000}.
  3663. Consecutive string constants are effectively concatenated. Thus,
  3664. @example
  3665. "Fo" "o!" @r{is equivalent to} "Foo!"
  3666. @end example
  3667. This is useful for writing a string containing multiple lines,
  3668. like this:
  3669. @example
  3670. "This message is so long that it needs more than\n"
  3671. "a single line of text. C does not allow a newline\n"
  3672. "to represent itself in a string constant, so we have to\n"
  3673. "write \\n to put it in the string. For readability of\n"
  3674. "the source code, it is advisable to put line breaks in\n"
  3675. "the source where they occur in the contents of the\n"
  3676. "constant.\n"
  3677. @end example
  3678. The sequence of a backslash and a newline is ignored anywhere
  3679. in a C program, and that includes inside a string constant.
  3680. Thus, you can write multi-line string constants this way:
  3681. @example
  3682. "This is another way to put newlines in a string constant\n\
  3683. and break the line after them in the source code."
  3684. @end example
  3685. @noindent
  3686. However, concatenation is the recommended way to do this.
  3687. You can also write perverse string constants like this,
  3688. @example
  3689. "Fo\
  3690. o!"
  3691. @end example
  3692. @noindent
  3693. but don't do that---write it like this instead:
  3694. @example
  3695. "Foo!"
  3696. @end example
  3697. Be careful to avoid passing a string constant to a function that
  3698. modifies the string it receives. The memory where the string constant
  3699. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3700. signal that normally terminates the function (@pxref{Signals}. Even
  3701. worse, the memory may not be read-only. Then the function might
  3702. modify the string constant, thus spoiling the contents of other string
  3703. constants that are supposed to contain the same value and are unified
  3704. by the compiler.
  3705. @node UTF-8 String Constants
  3706. @section UTF-8 String Constants
  3707. @cindex UTF-8 String Constants
  3708. Writing @samp{u8} immediately before a string constant, with no
  3709. intervening space, means to represent that string in UTF-8 encoding as
  3710. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3711. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3712. as multibyte sequences. Here is an example of a UTF-8 constant:
  3713. @example
  3714. u8"A cónstàñt"
  3715. @end example
  3716. This constant occupies 13 bytes plus the terminating null,
  3717. because each of the accented letters is a two-byte sequence.
  3718. Concatenating an ordinary string with a UTF-8 string conceptually
  3719. produces another UTF-8 string. However, if the ordinary string
  3720. contains character codes 128 and up, the results cannot be relied on.
  3721. @node Unicode Character Codes
  3722. @section Unicode Character Codes
  3723. @cindex Unicode character codes
  3724. @cindex universal character names
  3725. You can specify Unicode characters, for individual character constants
  3726. or as part of string constants (@pxref{String Constants}), using
  3727. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3728. hexadecimal Unicode character code. If the code value is too big for
  3729. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3730. Unicode character code. (These codes are called @dfn{universal
  3731. character names}.) For example,
  3732. @example
  3733. \u6C34 /* @r{16-bit code (UTF-16)} */
  3734. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3735. @end example
  3736. @noindent
  3737. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3738. Constants}). For instance,
  3739. @example
  3740. u8"fóó \u6C34 \U0010ABCD"
  3741. @end example
  3742. You can also use them in wide character constants (@pxref{Wide
  3743. Character Constants}), like this:
  3744. @example
  3745. u'\u6C34' /* @r{16-bit code} */
  3746. U'\U0010ABCD' /* @r{32-bit code} */
  3747. @end example
  3748. @noindent
  3749. and in wide string constants (@pxref{Wide String Constants}), like
  3750. this:
  3751. @example
  3752. u"\u6C34\u6C33" /* @r{16-bit code} */
  3753. U"\U0010ABCD" /* @r{32-bit code} */
  3754. @end example
  3755. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3756. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3757. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3758. actually ASCII control characters, and you can specify them with other
  3759. escape sequences (@pxref{Character Constants}).
  3760. @node Wide Character Constants
  3761. @section Wide Character Constants
  3762. @cindex wide character constants
  3763. @cindex constants, wide character
  3764. A @dfn{wide character constant} represents characters with more than 8
  3765. bits of character code. This is an obscure feature that we need to
  3766. document but that you probably won't ever use. If you're just
  3767. learning C, you may as well skip this section.
  3768. The original C wide character constant looks like @samp{L} (upper
  3769. case!) followed immediately by an ordinary character constant (with no
  3770. intervening space). Its data type is @code{wchar_t}, which is an
  3771. alias defined in @file{stddef.h} for one of the standard integer
  3772. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3773. it is 16 bits, these character constants use the UTF-16 form of
  3774. Unicode; if 32 bits, UTF-32.
  3775. There are also Unicode wide character constants which explicitly
  3776. specify the width. These constants start with @samp{u} or @samp{U}
  3777. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3778. character constant, and @samp{U} a 32-bit Unicode wide character
  3779. constant. Their types are, respectively, @code{char16_t} and
  3780. @w{@code{char32_t}}; they are declared in the header file
  3781. @file{uchar.h}. These character constants are valid even if
  3782. @file{uchar.h} is not included, but some uses of them may be
  3783. inconvenient without including it to declare those type names.
  3784. The character represented in a wide character constant can be an
  3785. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3786. are all valid, and they are all equal to @code{'a'}.
  3787. In all three kinds of wide character constants, you can write a
  3788. non-ASCII Unicode character in the constant itself; the constant's
  3789. value is the character's Unicode character code. Or you can specify
  3790. the Unicode character with an escape sequence (@pxref{Unicode
  3791. Character Codes}).
  3792. @node Wide String Constants
  3793. @section Wide String Constants
  3794. @cindex wide string constants
  3795. @cindex constants, wide string
  3796. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3797. characters. They are rarely used; if you're just
  3798. learning C, you may as well skip this section.
  3799. There are three kinds of wide string constants, which differ in the
  3800. data type used for each character in the string. Each wide string
  3801. constant is equivalent to an array of integers, but the data type of
  3802. those integers depends on the kind of wide string. Using the constant
  3803. in an expression will convert the array to a pointer to its first
  3804. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3805. For each kind of wide string constant, we state here what type that
  3806. pointer will be.
  3807. @table @code
  3808. @item char16_t
  3809. This is a 16-bit Unicode wide string constant: each element is a
  3810. 16-bit Unicode character code with type @code{char16_t}, so the string
  3811. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3812. @pxref{Pointer Type Designators}.) The constant is written as
  3813. @samp{u} (which must be lower case) followed (with no intervening
  3814. space) by a string constant with the usual syntax.
  3815. @item char32_t
  3816. This is a 32-bit Unicode wide string constant: each element is a
  3817. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3818. It's written as @samp{U} (which must be upper case) followed (with no
  3819. intervening space) by a string constant with the usual syntax.
  3820. @item wchar_t
  3821. This is the original kind of wide string constant. It's written as
  3822. @samp{L} (which must be upper case) followed (with no intervening
  3823. space) by a string constant with the usual syntax, and the string has
  3824. type @code{wchar_t@ *}.
  3825. The width of the data type @code{wchar_t} depends on the target
  3826. platform, which makes this kind of wide string somewhat less useful
  3827. than the newer kinds.
  3828. @end table
  3829. @code{char16_t} and @code{char32_t} are declared in the header file
  3830. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3831. Consecutive wide string constants of the same kind concatenate, just
  3832. like ordinary string constants. A wide string constant concatenated
  3833. with an ordinary string constant results in a wide string constant.
  3834. You can't concatenate two wide string constants of different kinds.
  3835. In addition, you can't concatenate a wide string constant (of any
  3836. kind) with a UTF-8 string constant.
  3837. @node Type Size
  3838. @chapter Type Size
  3839. @cindex type size
  3840. @cindex size of type
  3841. @findex sizeof
  3842. Each data type has a @dfn{size}, which is the number of bytes
  3843. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3844. a C program, use @code{sizeof}. There are two ways to use it:
  3845. @table @code
  3846. @item sizeof @var{expression}
  3847. This gives the size of @var{expression}, based on its data type. It
  3848. does not calculate the value of @var{expression}, only its size, so if
  3849. @var{expression} includes side effects or function calls, they do not
  3850. happen. Therefore, @code{sizeof} is always a compile-time operation
  3851. that has zero run-time cost.
  3852. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3853. operand of @code{sizeof}.
  3854. For example,
  3855. @example
  3856. double a;
  3857. i = sizeof a + 10;
  3858. @end example
  3859. @noindent
  3860. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3861. Here's how to determine the number of elements in an array
  3862. @code{array}:
  3863. @example
  3864. (sizeof array / sizeof array[0])
  3865. @end example
  3866. @noindent
  3867. The expression @code{sizeof array} gives the size of the array, not
  3868. the size of a pointer to an element. However, if @var{expression} is
  3869. a function parameter that was declared as an array, that
  3870. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3871. the result is the size of that pointer.
  3872. @item sizeof (@var{type})
  3873. This gives the size of @var{type}.
  3874. For example,
  3875. @example
  3876. i = sizeof (double) + 10;
  3877. @end example
  3878. @noindent
  3879. is equivalent to the previous example.
  3880. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3881. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3882. C, which makes adding an integer to a function pointer work as desired
  3883. (@pxref{Pointer Arithmetic}).
  3884. @end table
  3885. @strong{Warning}: When you use @code{sizeof} with a type
  3886. instead of an expression, you must write parentheses around the type.
  3887. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3888. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3889. the cast expression to avoid an ambiguity in the grammar of C@.
  3890. Specifically,
  3891. @example
  3892. sizeof (int) -x
  3893. @end example
  3894. @noindent
  3895. parses as
  3896. @example
  3897. (sizeof (int)) - x
  3898. @end example
  3899. @noindent
  3900. If what you want is
  3901. @example
  3902. sizeof ((int) -x)
  3903. @end example
  3904. @noindent
  3905. you must write it that way, with parentheses.
  3906. The data type of the value of the @code{sizeof} operator is always one
  3907. of the unsigned integer types; which one of those types depends on the
  3908. machine. The header file @code{stddef.h} defines the typedef name
  3909. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3910. Names}.
  3911. @node Pointers
  3912. @chapter Pointers
  3913. @cindex pointers
  3914. Among high-level languages, C is rather low-level, close to the
  3915. machine. This is mainly because it has explicit @dfn{pointers}. A
  3916. pointer value is the numeric address of data in memory. The type of
  3917. data to be found at that address is specified by the data type of the
  3918. pointer itself. Nothing in C can determine the ``correct'' data type
  3919. of data in memory; it can only blindly follow the data type of the
  3920. pointer you use to access the data.
  3921. The unary operator @samp{*} gets the data that a pointer points
  3922. to---this is called @dfn{dereferencing the pointer}. Its value
  3923. always has the type that the pointer points to.
  3924. C also allows pointers to functions, but since there are some
  3925. differences in how they work, we treat them later. @xref{Function
  3926. Pointers}.
  3927. @menu
  3928. * Address of Data:: Using the ``address-of'' operator.
  3929. * Pointer Types:: For each type, there is a pointer type.
  3930. * Pointer Declarations:: Declaring variables with pointer types.
  3931. * Pointer Type Designators:: Designators for pointer types.
  3932. * Pointer Dereference:: Accessing what a pointer points at.
  3933. * Null Pointers:: Pointers which do not point to any object.
  3934. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3935. * Void Pointers:: Totally generic pointers, can cast to any.
  3936. * Pointer Comparison:: Comparing memory address values.
  3937. * Pointer Arithmetic:: Computing memory address values.
  3938. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3939. * Low-Level Pointer Arithmetic:: More about computing memory address values.
  3940. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3941. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3942. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3943. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3944. @end menu
  3945. @node Address of Data
  3946. @section Address of Data
  3947. @cindex address-of operator
  3948. The most basic way to make a pointer is with the ``address-of''
  3949. operator, @samp{&}. Let's suppose we have these variables available:
  3950. @example
  3951. int i;
  3952. double a[5];
  3953. @end example
  3954. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3955. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3956. address of the element 3 of @code{a}. (It is actually the fourth
  3957. element in the array, since the first element has index 0.)
  3958. The address-of operator is unusual because it operates on a place to
  3959. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3960. stored there. (The left argument of a simple assignment is unusual in
  3961. the same way.) You can use it on any lvalue except a bit field
  3962. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3963. Constructors}).
  3964. @node Pointer Types
  3965. @section Pointer Types
  3966. For each data type @var{t}, there is a type for pointers to type
  3967. @var{t}. For these variables,
  3968. @example
  3969. int i;
  3970. double a[5];
  3971. @end example
  3972. @itemize @bullet
  3973. @item
  3974. @code{i} has type @code{int}; we say
  3975. @code{&i} is a ``pointer to @code{int}.''
  3976. @item
  3977. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3978. arrays of five @code{double}s.''
  3979. @item
  3980. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3981. to @code{double}.''
  3982. @end itemize
  3983. @node Pointer Declarations
  3984. @section Pointer-Variable Declarations
  3985. The way to declare that a variable @code{foo} points to type @var{t} is
  3986. @example
  3987. @var{t} *foo;
  3988. @end example
  3989. To remember this syntax, think ``if you dereference @code{foo}, using
  3990. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3991. points to type @var{t}.''
  3992. Thus, we can declare variables that hold pointers to these three
  3993. types, like this:
  3994. @example
  3995. int *ptri; /* @r{Pointer to @code{int}.} */
  3996. double *ptrd; /* @r{Pointer to @code{double}.} */
  3997. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3998. @end example
  3999. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  4000. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  4001. @code{ptrda}, then subscript it by an integer less than 5, you get a
  4002. @code{double}.'' The parentheses express the point that you would
  4003. dereference it first, then subscript it.
  4004. Contrast the last one with this:
  4005. @example
  4006. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  4007. @end example
  4008. @noindent
  4009. Because @samp{*} has lower syntactic precedence than subscripting,
  4010. @samp{double *aptrd[5]} means, ``if you subscript @code{aptrd} by an
  4011. integer less than 5, then dereference it, you get a @code{double}.''
  4012. Therefore, @code{*aptrd[5]} declares an array of pointers, not a
  4013. pointer to an array.
  4014. @node Pointer Type Designators
  4015. @section Pointer-Type Designators
  4016. Every type in C has a designator; you make it by deleting the variable
  4017. name and the semicolon from a declaration (@pxref{Type
  4018. Designators}). Here are the designators for the pointer
  4019. types of the example declarations in the previous section:
  4020. @example
  4021. int * /* @r{Pointer to @code{int}.} */
  4022. double * /* @r{Pointer to @code{double}.} */
  4023. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  4024. @end example
  4025. Remember, to understand what type a designator stands for, imagine the
  4026. corresponding variable declaration with a variable name in it, and
  4027. figure out what type that variable would have. Thus, the type
  4028. designator @code{double (*)[5]} corresponds to the variable declaration
  4029. @code{double (*@var{variable})[5]}. That deciares a pointer variable
  4030. which, when dereferenced, gives an array of 5 @code{double}s.
  4031. So the type designator means, ``pointer to an array of 5 @code{double}s.''
  4032. @node Pointer Dereference
  4033. @section Dereferencing Pointers
  4034. @cindex dereferencing pointers
  4035. @cindex pointer dereferencing
  4036. The main use of a pointer value is to @dfn{dereference it} (access the
  4037. data it points at) with the unary @samp{*} operator. For instance,
  4038. @code{*&i} is the value at @code{i}'s address---which is just
  4039. @code{i}. The two expressions are equivalent, provided @code{&i} is
  4040. valid.
  4041. A pointer-dereference expression whose type is data (not a function)
  4042. is an lvalue.
  4043. Pointers become really useful when we store them somewhere and use
  4044. them later. Here's a simple example to illustrate the practice:
  4045. @example
  4046. @{
  4047. int i;
  4048. int *ptr;
  4049. ptr = &i;
  4050. i = 5;
  4051. @r{@dots{}}
  4052. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  4053. @}
  4054. @end example
  4055. This shows how to declare the variable @code{ptr} as type
  4056. @code{int *} (pointer to @code{int}), store a pointer value into it
  4057. (pointing at @code{i}), and use it later to get the value of the
  4058. object it points at (the value in @code{i}).
  4059. If anyone can provide a useful example which is this basic,
  4060. I would be grateful.
  4061. @node Null Pointers
  4062. @section Null Pointers
  4063. @cindex null pointers
  4064. @cindex pointers, null
  4065. @c ???stdio loads sttddef
  4066. A pointer value can be @dfn{null}, which means it does not point to
  4067. any object. The cleanest way to get a null pointer is by writing
  4068. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4069. also do it by casting 0 to the desired pointer type, as in
  4070. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4071. @xref{Explicit Type Conversion}.)
  4072. You can store a null pointer in any lvalue whose data type
  4073. is a pointer type:
  4074. @example
  4075. char *foo;
  4076. foo = NULL;
  4077. @end example
  4078. These two, if consecutive, can be combined into a declaration with
  4079. initializer,
  4080. @example
  4081. char *foo = NULL;
  4082. @end example
  4083. You can also explicitly cast @code{NULL} to the specific pointer type
  4084. you want---it makes no difference.
  4085. @example
  4086. char *foo;
  4087. foo = (char *) NULL;
  4088. @end example
  4089. To test whether a pointer is null, compare it with zero or
  4090. @code{NULL}, as shown here:
  4091. @example
  4092. if (p != NULL)
  4093. /* @r{@code{p} is not null.} */
  4094. operate (p);
  4095. @end example
  4096. Since testing a pointer for not being null is basic and frequent, all
  4097. but beginners in C will understand the conditional without need for
  4098. @code{!= NULL}:
  4099. @example
  4100. if (p)
  4101. /* @r{@code{p} is not null.} */
  4102. operate (p);
  4103. @end example
  4104. @node Invalid Dereference
  4105. @section Dereferencing Null or Invalid Pointers
  4106. Trying to dereference a null pointer is an error. On most platforms,
  4107. it generally causes a signal, usually @code{SIGSEGV}
  4108. (@pxref{Signals}).
  4109. @example
  4110. char *foo = NULL;
  4111. c = *foo; /* @r{This causes a signal and terminates.} */
  4112. @end example
  4113. @noindent
  4114. Likewise a pointer that has the wrong alignment for the target data type
  4115. (on most types of computer), or points to a part of memory that has
  4116. not been allocated in the process's address space.
  4117. The signal terminates the program, unless the program has arranged to
  4118. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4119. The GNU C Library Reference Manual}).
  4120. However, the signal might not happen if the dereference is optimized
  4121. away. In the example above, if you don't subsequently use the value
  4122. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4123. can prevent such optimization using the @code{volatile} qualifier, as
  4124. shown here:
  4125. @example
  4126. volatile char *p;
  4127. volatile char c;
  4128. c = *p;
  4129. @end example
  4130. You can use this to test whether @code{p} points to unallocated
  4131. memory. Set up a signal handler first, so the signal won't terminate
  4132. the program.
  4133. @node Void Pointers
  4134. @section Void Pointers
  4135. @cindex void pointers
  4136. @cindex pointers, void
  4137. The peculiar type @code{void *}, a pointer whose target type is
  4138. @code{void}, is used often in C@. It represents a pointer to
  4139. we-don't-say-what. Thus,
  4140. @example
  4141. void *numbered_slot_pointer (int);
  4142. @end example
  4143. @noindent
  4144. declares a function @code{numbered_slot_pointer} that takes an
  4145. integer parameter and returns a pointer, but we don't say what type of
  4146. data it points to.
  4147. With type @code{void *}, you can pass the pointer around and test
  4148. whether it is null. However, dereferencing it gives a @code{void}
  4149. value that can't be used (@pxref{The Void Type}). To dereference the
  4150. pointer, first convert it to some other pointer type.
  4151. Assignments convert @code{void *} automatically to any other pointer
  4152. type, if the left operand has a pointer type; for instance,
  4153. @example
  4154. @{
  4155. int *p;
  4156. /* @r{Converts return value to @code{int *}.} */
  4157. p = numbered_slot_pointer (5);
  4158. @r{@dots{}}
  4159. @}
  4160. @end example
  4161. Passing an argument of type @code{void *} for a parameter that has a
  4162. pointer type also converts. For example, supposing the function
  4163. @code{hack} is declared to require type @code{float *} for its
  4164. argument, this will convert the null pointer to that type.
  4165. @example
  4166. /* @r{Declare @code{hack} that way.}
  4167. @r{We assume it is defined somewhere else.} */
  4168. void hack (float *);
  4169. @dots{}
  4170. /* @r{Now call @code{hack}.} */
  4171. @{
  4172. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4173. @r{to @code{float *} to pass it to @code{hack}.} */
  4174. hack (numbered_slot_pointer (5));
  4175. @r{@dots{}}
  4176. @}
  4177. @end example
  4178. You can also convert to another pointer type with an explicit cast
  4179. (@pxref{Explicit Type Conversion}), like this:
  4180. @example
  4181. (int *) numbered_slot_pointer (5)
  4182. @end example
  4183. Here is an example which decides at run time which pointer
  4184. type to convert to:
  4185. @example
  4186. void
  4187. extract_int_or_double (void *ptr, bool its_an_int)
  4188. @{
  4189. if (its_an_int)
  4190. handle_an_int (*(int *)ptr);
  4191. else
  4192. handle_a_double (*(double *)ptr);
  4193. @}
  4194. @end example
  4195. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4196. to type @code{int *}, then dereference it.
  4197. @node Pointer Comparison
  4198. @section Pointer Comparison
  4199. @cindex pointer comparison
  4200. @cindex comparison, pointer
  4201. Two pointer values are equal if they point to the same location, or if
  4202. they are both null. You can test for this with @code{==} and
  4203. @code{!=}. Here's a trivial example:
  4204. @example
  4205. @{
  4206. int i;
  4207. int *p, *q;
  4208. p = &i;
  4209. q = &i;
  4210. if (p == q)
  4211. printf ("This will be printed.\n");
  4212. if (p != q)
  4213. printf ("This won't be printed.\n");
  4214. @}
  4215. @end example
  4216. Ordering comparisons such as @code{>} and @code{>=} operate on
  4217. pointers by converting them to unsigned integers. The C standard says
  4218. the two pointers must point within the same object in memory, but on
  4219. GNU/Linux systems these operations simply compare the numeric values
  4220. of the pointers.
  4221. The pointer values to be compared should in principle have the same type, but
  4222. they are allowed to differ in limited cases. First of all, if the two
  4223. pointers' target types are nearly compatible (@pxref{Compatible
  4224. Types}), the comparison is allowed.
  4225. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4226. the other is another pointer type, the comparison operator converts
  4227. the @code{void *} pointer to the other type so as to compare them.
  4228. (In standard C, this is not allowed if the other type is a function
  4229. pointer type, but it works in GNU C@.)
  4230. Comparison operators also allow comparing the integer 0 with a pointer
  4231. value. This works by converting 0 to a null pointer of the same type
  4232. as the other operand.
  4233. @node Pointer Arithmetic
  4234. @section Pointer Arithmetic
  4235. @cindex pointer arithmetic
  4236. @cindex arithmetic, pointer
  4237. Adding an integer (positive or negative) to a pointer is valid in C@.
  4238. It assumes that the pointer points to an element in an array, and
  4239. advances or retracts the pointer across as many array elements as the
  4240. integer specifies. Here is an example, in which adding a positive
  4241. integer advances the pointer to a later element in the same array.
  4242. @example
  4243. void
  4244. incrementing_pointers ()
  4245. @{
  4246. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4247. int elt0, elt1, elt4;
  4248. int *p = &array[0];
  4249. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4250. elt0 = *p;
  4251. ++p;
  4252. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4253. elt1 = *p;
  4254. p += 3;
  4255. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4256. elt4 = *p;
  4257. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4258. elt0, elt1, elt4);
  4259. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4260. @}
  4261. @end example
  4262. Here's an example where adding a negative integer retracts the pointer
  4263. to an earlier element in the same array.
  4264. @example
  4265. void
  4266. decrementing_pointers ()
  4267. @{
  4268. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4269. int elt0, elt3, elt4;
  4270. int *p = &array[4];
  4271. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4272. elt4 = *p;
  4273. --p;
  4274. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4275. elt3 = *p;
  4276. p -= 3;
  4277. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4278. elt0 = *p;
  4279. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4280. elt0, elt3, elt4);
  4281. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4282. @}
  4283. @end example
  4284. If one pointer value was made by adding an integer to another
  4285. pointer value, it should be possible to subtract the pointer values
  4286. and recover that integer. That works too in C@.
  4287. @example
  4288. void
  4289. subtract_pointers ()
  4290. @{
  4291. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4292. int *p0, *p3, *p4;
  4293. int *p = &array[4];
  4294. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4295. p4 = p;
  4296. --p;
  4297. /* @r{Now @code{p} points at element 3. Save the value.} */
  4298. p3 = p;
  4299. p -= 3;
  4300. /* @r{Now @code{p} points at element 0. Save the value.} */
  4301. p0 = p;
  4302. printf ("%d, %d, %d, %d\n",
  4303. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4304. /* @r{Prints 4, 0, 3, -3.} */
  4305. @}
  4306. @end example
  4307. The addition operation does not know where arrays begin or end in
  4308. memory. All it does is add the integer (multiplied by target object
  4309. size) to the numeric value of the pointer. When the initial pointer
  4310. and the result point into the same array, the result is well-defined.
  4311. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4312. into different memory objects.
  4313. The difference between two pointers has type @code{int}, or
  4314. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4315. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4316. file @file{stddef.h}.
  4317. C defines pointer subtraction to be consistent with pointer-integer
  4318. addition, so that @code{(p3 - p1) + p1} equals @code{p3}, as in
  4319. ordinary algebra. Pointer subtraction works by subtracting
  4320. @code{p1}'s numeric value from @code{p3}'s, and dividing by target
  4321. object size. The two pointer arguments should point into the same
  4322. array.
  4323. In standard C, addition and subtraction are not allowed on @code{void
  4324. *}, since the target type's size is not defined in that case.
  4325. Likewise, they are not allowed on pointers to function types.
  4326. However, these operations work in GNU C, and the ``size of the target
  4327. type'' is taken as 1 byte.
  4328. @node Pointers and Arrays
  4329. @section Pointers and Arrays
  4330. @cindex pointers and arrays
  4331. @cindex arrays and pointers
  4332. The clean way to refer to an array element is
  4333. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4334. same job is to get the address of that element as a pointer, then
  4335. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4336. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4337. pointer to element zero, then increments it with @code{+} to point to
  4338. the desired element, then gets the value from there.
  4339. That pointer-arithmetic construct is the @emph{definition} of square
  4340. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4341. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4342. symmetrically, so one must be a pointer and the other an integer; it
  4343. does not matter which comes first.
  4344. Since indexing with square brackets is defined in terms of addition
  4345. and dereferencing, that too is symmetrical. Thus, you can write
  4346. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4347. would be foolish to write @code{3[array]}, since it has no advantage
  4348. and could confuse people who read the code.
  4349. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4350. @var{b})} requires a pointer, while @code{array[3]} uses an array value
  4351. instead. Why is this valid? The name of the array, when used by
  4352. itself as an expression (other than in @code{sizeof}), stands for a
  4353. pointer to the array's zeroth element. Thus, @code{array + 3}
  4354. converts @code{array} implicitly to @code{&array[0]}, and the result
  4355. is a pointer to element 3, equivalent to @code{&array[3]}.
  4356. Since square brackets are defined in terms of such an addition,
  4357. @code{array[3]} first converts @code{array} to a pointer. That's why
  4358. it works to use an array directly in that construct.
  4359. @node Low-Level Pointer Arithmetic
  4360. @section Pointer Arithmetic at Low-Level
  4361. @cindex pointer arithmetic, low-level
  4362. @cindex low level pointer arithmetic
  4363. The behavior of pointer arithmetic is theoretically defined only when
  4364. the pointer values all point within one object allocated in memory.
  4365. But the addition and subtraction operators can't tell whether the
  4366. pointer values are all within one object. They don't know where
  4367. objects start and end. So what do they really do?
  4368. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4369. address, which is in fact an integer---call it @var{pint}. It treats
  4370. @var{i} as a number of elements of the type that @var{p} points to.
  4371. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4372. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4373. (*@var{p})}. This value is reinterpreted as a pointer of the same
  4374. type as @var{p}.
  4375. If the starting pointer value @var{p} and the result do not point at
  4376. parts of the same object, the operation is not officially legitimate,
  4377. and C code is not ``supposed'' to do it. But you can do it anyway,
  4378. and it gives precisely the results described by the procedure above.
  4379. In some special situations it can do something useful, but non-wizards
  4380. should avoid it.
  4381. Here's a function to offset a pointer value @emph{as if} it pointed to
  4382. an object of any given size, by explicitly performing that calculation:
  4383. @example
  4384. #include <stdint.h>
  4385. void *
  4386. ptr_add (void *p, int i, int objsize)
  4387. @{
  4388. intptr_t p_address = (long) p;
  4389. intptr_t totalsize = i * objsize;
  4390. intptr_t new_address = p_address + totalsize;
  4391. return (void *) new_address;
  4392. @}
  4393. @end example
  4394. @noindent
  4395. @cindex @code{intptr_t}
  4396. This does the same job as @code{@var{p} + @var{i}} with the proper
  4397. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4398. defined in the header file @file{stdint.h}. (In practice, @code{long
  4399. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4400. @node Pointer Increment/Decrement
  4401. @section Pointer Increment and Decrement
  4402. @cindex pointer increment and decrement
  4403. @cindex incrementing pointers
  4404. @cindex decrementing pointers
  4405. The @samp{++} operator adds 1 to a variable. We have seen it for
  4406. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4407. For instance, suppose we have a series of positive integers,
  4408. terminated by a zero, and we want to add them up. Here is a simple
  4409. way to step forward through the array by advancing a pointer.
  4410. @example
  4411. int
  4412. sum_array_till_0 (int *p)
  4413. @{
  4414. int sum = 0;
  4415. for (;;)
  4416. @{
  4417. /* @r{Fetch the next integer.} */
  4418. int next = *p++;
  4419. /* @r{Exit the loop if it's 0.} */
  4420. if (next == 0)
  4421. break;
  4422. /* @r{Add it into running total.} */
  4423. sum += next;
  4424. @}
  4425. return sum;
  4426. @}
  4427. @end example
  4428. @noindent
  4429. The statement @samp{break;} will be explained further on (@pxref{break
  4430. Statement}). Used in this way, it immediately exits the surrounding
  4431. @code{for} statement.
  4432. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4433. takes precedence over a prefix operator. Therefore, it dereferences
  4434. the entering value of @code{p}, then increments @code{p} afterwards.
  4435. Incrementing a variable means adding 1 to it, as in @code{p = p + 1}.
  4436. Since @code{p} is a pointer, adding 1 to it advances it by the width
  4437. of the datum it points to---in this case, @code{sizeof (int)}.
  4438. Therefore, each iteration of the loop picks up the next integer from
  4439. the series and puts it into @code{next}.
  4440. This @code{for}-loop has no initialization expression since @code{p}
  4441. and @code{sum} are already initialized, has no end-test since the
  4442. @samp{break;} statement will exit it, and needs no expression to
  4443. advance it since that's done within the loop by incrementing @code{p}
  4444. and @code{sum}. Thus, those three expressions after @code{for} are
  4445. left empty.
  4446. Another way to write this function is by keeping the parameter value unchanged
  4447. and using indexing to access the integers in the table.
  4448. @example
  4449. int
  4450. sum_array_till_0_indexing (int *p)
  4451. @{
  4452. int i;
  4453. int sum = 0;
  4454. for (i = 0; ; i++)
  4455. @{
  4456. /* @r{Fetch the next integer.} */
  4457. int next = p[i];
  4458. /* @r{Exit the loop if it's 0.} */
  4459. if (next == 0)
  4460. break;
  4461. /* @r{Add it into running total.} */
  4462. sum += next;
  4463. @}
  4464. return sum;
  4465. @}
  4466. @end example
  4467. In this program, instead of advancing @code{p}, we advance @code{i}
  4468. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4469. i)}.) Either way, it uses the same address to get the next integer.
  4470. It makes no difference in this program whether we write @code{i++} or
  4471. @code{++i}, because the value @emph{of that expression} is not used.
  4472. We use it for its effect, to increment @code{i}.
  4473. The @samp{--} operator also works on pointers; it can be used
  4474. to step backwards through an array, like this:
  4475. @example
  4476. int
  4477. after_last_nonzero (int *p, int len)
  4478. @{
  4479. /* @r{Set up @code{q} to point just after the last array element.} */
  4480. int *q = p + len;
  4481. while (q != p)
  4482. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4483. if (*--q != 0)
  4484. /* @r{Return the index of the element after that nonzero.} */
  4485. return q - p + 1;
  4486. return 0;
  4487. @}
  4488. @end example
  4489. That function returns the length of the nonzero part of the
  4490. array specified by its arguments; that is, the index of the
  4491. first zero of the run of zeros at the end.
  4492. @node Pointer Arithmetic Drawbacks
  4493. @section Drawbacks of Pointer Arithmetic
  4494. @cindex drawbacks of pointer arithmetic
  4495. @cindex pointer arithmetic, drawbacks
  4496. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4497. major security flaw in the C language. Theoretically, it is only
  4498. valid to adjust a pointer within one object allocated as a unit in
  4499. memory. However, if you unintentionally adjust a pointer across the
  4500. bounds of the object and into some other object, the system has no way
  4501. to detect this error.
  4502. A bug which does that can easily result in clobbering (overwriting)
  4503. part of another object. For example, with @code{array[-1]} you can
  4504. read or write the nonexistent element before the beginning of an
  4505. array---probably part of some other data.
  4506. Combining pointer arithmetic with casts between pointer types, you can
  4507. create a pointer that fails to be properly aligned for its type. For
  4508. example,
  4509. @example
  4510. int a[2];
  4511. char *pa = (char *)a;
  4512. int *p = (int *)(pa + 1);
  4513. @end example
  4514. @noindent
  4515. gives @code{p} a value pointing to an ``integer'' that includes part
  4516. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4517. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4518. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4519. ``works,'' it may be quite slow. It can also cause aliasing
  4520. confusions (@pxref{Aliasing}).
  4521. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4522. unless it is really necessary.
  4523. @node Pointer-Integer Conversion
  4524. @section Pointer-Integer Conversion
  4525. @cindex pointer-integer conversion
  4526. @cindex conversion between pointers and integers
  4527. @cindex @code{uintptr_t}
  4528. On modern computers, an address is simply a number. It occupies the
  4529. same space as some size of integer. In C, you can convert a pointer
  4530. to the appropriate integer types and vice versa, without losing
  4531. information. The appropriate integer types are @code{uintptr_t} (an
  4532. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4533. in @file{stdint.h}.
  4534. For instance,
  4535. @example
  4536. #include <stdint.h>
  4537. #include <stdio.h>
  4538. void
  4539. print_pointer (void *ptr)
  4540. @{
  4541. uintptr_t converted = (uintptr_t) ptr;
  4542. printf ("Pointer value is 0x%x\n",
  4543. (unsigned int) converted);
  4544. @}
  4545. @end example
  4546. @noindent
  4547. The specification @samp{%x} in the template (the first argument) for
  4548. @code{printf} means to represent this argument using hexadecimal
  4549. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4550. printing treats the number as unsigned, but it won't actually matter:
  4551. all @code{printf} gets to see is the series of bits in the number.
  4552. @strong{Warning:} Converting pointers to integers is risky---don't do
  4553. it unless it is really necessary.
  4554. @node Printing Pointers
  4555. @section Printing Pointers
  4556. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4557. For example:
  4558. @example
  4559. void
  4560. print_pointer (void *ptr)
  4561. @{
  4562. printf ("Pointer value is %p\n", ptr);
  4563. @}
  4564. @end example
  4565. The specification @samp{%p} works with any pointer type. It prints
  4566. @samp{0x} followed by the address in hexadecimal, printed as the
  4567. appropriate unsigned integer type.
  4568. @node Structures
  4569. @chapter Structures
  4570. @cindex structures
  4571. @findex struct
  4572. @cindex fields in structures
  4573. A @dfn{structure} is a user-defined data type that holds various
  4574. @dfn{fields} of data. Each field has a name and a data type specified
  4575. in the structure's definition.
  4576. Here we define a structure suitable for storing a linked list of
  4577. integers. Each list item will hold one integer, plus a pointer
  4578. to the next item.
  4579. @example
  4580. struct intlistlink
  4581. @{
  4582. int datum;
  4583. struct intlistlink *next;
  4584. @};
  4585. @end example
  4586. The structure definition has a @dfn{type tag} so that the code can
  4587. refer to this structure. The type tag here is @code{intlistlink}.
  4588. The definition refers recursively to the same structure through that
  4589. tag.
  4590. You can define a structure without a type tag, but then you can't
  4591. refer to it again. That is useful only in some special contexts, such
  4592. as inside a @code{typedef} or a @code{union}.
  4593. The contents of the structure are specified by the @dfn{field
  4594. declarations} inside the braces. Each field in the structure needs a
  4595. declaration there. The fields in one structure definition must have
  4596. distinct names, but these names do not conflict with any other names
  4597. in the program.
  4598. A field declaration looks just like a variable declaration. You can
  4599. combine field declarations with the same beginning, just as you can
  4600. combine variable declarations.
  4601. This structure has two fields. One, named @code{datum}, has type
  4602. @code{int} and will hold one integer in the list. The other, named
  4603. @code{next}, is a pointer to another @code{struct intlistlink}
  4604. which would be the rest of the list. In the last list item, it would
  4605. be @code{NULL}.
  4606. This structure definition is recursive, since the type of the
  4607. @code{next} field refers to the structure type. Such recursion is not
  4608. a problem; in fact, you can use the type @code{struct intlistlink *}
  4609. before the definition of the type @code{struct intlistlink} itself.
  4610. That works because pointers to all kinds of structures really look the
  4611. same at the machine level.
  4612. After defining the structure, you can declare a variable of type
  4613. @code{struct intlistlink} like this:
  4614. @example
  4615. struct intlistlink foo;
  4616. @end example
  4617. The structure definition itself can serve as the beginning of a
  4618. variable declaration, so you can declare variables immediately after,
  4619. like this:
  4620. @example
  4621. struct intlistlink
  4622. @{
  4623. int datum;
  4624. struct intlistlink *next;
  4625. @} foo;
  4626. @end example
  4627. @noindent
  4628. But that is ugly. It is almost always clearer to separate the
  4629. definition of the structure from its uses.
  4630. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4631. the scope of the structure type name to that block. That means the
  4632. structure type is recognized only within that block. Declaring it in
  4633. a function parameter list, as here,
  4634. @example
  4635. int f (struct foo @{int a, b@} parm);
  4636. @end example
  4637. @noindent
  4638. (assuming that @code{struct foo} is not already defined) limits the
  4639. scope of the structure type @code{struct foo} to that parameter list;
  4640. that is basically useless, so it triggers a warning.
  4641. Standard C requires at least one field in a structure.
  4642. GNU C does not require this.
  4643. @menu
  4644. * Referencing Fields:: Accessing field values in a structure object.
  4645. * Arrays as Fields:: Accessing field values in a structure object.
  4646. * Dynamic Memory Allocation:: Allocating space for objects
  4647. while the program is running.
  4648. * Field Offset:: Memory layout of fields within a structure.
  4649. * Structure Layout:: Planning the memory layout of fields.
  4650. * Packed Structures:: Packing structure fields as close as possible.
  4651. * Bit Fields:: Dividing integer fields
  4652. into fields with fewer bits.
  4653. * Bit Field Packing:: How bit fields pack together in integers.
  4654. * const Fields:: Making structure fields immutable.
  4655. * Zero Length:: Zero-length array as a variable-length object.
  4656. * Flexible Array Fields:: Another approach to variable-length objects.
  4657. * Overlaying Structures:: Casting one structure type
  4658. over an object of another structure type.
  4659. * Structure Assignment:: Assigning values to structure objects.
  4660. * Unions:: Viewing the same object in different types.
  4661. * Packing With Unions:: Using a union type to pack various types into
  4662. the same memory space.
  4663. * Cast to Union:: Casting a value one of the union's alternative
  4664. types to the type of the union itself.
  4665. * Structure Constructors:: Building new structure objects.
  4666. * Unnamed Types as Fields:: Fields' types do not always need names.
  4667. * Incomplete Types:: Types which have not been fully defined.
  4668. * Intertwined Incomplete Types:: Defining mutually-recursive structure types.
  4669. * Type Tags:: Scope of structure and union type tags.
  4670. @end menu
  4671. @node Referencing Fields
  4672. @section Referencing Structure Fields
  4673. @cindex referencing structure fields
  4674. @cindex structure fields, referencing
  4675. To make a structure useful, there has to be a way to examine and store
  4676. its fields. The @samp{.} (period) operator does that; its use looks
  4677. like @code{@var{object}.@var{field}}.
  4678. Given this structure and variable,
  4679. @example
  4680. struct intlistlink
  4681. @{
  4682. int datum;
  4683. struct intlistlink *next;
  4684. @};
  4685. struct intlistlink foo;
  4686. @end example
  4687. @noindent
  4688. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4689. fields in the value of @code{foo}. These fields are lvalues, so you
  4690. can store values into them, and read the values out again.
  4691. Most often, structures are dynamically allocated (see the next
  4692. section), and we refer to the objects via pointers.
  4693. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4694. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4695. contains this declaration:
  4696. @example
  4697. struct intlistlink *ptr;
  4698. @end example
  4699. @noindent
  4700. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4701. to the two fields in the object that @code{ptr} points to.
  4702. If a unary operator precedes an expression using @samp{->},
  4703. the @samp{->} nests inside:
  4704. @example
  4705. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4706. @end example
  4707. You can intermix @samp{->} and @samp{.} without parentheses,
  4708. as shown here:
  4709. @example
  4710. struct @{ double d; struct intlistlink l; @} foo;
  4711. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4712. @end example
  4713. @node Arrays as Fields
  4714. @section Arrays as Fields
  4715. When you declare field in a structure as an array, as here:
  4716. @example
  4717. struct record
  4718. @{
  4719. char *name;
  4720. int data[4];
  4721. @};
  4722. @end example
  4723. @noindent
  4724. Each @code{struct record} object holds one string (a pointer, of
  4725. course) and four integers, all part of a field called @code{data}. If
  4726. @code{recptr} is a pointer of type @code{struct record *}, then it
  4727. points to a @code{struct record} which contains those things; you can
  4728. access the second integer in that record with @code{recptr->data[1]}.
  4729. If you have two objects of type @code{struct record}, each one contains
  4730. an array. With this declaration,
  4731. @example
  4732. struct record r1, r2;
  4733. @end example
  4734. @code{r1.data} holds space for 4 @code{int}s, and @code{r2.data} holds
  4735. space for another 4 @code{int}s,
  4736. @node Dynamic Memory Allocation
  4737. @section Dynamic Memory Allocation
  4738. @cindex dynamic memory allocation
  4739. @cindex memory allocation, dynamic
  4740. @cindex allocating memory dynamically
  4741. To allocate an object dynamically, call the library function
  4742. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4743. Reference Manual}). Here is how to allocate an object of type
  4744. @code{struct intlistlink}. To make this code work, include the file
  4745. @file{stdlib.h}, like this:
  4746. @example
  4747. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4748. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4749. @dots{}
  4750. struct intlistlink *
  4751. alloc_intlistlink ()
  4752. @{
  4753. struct intlistlink *p;
  4754. p = malloc (sizeof (struct intlistlink));
  4755. if (p == NULL)
  4756. fatal ("Ran out of storage");
  4757. /* @r{Initialize the contents.} */
  4758. p->datum = 0;
  4759. p->next = NULL;
  4760. return p;
  4761. @}
  4762. @end example
  4763. @noindent
  4764. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4765. will automatically convert it to type @code{struct intlistlink *}.
  4766. The return value of @code{malloc} is always sufficiently aligned
  4767. (@pxref{Type Alignment}) that it is valid for any data type.
  4768. The test for @code{p == NULL} is necessary because @code{malloc}
  4769. returns a null pointer if it cannot get any storage. We assume that
  4770. the program defines the function @code{fatal} to report a fatal error
  4771. to the user.
  4772. Here's how to add one more integer to the front of such a list:
  4773. @example
  4774. struct intlistlink *my_list = NULL;
  4775. void
  4776. add_to_mylist (int my_int)
  4777. @{
  4778. struct intlistlink *p = alloc_intlistlink ();
  4779. p->datum = my_int;
  4780. p->next = mylist;
  4781. mylist = p;
  4782. @}
  4783. @end example
  4784. The way to free the objects is by calling @code{free}. Here's
  4785. a function to free all the links in one of these lists:
  4786. @example
  4787. void
  4788. free_intlist (struct intlistlink *p)
  4789. @{
  4790. while (p)
  4791. @{
  4792. struct intlistlink *q = p;
  4793. p = p->next;
  4794. free (q);
  4795. @}
  4796. @}
  4797. @end example
  4798. We must extract the @code{next} pointer from the object before freeing
  4799. it, because @code{free} can clobber the data that was in the object.
  4800. For the same reason, the program must not use the list any more after
  4801. freeing its elements. To make sure it won't, it is best to clear out
  4802. the variable where the list was stored, like this:
  4803. @example
  4804. free_intlist (mylist);
  4805. mylist = NULL;
  4806. @end example
  4807. @node Field Offset
  4808. @section Field Offset
  4809. @cindex field offset
  4810. @cindex structure field offset
  4811. @cindex offset of structure fields
  4812. To determine the offset of a given field @var{field} in a structure
  4813. type @var{type}, use the macro @code{offsetof}, which is defined in
  4814. the file @file{stddef.h}. It is used like this:
  4815. @example
  4816. offsetof (@var{type}, @var{field})
  4817. @end example
  4818. Here is an example:
  4819. @example
  4820. struct foo
  4821. @{
  4822. int element;
  4823. struct foo *next;
  4824. @};
  4825. offsetof (struct foo, next)
  4826. /* @r{On most machines that is 4. It may be 8.} */
  4827. @end example
  4828. @node Structure Layout
  4829. @section Structure Layout
  4830. @cindex structure layout
  4831. @cindex layout of structures
  4832. The rest of this chapter covers advanced topics about structures. If
  4833. you are just learning C, you can skip it.
  4834. The precise layout of a @code{struct} type is crucial when using it to
  4835. overlay hardware registers, to access data structures in shared
  4836. memory, or to assemble and disassemble packets for network
  4837. communication. It is also important for avoiding memory waste when
  4838. the program makes many objects of that type. However, the layout
  4839. depends on the target platform. Each platform has conventions for
  4840. structure layout, which compilers need to follow.
  4841. Here are the conventions used on most platforms.
  4842. The structure's fields appear in the structure layout in the order
  4843. they are declared. When possible, consecutive fields occupy
  4844. consecutive bytes within the structure. However, if a field's type
  4845. demands more alignment than it would get that way, C gives it the
  4846. alignment it requires by leaving a gap after the previous field.
  4847. Once all the fields have been laid out, it is possible to determine
  4848. the structure's alignment and size. The structure's alignment is the
  4849. maximum alignment of any of the fields in it. Then the structure's
  4850. size is rounded up to a multiple of its alignment. That may require
  4851. leaving a gap at the end of the structure.
  4852. Here are some examples, where we assume that @code{char} has size and
  4853. alignment 1 (always true), and @code{int} has size and alignment 4
  4854. (true on most kinds of computers):
  4855. @example
  4856. struct foo
  4857. @{
  4858. char a, b;
  4859. int c;
  4860. @};
  4861. @end example
  4862. @noindent
  4863. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4864. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4865. There is a gap of 2 bytes before @code{c}.
  4866. Contrast that with this structure:
  4867. @example
  4868. struct foo
  4869. @{
  4870. char a;
  4871. int c;
  4872. char b;
  4873. @};
  4874. @end example
  4875. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4876. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4877. gaps: three bytes before @code{c}, and three bytes at the end.
  4878. These two structures have the same contents at the C level, but one
  4879. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4880. fields. A reliable way to avoid this sort of wastage is to order the
  4881. fields by size, biggest fields first.
  4882. @node Packed Structures
  4883. @section Packed Structures
  4884. @cindex packed structures
  4885. @cindex @code{__attribute__((packed))}
  4886. In GNU C you can force a structure to be laid out with no gaps by
  4887. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4888. end of the structure type declaration). Here's an example:
  4889. @example
  4890. struct __attribute__((packed)) foo
  4891. @{
  4892. char a;
  4893. int c;
  4894. char b;
  4895. @};
  4896. @end example
  4897. Without @code{__attribute__((packed))}, this structure occupies 12
  4898. bytes (as described in the previous section), assuming 4-byte
  4899. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4900. only 6 bytes long---the sum of the lengths of its fields.
  4901. Use of @code{__attribute__((packed))} often results in fields that
  4902. don't have the normal alignment for their types. Taking the address
  4903. of such a field can result in an invalid pointer because of its
  4904. improper alignment. Dereferencing such a pointer can cause a
  4905. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4906. unaligned pointers.
  4907. @xref{Attributes}.
  4908. @node Bit Fields
  4909. @section Bit Fields
  4910. @cindex bit fields
  4911. A structure field declaration with an integer type can specify the
  4912. number of bits the field should occupy. We call that a @dfn{bit
  4913. field}. These are useful because consecutive bit fields are packed
  4914. into a larger storage unit. For instance,
  4915. @example
  4916. unsigned char opcode: 4;
  4917. @end example
  4918. @noindent
  4919. specifies that this field takes just 4 bits.
  4920. Since it is unsigned, its possible values range
  4921. from 0 to 15. A signed field with 4 bits, such as this,
  4922. @example
  4923. signed char small: 4;
  4924. @end example
  4925. @noindent
  4926. can hold values from -8 to 7.
  4927. You can subdivide a single byte into those two parts by writing
  4928. @example
  4929. unsigned char opcode: 4;
  4930. signed char small: 4;
  4931. @end example
  4932. @noindent
  4933. in the structure. With bit fields, these two numbers fit into
  4934. a single @code{char}.
  4935. Here's how to declare a one-bit field that can hold either 0 or 1:
  4936. @example
  4937. unsigned char special_flag: 1;
  4938. @end example
  4939. You can also use the @code{bool} type for bit fields:
  4940. @example
  4941. bool special_flag: 1;
  4942. @end example
  4943. Except when using @code{bool} (which is always unsigned,
  4944. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4945. for a bit field. There is a default, if that's not specified: the bit
  4946. field is signed if plain @code{char} is signed, except that the option
  4947. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4948. is cleaner not to depend on this default.
  4949. Bit fields are special in that you cannot take their address with
  4950. @samp{&}. They are not stored with the size and alignment appropriate
  4951. for the specified type, so they cannot be addressed through pointers
  4952. to that type.
  4953. @node Bit Field Packing
  4954. @section Bit Field Packing
  4955. Programs to communicate with low-level hardware interfaces need to
  4956. define bit fields laid out to match the hardware data. This section
  4957. explains how to do that.
  4958. Consecutive bit fields are packed together, but each bit field must
  4959. fit within a single object of its specified type. In this example,
  4960. @example
  4961. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4962. @end example
  4963. @noindent
  4964. all five fields fit consecutively into one two-byte @code{short}.
  4965. They need 15 bits, and one @code{short} provides 16. By contrast,
  4966. @example
  4967. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4968. @end example
  4969. @noindent
  4970. needs three bytes. It fits @code{a} and @code{b} into one
  4971. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4972. add up to 9 bits). So @code{c} and @code{d} go into a second
  4973. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4974. Then @code{e} needs a third @code{char}. By contrast,
  4975. @example
  4976. unsigned char a : 3, b : 3;
  4977. unsigned int c : 3;
  4978. unsigned char d : 3, e : 3;
  4979. @end example
  4980. @noindent
  4981. needs only two bytes: the type @code{unsigned int}
  4982. allows @code{c} to straddle bytes that are in the same word.
  4983. You can leave a gap of a specified number of bits by defining a
  4984. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4985. It is allocated space in the structure just as a named bit field would
  4986. be allocated.
  4987. You can force the following bit field to advance to the following
  4988. aligned memory object with @code{@var{type} : 0;}.
  4989. Both of these constructs can syntactically share @var{type} with
  4990. ordinary bit fields. This example illustrates both:
  4991. @example
  4992. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4993. @end example
  4994. @noindent
  4995. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4996. between them. Then @code{: 0} advances to the next @code{int},
  4997. so @code{c} and @code{d} fit into that one.
  4998. These rules for packing bit fields apply to most target platforms,
  4999. including all the usual real computers. A few embedded controllers
  5000. have special layout rules.
  5001. @node const Fields
  5002. @section @code{const} Fields
  5003. @cindex const fields
  5004. @cindex structure fields, constant
  5005. @c ??? Is this a C standard feature?
  5006. A structure field declared @code{const} cannot be assigned to
  5007. (@pxref{const}). For instance, let's define this modified version of
  5008. @code{struct intlistlink}:
  5009. @example
  5010. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  5011. @{
  5012. const int datum;
  5013. struct intlistlink *next;
  5014. @};
  5015. @end example
  5016. This structure can be used to prevent part of the code from modifying
  5017. the @code{datum} field:
  5018. @example
  5019. /* @r{@code{p} has type @code{struct intlistlink *}.}
  5020. @r{Convert it to @code{struct intlistlink_ro *}.} */
  5021. struct intlistlink_ro *q
  5022. = (struct intlistlink_ro *) p;
  5023. q->datum = 5; /* @r{Error!} */
  5024. p->datum = 5; /* @r{Valid since @code{*p} is}
  5025. @r{not a @code{struct intlistlink_ro}.} */
  5026. @end example
  5027. A @code{const} field can get a value in two ways: by initialization of
  5028. the whole structure, and by making a pointer-to-structure point to an object
  5029. in which that field already has a value.
  5030. Any @code{const} field in a structure type makes assignment impossible
  5031. for structures of that type (@pxref{Structure Assignment}). That is
  5032. because structure assignment works by assigning the structure's
  5033. fields, one by one.
  5034. @node Zero Length
  5035. @section Arrays of Length Zero
  5036. @cindex array of length zero
  5037. @cindex zero-length arrays
  5038. @cindex length-zero arrays
  5039. GNU C allows zero-length arrays. They are useful as the last element
  5040. of a structure that is really a header for a variable-length object.
  5041. Here's an example, where we construct a variable-size structure
  5042. to hold a line which is @code{this_length} characters long:
  5043. @example
  5044. struct line @{
  5045. int length;
  5046. char contents[0];
  5047. @};
  5048. struct line *thisline
  5049. = ((struct line *)
  5050. malloc (sizeof (struct line)
  5051. + this_length));
  5052. thisline->length = this_length;
  5053. @end example
  5054. In ISO C90, we would have to give @code{contents} a length of 1, which
  5055. means either wasting space or complicating the argument to @code{malloc}.
  5056. @node Flexible Array Fields
  5057. @section Flexible Array Fields
  5058. @cindex flexible array fields
  5059. @cindex array fields, flexible
  5060. The C99 standard adopted a more complex equivalent of zero-length
  5061. array fields. It's called a @dfn{flexible array}, and it's indicated
  5062. by omitting the length, like this:
  5063. @example
  5064. struct line
  5065. @{
  5066. int length;
  5067. char contents[];
  5068. @};
  5069. @end example
  5070. The flexible array has to be the last field in the structure, and there
  5071. must be other fields before it.
  5072. Under the C standard, a structure with a flexible array can't be part
  5073. of another structure, and can't be an element of an array.
  5074. GNU C allows static initialization of flexible array fields. The effect
  5075. is to ``make the array long enough'' for the initializer.
  5076. @example
  5077. struct f1 @{ int x; int y[]; @} f1
  5078. = @{ 1, @{ 2, 3, 4 @} @};
  5079. @end example
  5080. @noindent
  5081. This defines a structure variable named @code{f1}
  5082. whose type is @code{struct f1}. In C, a variable name or function name
  5083. never conflicts with a structure type tag.
  5084. Omitting the flexible array field's size lets the initializer
  5085. determine it. This is allowed only when the flexible array is defined
  5086. in the outermost structure and you declare a variable of that
  5087. structure type. For example:
  5088. @example
  5089. struct foo @{ int x; int y[]; @};
  5090. struct bar @{ struct foo z; @};
  5091. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  5092. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5093. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  5094. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5095. @end example
  5096. @node Overlaying Structures
  5097. @section Overlaying Different Structures
  5098. @cindex overlaying structures
  5099. @cindex structures, overlaying
  5100. Be careful about using different structure types to refer to the same
  5101. memory within one function, because GNU C can optimize code assuming
  5102. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5103. aliasing that can cause the problem:
  5104. @example
  5105. struct a @{ int size; char *data; @};
  5106. struct b @{ int size; char *data; @};
  5107. struct a foo;
  5108. struct b *q = (struct b *) &foo;
  5109. @end example
  5110. Here @code{q} points to the same memory that the variable @code{foo}
  5111. occupies, but they have two different types. The two types
  5112. @code{struct a} and @code{struct b} are defined alike, but they are
  5113. not the same type. Interspersing references using the two types,
  5114. like this,
  5115. @example
  5116. p->size = 0;
  5117. q->size = 1;
  5118. x = p->size;
  5119. @end example
  5120. @noindent
  5121. allows GNU C to assume that @code{p->size} is still zero when it is
  5122. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5123. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5124. Other compilers might also do this optimization. The ISO C standard
  5125. considers such code erroneous, precisely so that this optimization
  5126. will be valid.
  5127. @node Structure Assignment
  5128. @section Structure Assignment
  5129. @cindex structure assignment
  5130. @cindex assigning structures
  5131. Assignment operating on a structure type copies the structure. The
  5132. left and right operands must have the same type. Here is an example:
  5133. @example
  5134. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5135. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5136. @r{@dots{}}
  5137. struct point @{ double x, y; @};
  5138. struct point *
  5139. copy_point (struct point point)
  5140. @{
  5141. struct point *p
  5142. = (struct point *) malloc (sizeof (struct point));
  5143. if (p == NULL)
  5144. fatal ("Out of memory");
  5145. *p = point;
  5146. return p;
  5147. @}
  5148. @end example
  5149. Notionally, assignment on a structure type works by copying each of
  5150. the fields. Thus, if any of the fields has the @code{const}
  5151. qualifier, that structure type does not allow assignment:
  5152. @example
  5153. struct point @{ const double x, y; @};
  5154. struct point a, b;
  5155. a = b; /* @r{Error!} */
  5156. @end example
  5157. @xref{Assignment Expressions}.
  5158. When a structure type has a field which is an array, as here,
  5159. @example
  5160. struct record
  5161. @{
  5162. char *name;
  5163. int data[4];
  5164. @};
  5165. struct record r1, r2;
  5166. @end example
  5167. @noindent
  5168. structure assigment such as @code{r1 = r2} copies array fields'
  5169. contents just as it copies all the other fields.
  5170. This is the only way in C that you can operate on the whole contents
  5171. of a array with one operation: when the array is contained in a
  5172. @code{struct}. You can't copy the contents of the @code{data} field
  5173. as an array, because
  5174. @example
  5175. r1.data = r2.data;
  5176. @end data
  5177. @noindent
  5178. would convert the array objects (as always) to pointers to the initial
  5179. elements of the arrays (of type @code{struct record *}), and the
  5180. assignment would be invalid because the left operand is not an lvalue.
  5181. @node Unions
  5182. @section Unions
  5183. @cindex unions
  5184. @findex union
  5185. A @dfn{union type} defines alternative ways of looking at the same
  5186. piece of memory. Each alternative view is defined with a data type,
  5187. and identified by a name. A union definition looks like this:
  5188. @example
  5189. union @var{name}
  5190. @{
  5191. @var{alternative declarations}@r{@dots{}}
  5192. @};
  5193. @end example
  5194. Each alternative declaration looks like a structure field declaration,
  5195. except that it can't be a bit field. For instance,
  5196. @example
  5197. union number
  5198. @{
  5199. long int integer;
  5200. double float;
  5201. @}
  5202. @end example
  5203. @noindent
  5204. lets you store either an integer (type @code{long int}) or a floating
  5205. point number (type @code{double}) in the same place in memory. The
  5206. length and alignment of the union type are the maximum of all the
  5207. alternatives---they do not have to be the same. In this union
  5208. example, @code{double} probably takes more space than @code{long int},
  5209. but that doesn't cause a problem in programs that use the union in the
  5210. normal way.
  5211. The members don't have to be different in data type. Sometimes
  5212. each member pertains to a way the data will be used. For instance,
  5213. @example
  5214. union datum
  5215. @{
  5216. double latitude;
  5217. double longitude;
  5218. double height;
  5219. double weight;
  5220. int continent;
  5221. @}
  5222. @end example
  5223. This union holds one of several kinds of data; most kinds are floating
  5224. points, but the value can also be a code for a continent which is an
  5225. integer. You @emph{could} use one member of type @code{double} to
  5226. access all the values which have that type, but the different member
  5227. names will make the program clearer.
  5228. The alignment of a union type is the maximum of the alignments of the
  5229. alternatives. The size of the union type is the maximum of the sizes
  5230. of the alternatives, rounded up to a multiple of the alignment
  5231. (because every type's size must be a multiple of its alignment).
  5232. All the union alternatives start at the address of the union itself.
  5233. If an alternative is shorter than the union as a whole, it occupies
  5234. the first part of the union's storage, leaving the last part unused
  5235. @emph{for that alternative}.
  5236. @strong{Warning:} if the code stores data using one union alternative
  5237. and accesses it with another, the results depend on the kind of
  5238. computer in use. Only wizards should try to do this. However, when
  5239. you need to do this, a union is a clean way to do it.
  5240. Assignment works on any union type by copying the entire value.
  5241. @node Packing With Unions
  5242. @section Packing With Unions
  5243. Sometimes we design a union with the intention of packing various
  5244. kinds of objects into a certain amount of memory space. For example.
  5245. @example
  5246. union bytes8
  5247. @{
  5248. long long big_int_elt;
  5249. double double_elt;
  5250. struct @{ int first, second; @} two_ints;
  5251. struct @{ void *first, *second; @} two_ptrs;
  5252. @};
  5253. union bytes8 *p;
  5254. @end example
  5255. This union makes it possible to look at 8 bytes of data that @code{p}
  5256. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5257. single floating-point number (@code{p->double_elt}), as a pair of
  5258. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5259. as a pair of pointers (@code{p->two_ptrs.first} and
  5260. @code{p->two_ptrs.second}).
  5261. To pack storage with such a union makes assumptions about the sizes of
  5262. all the types involved. This particular union was written expecting a
  5263. pointer to have the same size as @code{int}. On a machine where one
  5264. pointer takes 8 bytes, the code using this union probably won't work
  5265. as expected. The union, as such, will function correctly---if you
  5266. store two values through @code{two_ints} and extract them through
  5267. @code{two_ints}, you will get the same integers back---but the part of
  5268. the program that expects the union to be 8 bytes long could
  5269. malfunction, or at least use too much space.
  5270. The above example shows one case where a @code{struct} type with no
  5271. tag can be useful. Another way to get effectively the same result
  5272. is with arrays as members of the union:
  5273. @example
  5274. union eight_bytes
  5275. @{
  5276. long long big_int_elt;
  5277. double double_elt;
  5278. int two_ints[2];
  5279. void *two_ptrs[2];
  5280. @};
  5281. @end example
  5282. @node Cast to Union
  5283. @section Cast to a Union Type
  5284. @cindex cast to a union
  5285. @cindex union, casting to a
  5286. In GNU C, you can explicitly cast any of the alternative types to the
  5287. union type; for instance,
  5288. @example
  5289. (union eight_bytes) (long long) 5
  5290. @end example
  5291. @noindent
  5292. makes a value of type @code{union eight_bytes} which gets its contents
  5293. through the alternative named @code{big_int_elt}.
  5294. The value being cast must exactly match the type of the alternative,
  5295. so this is not valid:
  5296. @example
  5297. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5298. @end example
  5299. A cast to union type looks like any other cast, except that the type
  5300. specified is a union type. You can specify the type either with
  5301. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5302. Typedef Names}).
  5303. Using the cast as the right-hand side of an assignment to a variable of
  5304. union type is equivalent to storing in an alternative of the union:
  5305. @example
  5306. union foo u;
  5307. u = (union foo) x @r{means} u.i = x
  5308. u = (union foo) y @r{means} u.d = y
  5309. @end example
  5310. You can also use the union cast as a function argument:
  5311. @example
  5312. void hack (union foo);
  5313. @r{@dots{}}
  5314. hack ((union foo) x);
  5315. @end example
  5316. @node Structure Constructors
  5317. @section Structure Constructors
  5318. @cindex structure constructors
  5319. @cindex constructors, structure
  5320. You can construct a structure value by writing its type in
  5321. parentheses, followed by an initializer that would be valid in a
  5322. declaration for that type. For instance, given this declaration,
  5323. @example
  5324. struct foo @{int a; char b[2];@} structure;
  5325. @end example
  5326. @noindent
  5327. you can create a @code{struct foo} value as follows:
  5328. @example
  5329. ((struct foo) @{x + y, 'a', 0@})
  5330. @end example
  5331. @noindent
  5332. This specifies @code{x + y} for field @code{a},
  5333. the character @samp{a} for field @code{b}'s element 0,
  5334. and the null character for field @code{b}'s element 1.
  5335. The parentheses around that constructor are to necessary, but we
  5336. recommend writing them to make the nesting of the containing
  5337. expression clearer.
  5338. You can also show the nesting of the two by writing it like
  5339. this:
  5340. @example
  5341. ((struct foo) @{x + y, @{'a', 0@} @})
  5342. @end example
  5343. Each of those is equivalent to writing the following statement
  5344. expression (@pxref{Statement Exprs}):
  5345. @example
  5346. (@{
  5347. struct foo temp = @{x + y, 'a', 0@};
  5348. temp;
  5349. @})
  5350. @end example
  5351. You can also create a union value this way, but it is not especially
  5352. useful since that is equivalent to doing a cast:
  5353. @example
  5354. ((union whosis) @{@var{value}@})
  5355. @r{is equivalent to}
  5356. ((union whosis) (@var{value}))
  5357. @end example
  5358. @node Unnamed Types as Fields
  5359. @section Unnamed Types as Fields
  5360. @cindex unnamed structures
  5361. @cindex unnamed unions
  5362. @cindex structures, unnamed
  5363. @cindex unions, unnamed
  5364. A structure or a union can contain, as fields,
  5365. unnamed structures and unions. Here's an example:
  5366. @example
  5367. struct
  5368. @{
  5369. int a;
  5370. union
  5371. @{
  5372. int b;
  5373. float c;
  5374. @};
  5375. int d;
  5376. @} foo;
  5377. @end example
  5378. @noindent
  5379. You can access the fields of the unnamed union within @code{foo} as if they
  5380. were individual fields at the same level as the union definition:
  5381. @example
  5382. foo.a = 42;
  5383. foo.b = 47;
  5384. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5385. foo.d = 314;
  5386. @end example
  5387. Avoid using field names that could cause ambiguity. For example, with
  5388. this definition:
  5389. @example
  5390. struct
  5391. @{
  5392. int a;
  5393. struct
  5394. @{
  5395. int a;
  5396. float b;
  5397. @};
  5398. @} foo;
  5399. @end example
  5400. @noindent
  5401. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5402. an error when a definition is ambiguous in this way.
  5403. @node Incomplete Types
  5404. @section Incomplete Types
  5405. @cindex incomplete types
  5406. @cindex types, incomplete
  5407. A type that has not been fully defined is called an @dfn{incomplete
  5408. type}. Structure and union types are incomplete when the code makes a
  5409. forward reference, such as @code{struct foo}, before defining the
  5410. type. An array type is incomplete when its length is unspecified.
  5411. You can't use an incomplete type to declare a variable or field, or
  5412. use it for a function parameter or return type. The operators
  5413. @code{sizeof} and @code{_Alignof} give errors when used on an
  5414. incomplete type.
  5415. However, you can define a pointer to an incomplete type, and declare a
  5416. variable or field with such a pointer type. In general, you can do
  5417. everything with such pointers except dereference them. For example:
  5418. @example
  5419. extern void bar (struct mysterious_value *);
  5420. void
  5421. foo (struct mysterious_value *arg)
  5422. @{
  5423. bar (arg);
  5424. @}
  5425. @r{@dots{}}
  5426. @{
  5427. struct mysterious_value *p, **q;
  5428. p = *q;
  5429. foo (p);
  5430. @}
  5431. @end example
  5432. @noindent
  5433. These examples are valid because the code doesn't try to understand
  5434. what @code{p} points to; it just passes the pointer around.
  5435. (Presumably @code{bar} is defined in some other file that really does
  5436. have a definition for @code{struct mysterious_value}.) However,
  5437. dereferencing the pointer would get an error; that requires a
  5438. definition for the structure type.
  5439. @node Intertwined Incomplete Types
  5440. @section Intertwined Incomplete Types
  5441. When several structure types contain pointers to each other, you can
  5442. define the types in any order because pointers to types that come
  5443. later are incomplete types. Thus,
  5444. Here is an example.
  5445. @example
  5446. /* @r{An employee record points to a group.} */
  5447. struct employee
  5448. @{
  5449. char *name;
  5450. @r{@dots{}}
  5451. struct group *group; /* @r{incomplete type.} */
  5452. @r{@dots{}}
  5453. @};
  5454. /* @r{An employee list points to employees.} */
  5455. struct employee_list
  5456. @{
  5457. struct employee *this_one;
  5458. struct employee_list *next; /* @r{incomplete type.} */
  5459. @r{@dots{}}
  5460. @};
  5461. /* @r{A group points to one employee_list.} */
  5462. struct group
  5463. @{
  5464. char *name;
  5465. @r{@dots{}}
  5466. struct employee_list *employees;
  5467. @r{@dots{}}
  5468. @};
  5469. @end example
  5470. @node Type Tags
  5471. @section Type Tags
  5472. @cindex type tags
  5473. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5474. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5475. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5476. name or function name; the type tags have a separate @dfn{name space}.
  5477. Thus, there is no name conflict in this code:
  5478. @example
  5479. struct pair @{ int a, b; @};
  5480. int pair = 1;
  5481. @end example
  5482. @noindent
  5483. nor in this one:
  5484. @example
  5485. struct pair @{ int a, b; @} pair;
  5486. @end example
  5487. @noindent
  5488. where @code{pair} is both a structure type tag and a variable name.
  5489. However, @code{struct}, @code{union}, and @code{enum} share the same
  5490. name space of tags, so this is a conflict:
  5491. @example
  5492. struct pair @{ int a, b; @};
  5493. enum pair @{ c, d @};
  5494. @end example
  5495. @noindent
  5496. and so is this:
  5497. @example
  5498. struct pair @{ int a, b; @};
  5499. struct pair @{ int c, d; @};
  5500. @end example
  5501. When the code defines a type tag inside a block, the tag's scope is
  5502. limited to that block (as for local variables). Two definitions for
  5503. one type tag do not conflict if they are in different scopes; rather,
  5504. each is valid in its scope. For example,
  5505. @example
  5506. struct pair @{ int a, b; @};
  5507. void
  5508. pair_up_doubles (int len, double array[])
  5509. @{
  5510. struct pair @{ double a, b; @};
  5511. @r{@dots{}}
  5512. @}
  5513. @end example
  5514. @noindent
  5515. has two definitions for @code{struct pair} which do not conflict. The
  5516. one inside the function applies only within the definition of
  5517. @code{pair_up_doubles}. Within its scope, that definition
  5518. @dfn{shadows} the outer definition.
  5519. If @code{struct pair} appears inside the function body, before the
  5520. inner definition, it refers to the outer definition---the only one
  5521. that has been seen at that point. Thus, in this code,
  5522. @example
  5523. struct pair @{ int a, b; @};
  5524. void
  5525. pair_up_doubles (int len, double array[])
  5526. @{
  5527. struct two_pairs @{ struct pair *p, *q; @};
  5528. struct pair @{ double a, b; @};
  5529. @r{@dots{}}
  5530. @}
  5531. @end example
  5532. @noindent
  5533. the structure @code{two_pairs} has pointers to the outer definition of
  5534. @code{struct pair}, which is probably not desirable.
  5535. To prevent that, you can write @code{struct pair;} inside the function
  5536. body as a variable declaration with no variables. This is a
  5537. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5538. type tag local to the current block, with the details of the type to
  5539. come later. Here's an example:
  5540. @example
  5541. void
  5542. pair_up_doubles (int len, double array[])
  5543. @{
  5544. /* @r{Forward declaration for @code{pair}.} */
  5545. struct pair;
  5546. struct two_pairs @{ struct pair *p, *q; @};
  5547. /* @r{Give the details.} */
  5548. struct pair @{ double a, b; @};
  5549. @r{@dots{}}
  5550. @}
  5551. @end example
  5552. However, the cleanest practice is to avoid shadowing type tags.
  5553. @node Arrays
  5554. @chapter Arrays
  5555. @cindex array
  5556. @cindex elements of arrays
  5557. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5558. all of the same data type. Each element is identified by its numeric
  5559. @var{index} within the array.
  5560. We presented arrays of numbers in the sample programs early in this
  5561. manual (@pxref{Array Example}). However, arrays can have elements of
  5562. any data type, including pointers, structures, unions, and other
  5563. arrays.
  5564. If you know another programming language, you may suppose that you know all
  5565. about arrays, but C arrays have special quirks, so in this chapter we
  5566. collect all the information about arrays in C@.
  5567. The elements of a C array are allocated consecutively in memory,
  5568. with no gaps between them. Each element is aligned as required
  5569. for its data type (@pxref{Type Alignment}).
  5570. @menu
  5571. * Accessing Array Elements:: How to access individual elements of an array.
  5572. * Declaring an Array:: How to name and reserve space for a new array.
  5573. * Strings:: A string in C is a special case of array.
  5574. * Array Type Designators:: Referring to a specific array type.
  5575. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5576. * Limitations of C Arrays:: Arrays are not first-class objects.
  5577. * Multidimensional Arrays:: Arrays of arrays.
  5578. * Constructing Array Values:: Assigning values to an entire array at once.
  5579. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5580. @end menu
  5581. @node Accessing Array Elements
  5582. @section Accessing Array Elements
  5583. @cindex accessing array elements
  5584. @cindex array elements, accessing
  5585. If the variable @code{a} is an array, the @var{n}th element of
  5586. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5587. an element's value or to assign to it:
  5588. @example
  5589. x = a[5];
  5590. a[6] = 1;
  5591. @end example
  5592. @noindent
  5593. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5594. lvalue.
  5595. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5596. valid index is one less than the number of elements.
  5597. The C language does not check whether array indices are in bounds, so
  5598. if the code uses an out-of-range index, it will access memory outside the
  5599. array.
  5600. @strong{Warning:} Using only valid index values in C is the
  5601. programmer's responsibility.
  5602. Array indexing in C is not a primitive operation: it is defined in
  5603. terms of pointer arithmetic and dereferencing. Now that we know
  5604. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5605. its job.
  5606. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5607. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5608. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5609. When an expression with array type (such as @code{a}) appears as part
  5610. of a larger C expression, it is converted automatically to a pointer
  5611. to element zero of that array. For instance, @code{a} in an
  5612. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5613. computed as @code{*(&a[0]+i)}.
  5614. Now we can analyze how that expression gives us the desired element of
  5615. the array. It makes a pointer to element 0 of @code{a}, advances it
  5616. by the value of @code{i}, and dereferences that pointer.
  5617. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5618. @node Declaring an Array
  5619. @section Declaring an Array
  5620. @cindex declaring an array
  5621. @cindex array, declaring
  5622. To make an array declaration, write @code{[@var{length}]} after the
  5623. name being declared. This construct is valid in the declaration of a
  5624. variable, a function parameter, a function value type (the value can't
  5625. be an array, but it can be a pointer to one), a structure field, or a
  5626. union alternative.
  5627. The surrounding declaration specifies the element type of the array;
  5628. that can be any type of data, but not @code{void} or a function type.
  5629. For instance,
  5630. @example
  5631. double a[5];
  5632. @end example
  5633. @noindent
  5634. declares @code{a} as an array of 5 @code{double}s.
  5635. @example
  5636. struct foo bstruct[length];
  5637. @end example
  5638. @noindent
  5639. declares @code{bstruct} as an array of @code{length} objects of type
  5640. @code{struct foo}. A variable array size like this is allowed when
  5641. the array is not file-scope.
  5642. Other declaration constructs can nest within the array declaration
  5643. construct. For instance:
  5644. @example
  5645. struct foo *b[length];
  5646. @end example
  5647. @noindent
  5648. declares @code{b} as an array of @code{length} pointers to
  5649. @code{struct foo}. This shows that the length need not be a constant
  5650. (@pxref{Arrays of Variable Length}).
  5651. @example
  5652. double (*c)[5];
  5653. @end example
  5654. @noindent
  5655. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5656. @example
  5657. char *(*f (int))[5];
  5658. @end example
  5659. @noindent
  5660. declares @code{f} as a function taking an @code{int} argument and
  5661. returning a pointer to an array of 5 strings (pointers to
  5662. @code{char}s).
  5663. @example
  5664. double aa[5][10];
  5665. @end example
  5666. @noindent
  5667. declares @code{aa} as an array of 5 elements, each of which is an
  5668. array of 10 @code{double}s. This shows how to declare a
  5669. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5670. All these declarations specify the array's length, which is needed in
  5671. these cases in order to allocate storage for the array.
  5672. @node Strings
  5673. @section Strings
  5674. @cindex string
  5675. A string in C is a sequence of elements of type @code{char},
  5676. terminated with the null character, the character with code zero.
  5677. Programs often need to use strings with specific, fixed contents. To
  5678. write one in a C program, use a @dfn{string constant} such as
  5679. @code{"Take me to your leader!"}. The data type of a string constant
  5680. is @code{char *}. For the full syntactic details of writing string
  5681. constants, @ref{String Constants}.
  5682. To declare a place to store a non-constant string, declare an array of
  5683. @code{char}. Keep in mind that it must include one extra @code{char}
  5684. for the terminating null. For instance,
  5685. @example
  5686. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5687. @end example
  5688. @noindent
  5689. declares an array named @samp{text} with six elements---five letters
  5690. and the terminating null character. An equivalent way to get the same
  5691. result is this,
  5692. @example
  5693. char text[] = "Hello";
  5694. @end example
  5695. @noindent
  5696. which copies the elements of the string constant, including @emph{its}
  5697. terminating null character.
  5698. @example
  5699. char message[200];
  5700. @end example
  5701. @noindent
  5702. declares an array long enough to hold a string of 199 ASCII characters
  5703. plus the terminating null character.
  5704. When you store a string into @code{message} be sure to check or prove
  5705. that the length does not exceed its size. For example,
  5706. @example
  5707. void
  5708. set_message (char *text)
  5709. @{
  5710. int i;
  5711. for (i = 0; i < sizeof (message); i++)
  5712. @{
  5713. message[i] = text[i];
  5714. if (text[i] == 0)
  5715. return;
  5716. @}
  5717. fatal_error ("Message is too long for `message');
  5718. @}
  5719. @end example
  5720. It's easy to do this with the standard library function
  5721. @code{strncpy}, which fills out the whole destination array (up to a
  5722. specified length) with null characters. Thus, if the last character
  5723. of the destination is not null, the string did not fit. Many system
  5724. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5725. to run faster than an explicit @code{for}-loop.
  5726. Here's what the code looks like:
  5727. @example
  5728. void
  5729. set_message (char *text)
  5730. @{
  5731. strncpy (message, text, sizeof (message));
  5732. if (message[sizeof (message) - 1] != 0)
  5733. fatal_error ("Message is too long for `message');
  5734. @}
  5735. @end example
  5736. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5737. Library Reference Manual}, for more information about the standard
  5738. library functions for operating on strings.
  5739. You can avoid putting a fixed length limit on strings you construct or
  5740. operate on by allocating the space for them dynamically.
  5741. @xref{Dynamic Memory Allocation}.
  5742. @node Array Type Designators
  5743. @section Array Type Designators
  5744. Every C type has a type designator, which you make by deleting the
  5745. variable name and the semicolon from a declaration (@pxref{Type
  5746. Designators}). The designators for array types follow this rule, but
  5747. they may appear surprising.
  5748. @example
  5749. @r{type} int a[5]; @r{designator} int [5]
  5750. @r{type} double a[5][3]; @r{designator} double [5][3]
  5751. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5752. @end example
  5753. @node Incomplete Array Types
  5754. @section Incomplete Array Types
  5755. @cindex incomplete array types
  5756. @cindex array types, incomplete
  5757. An array is equivalent, for most purposes, to a pointer to its zeroth
  5758. element. When that is true, the length of the array is irrelevant.
  5759. The length needs to be known only for allocating space for the array, or
  5760. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5761. contexts C allows
  5762. @itemize @bullet
  5763. @item
  5764. An @code{extern} declaration says how to refer to a variable allocated
  5765. elsewhere. It does not need to allocate space for the variable,
  5766. so if it is an array, you can omit the length. For example,
  5767. @example
  5768. extern int foo[];
  5769. @end example
  5770. @item
  5771. When declaring a function parameter as an array, the argument value
  5772. passed to the function is really a pointer to the array's zeroth
  5773. element. This value does not say how long the array really is, there
  5774. is no need to declare it. For example,
  5775. @example
  5776. int
  5777. func (int foo[])
  5778. @end example
  5779. @end itemize
  5780. These declarations are examples of @dfn{incomplete} array types, types
  5781. that are not fully specified. The incompleteness makes no difference
  5782. for accessing elements of the array, but it matters for some other
  5783. things. For instance, @code{sizeof} is not allowed on an incomplete
  5784. type.
  5785. With multidimensional arrays, only the first dimension can be omitted:
  5786. @example
  5787. extern struct chesspiece *funnyboard foo[][8];
  5788. @end example
  5789. In other words, the code doesn't have to say how many rows there are,
  5790. but it must state how big each row is.
  5791. @node Limitations of C Arrays
  5792. @section Limitations of C Arrays
  5793. @cindex limitations of C arrays
  5794. @cindex first-class object
  5795. Arrays have quirks in C because they are not ``first-class objects'':
  5796. there is no way in C to operate on an array as a unit.
  5797. The other composite objects in C, structures and unions, are
  5798. first-class objects: a C program can copy a structure or union value
  5799. in an assignment, or pass one as an argument to a function, or make a
  5800. function return one. You can't do those things with an array in C@.
  5801. That is because a value you can operate on never has an array type.
  5802. An expression in C can have an array type, but that doesn't produce
  5803. the array as a value. Instead it is converted automatically to a
  5804. pointer to the array's element at index zero. The code can operate
  5805. on the pointer, and through that on individual elements of the array,
  5806. but it can't get and operate on the array as a unit.
  5807. There are three exceptions to this conversion rule, but none of them
  5808. offers a way to operate on the array as a whole.
  5809. First, @samp{&} applied to an expression with array type gives you the
  5810. address of the array, as an array type. However, you can't operate on the
  5811. whole array that way---if you apply @samp{*} to get the array back,
  5812. that expression converts, as usual, to a pointer to its zeroth
  5813. element.
  5814. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5815. @code{typeof} do not convert the array to a pointer; they leave it as
  5816. an array. But they don't operate on the array's data---they only give
  5817. information about its type.
  5818. Third, a string constant used as an initializer for an array is not
  5819. converted to a pointer---rather, the declaration copies the
  5820. @emph{contents} of that string in that one special case.
  5821. You @emph{can} copy the contents of an array, just not with an
  5822. assignment operator. You can do it by calling the library function
  5823. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5824. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5825. when a structure contains just an array, you can copy that structure.
  5826. An array itself is an lvalue if it is a declared variable, or part of
  5827. a structure or union that is an lvalue. When you construct an array
  5828. from elements (@pxref{Constructing Array Values}), that array is not
  5829. an lvalue.
  5830. @node Multidimensional Arrays
  5831. @section Multidimensional Arrays
  5832. @cindex multidimensional arrays
  5833. @cindex array, multidimensional
  5834. Strictly speaking, all arrays in C are unidimensional. However, you
  5835. can create an array of arrays, which is more or less equivalent to a
  5836. multidimensional array. For example,
  5837. @example
  5838. struct chesspiece *board[8][8];
  5839. @end example
  5840. @noindent
  5841. declares an array of 8 arrays of 8 pointers to @code{struct
  5842. chesspiece}. This data type could represent the state of a chess
  5843. game. To access one square's contents requires two array index
  5844. operations, one for each dimension. For instance, you can write
  5845. @code{board[row][column]}, assuming @code{row} and @code{column}
  5846. are variables with integer values in the proper range.
  5847. How does C understand @code{board[row][column]}? First of all,
  5848. @code{board} is converted automatically to a pointer to the zeroth
  5849. element (at index zero) of @code{board}. Adding @code{row} to that
  5850. makes it point to the desired element. Thus, @code{board[row]}'s
  5851. value is an element of @code{board}---an array of 8 pointers.
  5852. However, as an expression with array type, it is converted
  5853. automatically to a pointer to the array's zeroth element. The second
  5854. array index operation, @code{[column]}, accesses the chosen element
  5855. from that array.
  5856. As this shows, pointer-to-array types are meaningful in C@.
  5857. You can declare a variable that points to a row in a chess board
  5858. like this:
  5859. @example
  5860. struct chesspiece *(*rowptr)[8];
  5861. @end example
  5862. @noindent
  5863. This points to an array of 8 pointers to @code{struct chesspiece}.
  5864. You can assign to it as follows:
  5865. @example
  5866. rowptr = &board[5];
  5867. @end example
  5868. The dimensions don't have to be equal in length. Here we declare
  5869. @code{statepop} as an array to hold the population of each state in
  5870. the United States for each year since 1900:
  5871. @example
  5872. #define NSTATES 50
  5873. @{
  5874. int nyears = current_year - 1900 + 1;
  5875. int statepop[NSTATES][nyears];
  5876. @r{@dots{}}
  5877. @}
  5878. @end example
  5879. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5880. each indexed by the year (counting from 1900). Thus, to get the
  5881. element for a particular state and year, we must subscript it first
  5882. by the number that indicates the state, and second by the index for
  5883. the year:
  5884. @example
  5885. statepop[state][year - 1900]
  5886. @end example
  5887. @cindex array, layout in memory
  5888. The subarrays within the multidimensional array are allocated
  5889. consecutively in memory, and within each subarray, its elements are
  5890. allocated consecutively in memory. The most efficient way to process
  5891. all the elements in the array is to scan the last subscript in the
  5892. innermost loop. This means consecutive accesses go to consecutive
  5893. memory locations, which optimizes use of the processor's memory cache.
  5894. For example:
  5895. @example
  5896. int total = 0;
  5897. float average;
  5898. for (int state = 0; state < NSTATES, ++state)
  5899. @{
  5900. for (int year = 0; year < nyears; ++year)
  5901. @{
  5902. total += statepop[state][year];
  5903. @}
  5904. @}
  5905. average = total / nyears;
  5906. @end example
  5907. C's layout for multidimensional arrays is different from Fortran's
  5908. layout. In Fortran, a multidimensional array is not an array of
  5909. arrays; rather, multidimensional arrays are a primitive feature, and
  5910. it is the first index that varies most rapidly between consecutive
  5911. memory locations. Thus, the memory layout of a 50x114 array in C
  5912. matches that of a 114x50 array in Fortran.
  5913. @node Constructing Array Values
  5914. @section Constructing Array Values
  5915. @cindex constructing array values
  5916. @cindex array values, constructing
  5917. You can construct an array from elements by writing them inside
  5918. braces, and preceding all that with the array type's designator in
  5919. parentheses. There is no need to specify the array length, since the
  5920. number of elements determines that. The constructor looks like this:
  5921. @example
  5922. (@var{elttype}[]) @{ @var{elements} @};
  5923. @end example
  5924. Here is an example, which constructs an array of string pointers:
  5925. @example
  5926. (char *[]) @{ "x", "y", "z" @};
  5927. @end example
  5928. That's equivalent in effect to declaring an array with the same
  5929. initializer, like this:
  5930. @example
  5931. char *array[] = @{ "x", "y", "z" @};
  5932. @end example
  5933. and then using the array.
  5934. If all the elements are simple constant expressions, or made up of
  5935. such, then the compound literal can be coerced to a pointer to its
  5936. zeroth element and used to initialize a file-scope variable
  5937. (@pxref{File-Scope Variables}), as shown here:
  5938. @example
  5939. char **foo = (char *[]) @{ "x", "y", "z" @};
  5940. @end example
  5941. @noindent
  5942. The data type of @code{foo} is @code{char **}, which is a pointer
  5943. type, not an array type. The declaration is equivalent to defining
  5944. and then using an array-type variable:
  5945. @example
  5946. char *nameless_array[] = @{ "x", "y", "z" @};
  5947. char **foo = &nameless_array[0];
  5948. @end example
  5949. @node Arrays of Variable Length
  5950. @section Arrays of Variable Length
  5951. @cindex array of variable length
  5952. @cindex variable-length arrays
  5953. In GNU C, you can declare variable-length arrays like any other
  5954. arrays, but with a length that is not a constant expression. The
  5955. storage is allocated at the point of declaration and deallocated when
  5956. the block scope containing the declaration exits. For example:
  5957. @example
  5958. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5959. #include <string.h> /* @r{Declares @code{str}.} */
  5960. FILE *
  5961. concat_fopen (char *s1, char *s2, char *mode)
  5962. @{
  5963. char str[strlen (s1) + strlen (s2) + 1];
  5964. strcpy (str, s1);
  5965. strcat (str, s2);
  5966. return fopen (str, mode);
  5967. @}
  5968. @end example
  5969. @noindent
  5970. (This uses some standard library functions; see @ref{String and Array
  5971. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5972. The length of an array is computed once when the storage is allocated
  5973. and is remembered for the scope of the array in case it is used in
  5974. @code{sizeof}.
  5975. @strong{Warning:} don't allocate a variable-length array if the size
  5976. might be very large (more than 100,000), or in a recursive function,
  5977. because that is likely to cause stack overflow. Allocate the array
  5978. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5979. Jumping or breaking out of the scope of the array name deallocates the
  5980. storage. Jumping into the scope is not allowed; that gives an error
  5981. message.
  5982. You can also use variable-length arrays as arguments to functions:
  5983. @example
  5984. struct entry
  5985. tester (int len, char data[len][len])
  5986. @{
  5987. @r{@dots{}}
  5988. @}
  5989. @end example
  5990. As usual, a function argument declared with an array type
  5991. is really a pointer to an array that already exists.
  5992. Calling the function does not allocate the array, so there's no
  5993. particular danger of stack overflow in using this construct.
  5994. To pass the array first and the length afterward, use a forward
  5995. declaration in the function's parameter list (another GNU extension).
  5996. For example,
  5997. @example
  5998. struct entry
  5999. tester (int len; char data[len][len], int len)
  6000. @{
  6001. @r{@dots{}}
  6002. @}
  6003. @end example
  6004. The @code{int len} before the semicolon is a @dfn{parameter forward
  6005. declaration}, and it serves the purpose of making the name @code{len}
  6006. known when the declaration of @code{data} is parsed.
  6007. You can write any number of such parameter forward declarations in the
  6008. parameter list. They can be separated by commas or semicolons, but
  6009. the last one must end with a semicolon, which is followed by the
  6010. ``real'' parameter declarations. Each forward declaration must match
  6011. a ``real'' declaration in parameter name and data type. ISO C11 does
  6012. not support parameter forward declarations.
  6013. @node Enumeration Types
  6014. @chapter Enumeration Types
  6015. @cindex enumeration types
  6016. @cindex types, enumeration
  6017. @cindex enumerator
  6018. An @dfn{enumeration type} represents a limited set of integer values,
  6019. each with a name. It is effectively equivalent to a primitive integer
  6020. type.
  6021. Suppose we have a list of possible emotional states to store in an
  6022. integer variable. We can give names to these alternative values with
  6023. an enumeration:
  6024. @example
  6025. enum emotion_state @{ neutral, happy, sad, worried,
  6026. calm, nervous @};
  6027. @end example
  6028. @noindent
  6029. (Never mind that this is a simplistic way to classify emotional states;
  6030. it's just a code example.)
  6031. The names inside the enumeration are called @dfn{enumerators}. The
  6032. enumeration type defines them as constants, and their values are
  6033. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  6034. @code{sad} is 2, and so on. Alternatively, you can specify values for
  6035. the enumerators explicitly like this:
  6036. @example
  6037. enum emotion_state @{ neutral = 2, happy = 5,
  6038. sad = 20, worried = 10,
  6039. calm = -5, nervous = -300 @};
  6040. @end example
  6041. Each enumerator which does not specify a value gets value zero
  6042. (if it is at the beginning) or the next consecutive integer.
  6043. @example
  6044. /* @r{@code{neutral} is 0 by default,}
  6045. @r{and @code{worried} is 21 by default.} */
  6046. enum emotion_state @{ neutral,
  6047. happy = 5, sad = 20, worried,
  6048. calm = -5, nervous = -300 @};
  6049. @end example
  6050. If an enumerator is obsolete, you can specify that using it should
  6051. cause a warning, by including an attribute in the enumerator's
  6052. declaration. Here is how @code{happy} would look with this
  6053. attribute:
  6054. @example
  6055. happy __attribute__
  6056. ((deprecated
  6057. ("impossible under plutocratic rule")))
  6058. = 5,
  6059. @end example
  6060. @xref{Attributes}.
  6061. You can declare variables with the enumeration type:
  6062. @example
  6063. enum emotion_state feelings_now;
  6064. @end example
  6065. In the C code itself, this is equivalent to declaring the variable
  6066. @code{int}. (If all the enumeration values are positive, it is
  6067. equivalent to @code{unsigned int}.) However, declaring it with the
  6068. enumeration type has an advantage in debugging, because GDB knows it
  6069. should display the current value of the variable using the
  6070. corresponding name. If the variable's type is @code{int}, GDB can
  6071. only show the value as a number.
  6072. The identifier that follows @code{enum} is called a @dfn{type tag}
  6073. since it distinguishes different enumeration types. Type tags are in
  6074. a separate name space and belong to scopes like most other names in C@.
  6075. @xref{Type Tags}, for explanation.
  6076. You can predeclare an @code{enum} type tag like a structure or union
  6077. type tag, like this:
  6078. @example
  6079. enum foo;
  6080. @end example
  6081. @noindent
  6082. The @code{enum} type is incomplete until you finish defining it.
  6083. You can optionally include a trailing comma at the end of a list of
  6084. enumeration values:
  6085. @example
  6086. enum emotion_state @{ neutral, happy, sad, worried,
  6087. calm, nervous, @};
  6088. @end example
  6089. @noindent
  6090. This is useful in some macro definitions, since it enables you to
  6091. assemble the list of enumerators without knowing which one is last.
  6092. The extra comma does not change the meaning of the enumeration in any
  6093. way.
  6094. @node Defining Typedef Names
  6095. @chapter Defining Typedef Names
  6096. @cindex typedef names
  6097. @findex typedef
  6098. You can define a data type keyword as an alias for any type, and then
  6099. use the alias syntactically like a built-in type keyword such as
  6100. @code{int}. You do this using @code{typedef}, so these aliases are
  6101. also called @dfn{typedef names}.
  6102. @code{typedef} is followed by text that looks just like a variable
  6103. declaration, but instead of declaring variables it defines data type
  6104. keywords.
  6105. Here's how to define @code{fooptr} as a typedef alias for the type
  6106. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  6107. with that type:
  6108. @example
  6109. typedef struct foo *fooptr;
  6110. fooptr x, y;
  6111. @end example
  6112. @noindent
  6113. That declaration is equivalent to the following one:
  6114. @example
  6115. struct foo *x, *y;
  6116. @end example
  6117. You can define a typedef alias for any type. For instance, this makes
  6118. @code{frobcount} an alias for type @code{int}:
  6119. @example
  6120. typedef int frobcount;
  6121. @end example
  6122. @noindent
  6123. This doesn't define a new type distinct from @code{int}. Rather,
  6124. @code{frobcount} is another name for the type @code{int}. Once the
  6125. variable is declared, it makes no difference which name the
  6126. declaration used.
  6127. There is a syntactic difference, however, between @code{frobcount} and
  6128. @code{int}: A typedef name cannot be used with
  6129. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6130. to specify the type all by itself. So you can't write this:
  6131. @example
  6132. unsigned frobcount f1; /* @r{Error!} */
  6133. @end example
  6134. But you can write this:
  6135. @example
  6136. typedef unsigned int unsigned_frobcount;
  6137. unsigned_frobcount f1;
  6138. @end example
  6139. In other words, a typedef name is not an alias for @emph{a keyword}
  6140. such as @code{int}. It stands for a @emph{type}, and that could be
  6141. the type @code{int}.
  6142. Typedef names are in the same namespace as functions and variables, so
  6143. you can't use the same name for a typedef and a function, or a typedef
  6144. and a variable. When a typedef is declared inside a code block, it is
  6145. in scope only in that block.
  6146. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6147. because many of these have standard meanings.
  6148. You can redefine a typedef name to the exact same type as its first
  6149. definition, but you cannot redefine a typedef name to a
  6150. different type, even if the two types are compatible. For example, this
  6151. is valid:
  6152. @example
  6153. typedef int frobcount;
  6154. typedef int frotzcount;
  6155. typedef frotzcount frobcount;
  6156. typedef frobcount frotzcount;
  6157. @end example
  6158. @noindent
  6159. because each typedef name is always defined with the same type
  6160. (@code{int}), but this is not valid:
  6161. @example
  6162. enum foo @{f1, f2, f3@};
  6163. typedef enum foo frobcount;
  6164. typedef int frobcount;
  6165. @end example
  6166. @noindent
  6167. Even though the type @code{enum foo} is compatible with @code{int},
  6168. they are not the @emph{same} type.
  6169. @node Statements
  6170. @chapter Statements
  6171. @cindex statements
  6172. A @dfn{statement} specifies computations to be done for effect; it
  6173. does not produce a value, as an expression would. In general a
  6174. statement ends with a semicolon (@samp{;}), but blocks (which are
  6175. statements, more or less) are an exception to that rule.
  6176. @ifnottex
  6177. @xref{Blocks}.
  6178. @end ifnottex
  6179. The places to use statements are inside a block, and inside a
  6180. complex statement. A @dfn{complex statement} contains one or two
  6181. components that are nested statements. Each such component must
  6182. consist of one and only one statement. The way to put multiple
  6183. statements in such a component is to group them into a @dfn{block}
  6184. (@pxref{Blocks}), which counts as one statement.
  6185. The following sections describe the various kinds of statement.
  6186. @menu
  6187. * Expression Statement:: Evaluate an expression, as a statement,
  6188. usually done for a side effect.
  6189. * if Statement:: Basic conditional execution.
  6190. * if-else Statement:: Multiple branches for conditional execution.
  6191. * Blocks:: Grouping multiple statements together.
  6192. * return Statement:: Return a value from a function.
  6193. * Loop Statements:: Repeatedly executing a statement or block.
  6194. * switch Statement:: Multi-way conditional choices.
  6195. * switch Example:: A plausible example of using @code{switch}.
  6196. * Duffs Device:: A special way to use @code{switch}.
  6197. * Case Ranges:: Ranges of values for @code{switch} cases.
  6198. * Null Statement:: A statement that does nothing.
  6199. * goto Statement:: Jump to another point in the source code,
  6200. identified by a label.
  6201. * Local Labels:: Labels with limited scope.
  6202. * Labels as Values:: Getting the address of a label.
  6203. * Statement Exprs:: A series of statements used as an expression.
  6204. @end menu
  6205. @node Expression Statement
  6206. @section Expression Statement
  6207. @cindex expression statement
  6208. @cindex statement, expression
  6209. The most common kind of statement in C is an @dfn{expression statement}.
  6210. It consists of an expression followed by a
  6211. semicolon. The expression's value is discarded, so the expressions
  6212. that are useful are those that have side effects: assignment
  6213. expressions, increment and decrement expressions, and function calls.
  6214. Here are examples of expression statements:
  6215. @smallexample
  6216. x = 5; /* @r{Assignment expression.} */
  6217. p++; /* @r{Increment expression.} */
  6218. printf ("Done\n"); /* @r{Function call expression.} */
  6219. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6220. x + y; /* @r{Useless statement without effect.} */
  6221. @end smallexample
  6222. In very unusual circumstances we use an expression statement
  6223. whose purpose is to get a fault if an address is invalid:
  6224. @smallexample
  6225. volatile char *p;
  6226. @r{@dots{}}
  6227. *p; /* @r{Cause signal if @code{p} is null.} */
  6228. @end smallexample
  6229. If the target of @code{p} is not declared @code{volatile}, the
  6230. compiler might optimize away the memory access, since it knows that
  6231. the value isn't really used. @xref{volatile}.
  6232. @node if Statement
  6233. @section @code{if} Statement
  6234. @cindex @code{if} statement
  6235. @cindex statement, @code{if}
  6236. @findex if
  6237. An @code{if} statement computes an expression to decide
  6238. whether to execute the following statement or not.
  6239. It looks like this:
  6240. @example
  6241. if (@var{condition})
  6242. @var{execute-if-true}
  6243. @end example
  6244. The first thing this does is compute the value of @var{condition}. If
  6245. that is true (nonzero), then it executes the statement
  6246. @var{execute-if-true}. If the value of @var{condition} is false
  6247. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6248. nothing.
  6249. This is a @dfn{complex statement} because it contains a component
  6250. @var{if-true-substatement} that is a nested statement. It must be one
  6251. and only one statement. The way to put multiple statements there is
  6252. to group them into a @dfn{block} (@pxref{Blocks}).
  6253. @node if-else Statement
  6254. @section @code{if-else} Statement
  6255. @cindex @code{if}@dots{}@code{else} statement
  6256. @cindex statement, @code{if}@dots{}@code{else}
  6257. @findex else
  6258. An @code{if}-@code{else} statement computes an expression to decide
  6259. which of two nested statements to execute.
  6260. It looks like this:
  6261. @example
  6262. if (@var{condition})
  6263. @var{if-true-substatement}
  6264. else
  6265. @var{if-false-substatement}
  6266. @end example
  6267. The first thing this does is compute the value of @var{condition}. If
  6268. that is true (nonzero), then it executes the statement
  6269. @var{if-true-substatement}. If the value of @var{condition} is false
  6270. (zero), then it executes the statement @var{if-false-substatement} instead.
  6271. This is a @dfn{complex statement} because it contains components
  6272. @var{if-true-substatement} and @var{if-else-substatement} that are
  6273. nested statements. Each must be one and only one statement. The way
  6274. to put multiple statements in such a component is to group them into a
  6275. @dfn{block} (@pxref{Blocks}).
  6276. @node Blocks
  6277. @section Blocks
  6278. @cindex block
  6279. @cindex compound statement
  6280. A @dfn{block} is a construct that contains multiple statements of any
  6281. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6282. series of statements and declarations in between. Another name for
  6283. blocks is @dfn{compound statements}.
  6284. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6285. normal statement---it does not end with a semicolon. But you can
  6286. @emph{use} it like a statement; anywhere that a statement is required
  6287. or allowed, you can write a block and consider that block a statement.
  6288. So far it seems that a block is a kind of statement with an unusual
  6289. syntax. But that is not entirely true: a function body is also a
  6290. block, and that block is definitely not a statement. The text after a
  6291. function header is not treated as a statement; only a function body is
  6292. allowed there, and nothing else would be meaningful there.
  6293. In a formal grammar we would have to choose---either a block is a kind
  6294. of statement or it is not. But this manual is meant for humans, not
  6295. for parser generators. The clearest answer for humans is, ``a block
  6296. is a statement, in some ways.''
  6297. @cindex nested block
  6298. @cindex internal block
  6299. A block that isn't a function body is called an @dfn{internal block}
  6300. or a @dfn{nested block}. You can put a nested block directly inside
  6301. another block, but more often the nested block is inside some complex
  6302. statement, such as a @code{for} statement or an @code{if} statement.
  6303. There are two uses for nested blocks in C:
  6304. @itemize @bullet
  6305. @item
  6306. To specify the scope for local declarations. For instance, a local
  6307. variable's scope is the rest of the innermost containing block.
  6308. @item
  6309. To write a series of statements where, syntactically, one statement is
  6310. called for. For instance, the @var{execute-if-true} of an @code{if}
  6311. statement is one statement. To put multiple statements there, they
  6312. have to be wrapped in a block, like this:
  6313. @example
  6314. if (x < 0)
  6315. @{
  6316. printf ("x was negative\n");
  6317. x = -x;
  6318. @}
  6319. @end example
  6320. @end itemize
  6321. This example (repeated from above) shows a nested block which serves
  6322. both purposes: it includes two statements (plus a declaration) in the
  6323. body of a @code{while} statement, and it provides the scope for the
  6324. declaration of @code{q}.
  6325. @example
  6326. void
  6327. free_intlist (struct intlistlink *p)
  6328. @{
  6329. while (p)
  6330. @{
  6331. struct intlistlink *q = p;
  6332. p = p->next;
  6333. free (q);
  6334. @}
  6335. @}
  6336. @end example
  6337. @node return Statement
  6338. @section @code{return} Statement
  6339. @cindex @code{return} statement
  6340. @cindex statement, @code{return}
  6341. @findex return
  6342. The @code{return} statement makes the containing function return
  6343. immediately. It has two forms. This one specifies no value to
  6344. return:
  6345. @example
  6346. return;
  6347. @end example
  6348. @noindent
  6349. That form is meant for functions whose return type is @code{void}
  6350. (@pxref{The Void Type}). You can also use it in a function that
  6351. returns nonvoid data, but that's a bad idea, since it makes the
  6352. function return garbage.
  6353. The form that specifies a value looks like this:
  6354. @example
  6355. return @var{value};
  6356. @end example
  6357. @noindent
  6358. which computes the expression @var{value} and makes the function
  6359. return that. If necessary, the value undergoes type conversion to
  6360. the function's declared return value type, which works like
  6361. assigning the value to a variable of that type.
  6362. @node Loop Statements
  6363. @section Loop Statements
  6364. @cindex loop statements
  6365. @cindex statements, loop
  6366. @cindex iteration
  6367. You can use a loop statement when you need to execute a series of
  6368. statements repeatedly, making an @dfn{iteration}. C provides several
  6369. different kinds of loop statements, described in the following
  6370. subsections.
  6371. Every kind of loop statement is a complex statement because contains a
  6372. component, here called @var{body}, which is a nested statement.
  6373. Most often the body is a block.
  6374. @menu
  6375. * while Statement:: Loop as long as a test expression is true.
  6376. * do-while Statement:: Execute a loop once, with further looping
  6377. as long as a test expression is true.
  6378. * break Statement:: End a loop immediately.
  6379. * for Statement:: Iterative looping.
  6380. * Example of for:: An example of iterative looping.
  6381. * Omitted for-Expressions:: for-loop expression options.
  6382. * for-Index Declarations:: for-loop declaration options.
  6383. * continue Statement:: Begin the next cycle of a loop.
  6384. @end menu
  6385. @node while Statement
  6386. @subsection @code{while} Statement
  6387. @cindex @code{while} statement
  6388. @cindex statement, @code{while}
  6389. @findex while
  6390. The @code{while} statement is the simplest loop construct.
  6391. It looks like this:
  6392. @example
  6393. while (@var{test})
  6394. @var{body}
  6395. @end example
  6396. Here, @var{body} is a statement (often a nested block) to repeat, and
  6397. @var{test} is the test expression that controls whether to repeat it again.
  6398. Each iteration of the loop starts by computing @var{test} and, if it
  6399. is true (nonzero), that means the loop should execute @var{body} again
  6400. and then start over.
  6401. Here's an example of advancing to the last structure in a chain of
  6402. structures chained through the @code{next} field:
  6403. @example
  6404. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6405. @r{@dots{}}
  6406. while (chain->next != NULL)
  6407. chain = chain->next;
  6408. @end example
  6409. @noindent
  6410. This code assumes the chain isn't empty to start with; if the chain is
  6411. empty (that is, if @code{chain} is a null pointer), the code gets a
  6412. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6413. @node do-while Statement
  6414. @subsection @code{do-while} Statement
  6415. @cindex @code{do}--@code{while} statement
  6416. @cindex statement, @code{do}--@code{while}
  6417. @findex do
  6418. The @code{do}--@code{while} statement is a simple loop construct that
  6419. performs the test at the end of the iteration.
  6420. @example
  6421. do
  6422. @var{body}
  6423. while (@var{test});
  6424. @end example
  6425. Here, @var{body} is a statement (possibly a block) to repeat, and
  6426. @var{test} is an expression that controls whether to repeat it again.
  6427. Each iteration of the loop starts by executing @var{body}. Then it
  6428. computes @var{test} and, if it is true (nonzero), that means to go
  6429. back and start over with @var{body}. If @var{test} is false (zero),
  6430. then the loop stops repeating and execution moves on past it.
  6431. @node break Statement
  6432. @subsection @code{break} Statement
  6433. @cindex @code{break} statement
  6434. @cindex statement, @code{break}
  6435. @findex break
  6436. The @code{break} statement looks like @samp{break;}. Its effect is to
  6437. exit immediately from the innermost loop construct or @code{switch}
  6438. statement (@pxref{switch Statement}).
  6439. For example, this loop advances @code{p} until the next null
  6440. character or newline.
  6441. @example
  6442. while (*p)
  6443. @{
  6444. /* @r{End loop if we have reached a newline.} */
  6445. if (*p == '\n')
  6446. break;
  6447. p++
  6448. @}
  6449. @end example
  6450. When there are nested loops, the @code{break} statement exits from the
  6451. innermost loop containing it.
  6452. @example
  6453. struct list_if_tuples
  6454. @{
  6455. struct list_if_tuples next;
  6456. int length;
  6457. data *contents;
  6458. @};
  6459. void
  6460. process_all_elements (struct list_if_tuples *list)
  6461. @{
  6462. while (list)
  6463. @{
  6464. /* @r{Process all the elements in this node's vector,}
  6465. @r{stopping when we reach one that is null.} */
  6466. for (i = 0; i < list->length; i++
  6467. @{
  6468. /* @r{Null element terminates this node's vector.} */
  6469. if (list->contents[i] == NULL)
  6470. /* @r{Exit the @code{for} loop.} */
  6471. break;
  6472. /* @r{Operate on the next element.} */
  6473. process_element (list->contents[i]);
  6474. @}
  6475. list = list->next;
  6476. @}
  6477. @}
  6478. @end example
  6479. The only way in C to exit from an outer loop is with
  6480. @code{goto} (@pxref{goto Statement}).
  6481. @node for Statement
  6482. @subsection @code{for} Statement
  6483. @cindex @code{for} statement
  6484. @cindex statement, @code{for}
  6485. @findex for
  6486. A @code{for} statement uses three expressions written inside a
  6487. parenthetical group to define the repetition of the loop. The first
  6488. expression says how to prepare to start the loop. The second says how
  6489. to test, before each iteration, whether to continue looping. The
  6490. third says how to advance, at the end of an iteration, for the next
  6491. iteration. All together, it looks like this:
  6492. @example
  6493. for (@var{start}; @var{continue-test}; @var{advance})
  6494. @var{body}
  6495. @end example
  6496. The first thing the @code{for} statement does is compute @var{start}.
  6497. The next thing it does is compute the expression @var{continue-test}.
  6498. If that expression is false (zero), the @code{for} statement finishes
  6499. immediately, so @var{body} is executed zero times.
  6500. However, if @var{continue-test} is true (nonzero), the @code{for}
  6501. statement executes @var{body}, then @var{advance}. Then it loops back
  6502. to the not-quite-top to test @var{continue-test} again. But it does
  6503. not compute @var{start} again.
  6504. @node Example of for
  6505. @subsection Example of @code{for}
  6506. Here is the @code{for} statement from the iterative Fibonacci
  6507. function:
  6508. @example
  6509. int i;
  6510. for (i = 1; i < n; ++i)
  6511. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6512. /* @r{since @code{i < n} is false the first time.} */
  6513. @{
  6514. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6515. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6516. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6517. int next = prev + last;
  6518. /* @r{Shift the values down.} */
  6519. prev = last;
  6520. last = next;
  6521. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6522. @r{and @var{prev} is @code{fib (@var{i})}.}
  6523. @r{But that won't stay true for long,}
  6524. @r{because we are about to increment @var{i}.} */
  6525. @}
  6526. @end example
  6527. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6528. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6529. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6530. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6531. that contains a declaration and two statements.
  6532. @node Omitted for-Expressions
  6533. @subsection Omitted @code{for}-Expressions
  6534. A fully-fleshed @code{for} statement contains all these parts,
  6535. @example
  6536. for (@var{start}; @var{continue-test}; @var{advance})
  6537. @var{body}
  6538. @end example
  6539. @noindent
  6540. but you can omit any of the three expressions inside the parentheses.
  6541. The parentheses and the two semicolons are required syntactically, but
  6542. the expressions between them may be missing. A missing expression
  6543. means this loop doesn't use that particular feature of the @code{for}
  6544. statement.
  6545. @c ??? You can't do this if START is a declaration.
  6546. Instead of using @var{start}, you can do the loop preparation
  6547. before the @code{for} statement: the effect is the same. So we
  6548. could have written the beginning of the previous example this way:
  6549. @example
  6550. int i = 0;
  6551. for (; i < n; ++i)
  6552. @end example
  6553. @noindent
  6554. instead of this way:
  6555. @example
  6556. int i;
  6557. for (i = 0; i < n; ++i)
  6558. @end example
  6559. Omitting @var{continue-test} means the loop runs forever (or until
  6560. something else causes exit from it). Statements inside the loop can
  6561. test conditions for termination and use @samp{break;} to exit. This
  6562. is more flexible since you can put those tests anywhere in the loop,
  6563. not solely at the beginning.
  6564. Putting an expression in @var{advance} is almost equivalent to writing
  6565. it at the end of the loop body; it does almost the same thing. The
  6566. only difference is for the @code{continue} statement (@pxref{continue
  6567. Statement}). So we could have written this:
  6568. @example
  6569. for (i = 0; i < n;)
  6570. @{
  6571. @r{@dots{}}
  6572. ++i;
  6573. @}
  6574. @end example
  6575. @noindent
  6576. instead of this:
  6577. @example
  6578. for (i = 0; i < n; ++i)
  6579. @{
  6580. @r{@dots{}}
  6581. @}
  6582. @end example
  6583. The choice is mainly a matter of what is more readable for
  6584. programmers. However, there is also a syntactic difference:
  6585. @var{advance} is an expression, not a statement. It can't include
  6586. loops, blocks, declarations, etc.
  6587. @node for-Index Declarations
  6588. @subsection @code{for}-Index Declarations
  6589. You can declare loop-index variables directly in the @var{start}
  6590. portion of the @code{for}-loop, like this:
  6591. @example
  6592. for (int i = 0; i < n; ++i)
  6593. @{
  6594. @r{@dots{}}
  6595. @}
  6596. @end example
  6597. This kind of @var{start} is limited to a single declaration; it can
  6598. declare one or more variables, separated by commas, all of which are
  6599. the same @var{basetype} (@code{int}, in this example):
  6600. @example
  6601. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6602. @{
  6603. @r{@dots{}}
  6604. @}
  6605. @end example
  6606. @noindent
  6607. The scope of these variables is the @code{for} statement as a whole.
  6608. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6609. Variables declared in @code{for} statements should have initializers.
  6610. Omitting the initialization gives the variables unpredictable initial
  6611. values, so this code is erroneous.
  6612. @example
  6613. for (int i; i < n; ++i)
  6614. @{
  6615. @r{@dots{}}
  6616. @}
  6617. @end example
  6618. @node continue Statement
  6619. @subsection @code{continue} Statement
  6620. @cindex @code{continue} statement
  6621. @cindex statement, @code{continue}
  6622. @findex continue
  6623. The @code{continue} statement looks like @samp{continue;}, and its
  6624. effect is to jump immediately to the end of the innermost loop
  6625. construct. If it is a @code{for}-loop, the next thing that happens
  6626. is to execute the loop's @var{advance} expression.
  6627. For example, this loop increments @code{p} until the next null character
  6628. or newline, and operates (in some way not shown) on all the characters
  6629. in the line except for spaces. All it does with spaces is skip them.
  6630. @example
  6631. for (;*p; ++p)
  6632. @{
  6633. /* @r{End loop if we have reached a newline.} */
  6634. if (*p == '\n')
  6635. break;
  6636. /* @r{Pay no attention to spaces.} */
  6637. if (*p == ' ')
  6638. continue;
  6639. /* @r{Operate on the next character.} */
  6640. @r{@dots{}}
  6641. @}
  6642. @end example
  6643. @noindent
  6644. Executing @samp{continue;} skips the loop body but it does not
  6645. skip the @var{advance} expression, @code{p++}.
  6646. We could also write it like this:
  6647. @example
  6648. for (;*p; ++p)
  6649. @{
  6650. /* @r{Exit if we have reached a newline.} */
  6651. if (*p == '\n')
  6652. break;
  6653. /* @r{Pay no attention to spaces.} */
  6654. if (*p != ' ')
  6655. @{
  6656. /* @r{Operate on the next character.} */
  6657. @r{@dots{}}
  6658. @}
  6659. @}
  6660. @end example
  6661. The advantage of using @code{continue} is that it reduces the
  6662. depth of nesting.
  6663. Contrast @code{continue} with the @code{break} statement. @xref{break
  6664. Statement}.
  6665. @node switch Statement
  6666. @section @code{switch} Statement
  6667. @cindex @code{switch} statement
  6668. @cindex statement, @code{switch}
  6669. @findex switch
  6670. @findex case
  6671. @findex default
  6672. The @code{switch} statement selects code to run according to the value
  6673. of an expression. The expression, in parentheses, follows the keyword
  6674. @code{switch}. After that come all the cases to select among,
  6675. inside braces. It looks like this:
  6676. @example
  6677. switch (@var{selector})
  6678. @{
  6679. @var{cases}@r{@dots{}}
  6680. @}
  6681. @end example
  6682. A case can look like this:
  6683. @example
  6684. case @var{value}:
  6685. @var{statements}
  6686. break;
  6687. @end example
  6688. @noindent
  6689. which means ``come here if @var{selector} happens to have the value
  6690. @var{value},'' or like this (a GNU C extension):
  6691. @example
  6692. case @var{rangestart} ... @var{rangeend}:
  6693. @var{statements}
  6694. break;
  6695. @end example
  6696. @noindent
  6697. which means ``come here if @var{selector} happens to have a value
  6698. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6699. Ranges}.
  6700. The values in @code{case} labels must reduce to integer constants.
  6701. They can use arithmetic, and @code{enum} constants, but they cannot
  6702. refer to data in memory, because they have to be computed at compile
  6703. time. It is an error if two @code{case} labels specify the same
  6704. value, or ranges that overlap, or if one is a range and the other is a
  6705. value in that range.
  6706. You can also define a default case to handle ``any other value,'' like
  6707. this:
  6708. @example
  6709. default:
  6710. @var{statements}
  6711. break;
  6712. @end example
  6713. If the @code{switch} statement has no @code{default:} label, then it
  6714. does nothing when the value matches none of the cases.
  6715. The brace-group inside the @code{switch} statement is a block, and you
  6716. can declare variables with that scope just as in any other block
  6717. (@pxref{Blocks}). However, initializers in these declarations won't
  6718. necessarily be executed every time the @code{switch} statement runs,
  6719. so it is best to avoid giving them initializers.
  6720. @code{break;} inside a @code{switch} statement exits immediately from
  6721. the @code{switch} statement. @xref{break Statement}.
  6722. If there is no @code{break;} at the end of the code for a case,
  6723. execution continues into the code for the following case. This
  6724. happens more often by mistake than intentionally, but since this
  6725. feature is used in real code, we cannot eliminate it.
  6726. @strong{Warning:} When one case is intended to fall through to the
  6727. next, write a comment like @samp{falls through} to say it's
  6728. intentional. That way, other programmers won't assume it was an error
  6729. and ``fix'' it erroneously.
  6730. Consecutive @code{case} statements could, pedantically, be considered
  6731. an instance of falling through, but we don't consider or treat them that
  6732. way because they won't confuse anyone.
  6733. @node switch Example
  6734. @section Example of @code{switch}
  6735. Here's an example of using the @code{switch} statement
  6736. to distinguish among characters:
  6737. @cindex counting vowels and punctuation
  6738. @example
  6739. struct vp @{ int vowels, punct; @};
  6740. struct vp
  6741. count_vowels_and_punct (char *string)
  6742. @{
  6743. int c;
  6744. int vowels = 0;
  6745. int punct = 0;
  6746. /* @r{Don't change the parameter itself.} */
  6747. /* @r{That helps in debugging.} */
  6748. char *p = string;
  6749. struct vp value;
  6750. while (c = *p++)
  6751. switch (c)
  6752. @{
  6753. case 'y':
  6754. case 'Y':
  6755. /* @r{We assume @code{y_is_consonant} will check surrounding
  6756. letters to determine whether this y is a vowel.} */
  6757. if (y_is_consonant (p - 1))
  6758. break;
  6759. /* @r{Falls through} */
  6760. case 'a':
  6761. case 'e':
  6762. case 'i':
  6763. case 'o':
  6764. case 'u':
  6765. case 'A':
  6766. case 'E':
  6767. case 'I':
  6768. case 'O':
  6769. case 'U':
  6770. vowels++;
  6771. break;
  6772. case '.':
  6773. case ',':
  6774. case ':':
  6775. case ';':
  6776. case '?':
  6777. case '!':
  6778. case '\"':
  6779. case '\'':
  6780. punct++;
  6781. break;
  6782. @}
  6783. value.vowels = vowels;
  6784. value.punct = punct;
  6785. return value;
  6786. @}
  6787. @end example
  6788. @node Duffs Device
  6789. @section Duff's Device
  6790. @cindex Duff's device
  6791. The cases in a @code{switch} statement can be inside other control
  6792. constructs. For instance, we can use a technique known as @dfn{Duff's
  6793. device} to optimize this simple function,
  6794. @example
  6795. void
  6796. copy (char *to, char *from, int count)
  6797. @{
  6798. while (count > 0)
  6799. *to++ = *from++, count--;
  6800. @}
  6801. @end example
  6802. @noindent
  6803. which copies memory starting at @var{from} to memory starting at
  6804. @var{to}.
  6805. Duff's device involves unrolling the loop so that it copies
  6806. several characters each time around, and using a @code{switch} statement
  6807. to enter the loop body at the proper point:
  6808. @example
  6809. void
  6810. copy (char *to, char *from, int count)
  6811. @{
  6812. if (count <= 0)
  6813. return;
  6814. int n = (count + 7) / 8;
  6815. switch (count % 8)
  6816. @{
  6817. do @{
  6818. case 0: *to++ = *from++;
  6819. case 7: *to++ = *from++;
  6820. case 6: *to++ = *from++;
  6821. case 5: *to++ = *from++;
  6822. case 4: *to++ = *from++;
  6823. case 3: *to++ = *from++;
  6824. case 2: *to++ = *from++;
  6825. case 1: *to++ = *from++;
  6826. @} while (--n > 0);
  6827. @}
  6828. @}
  6829. @end example
  6830. @node Case Ranges
  6831. @section Case Ranges
  6832. @cindex case ranges
  6833. @cindex ranges in case statements
  6834. You can specify a range of consecutive values in a single @code{case} label,
  6835. like this:
  6836. @example
  6837. case @var{low} ... @var{high}:
  6838. @end example
  6839. @noindent
  6840. This has the same effect as the proper number of individual @code{case}
  6841. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6842. This feature is especially useful for ranges of ASCII character codes:
  6843. @example
  6844. case 'A' ... 'Z':
  6845. @end example
  6846. @strong{Be careful:} with integers, write spaces around the @code{...}
  6847. to prevent it from being parsed wrong. For example, write this:
  6848. @example
  6849. case 1 ... 5:
  6850. @end example
  6851. @noindent
  6852. rather than this:
  6853. @example
  6854. case 1...5:
  6855. @end example
  6856. @node Null Statement
  6857. @section Null Statement
  6858. @cindex null statement
  6859. @cindex statement, null
  6860. A @dfn{null statement} is just a semicolon. It does nothing.
  6861. A null statement is a placeholder for use where a statement is
  6862. grammatically required, but there is nothing to be done. For
  6863. instance, sometimes all the work of a @code{for}-loop is done in the
  6864. @code{for}-header itself, leaving no work for the body. Here is an
  6865. example that searches for the first newline in @code{array}:
  6866. @example
  6867. for (p = array; *p != '\n'; p++)
  6868. ;
  6869. @end example
  6870. @node goto Statement
  6871. @section @code{goto} Statement and Labels
  6872. @cindex @code{goto} statement
  6873. @cindex statement, @code{goto}
  6874. @cindex label
  6875. @findex goto
  6876. The @code{goto} statement looks like this:
  6877. @example
  6878. goto @var{label};
  6879. @end example
  6880. @noindent
  6881. Its effect is to transfer control immediately to another part of the
  6882. current function---where the label named @var{label} is defined.
  6883. An ordinary label definition looks like this:
  6884. @example
  6885. @var{label}:
  6886. @end example
  6887. @noindent
  6888. and it can appear before any statement. You can't use @code{default}
  6889. as a label, since that has a special meaning for @code{switch}
  6890. statements.
  6891. An ordinary label doesn't need a separate declaration; defining it is
  6892. enough.
  6893. Here's an example of using @code{goto} to implement a loop
  6894. equivalent to @code{do}--@code{while}:
  6895. @example
  6896. @{
  6897. loop_restart:
  6898. @var{body}
  6899. if (@var{condition})
  6900. goto loop_restart;
  6901. @}
  6902. @end example
  6903. The name space of labels is separate from that of variables and functions.
  6904. Thus, there is no error in using a single name in both ways:
  6905. @example
  6906. @{
  6907. int foo; // @r{Variable @code{foo}.}
  6908. foo: // @r{Label @code{foo}.}
  6909. @var{body}
  6910. if (foo > 0) // @r{Variable @code{foo}.}
  6911. goto foo; // @r{Label @code{foo}.}
  6912. @}
  6913. @end example
  6914. Blocks have no effect on ordinary labels; each label name is defined
  6915. throughout the whole of the function it appears in. It looks strange to
  6916. jump into a block with @code{goto}, but it works. For example,
  6917. @example
  6918. if (x < 0)
  6919. goto negative;
  6920. if (y < 0)
  6921. @{
  6922. negative:
  6923. printf ("Negative\n");
  6924. return;
  6925. @}
  6926. @end example
  6927. If the goto jumps into the scope of a variable, it does not
  6928. initialize the variable. For example, if @code{x} is negative,
  6929. @example
  6930. if (x < 0)
  6931. goto negative;
  6932. if (y < 0)
  6933. @{
  6934. int i = 5;
  6935. negative:
  6936. printf ("Negative, and i is %d\n", i);
  6937. return;
  6938. @}
  6939. @end example
  6940. @noindent
  6941. prints junk because @code{i} was not initialized.
  6942. If the block declares a variable-length automatic array, jumping into
  6943. it gives a compilation error. However, jumping out of the scope of a
  6944. variable-length array works fine, and deallocates its storage.
  6945. A label can't come directly before a declaration, so the code can't
  6946. jump directly to one. For example, this is not allowed:
  6947. @example
  6948. @{
  6949. goto foo;
  6950. foo:
  6951. int x = 5;
  6952. bar(&x);
  6953. @}
  6954. @end example
  6955. @noindent
  6956. The workaround is to add a statement, even an empty statement,
  6957. directly after the label. For example:
  6958. @example
  6959. @{
  6960. goto foo;
  6961. foo:
  6962. ;
  6963. int x = 5;
  6964. bar(&x);
  6965. @}
  6966. @end example
  6967. Likewise, a label can't be the last thing in a block. The workaround
  6968. solution is the same: add a semicolon after the label.
  6969. These unnecessary restrictions on labels make no sense, and ought in
  6970. principle to be removed; but they do only a little harm since labels
  6971. and @code{goto} are rarely the best way to write a program.
  6972. These examples are all artificial; it would be more natural to
  6973. write them in other ways, without @code{goto}. For instance,
  6974. the clean way to write the example that prints @samp{Negative} is this:
  6975. @example
  6976. if (x < 0 || y < 0)
  6977. @{
  6978. printf ("Negative\n");
  6979. return;
  6980. @}
  6981. @end example
  6982. @noindent
  6983. It is hard to construct simple examples where @code{goto} is actually
  6984. the best way to write a program. Its rare good uses tend to be in
  6985. complex code, thus not apt for the purpose of explaining the meaning
  6986. of @code{goto}.
  6987. The only good time to use @code{goto} is when it makes the code
  6988. simpler than any alternative. Jumping backward is rarely desirable,
  6989. because usually the other looping and control constructs give simpler
  6990. code. Using @code{goto} to jump forward is more often desirable, for
  6991. instance when a function needs to do some processing in an error case
  6992. and errors can occur at various different places within the function.
  6993. @node Local Labels
  6994. @section Locally Declared Labels
  6995. @cindex local labels
  6996. @cindex macros, local labels
  6997. @findex __label__
  6998. In GNU C you can declare @dfn{local labels} in any nested block
  6999. scope. A local label is used in a @code{goto} statement just like an
  7000. ordinary label, but you can only reference it within the block in
  7001. which it was declared.
  7002. A local label declaration looks like this:
  7003. @example
  7004. __label__ @var{label};
  7005. @end example
  7006. @noindent
  7007. or
  7008. @example
  7009. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  7010. @end example
  7011. Local label declarations must come at the beginning of the block,
  7012. before any ordinary declarations or statements.
  7013. The label declaration declares the label @emph{name}, but does not define
  7014. the label itself. That's done in the usual way, with
  7015. @code{@var{label}:}, before one of the statements in the block.
  7016. The local label feature is useful for complex macros. If a macro
  7017. contains nested loops, a @code{goto} can be useful for breaking out of
  7018. them. However, an ordinary label whose scope is the whole function
  7019. cannot be used: if the macro can be expanded several times in one
  7020. function, the label will be multiply defined in that function. A
  7021. local label avoids this problem. For example:
  7022. @example
  7023. #define SEARCH(value, array, target) \
  7024. do @{ \
  7025. __label__ found; \
  7026. __auto_type _SEARCH_target = (target); \
  7027. __auto_type _SEARCH_array = (array); \
  7028. int i, j; \
  7029. int value; \
  7030. for (i = 0; i < max; i++) \
  7031. for (j = 0; j < max; j++) \
  7032. if (_SEARCH_array[i][j] == _SEARCH_target) \
  7033. @{ (value) = i; goto found; @} \
  7034. (value) = -1; \
  7035. found:; \
  7036. @} while (0)
  7037. @end example
  7038. This could also be written using a statement expression
  7039. (@pxref{Statement Exprs}):
  7040. @example
  7041. #define SEARCH(array, target) \
  7042. (@{ \
  7043. __label__ found; \
  7044. __auto_type _SEARCH_target = (target); \
  7045. __auto_type _SEARCH_array = (array); \
  7046. int i, j; \
  7047. int value; \
  7048. for (i = 0; i < max; i++) \
  7049. for (j = 0; j < max; j++) \
  7050. if (_SEARCH_array[i][j] == _SEARCH_target) \
  7051. @{ value = i; goto found; @} \
  7052. value = -1; \
  7053. found: \
  7054. value; \
  7055. @})
  7056. @end example
  7057. Ordinary labels are visible throughout the function where they are
  7058. defined, and only in that function. However, explicitly declared
  7059. local labels of a block are visible in nested function definitions
  7060. inside that block. @xref{Nested Functions}, for details.
  7061. @xref{goto Statement}.
  7062. @node Labels as Values
  7063. @section Labels as Values
  7064. @cindex labels as values
  7065. @cindex computed gotos
  7066. @cindex goto with computed label
  7067. @cindex address of a label
  7068. In GNU C, you can get the address of a label defined in the current
  7069. function (or a local label defined in the containing function) with
  7070. the unary operator @samp{&&}. The value has type @code{void *}. This
  7071. value is a constant and can be used wherever a constant of that type
  7072. is valid. For example:
  7073. @example
  7074. void *ptr;
  7075. @r{@dots{}}
  7076. ptr = &&foo;
  7077. @end example
  7078. To use these values requires a way to jump to one. This is done
  7079. with the computed goto statement@footnote{The analogous feature in
  7080. Fortran is called an assigned goto, but that name seems inappropriate in
  7081. C, since you can do more with label addresses than store them in special label
  7082. variables.}, @code{goto *@var{exp};}. For example,
  7083. @example
  7084. goto *ptr;
  7085. @end example
  7086. @noindent
  7087. Any expression of type @code{void *} is allowed.
  7088. @xref{goto Statement}.
  7089. @menu
  7090. * Label Value Uses:: Examples of using label values.
  7091. * Label Value Caveats:: Limitations of label values.
  7092. @end menu
  7093. @node Label Value Uses
  7094. @subsection Label Value Uses
  7095. One use for label-valued constants is to initialize a static array to
  7096. serve as a jump table:
  7097. @example
  7098. static void *array[] = @{ &&foo, &&bar, &&hack @};
  7099. @end example
  7100. Then you can select a label with indexing, like this:
  7101. @example
  7102. goto *array[i];
  7103. @end example
  7104. @noindent
  7105. Note that this does not check whether the subscript is in bounds---array
  7106. indexing in C never checks that.
  7107. You can make the table entries offsets instead of addresses
  7108. by subtracting one label from the others. Here is an example:
  7109. @example
  7110. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  7111. &&hack - &&foo @};
  7112. goto *(&&foo + array[i]);
  7113. @end example
  7114. @noindent
  7115. Using offsets is preferable in shared libraries, as it avoids the need
  7116. for dynamic relocation of the array elements; therefore, the array can
  7117. be read-only.
  7118. An array of label values or offsets serves a purpose much like that of
  7119. the @code{switch} statement. The @code{switch} statement is cleaner,
  7120. so use @code{switch} by preference when feasible.
  7121. Another use of label values is in an interpreter for threaded code.
  7122. The labels within the interpreter function can be stored in the
  7123. threaded code for super-fast dispatching.
  7124. @node Label Value Caveats
  7125. @subsection Label Value Caveats
  7126. Jumping to a label defined in another function does not work.
  7127. It can cause unpredictable results.
  7128. The best way to avoid this is to store label values only in
  7129. automatic variables, or static variables whose names are declared
  7130. within the function. Never pass them as arguments.
  7131. @cindex cloning
  7132. An optimization known as @dfn{cloning} generates multiple simplified
  7133. variants of a function's code, for use with specific fixed arguments.
  7134. Using label values in certain ways, such as saving the address in one
  7135. call to the function and using it again in another call, would make cloning
  7136. give incorrect results. These functions must disable cloning.
  7137. Inlining calls to the function would also result in multiple copies of
  7138. the code, each with its own value of the same label. Using the label
  7139. in a computed goto is no problem, because the computed goto inhibits
  7140. inlining. However, using the label value in some other way, such as
  7141. an indication of where an error occurred, would be optimized wrong.
  7142. These functions must disable inlining.
  7143. To prevent inlining or cloning of a function, specify
  7144. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7145. @xref{Attributes}.
  7146. When a function uses a label value in a static variable initializer,
  7147. that automatically prevents inlining or cloning the function.
  7148. @node Statement Exprs
  7149. @section Statements and Declarations in Expressions
  7150. @cindex statements inside expressions
  7151. @cindex declarations inside expressions
  7152. @cindex expressions containing statements
  7153. @c the above section title wrapped and causes an underfull hbox.. i
  7154. @c changed it from "within" to "in". --mew 4feb93
  7155. A block enclosed in parentheses can be used as an expression in GNU
  7156. C@. This provides a way to use local variables, loops and switches within
  7157. an expression. We call it a @dfn{statement expression}.
  7158. Recall that a block is a sequence of statements
  7159. surrounded by braces. In this construct, parentheses go around the
  7160. braces. For example:
  7161. @example
  7162. (@{ int y = foo (); int z;
  7163. if (y > 0) z = y;
  7164. else z = - y;
  7165. z; @})
  7166. @end example
  7167. @noindent
  7168. is a valid (though slightly more complex than necessary) expression
  7169. for the absolute value of @code{foo ()}.
  7170. The last statement in the block should be an expression statement; an
  7171. expression followed by a semicolon, that is. The value of this
  7172. expression serves as the value of statement expression. If the last
  7173. statement is anything else, the statement expression's value is
  7174. @code{void}.
  7175. This feature is mainly useful in making macro definitions compute each
  7176. operand exactly once. @xref{Macros and Auto Type}.
  7177. Statement expressions are not allowed in expressions that must be
  7178. constant, such as the value for an enumerator, the width of a
  7179. bit-field, or the initial value of a static variable.
  7180. Jumping into a statement expression---with @code{goto}, or using a
  7181. @code{switch} statement outside the statement expression---is an
  7182. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7183. compiler can't detect the error, but it still won't work.
  7184. Jumping out of a statement expression is permitted, but since
  7185. subexpressions in C are not computed in a strict order, it is
  7186. unpredictable which other subexpressions will have been computed by
  7187. then. For example,
  7188. @example
  7189. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7190. @end example
  7191. @noindent
  7192. calls @code{foo} and @code{bar1} before it jumps, and never
  7193. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7194. does get called, that occurs after @code{foo} and before @code{bar1}.
  7195. @node Variables
  7196. @chapter Variables
  7197. @cindex variables
  7198. Every variable used in a C program needs to be made known by a
  7199. @dfn{declaration}. It can be used only after it has been declared.
  7200. It is an error to declare a variable name more than once in the same
  7201. scope; an exception is that @code{extern} declarations and tentative
  7202. definitions can coexist with another declaration of the same
  7203. variable.
  7204. Variables can be declared anywhere within a block or file. (Older
  7205. versions of C required that all variable declarations within a block
  7206. occur before any statements.)
  7207. Variables declared within a function or block are @dfn{local} to
  7208. it. This means that the variable name is visible only until the end
  7209. of that function or block, and the memory space is allocated only
  7210. while control is within it.
  7211. Variables declared at the top level in a file are called @dfn{file-scope}.
  7212. They are assigned fixed, distinct memory locations, so they retain
  7213. their values for the whole execution of the program.
  7214. @menu
  7215. * Variable Declarations:: Name a variable and and reserve space for it.
  7216. * Initializers:: Assigning initial values to variables.
  7217. * Designated Inits:: Assigning initial values to array elements
  7218. at particular array indices.
  7219. * Auto Type:: Obtaining the type of a variable.
  7220. * Local Variables:: Variables declared in function definitions.
  7221. * File-Scope Variables:: Variables declared outside of
  7222. function definitions.
  7223. * Static Local Variables:: Variables declared within functions,
  7224. but with permanent storage allocation.
  7225. * Extern Declarations:: Declaring a variable
  7226. which is allocated somewhere else.
  7227. * Allocating File-Scope:: When is space allocated
  7228. for file-scope variables?
  7229. * auto and register:: Historically used storage directions.
  7230. * Omitting Types:: The bad practice of declaring variables
  7231. with implicit type.
  7232. @end menu
  7233. @node Variable Declarations
  7234. @section Variable Declarations
  7235. @cindex variable declarations
  7236. @cindex declaration of variables
  7237. Here's what a variable declaration looks like:
  7238. @example
  7239. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7240. @end example
  7241. The @var{keywords} specify how to handle the scope of the variable
  7242. name and the allocation of its storage. Most declarations have
  7243. no keywords because the defaults are right for them.
  7244. C allows these keywords to come before or after @var{basetype}, or
  7245. even in the middle of it as in @code{unsigned static int}, but don't
  7246. do that---it would surprise other programmers. Always write the
  7247. keywords first.
  7248. The @var{basetype} can be any of the predefined types of C, or a type
  7249. keyword defined with @code{typedef}. It can also be @code{struct
  7250. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7251. addition, it can include type qualifiers such as @code{const} and
  7252. @code{volatile} (@pxref{Type Qualifiers}).
  7253. In the simplest case, @var{decorated-variable} is just the variable
  7254. name. That declares the variable with the type specified by
  7255. @var{basetype}. For instance,
  7256. @example
  7257. int foo;
  7258. @end example
  7259. @noindent
  7260. uses @code{int} as the @var{basetype} and @code{foo} as the
  7261. @var{decorated-variable}. It declares @code{foo} with type
  7262. @code{int}.
  7263. @example
  7264. struct tree_node foo;
  7265. @end example
  7266. @noindent
  7267. declares @code{foo} with type @code{struct tree_node}.
  7268. @menu
  7269. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7270. array and pointer types.
  7271. * Combining Variable Declarations:: More than one variable declaration
  7272. in a single statement.
  7273. @end menu
  7274. @node Declaring Arrays and Pointers
  7275. @subsection Declaring Arrays and Pointers
  7276. @cindex declaring arrays and pointers
  7277. @cindex array, declaring
  7278. @cindex pointers, declaring
  7279. To declare a variable that is an array, write
  7280. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7281. @example
  7282. int foo[5];
  7283. @end example
  7284. To declare a variable that has a pointer type, write
  7285. @code{*@var{variable}} for @var{decorated-variable}:
  7286. @example
  7287. struct list_elt *foo;
  7288. @end example
  7289. These constructs nest. For instance,
  7290. @example
  7291. int foo[3][5];
  7292. @end example
  7293. @noindent
  7294. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7295. @example
  7296. struct list_elt *foo[5];
  7297. @end example
  7298. @noindent
  7299. declares @code{foo} as an array of 5 pointers to structures, and
  7300. @example
  7301. struct list_elt **foo;
  7302. @end example
  7303. @noindent
  7304. declares @code{foo} as a pointer to a pointer to a structure.
  7305. @example
  7306. int **(*foo[30])(int, double);
  7307. @end example
  7308. @noindent
  7309. declares @code{foo} as an array of 30 pointers to functions
  7310. (@pxref{Function Pointers}), each of which must accept two arguments
  7311. (one @code{int} and one @code{double}) and return type @code{int **}.
  7312. @example
  7313. void
  7314. bar (int size)
  7315. @{
  7316. int foo[size];
  7317. @r{@dots{}}
  7318. @}
  7319. @end example
  7320. @noindent
  7321. declares @code{foo} as an array of integers with a size specified at
  7322. run time when the function @code{bar} is called.
  7323. @node Combining Variable Declarations
  7324. @subsection Combining Variable Declarations
  7325. @cindex combining variable declarations
  7326. @cindex variable declarations, combining
  7327. @cindex declarations, combining
  7328. When multiple declarations have the same @var{keywords} and
  7329. @var{basetype}, you can combine them using commas. Thus,
  7330. @example
  7331. @var{keywords} @var{basetype}
  7332. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7333. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7334. @end example
  7335. @noindent
  7336. is equivalent to
  7337. @example
  7338. @var{keywords} @var{basetype}
  7339. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7340. @var{keywords} @var{basetype}
  7341. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7342. @end example
  7343. Here are some simple examples:
  7344. @example
  7345. int a, b;
  7346. int a = 1, b = 2;
  7347. int a, *p, array[5];
  7348. int a = 0, *p = &a, array[5] = @{1, 2@};
  7349. @end example
  7350. @noindent
  7351. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7352. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7353. Since the initializer for @code{array} specifies only two elements,
  7354. the other three elements are initialized to zero.
  7355. @node Initializers
  7356. @section Initializers
  7357. @cindex initializers
  7358. A variable's declaration, unless it is @code{extern}, should also
  7359. specify its initial value. For numeric and pointer-type variables,
  7360. the initializer is an expression for the value. If necessary, it is
  7361. converted to the variable's type, just as in an assignment.
  7362. You can also initialize a local structure-type (@pxref{Structures}) or
  7363. local union-type (@pxref{Unions}) variable this way, from an
  7364. expression whose value has the same type. But you can't initialize an
  7365. array this way (@pxref{Arrays}), since arrays are not first-class
  7366. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7367. assignment.
  7368. You can initialize arrays and structures componentwise,
  7369. with a list of the elements or components. You can initialize
  7370. a union with any one of its alternatives.
  7371. @itemize @bullet
  7372. @item
  7373. A component-wise initializer for an array consists of element values
  7374. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7375. don't cover all the elements in the array, the remaining elements are
  7376. initialized to zero.
  7377. You can omit the size of the array when you declare it, and let
  7378. the initializer specify the size:
  7379. @example
  7380. int array[] = @{ 3, 9, 12 @};
  7381. @end example
  7382. @item
  7383. A component-wise initializer for a structure consists of field values
  7384. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7385. order as the fields are declared in the structure. If the values in
  7386. the initializer don't cover all the fields in the structure, the
  7387. remaining fields are initialized to zero.
  7388. @item
  7389. The initializer for a union-type variable has the form @code{@{
  7390. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7391. in the union definition.
  7392. @end itemize
  7393. For an array of arrays, a structure containing arrays, an array of
  7394. structures, etc., you can nest these constructs. For example,
  7395. @example
  7396. struct point @{ double x, y; @};
  7397. struct point series[]
  7398. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7399. @end example
  7400. You can omit a pair of inner braces if they contain the right
  7401. number of elements for the sub-value they initialize, so that
  7402. no elements or fields need to be filled in with zeros.
  7403. But don't do that very much, as it gets confusing.
  7404. An array of @code{char} can be initialized using a string constant.
  7405. Recall that the string constant includes an implicit null character at
  7406. the end (@pxref{String Constants}). Using a string constant as
  7407. initializer means to use its contents as the initial values of the
  7408. array elements. Here are examples:
  7409. @example
  7410. char text[6] = "text!"; /* @r{Includes the null.} */
  7411. char text[5] = "text!"; /* @r{Excludes the null.} */
  7412. char text[] = "text!"; /* @r{Gets length 6.} */
  7413. char text[]
  7414. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7415. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7416. @end example
  7417. @noindent
  7418. and this kind of initializer can be nested inside braces to initialize
  7419. structures or arrays that contain a @code{char}-array.
  7420. In like manner, you can use a wide string constant to initialize
  7421. an array of @code{wchar_t}.
  7422. @node Designated Inits
  7423. @section Designated Initializers
  7424. @cindex initializers with labeled elements
  7425. @cindex labeled elements in initializers
  7426. @cindex case labels in initializers
  7427. @cindex designated initializers
  7428. In a complex structure or long array, it's useful to indicate
  7429. which field or element we are initializing.
  7430. To designate specific array elements during initialization, include
  7431. the array index in brackets, and an assignment operator, for each
  7432. element:
  7433. @example
  7434. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7435. @end example
  7436. @noindent
  7437. This does the same thing as:
  7438. @example
  7439. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7440. @end example
  7441. The array initialization can include non-designated element values
  7442. alongside designated indices; these follow the expected ordering
  7443. of the array initialization, so that
  7444. @example
  7445. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7446. @end example
  7447. @noindent
  7448. does the same thing as:
  7449. @example
  7450. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7451. @end example
  7452. Note that you can only use constant expressions as array index values,
  7453. not variables.
  7454. If you need to initialize a subsequence of sequential array elements to
  7455. the same value, you can specify a range:
  7456. @example
  7457. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7458. @end example
  7459. @noindent
  7460. Using a range this way is a GNU C extension.
  7461. When subsequence ranges overlap, each element is initialized by the
  7462. last specification that applies to it. Thus, this initialization is
  7463. equivalent to the previous one.
  7464. @example
  7465. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7466. @end example
  7467. @noindent
  7468. as the second overrides the first for elements 0 through 19.
  7469. The value used to initialize a range of elements is evaluated only
  7470. once, for the first element in the range. So for example, this code
  7471. @example
  7472. int random_values[100]
  7473. = @{ [0 ... 99] = get_random_number() @};
  7474. @end example
  7475. @noindent
  7476. would initialize all 100 elements of the array @code{random_values} to
  7477. the same value---probably not what is intended.
  7478. Similarly, you can initialize specific fields of a structure variable
  7479. by specifying the field name prefixed with a dot:
  7480. @example
  7481. struct point @{ int x; int y; @};
  7482. struct point foo = @{ .y = 42; @};
  7483. @end example
  7484. @noindent
  7485. The same syntax works for union variables as well:
  7486. @example
  7487. union int_double @{ int i; double d; @};
  7488. union int_double foo = @{ .d = 34 @};
  7489. @end example
  7490. @noindent
  7491. This casts the integer value 34 to a double and stores it
  7492. in the union variable @code{foo}.
  7493. You can designate both array elements and structure elements in
  7494. the same initialization; for example, here's an array of point
  7495. structures:
  7496. @example
  7497. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7498. @end example
  7499. Along with the capability to specify particular array and structure
  7500. elements to initialize comes the possibility of initializing the same
  7501. element more than once:
  7502. @example
  7503. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7504. @end example
  7505. @noindent
  7506. In such a case, the last initialization value is retained.
  7507. @node Auto Type
  7508. @section Referring to a Type with @code{__auto_type}
  7509. @findex __auto_type
  7510. @findex typeof
  7511. @cindex macros, types of arguments
  7512. You can declare a variable copying the type from
  7513. the initializer by using @code{__auto_type} instead of a particular type.
  7514. Here's an example:
  7515. @example
  7516. #define max(a,b) \
  7517. (@{ __auto_type _a = (a); \
  7518. __auto_type _b = (b); \
  7519. _a > _b ? _a : _b @})
  7520. @end example
  7521. This defines @code{_a} to be of the same type as @code{a}, and
  7522. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7523. to do in a macro that ought to be able to handle any type of data
  7524. (@pxref{Macros and Auto Type}).
  7525. The original GNU C method for obtaining the type of a value is to use
  7526. @code{typeof}, which takes as an argument either a value or the name of
  7527. a type. The previous example could also be written as:
  7528. @example
  7529. #define max(a,b) \
  7530. (@{ typeof(a) _a = (a); \
  7531. typeof(b) _b = (b); \
  7532. _a > _b ? _a : _b @})
  7533. @end example
  7534. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7535. principal use case for @code{typeof} is in variable declarations with
  7536. initialization, which is exactly what @code{__auto_type} handles.
  7537. @node Local Variables
  7538. @section Local Variables
  7539. @cindex local variables
  7540. @cindex variables, local
  7541. Declaring a variable inside a function definition (@pxref{Function
  7542. Definitions}) makes the variable name @dfn{local} to the containing
  7543. block---that is, the containing pair of braces. More precisely, the
  7544. variable's name is visible starting just after where it appears in the
  7545. declaration, and its visibility continues until the end of the block.
  7546. Local variables in C are generally @dfn{automatic} variables: each
  7547. variable's storage exists only from the declaration to the end of the
  7548. block. Execution of the declaration allocates the storage, computes
  7549. the initial value, and stores it in the variable. The end of the
  7550. block deallocates the storage.@footnote{Due to compiler optimizations,
  7551. allocation and deallocation don't necessarily really happen at
  7552. those times.}
  7553. @strong{Warning:} Two declarations for the same local variable
  7554. in the same scope are an error.
  7555. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7556. The total space for the program's stack may be limited; therefore,
  7557. in using very large arrays, it may be necessary to allocate
  7558. them in some other way to stop the program from crashing.
  7559. @strong{Warning:} If the declaration of an automatic variable does not
  7560. specify an initial value, the variable starts out containing garbage.
  7561. In this example, the value printed could be anything at all:
  7562. @example
  7563. @{
  7564. int i;
  7565. printf ("Print junk %d\n", i);
  7566. @}
  7567. @end example
  7568. In a simple test program, that statement is likely to print 0, simply
  7569. because every process starts with memory zeroed. But don't rely on it
  7570. to be zero---that is erroneous.
  7571. @strong{Note:} Make sure to store a value into each local variable (by
  7572. assignment, or by initialization) before referring to its value.
  7573. @node File-Scope Variables
  7574. @section File-Scope Variables
  7575. @cindex file-scope variables
  7576. @cindex global variables
  7577. @cindex variables, file-scope
  7578. @cindex variables, global
  7579. A variable declaration at the top level in a file (not inside a
  7580. function definition) declares a @dfn{file-scope variable}. Loading a
  7581. program allocates the storage for all the file-scope variables in it,
  7582. and initializes them too.
  7583. Each file-scope variable is either @dfn{static} (limited to one
  7584. compilation module) or @dfn{global} (shared with all compilation
  7585. modules in the program). To make the variable static, write the
  7586. keyword @code{static} at the start of the declaration. Omitting
  7587. @code{static} makes the variable global.
  7588. The initial value for a file-scope variable can't depend on the
  7589. contents of storage, and can't call any functions.
  7590. @example
  7591. int foo = 5; /* @r{Valid.} */
  7592. int bar = foo; /* @r{Invalid!} */
  7593. int bar = sin (1.0); /* @r{Invalid!} */
  7594. @end example
  7595. But it can use the address of another file-scope variable:
  7596. @example
  7597. int foo;
  7598. int *bar = &foo; /* @r{Valid.} */
  7599. int arr[5];
  7600. int *bar3 = &arr[3]; /* @r{Valid.} */
  7601. int *bar4 = arr + 4; /* @r{Valid.} */
  7602. @end example
  7603. It is valid for a module to have multiple declarations for a
  7604. file-scope variable, as long as they are all global or all static, but
  7605. at most one declaration can specify an initial value for it.
  7606. @node Static Local Variables
  7607. @section Static Local Variables
  7608. @cindex static local variables
  7609. @cindex variables, static local
  7610. @findex static
  7611. The keyword @code{static} in a local variable declaration says to
  7612. allocate the storage for the variable permanently, just like a
  7613. file-scope variable, even if the declaration is within a function.
  7614. Here's an example:
  7615. @example
  7616. int
  7617. increment_counter ()
  7618. @{
  7619. static int counter = 0;
  7620. return ++counter;
  7621. @}
  7622. @end example
  7623. The scope of the name @code{counter} runs from the declaration to the
  7624. end of the containing block, just like an automatic local variable,
  7625. but its storage is permanent, so the value persists from one call to
  7626. the next. As a result, each call to @code{increment_counter}
  7627. returns a different, unique value.
  7628. The initial value of a static local variable has the same limitations
  7629. as for file-scope variables: it can't depend on the contents of
  7630. storage or call any functions. It can use the address of a file-scope
  7631. variable or a static local variable, because those addresses are
  7632. determined before the program runs.
  7633. @node Extern Declarations
  7634. @section @code{extern} Declarations
  7635. @cindex @code{extern} declarations
  7636. @cindex declarations, @code{extern}
  7637. @findex extern
  7638. An @code{extern} declaration is used to refer to a global variable
  7639. whose principal declaration comes elsewhere---in the same module, or in
  7640. another compilation module. It looks like this:
  7641. @example
  7642. extern @var{basetype} @var{decorated-variable};
  7643. @end example
  7644. Its meaning is that, in the current scope, the variable name refers to
  7645. the file-scope variable of that name---which needs to be declared in a
  7646. non-@code{extern}, non-@code{static} way somewhere else.
  7647. For instance, if one compilation module has this global variable
  7648. declaration
  7649. @example
  7650. int error_count = 0;
  7651. @end example
  7652. @noindent
  7653. then other compilation modules can specify this
  7654. @example
  7655. extern int error_count;
  7656. @end example
  7657. @noindent
  7658. to allow reference to the same variable.
  7659. The usual place to write an @code{extern} declaration is at top level
  7660. in a source file, but you can write an @code{extern} declaration
  7661. inside a block to make a global or static file-scope variable
  7662. accessible in that block.
  7663. Since an @code{extern} declaration does not allocate space for the
  7664. variable, it can omit the size of an array:
  7665. @example
  7666. extern int array[];
  7667. @end example
  7668. You can use @code{array} normally in all contexts where it is
  7669. converted automatically to a pointer. However, to use it as the
  7670. operand of @code{sizeof} is an error, since the size is unknown.
  7671. It is valid to have multiple @code{extern} declarations for the same
  7672. variable, even in the same scope, if they give the same type. They do
  7673. not conflict---they agree. For an array, it is legitimate for some
  7674. @code{extern} declarations can specify the size while others omit it.
  7675. However, if two declarations give different sizes, that is an error.
  7676. Likewise, you can use @code{extern} declarations at file scope
  7677. (@pxref{File-Scope Variables}) followed by an ordinary global
  7678. (non-static) declaration of the same variable. They do not conflict,
  7679. because they say compatible things about the same meaning of the variable.
  7680. @node Allocating File-Scope
  7681. @section Allocating File-Scope Variables
  7682. @cindex allocation file-scope variables
  7683. @cindex file-scope variables, allocating
  7684. Some file-scope declarations allocate space for the variable, and some
  7685. don't.
  7686. A file-scope declaration with an initial value @emph{must} allocate
  7687. space for the variable; if there are two of such declarations for the
  7688. same variable, even in different compilation modules, they conflict.
  7689. An @code{extern} declaration @emph{never} allocates space for the variable.
  7690. If all the top-level declarations of a certain variable are
  7691. @code{extern}, the variable never gets memory space. If that variable
  7692. is used anywhere in the program, the use will be reported as an error,
  7693. saying that the variable is not defined.
  7694. @cindex tentative definition
  7695. A file-scope declaration without an initial value is called a
  7696. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7697. allocate space for the variable, but does not insist. So it causes no
  7698. conflict, no error, if the variable has another declaration that
  7699. allocates space for it, perhaps in another compilation module. But if
  7700. nothing else allocates space for the variable, the tentative
  7701. definition will do it. Any number of compilation modules can declare
  7702. the same variable in this way, and that is sufficient for all of them
  7703. to use the variable.
  7704. @c @opindex -fno-common
  7705. @c @opindex --warn_common
  7706. In programs that are very large or have many contributors, it may be
  7707. wise to adopt the convention of never using tentative definitions.
  7708. You can use the compilation option @option{-fno-common} to make them
  7709. an error, or @option{--warn-common} to warn about them.
  7710. If a file-scope variable gets its space through a tentative
  7711. definition, it starts out containing all zeros.
  7712. @node auto and register
  7713. @section @code{auto} and @code{register}
  7714. @cindex @code{auto} declarations
  7715. @cindex @code{register} declarations
  7716. @findex auto
  7717. @findex register
  7718. For historical reasons, you can write @code{auto} or @code{register}
  7719. before a local variable declaration. @code{auto} merely emphasizes
  7720. that the variable isn't static; it changes nothing.
  7721. @code{register} suggests to the compiler storing this variable in a
  7722. register. However, GNU C ignores this suggestion, since it can
  7723. choose the best variables to store in registers without any hints.
  7724. It is an error to take the address of a variable declared
  7725. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7726. If the variable is an array, you can't use it at all (other than as
  7727. the operand of @code{sizeof}), which makes it rather useless.
  7728. @node Omitting Types
  7729. @section Omitting Types in Declarations
  7730. @cindex omitting types in declarations
  7731. The syntax of C traditionally allows omitting the data type in a
  7732. declaration if it specifies a storage class, a type qualifier (see the
  7733. next chapter), or @code{auto} or @code{register}. Then the type
  7734. defaults to @code{int}. For example:
  7735. @example
  7736. auto foo = 42;
  7737. @end example
  7738. This is bad practice; if you see it, fix it.
  7739. @node Type Qualifiers
  7740. @chapter Type Qualifiers
  7741. A declaration can include type qualifiers to advise the compiler
  7742. about how the variable will be used. There are three different
  7743. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7744. pertain to different issues, so you can use more than one together.
  7745. For instance, @code{const volatile} describes a value that the
  7746. program is not allowed to change, but might have a different value
  7747. each time the program examines it. (This might perhaps be a special
  7748. hardware register, or part of shared memory.)
  7749. If you are just learning C, you can skip this chapter.
  7750. @menu
  7751. * const:: Variables whose values don't change.
  7752. * volatile:: Variables whose values may be accessed
  7753. or changed outside of the control of
  7754. this program.
  7755. * restrict Pointers:: Restricted pointers for code optimization.
  7756. * restrict Pointer Example:: Example of how that works.
  7757. @end menu
  7758. @node const
  7759. @section @code{const} Variables and Fields
  7760. @cindex @code{const} variables and fields
  7761. @cindex variables, @code{const}
  7762. @findex const
  7763. You can mark a variable as ``constant'' by writing @code{const} in
  7764. front of the declaration. This says to treat any assignment to that
  7765. variable as an error. It may also permit some compiler
  7766. optimizations---for instance, to fetch the value only once to satisfy
  7767. multiple references to it. The construct looks like this:
  7768. @example
  7769. const double pi = 3.14159;
  7770. @end example
  7771. After this definition, the code can use the variable @code{pi}
  7772. but cannot assign a different value to it.
  7773. @example
  7774. pi = 3.0; /* @r{Error!} */
  7775. @end example
  7776. Simple variables that are constant can be used for the same purposes
  7777. as enumeration constants, and they are not limited to integers. The
  7778. constantness of the variable propagates into pointers, too.
  7779. A pointer type can specify that the @emph{target} is constant. For
  7780. example, the pointer type @code{const double *} stands for a pointer
  7781. to a constant @code{double}. That's the type that results from taking
  7782. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7783. left side of an assignment.
  7784. @example
  7785. *(&pi) = 3.0; /* @r{Error!} */
  7786. @end example
  7787. Nonconstant pointers can be converted automatically to constant
  7788. pointers, but not vice versa. For instance,
  7789. @example
  7790. const double *cptr;
  7791. double *ptr;
  7792. cptr = &pi; /* @r{Valid.} */
  7793. cptr = ptr; /* @r{Valid.} */
  7794. ptr = cptr; /* @r{Error!} */
  7795. ptr = &pi; /* @r{Error!} */
  7796. @end example
  7797. This is not an ironclad protection against modifying the value. You
  7798. can always cast the constant pointer to a nonconstant pointer type:
  7799. @example
  7800. ptr = (double *)cptr; /* @r{Valid.} */
  7801. ptr = (double *)&pi; /* @r{Valid.} */
  7802. @end example
  7803. However, @code{const} provides a way to show that a certain function
  7804. won't modify the data structure whose address is passed to it. Here's
  7805. an example:
  7806. @example
  7807. int
  7808. string_length (const char *string)
  7809. @{
  7810. int count = 0;
  7811. while (*string++)
  7812. count++;
  7813. return count;
  7814. @}
  7815. @end example
  7816. @noindent
  7817. Using @code{const char *} for the parameter is a way of saying this
  7818. function never modifies the memory of the string itself.
  7819. In calling @code{string_length}, you can specify an ordinary
  7820. @code{char *} since that can be converted automatically to @code{const
  7821. char *}.
  7822. @node volatile
  7823. @section @code{volatile} Variables and Fields
  7824. @cindex @code{volatile} variables and fields
  7825. @cindex variables, @code{volatile}
  7826. @findex volatile
  7827. The GNU C compiler often performs optimizations that eliminate the
  7828. need to write or read a variable. For instance,
  7829. @example
  7830. int foo;
  7831. foo = 1;
  7832. foo++;
  7833. @end example
  7834. @noindent
  7835. might simply store the value 2 into @code{foo}, without ever storing 1.
  7836. These optimizations can also apply to structure fields in some cases.
  7837. If the memory containing @code{foo} is shared with another program,
  7838. or if it is examined asynchronously by hardware, such optimizations
  7839. could confuse the communication. Using @code{volatile} is one way
  7840. to prevent them.
  7841. Writing @code{volatile} with the type in a variable or field declaration
  7842. says that the value may be examined or changed for reasons outside the
  7843. control of the program at any moment. Therefore, the program must
  7844. execute in a careful way to assure correct interaction with those
  7845. accesses, whenever they may occur.
  7846. The simplest use looks like this:
  7847. @example
  7848. volatile int lock;
  7849. @end example
  7850. This directs the compiler not to do certain common optimizations on
  7851. use of the variable @code{lock}. All the reads and writes for a volatile
  7852. variable or field are really done, and done in the order specified
  7853. by the source code. Thus, this code:
  7854. @example
  7855. lock = 1;
  7856. list = list->next;
  7857. if (lock)
  7858. lock_broken (&lock);
  7859. lock = 0;
  7860. @end example
  7861. @noindent
  7862. really stores the value 1 in @code{lock}, even though there is no
  7863. sign it is really used, and the @code{if} statement reads and
  7864. checks the value of @code{lock}, rather than assuming it is still 1.
  7865. A limited amount of optimization can be done, in principle, on
  7866. @code{volatile} variables and fields: multiple references between two
  7867. sequence points (@pxref{Sequence Points}) can be simplified together.
  7868. Use of @code{volatile} does not eliminate the flexibility in ordering
  7869. the computation of the operands of most operators. For instance, in
  7870. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7871. @code{foo} is not specified, so they may be done in either order; the
  7872. fact that @code{lock} is @code{volatile} has no effect on that.
  7873. @node restrict Pointers
  7874. @section @code{restrict}-Qualified Pointers
  7875. @cindex @code{restrict} pointers
  7876. @cindex pointers, @code{restrict}-qualified
  7877. @findex restrict
  7878. You can declare a pointer as ``restricted'' using the @code{restrict}
  7879. type qualifier, like this:
  7880. @example
  7881. int *restrict p = x;
  7882. @end example
  7883. @noindent
  7884. This enables better optimization of code that uses the pointer.
  7885. If @code{p} is declared with @code{restrict}, and then the code
  7886. references the object that @code{p} points to (using @code{*p} or
  7887. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7888. code will not access that object in any other way---only through
  7889. @code{p}.
  7890. For instance, it means the code must not use another pointer
  7891. to access the same space, as shown here:
  7892. @example
  7893. int *restrict p = @var{whatever};
  7894. int *q = p;
  7895. foo (*p, *q);
  7896. @end example
  7897. @noindent
  7898. That contradicts the @code{restrict} promise by accessing the object
  7899. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7900. Likewise, it must not do this:
  7901. @example
  7902. int *restrict p = @var{whatever};
  7903. struct @{ int *a, *b; @} s;
  7904. s.a = p;
  7905. foo (*p, *s.a);
  7906. @end example
  7907. @noindent
  7908. This example uses a structure field instead of the variable @code{q}
  7909. to hold the other pointer, and that contradicts the promise just the
  7910. same.
  7911. The keyword @code{restrict} also promises that @code{p} won't point to
  7912. the allocated space of any automatic or static variable. So the code
  7913. must not do this:
  7914. @example
  7915. int a;
  7916. int *restrict p = &a;
  7917. foo (*p, a);
  7918. @end example
  7919. @noindent
  7920. because that does direct access to the object (@code{a}) that @code{p}
  7921. points to, which bypasses @code{p}.
  7922. If the code makes such promises with @code{restrict} then breaks them,
  7923. execution is unpredictable.
  7924. @node restrict Pointer Example
  7925. @section @code{restrict} Pointer Example
  7926. Here are examples where @code{restrict} enables real optimization.
  7927. In this example, @code{restrict} assures GCC that the array @code{out}
  7928. points to does not overlap with the array @code{in} points to.
  7929. @example
  7930. void
  7931. process_data (const char *in,
  7932. char * restrict out,
  7933. size_t size)
  7934. @{
  7935. for (i = 0; i < size; i++)
  7936. out[i] = in[i] + in[i + 1];
  7937. @}
  7938. @end example
  7939. Here's a simple tree structure, where each tree node holds data of
  7940. type @code{PAYLOAD} plus two subtrees.
  7941. @example
  7942. struct foo
  7943. @{
  7944. PAYLOAD payload;
  7945. struct foo *left;
  7946. struct foo *right;
  7947. @};
  7948. @end example
  7949. Now here's a function to null out both pointers in the @code{left}
  7950. subtree.
  7951. @example
  7952. void
  7953. null_left (struct foo *a)
  7954. @{
  7955. a->left->left = NULL;
  7956. a->left->right = NULL;
  7957. @}
  7958. @end example
  7959. Since @code{*a} and @code{*a->left} have the same data type,
  7960. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7961. the compiled code for @code{null_left} must read @code{a->left}
  7962. again from memory when executing the second assignment statement.
  7963. We can enable optimization, so that it does not need to read
  7964. @code{a->left} again, by writing @code{null_left} in a less
  7965. obvious way.
  7966. @example
  7967. void
  7968. null_left (struct foo *a)
  7969. @{
  7970. struct foo *b = a->left;
  7971. b->left = NULL;
  7972. b->right = NULL;
  7973. @}
  7974. @end example
  7975. A more elegant way to fix this is with @code{restrict}.
  7976. @example
  7977. void
  7978. null_left (struct foo *restrict a)
  7979. @{
  7980. a->left->left = NULL;
  7981. a->left->right = NULL;
  7982. @}
  7983. @end example
  7984. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7985. as @code{a->left} will not point to the same memory space as @code{a}.
  7986. Therefore, the memory location @code{a->left->left} cannot be the same
  7987. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7988. reloading @code{a->left} for the second statement.
  7989. @node Functions
  7990. @chapter Functions
  7991. @cindex functions
  7992. We have already presented many examples of functions, so if you've
  7993. read this far, you basically understand the concept of a function. It
  7994. is vital, nonetheless, to have a chapter in the manual that collects
  7995. all the information about functions.
  7996. @menu
  7997. * Function Definitions:: Writing the body of a function.
  7998. * Function Declarations:: Declaring the interface of a function.
  7999. * Function Calls:: Using functions.
  8000. * Function Call Semantics:: Call-by-value argument passing.
  8001. * Function Pointers:: Using references to functions.
  8002. * The main Function:: Where execution of a GNU C program begins.
  8003. * Advanced Definitions:: Advanced features of function definitions.
  8004. * Obsolete Definitions:: Obsolete features still used
  8005. in function definitions in old code.
  8006. @end menu
  8007. @node Function Definitions
  8008. @section Function Definitions
  8009. @cindex function definitions
  8010. @cindex defining functions
  8011. We have already presented many examples of function definitions. To
  8012. summarize the rules, a function definition looks like this:
  8013. @example
  8014. @var{returntype}
  8015. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  8016. @{
  8017. @var{body}
  8018. @}
  8019. @end example
  8020. The part before the open-brace is called the @dfn{function header}.
  8021. Write @code{void} as the @var{returntype} if the function does
  8022. not return a value.
  8023. @menu
  8024. * Function Parameter Variables:: Syntax and semantics
  8025. of function parameters.
  8026. * Forward Function Declarations:: Functions can only be called after
  8027. they have been defined or declared.
  8028. * Static Functions:: Limiting visibility of a function.
  8029. * Arrays as Parameters:: Functions that accept array arguments.
  8030. * Structs as Parameters:: Functions that accept structure arguments.
  8031. @end menu
  8032. @node Function Parameter Variables
  8033. @subsection Function Parameter Variables
  8034. @cindex function parameter variables
  8035. @cindex parameter variables in functions
  8036. @cindex parameter list
  8037. A function parameter variable is a local variable (@pxref{Local
  8038. Variables}) used within the function to store the value passed as an
  8039. argument in a call to the function. Usually we say ``function
  8040. parameter'' or ``parameter'' for short, not mentioning the fact that
  8041. it's a variable.
  8042. We declare these variables in the beginning of the function
  8043. definition, in the @dfn{parameter list}. For example,
  8044. @example
  8045. fib (int n)
  8046. @end example
  8047. @noindent
  8048. has a parameter list with one function parameter @code{n}, which has
  8049. type @code{int}.
  8050. Function parameter declarations differ from ordinary variable
  8051. declarations in several ways:
  8052. @itemize @bullet
  8053. @item
  8054. Inside the function definition header, commas separate parameter
  8055. declarations, and each parameter needs a complete declaration
  8056. including the type. For instance, if a function @code{foo} has two
  8057. @code{int} parameters, write this:
  8058. @example
  8059. foo (int a, int b)
  8060. @end example
  8061. You can't share the common @code{int} between the two declarations:
  8062. @example
  8063. foo (int a, b) /* @r{Invalid!} */
  8064. @end example
  8065. @item
  8066. A function parameter variable is initialized to whatever value is
  8067. passed in the function call, so its declaration cannot specify an
  8068. initial value.
  8069. @item
  8070. Writing an array type in a function parameter declaration has the
  8071. effect of declaring it as a pointer. The size specified for the array
  8072. has no effect at all, and we normally omit the size. Thus,
  8073. @example
  8074. foo (int a[5])
  8075. foo (int a[])
  8076. foo (int *a)
  8077. @end example
  8078. @noindent
  8079. are equivalent.
  8080. @item
  8081. The scope of the parameter variables is the entire function body,
  8082. notwithstanding the fact that they are written in the function header,
  8083. which is just outside the function body.
  8084. @end itemize
  8085. If a function has no parameters, it would be most natural for the
  8086. list of parameters in its definition to be empty. But that, in C, has
  8087. a special meaning for historical reasons: ``Do not check that calls to
  8088. this function have the right number of arguments.'' Thus,
  8089. @example
  8090. int
  8091. foo ()
  8092. @{
  8093. return 5;
  8094. @}
  8095. int
  8096. bar (int x)
  8097. @{
  8098. return foo (x);
  8099. @}
  8100. @end example
  8101. @noindent
  8102. would not report a compilation error in passing @code{x} as an
  8103. argument to @code{foo}. By contrast,
  8104. @example
  8105. int
  8106. foo (void)
  8107. @{
  8108. return 5;
  8109. @}
  8110. int
  8111. bar (int x)
  8112. @{
  8113. return foo (x);
  8114. @}
  8115. @end example
  8116. @noindent
  8117. would report an error because @code{foo} is supposed to receive
  8118. no arguments.
  8119. @node Forward Function Declarations
  8120. @subsection Forward Function Declarations
  8121. @cindex forward function declarations
  8122. @cindex function declarations, forward
  8123. The order of the function definitions in the source code makes no
  8124. difference, except that each function needs to be defined or declared
  8125. before code uses it.
  8126. The definition of a function also declares its name for the rest of
  8127. the containing scope. But what if you want to call the function
  8128. before its definition? To permit that, write a compatible declaration
  8129. of the same function, before the first call. A declaration that
  8130. prefigures a subsequent definition in this way is called a
  8131. @dfn{forward declaration}. The function declaration can be at top
  8132. @c ??? file scope
  8133. level or within a block, and it applies until the end of the containing
  8134. scope.
  8135. @xref{Function Declarations}, for more information about these
  8136. declarations.
  8137. @node Static Functions
  8138. @subsection Static Functions
  8139. @cindex static functions
  8140. @cindex functions, static
  8141. @findex static
  8142. The keyword @code{static} in a function definition limits the
  8143. visibility of the name to the current compilation module. (That's the
  8144. same thing @code{static} does in variable declarations;
  8145. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8146. contains this code:
  8147. @example
  8148. static int
  8149. foo (void)
  8150. @{
  8151. @r{@dots{}}
  8152. @}
  8153. @end example
  8154. @noindent
  8155. then the code of that compilation module can call @code{foo} anywhere
  8156. after the definition, but other compilation modules cannot refer to it
  8157. at all.
  8158. @cindex forward declaration
  8159. @cindex static function, declaration
  8160. To call @code{foo} before its definition, it needs a forward
  8161. declaration, which should use @code{static} since the function
  8162. definition does. For this function, it looks like this:
  8163. @example
  8164. static int foo (void);
  8165. @end example
  8166. It is generally wise to use @code{static} on the definitions of
  8167. functions that won't be called from outside the same compilation
  8168. module. This makes sure that calls are not added in other modules.
  8169. If programmers decide to change the function's calling convention, or
  8170. understand all the consequences of its use, they will only have to
  8171. check for calls in the same compilation module.
  8172. @node Arrays as Parameters
  8173. @subsection Arrays as Parameters
  8174. @cindex array as parameters
  8175. @cindex functions with array parameters
  8176. Arrays in C are not first-class objects: it is impossible to copy
  8177. them. So they cannot be passed as arguments like other values.
  8178. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8179. a special way.
  8180. @menu
  8181. * Array Parm Pointer::
  8182. * Passing Array Args::
  8183. * Array Parm Qualifiers::
  8184. @end menu
  8185. @node Array Parm Pointer
  8186. @subsubsection Array parameters are pointers
  8187. Declaring a function parameter variable as an array really gives it a
  8188. pointer type. C does this because an expression with array type, if
  8189. used as an argument in a function call, is converted automatically to
  8190. a pointer (to the zeroth element of the array). If you declare the
  8191. corresponding parameter as an ``array'', it will work correctly with
  8192. the pointer value that really gets passed.
  8193. This relates to the fact that C does not check array bounds in access
  8194. to elements of the array (@pxref{Accessing Array Elements}).
  8195. For example, in this function,
  8196. @example
  8197. void
  8198. clobber4 (int array[20])
  8199. @{
  8200. array[4] = 0;
  8201. @}
  8202. @end example
  8203. @noindent
  8204. the parameter @code{array}'s real type is @code{int *}; the specified
  8205. length, 20, has no effect on the program. You can leave out the length
  8206. and write this:
  8207. @example
  8208. void
  8209. clobber4 (int array[])
  8210. @{
  8211. array[4] = 0;
  8212. @}
  8213. @end example
  8214. @noindent
  8215. or write the parameter declaration explicitly as a pointer:
  8216. @example
  8217. void
  8218. clobber4 (int *array)
  8219. @{
  8220. array[4] = 0;
  8221. @}
  8222. @end example
  8223. They are all equivalent.
  8224. @node Passing Array Args
  8225. @subsubsection Passing array arguments
  8226. The function call passes this pointer by
  8227. value, like all argument values in C@. However, the result is
  8228. paradoxical in that the array itself is passed by reference: its
  8229. contents are treated as shared memory---shared between the caller and
  8230. the called function, that is. When @code{clobber4} assigns to element
  8231. 4 of @code{array}, the effect is to alter element 4 of the array
  8232. specified in the call.
  8233. @example
  8234. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8235. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8236. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8237. int
  8238. main (void)
  8239. @{
  8240. int data[] = @{1, 2, 3, 4, 5, 6@};
  8241. int i;
  8242. /* @r{Show the initial value of element 4.} */
  8243. for (i = 0; i < 6; i++)
  8244. printf ("data[%d] = %d\n", i, data[i]);
  8245. printf ("\n");
  8246. clobber4 (data);
  8247. /* @r{Show that element 4 has been changed.} */
  8248. for (i = 0; i < 6; i++)
  8249. printf ("data[%d] = %d\n", i, data[i]);
  8250. printf ("\n");
  8251. return EXIT_SUCCESS;
  8252. @}
  8253. @end example
  8254. @noindent
  8255. shows that @code{data[4]} has become zero after the call to
  8256. @code{clobber4}.
  8257. The array @code{data} has 6 elements, but passing it to a function
  8258. whose argument type is written as @code{int [20]} is not an error,
  8259. because that really stands for @code{int *}. The pointer that is the
  8260. real argument carries no indication of the length of the array it
  8261. points into. It is not required to point to the beginning of the
  8262. array, either. For instance,
  8263. @example
  8264. clobber4 (data+1);
  8265. @end example
  8266. @noindent
  8267. passes an ``array'' that starts at element 1 of @code{data}, and the
  8268. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8269. If all calls to the function will provide an array of a particular
  8270. size, you can specify the size of the array to be @code{static}:
  8271. @example
  8272. void
  8273. clobber4 (int array[static 20])
  8274. @r{@dots{}}
  8275. @end example
  8276. @noindent
  8277. This is a promise to the compiler that the function will always be
  8278. called with an array of 20 elements, so that the compiler can optimize
  8279. code accordingly. If the code breaks this promise and calls the
  8280. function with, for example, a shorter array, unpredictable things may
  8281. happen.
  8282. @node Array Parm Qualifiers
  8283. @subsubsection Type qualifiers on array parameters
  8284. You can use the type qualifiers @code{const}, @code{restrict}, and
  8285. @code{volatile} with array parameters; for example:
  8286. @example
  8287. void
  8288. clobber4 (volatile int array[20])
  8289. @r{@dots{}}
  8290. @end example
  8291. @noindent
  8292. denotes that @code{array} is equivalent to a pointer to a volatile
  8293. @code{int}. Alternatively:
  8294. @example
  8295. void
  8296. clobber4 (int array[const 20])
  8297. @r{@dots{}}
  8298. @end example
  8299. @noindent
  8300. makes the array parameter equivalent to a constant pointer to an
  8301. @code{int}. If we want the @code{clobber4} function to succeed, it
  8302. would not make sense to write
  8303. @example
  8304. void
  8305. clobber4 (const int array[20])
  8306. @r{@dots{}}
  8307. @end example
  8308. @noindent
  8309. as this would tell the compiler that the parameter should point to an
  8310. array of constant @code{int} values, and then we would not be able to
  8311. store zeros in them.
  8312. In a function with multiple array parameters, you can use @code{restrict}
  8313. to tell the compiler that each array parameter passed in will be distinct:
  8314. @example
  8315. void
  8316. foo (int array1[restrict 10], int array2[restrict 10])
  8317. @r{@dots{}}
  8318. @end example
  8319. @noindent
  8320. Using @code{restrict} promises the compiler that callers will
  8321. not pass in the same array for more than one @code{restrict} array
  8322. parameter. Knowing this enables the compiler to perform better code
  8323. optimization. This is the same effect as using @code{restrict}
  8324. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8325. the code that an array of a specific size is expected.
  8326. @node Structs as Parameters
  8327. @subsection Functions That Accept Structure Arguments
  8328. Structures in GNU C are first-class objects, so using them as function
  8329. parameters and arguments works in the natural way. This function
  8330. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8331. and returns a structure of the same type but with the fields
  8332. exchanged.
  8333. @example
  8334. struct foo @{ int a, b; @};
  8335. struct foo x;
  8336. struct foo
  8337. swapfoo (struct foo inval)
  8338. @{
  8339. struct foo outval;
  8340. outval.a = inval.b;
  8341. outval.b = inval.a;
  8342. return outval;
  8343. @}
  8344. @end example
  8345. This simpler definition of @code{swapfoo} avoids using a local
  8346. variable to hold the result about to be return, by using a structure
  8347. constructor (@pxref{Structure Constructors}), like this:
  8348. @example
  8349. struct foo
  8350. swapfoo (struct foo inval)
  8351. @{
  8352. return (struct foo) @{ inval.b, inval.a @};
  8353. @}
  8354. @end example
  8355. It is valid to define a structure type in a function's parameter list,
  8356. as in
  8357. @example
  8358. int
  8359. frob_bar (struct bar @{ int a, b; @} inval)
  8360. @{
  8361. @var{body}
  8362. @}
  8363. @end example
  8364. @noindent
  8365. and @var{body} can access the fields of @var{inval} since the
  8366. structure type @code{struct bar} is defined for the whole function
  8367. body. However, there is no way to create a @code{struct bar} argument
  8368. to pass to @code{frob_bar}, except with kludges. As a result,
  8369. defining a structure type in a parameter list is useless in practice.
  8370. @node Function Declarations
  8371. @section Function Declarations
  8372. @cindex function declarations
  8373. @cindex declararing functions
  8374. To call a function, or use its name as a pointer, a @dfn{function
  8375. declaration} for the function name must be in effect at that point in
  8376. the code. The function's definition serves as a declaration of that
  8377. function for the rest of the containing scope, but to use the function
  8378. in code before the definition, or from another compilation module, a
  8379. separate function declaration must precede the use.
  8380. A function declaration looks like the start of a function definition.
  8381. It begins with the return value type (@code{void} if none) and the
  8382. function name, followed by argument declarations in parentheses
  8383. (though these can sometimes be omitted). But that's as far as the
  8384. similarity goes: instead of the function body, the declaration uses a
  8385. semicolon.
  8386. @cindex function prototype
  8387. @cindex prototype of a function
  8388. A declaration that specifies argument types is called a @dfn{function
  8389. prototype}. You can include the argument names or omit them. The
  8390. names, if included in the declaration, have no effect, but they may
  8391. serve as documentation.
  8392. This form of prototype specifies fixed argument types:
  8393. @example
  8394. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8395. @end example
  8396. @noindent
  8397. This form says the function takes no arguments:
  8398. @example
  8399. @var{rettype} @var{function} (void);
  8400. @end example
  8401. @noindent
  8402. This form declares types for some arguments, and allows additional
  8403. arguments whose types are not specified:
  8404. @example
  8405. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8406. @end example
  8407. For a parameter that's an array of variable length, you can write
  8408. its declaration with @samp{*} where the ``length'' of the array would
  8409. normally go; for example, these are all equivalent.
  8410. @example
  8411. double maximum (int n, int m, double a[n][m]);
  8412. double maximum (int n, int m, double a[*][*]);
  8413. double maximum (int n, int m, double a[ ][*]);
  8414. double maximum (int n, int m, double a[ ][m]);
  8415. @end example
  8416. @noindent
  8417. The old-fashioned form of declaration, which is not a prototype, says
  8418. nothing about the types of arguments or how many they should be:
  8419. @example
  8420. @var{rettype} @var{function} ();
  8421. @end example
  8422. @strong{Warning:} Arguments passed to a function declared without a
  8423. prototype are converted with the default argument promotions
  8424. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8425. types are unspecified.
  8426. Function declarations are usually written at the top level in a source file,
  8427. but you can also put them inside code blocks. Then the function name
  8428. is visible for the rest of the containing scope. For example:
  8429. @example
  8430. void
  8431. foo (char *file_name)
  8432. @{
  8433. void save_file (char *);
  8434. save_file (file_name);
  8435. @}
  8436. @end example
  8437. If another part of the code tries to call the function
  8438. @code{save_file}, this declaration won't be in effect there. So the
  8439. function will get an implicit declaration of the form @code{extern int
  8440. save_file ();}. That conflicts with the explicit declaration
  8441. here, and the discrepancy generates a warning.
  8442. The syntax of C traditionally allows omitting the data type in a
  8443. function declaration if it specifies a storage class or a qualifier.
  8444. Then the type defaults to @code{int}. For example:
  8445. @example
  8446. static foo (double x);
  8447. @end example
  8448. @noindent
  8449. defaults the return type to @code{int}.
  8450. This is bad practice; if you see it, fix it.
  8451. Calling a function that is undeclared has the effect of an creating
  8452. @dfn{implicit} declaration in the innermost containing scope,
  8453. equivalent to this:
  8454. @example
  8455. extern int @dfn{function} ();
  8456. @end example
  8457. @noindent
  8458. This declaration says that the function returns @code{int} but leaves
  8459. its argument types unspecified. If that does not accurately fit the
  8460. function, then the program @strong{needs} an explicit declaration of
  8461. the function with argument types in order to call it correctly.
  8462. Implicit declarations are deprecated, and a function call that creates one
  8463. causes a warning.
  8464. @node Function Calls
  8465. @section Function Calls
  8466. @cindex function calls
  8467. @cindex calling functions
  8468. Starting a program automatically calls the function named @code{main}
  8469. (@pxref{The main Function}). Aside from that, a function does nothing
  8470. except when it is @dfn{called}. That occurs during the execution of a
  8471. function-call expression specifying that function.
  8472. A function-call expression looks like this:
  8473. @example
  8474. @var{function} (@var{arguments}@r{@dots{}})
  8475. @end example
  8476. Most of the time, @var{function} is a function name. However, it can
  8477. also be an expression with a function pointer value; that way, the
  8478. program can determine at run time which function to call.
  8479. The @var{arguments} are a series of expressions separated by commas.
  8480. Each expression specifies one argument to pass to the function.
  8481. The list of arguments in a function call looks just like use of the
  8482. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8483. the parentheses of a function call gives it a different meaning.
  8484. Here's an example of a function call, taken from an example near the
  8485. beginning (@pxref{Complete Program}).
  8486. @example
  8487. printf ("Fibonacci series item %d is %d\n",
  8488. 19, fib (19));
  8489. @end example
  8490. The three arguments given to @code{printf} are a constant string, the
  8491. integer 19, and the integer returned by @code{fib (19)}.
  8492. @node Function Call Semantics
  8493. @section Function Call Semantics
  8494. @cindex function call semantics
  8495. @cindex semantics of function calls
  8496. @cindex call-by-value
  8497. The meaning of a function call is to compute the specified argument
  8498. expressions, convert their values according to the function's
  8499. declaration, then run the function giving it copies of the converted
  8500. values. (This method of argument passing is known as
  8501. @dfn{call-by-value}.) When the function finishes, the value it
  8502. returns becomes the value of the function-call expression.
  8503. Call-by-value implies that an assignment to the function argument
  8504. variable has no direct effect on the caller. For instance,
  8505. @example
  8506. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8507. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8508. void
  8509. subroutine (int x)
  8510. @{
  8511. x = 5;
  8512. @}
  8513. void
  8514. main (void)
  8515. @{
  8516. int y = 20;
  8517. subroutine (y);
  8518. printf ("y is %d\n", y);
  8519. return EXIT_SUCCESS;
  8520. @}
  8521. @end example
  8522. @noindent
  8523. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8524. from the value of @code{y}, but this does not establish any other
  8525. relationship between the two variables. Thus, the assignment to
  8526. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8527. If an argument's type is specified by the function's declaration, the
  8528. function call converts the argument expression to that type if
  8529. possible. If the conversion is impossible, that is an error.
  8530. If the function's declaration doesn't specify the type of that
  8531. argument, then the @emph{default argument promotions} apply.
  8532. @xref{Argument Promotions}.
  8533. @node Function Pointers
  8534. @section Function Pointers
  8535. @cindex function pointers
  8536. @cindex pointers to functions
  8537. A function name refers to a fixed function. Sometimes it is useful to
  8538. call a function to be determined at run time; to do this, you can use
  8539. a @dfn{function pointer value} that points to the chosen function
  8540. (@pxref{Pointers}).
  8541. Pointer-to-function types can be used to declare variables and other
  8542. data, including array elements, structure fields, and union
  8543. alternatives. They can also be used for function arguments and return
  8544. values. These types have the peculiarity that they are never
  8545. converted automatically to @code{void *} or vice versa. However, you
  8546. can do that conversion with a cast.
  8547. @menu
  8548. * Declaring Function Pointers:: How to declare a pointer to a function.
  8549. * Assigning Function Pointers:: How to assign values to function pointers.
  8550. * Calling Function Pointers:: How to call functions through pointers.
  8551. @end menu
  8552. @node Declaring Function Pointers
  8553. @subsection Declaring Function Pointers
  8554. @cindex declaring function pointers
  8555. @cindex function pointers, declaring
  8556. The declaration of a function pointer variable (or structure field)
  8557. looks almost like a function declaration, except it has an additional
  8558. @samp{*} just before the variable name. Proper nesting requires a
  8559. pair of parentheses around the two of them. For instance, @code{int
  8560. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8561. an @code{int}-returning function.''
  8562. Contrast these three declarations:
  8563. @example
  8564. /* @r{Declare a function returning @code{char *}.} */
  8565. char *a (char *);
  8566. /* @r{Declare a pointer to a function returning @code{char}.} */
  8567. char (*a) (char *);
  8568. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8569. char *(*a) (char *);
  8570. @end example
  8571. The possible argument types of the function pointed to are the same
  8572. as in a function declaration. You can write a prototype
  8573. that specifies all the argument types:
  8574. @example
  8575. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8576. @end example
  8577. @noindent
  8578. or one that specifies some and leaves the rest unspecified:
  8579. @example
  8580. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8581. @end example
  8582. @noindent
  8583. or one that says there are no arguments:
  8584. @example
  8585. @var{rettype} (*@var{function}) (void);
  8586. @end example
  8587. You can also write a non-prototype declaration that says
  8588. nothing about the argument types:
  8589. @example
  8590. @var{rettype} (*@var{function}) ();
  8591. @end example
  8592. For example, here's a declaration for a variable that should
  8593. point to some arithmetic function that operates on two @code{double}s:
  8594. @example
  8595. double (*binary_op) (double, double);
  8596. @end example
  8597. Structure fields, union alternatives, and array elements can be
  8598. function pointers; so can parameter variables. The function pointer
  8599. declaration construct can also be combined with other operators
  8600. allowed in declarations. For instance,
  8601. @example
  8602. int **(*foo)();
  8603. @end example
  8604. @noindent
  8605. declares @code{foo} as a pointer to a function that returns
  8606. type @code{int **}, and
  8607. @example
  8608. int **(*foo[30])();
  8609. @end example
  8610. @noindent
  8611. declares @code{foo} as an array of 30 pointers to functions that
  8612. return type @code{int **}.
  8613. @example
  8614. int **(**foo)();
  8615. @end example
  8616. @noindent
  8617. declares @code{foo} as a pointer to a pointer to a function that
  8618. returns type @code{int **}.
  8619. @node Assigning Function Pointers
  8620. @subsection Assigning Function Pointers
  8621. @cindex assigning function pointers
  8622. @cindex function pointers, assigning
  8623. Assuming we have declared the variable @code{binary_op} as in the
  8624. previous section, giving it a value requires a suitable function to
  8625. use. So let's define a function suitable for the variable to point
  8626. to. Here's one:
  8627. @example
  8628. double
  8629. double_add (double a, double b)
  8630. @{
  8631. return a+b;
  8632. @}
  8633. @end example
  8634. Now we can give it a value:
  8635. @example
  8636. binary_op = double_add;
  8637. @end example
  8638. The target type of the function pointer must be upward compatible with
  8639. the type of the function (@pxref{Compatible Types}).
  8640. There is no need for @samp{&} in front of @code{double_add}.
  8641. Using a function name such as @code{double_add} as an expression
  8642. automatically converts it to the function's address, with the
  8643. appropriate function pointer type. However, it is ok to use
  8644. @samp{&} if you feel that is clearer:
  8645. @example
  8646. binary_op = &double_add;
  8647. @end example
  8648. @node Calling Function Pointers
  8649. @subsection Calling Function Pointers
  8650. @cindex calling function pointers
  8651. @cindex function pointers, calling
  8652. To call the function specified by a function pointer, just write the
  8653. function pointer value in a function call. For instance, here's a
  8654. call to the function @code{binary_op} points to:
  8655. @example
  8656. binary_op (x, 5)
  8657. @end example
  8658. Since the data type of @code{binary_op} explicitly specifies type
  8659. @code{double} for the arguments, the call converts @code{x} and 5 to
  8660. @code{double}.
  8661. The call conceptually dereferences the pointer @code{binary_op} to
  8662. ``get'' the function it points to, and calls that function. If you
  8663. wish, you can explicitly represent the dereference by writing the
  8664. @code{*} operator:
  8665. @example
  8666. (*binary_op) (x, 5)
  8667. @end example
  8668. The @samp{*} reminds people reading the code that @code{binary_op} is
  8669. a function pointer rather than the name of a specific function.
  8670. @node The main Function
  8671. @section The @code{main} Function
  8672. @cindex @code{main} function
  8673. @findex main
  8674. Every complete executable program requires at least one function,
  8675. called @code{main}, which is where execution begins. You do not have
  8676. to explicitly declare @code{main}, though GNU C permits you to do so.
  8677. Conventionally, @code{main} should be defined to follow one of these
  8678. calling conventions:
  8679. @example
  8680. int main (void) @{@r{@dots{}}@}
  8681. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8682. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8683. @end example
  8684. @noindent
  8685. Using @code{void} as the parameter list means that @code{main} does
  8686. not use the arguments. You can write @code{char **argv} instead of
  8687. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8688. constructs are equivalent.
  8689. @ignore @c Not so at present
  8690. Defining @code{main} in any other way generates a warning. Your
  8691. program will still compile, but you may get unexpected results when
  8692. executing it.
  8693. @end ignore
  8694. You can call @code{main} from C code, as you can call any other
  8695. function, though that is an unusual thing to do. When you do that,
  8696. you must write the call to pass arguments that match the parameters in
  8697. the definition of @code{main}.
  8698. The @code{main} function is not actually the first code that runs when
  8699. a program starts. In fact, the first code that runs is system code
  8700. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8701. code, but in GNU we replaced it with C code. Its job is to find
  8702. the arguments for @code{main} and call that.
  8703. @menu
  8704. * Values from main:: Returning values from the main function.
  8705. * Command-line Parameters:: Accessing command-line parameters
  8706. provided to the program.
  8707. * Environment Variables:: Accessing system environment variables.
  8708. @end menu
  8709. @node Values from main
  8710. @subsection Returning Values from @code{main}
  8711. @cindex returning values from @code{main}
  8712. @cindex success
  8713. @cindex failure
  8714. @cindex exit status
  8715. When @code{main} returns, the process terminates. Whatever value
  8716. @code{main} returns becomes the exit status which is reported to the
  8717. parent process. While nominally the return value is of type
  8718. @code{int}, in fact the exit status gets truncated to eight bits; if
  8719. @code{main} returns the value 256, the exit status is 0.
  8720. Normally, programs return only one of two values: 0 for success,
  8721. and 1 for failure. For maximum portability, use the macro
  8722. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8723. @code{stdlib.h}. Here's an example:
  8724. @cindex @code{EXIT_FAILURE}
  8725. @cindex @code{EXIT_SUCCESS}
  8726. @example
  8727. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8728. /* @r{and @code{EXIT_FAILURE}.} */
  8729. int
  8730. main (void)
  8731. @{
  8732. @r{@dots{}}
  8733. if (foo)
  8734. return EXIT_SUCCESS;
  8735. else
  8736. return EXIT_FAILURE;
  8737. @}
  8738. @end example
  8739. Some types of programs maintain special conventions for various return
  8740. values; for example, comparison programs including @code{cmp} and
  8741. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8742. the comparison couldn't be performed.
  8743. @node Command-line Parameters
  8744. @subsection Accessing Command-line Parameters
  8745. @cindex command-line parameters
  8746. @cindex parameters, command-line
  8747. If the program was invoked with any command-line arguments, it can
  8748. access them through the arguments of @code{main}, @code{argc} and
  8749. @code{argv}. (You can give these arguments any names, but the names
  8750. @code{argc} and @code{argv} are customary.)
  8751. The value of @code{argv} is an array containing all of the
  8752. command-line arguments as strings, with the name of the command
  8753. invoked as the first string. @code{argc} is an integer that says how
  8754. many strings @code{argv} contains. Here is an example of accessing
  8755. the command-line parameters, retrieving the program's name and
  8756. checking for the standard @option{--version} and @option{--help} options:
  8757. @example
  8758. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8759. int
  8760. main (int argc, char *argv[])
  8761. @{
  8762. char *program_name = argv[0];
  8763. for (int i = 1; i < argc; i++)
  8764. @{
  8765. if (!strcmp (argv[i], "--version"))
  8766. @{
  8767. /* @r{Print version information and exit.} */
  8768. @r{@dots{}}
  8769. @}
  8770. else if (!strcmp (argv[i], "--help"))
  8771. @{
  8772. /* @r{Print help information and exit.} */
  8773. @r{@dots{}}
  8774. @}
  8775. @}
  8776. @r{@dots{}}
  8777. @}
  8778. @end example
  8779. @node Environment Variables
  8780. @subsection Accessing Environment Variables
  8781. @cindex environment variables
  8782. You can optionally include a third parameter to @code{main}, another
  8783. array of strings, to capture the environment variables available to
  8784. the program. Unlike what happens with @code{argv}, there is no
  8785. additional parameter for the count of environment variables; rather,
  8786. the array of environment variables concludes with a null pointer.
  8787. @example
  8788. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8789. int
  8790. main (int argc, char *argv[], char *envp[])
  8791. @{
  8792. /* @r{Print out all environment variables.} */
  8793. int i = 0;
  8794. while (envp[i])
  8795. @{
  8796. printf ("%s\n", envp[i]);
  8797. i++;
  8798. @}
  8799. @}
  8800. @end example
  8801. Another method of retrieving environment variables is to use the
  8802. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8803. Using @code{getenv} does not require defining @code{main} to accept the
  8804. @code{envp} pointer. For example, here is a program that fetches and prints
  8805. the user's home directory (if defined):
  8806. @example
  8807. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8808. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8809. int
  8810. main (void)
  8811. @{
  8812. char *home_directory = getenv ("HOME");
  8813. if (home_directory)
  8814. printf ("My home directory is: %s\n", home_directory);
  8815. else
  8816. printf ("My home directory is not defined!\n");
  8817. @}
  8818. @end example
  8819. @node Advanced Definitions
  8820. @section Advanced Function Features
  8821. This section describes some advanced or obscure features for GNU C
  8822. function definitions. If you are just learning C, you can skip the
  8823. rest of this chapter.
  8824. @menu
  8825. * Variable-Length Array Parameters:: Functions that accept arrays
  8826. of variable length.
  8827. * Variable Number of Arguments:: Variadic functions.
  8828. * Nested Functions:: Defining functions within functions.
  8829. * Inline Function Definitions:: A function call optimization technique.
  8830. @end menu
  8831. @node Variable-Length Array Parameters
  8832. @subsection Variable-Length Array Parameters
  8833. @cindex variable-length array parameters
  8834. @cindex array parameters, variable-length
  8835. @cindex functions that accept variable-length arrays
  8836. An array parameter can have variable length: simply declare the array
  8837. type with a size that isn't constant. In a nested function, the
  8838. length can refer to a variable defined in a containing scope. In any
  8839. function, it can refer to a previous parameter, like this:
  8840. @example
  8841. struct entry
  8842. tester (int len, char data[len][len])
  8843. @{
  8844. @r{@dots{}}
  8845. @}
  8846. @end example
  8847. Alternatively, in function declarations (but not in function
  8848. definitions), you can use @code{[*]} to denote that the array
  8849. parameter is of a variable length, such that these two declarations
  8850. mean the same thing:
  8851. @example
  8852. struct entry
  8853. tester (int len, char data[len][len]);
  8854. @end example
  8855. @example
  8856. struct entry
  8857. tester (int len, char data[*][*]);
  8858. @end example
  8859. @noindent
  8860. The two forms of input are equivalent in GNU C, but emphasizing that
  8861. the array parameter is variable-length may be helpful to those
  8862. studying the code.
  8863. You can also omit the length parameter, and instead use some other
  8864. in-scope variable for the length in the function definition:
  8865. @example
  8866. struct entry
  8867. tester (char data[*][*]);
  8868. @r{@dots{}}
  8869. int dataLength = 20;
  8870. @r{@dots{}}
  8871. struct entry
  8872. tester (char data[dataLength][dataLength])
  8873. @{
  8874. @r{@dots{}}
  8875. @}
  8876. @end example
  8877. @c ??? check text above
  8878. @cindex parameter forward declaration
  8879. In GNU C, to pass the array first and the length afterward, you can
  8880. use a @dfn{parameter forward declaration}, like this:
  8881. @example
  8882. struct entry
  8883. tester (int len; char data[len][len], int len)
  8884. @{
  8885. @r{@dots{}}
  8886. @}
  8887. @end example
  8888. The @samp{int len} before the semicolon is the parameter forward
  8889. declaration; it serves the purpose of making the name @code{len} known
  8890. when the declaration of @code{data} is parsed.
  8891. You can write any number of such parameter forward declarations in the
  8892. parameter list. They can be separated by commas or semicolons, but
  8893. the last one must end with a semicolon, which is followed by the
  8894. ``real'' parameter declarations. Each forward declaration must match
  8895. a subsequent ``real'' declaration in parameter name and data type.
  8896. Standard C does not support parameter forward declarations.
  8897. @node Variable Number of Arguments
  8898. @subsection Variable-Length Parameter Lists
  8899. @cindex variable-length parameter lists
  8900. @cindex parameters lists, variable length
  8901. @cindex function parameter lists, variable length
  8902. @cindex variadic function
  8903. A function that takes a variable number of arguments is called a
  8904. @dfn{variadic function}. In C, a variadic function must specify at
  8905. least one fixed argument with an explicitly declared data type.
  8906. Additional arguments can follow, and can vary in both quantity and
  8907. data type.
  8908. In the function header, declare the fixed parameters in the normal
  8909. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8910. example of a variadic function header:
  8911. @example
  8912. int add_multiple_values (int number, ...)
  8913. @end example
  8914. @cindex @code{va_list}
  8915. @cindex @code{va_start}
  8916. @cindex @code{va_end}
  8917. The function body can refer to fixed arguments by their parameter
  8918. names, but the additional arguments have no names. Accessing them in
  8919. the function body uses certain standard macros. They are defined in
  8920. the library header file @file{stdarg.h}, so the code must
  8921. @code{#include} that file.
  8922. In the body, write
  8923. @example
  8924. va_list ap;
  8925. va_start (ap, @var{last_fixed_parameter});
  8926. @end example
  8927. @noindent
  8928. This declares the variable @code{ap} (you can use any name for it)
  8929. and then sets it up to point before the first additional argument.
  8930. Then, to fetch the next consecutive additional argument, write this:
  8931. @example
  8932. va_arg (ap, @var{type})
  8933. @end example
  8934. After fetching all the additional arguments (or as many as need to be
  8935. used), write this:
  8936. @example
  8937. va_end (ap);
  8938. @end example
  8939. Here's an example of a variadic function definition that adds any
  8940. number of @code{int} arguments. The first (fixed) argument says how
  8941. many more arguments follow.
  8942. @example
  8943. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8944. @r{@dots{}}
  8945. int
  8946. add_multiple_values (int argcount, ...)
  8947. @{
  8948. int counter, total = 0;
  8949. /* @r{Declare a variable of type @code{va_list}.} */
  8950. va_list argptr;
  8951. /* @r{Initialize that variable..} */
  8952. va_start (argptr, argcount);
  8953. for (counter = 0; counter < argcount; counter++)
  8954. @{
  8955. /* @r{Get the next additional argument.} */
  8956. total += va_arg (argptr, int);
  8957. @}
  8958. /* @r{End use of the @code{argptr} variable.} */
  8959. va_end (argptr);
  8960. return total;
  8961. @}
  8962. @end example
  8963. With GNU C, @code{va_end} is superfluous, but some other compilers
  8964. might make @code{va_start} allocate memory so that calling
  8965. @code{va_end} is necessary to avoid a memory leak. Before doing
  8966. @code{va_start} again with the same variable, do @code{va_end}
  8967. first.
  8968. @cindex @code{va_copy}
  8969. Because of this possible memory allocation, it is risky (in principle)
  8970. to copy one @code{va_list} variable to another with assignment.
  8971. Instead, use @code{va_copy}, which copies the substance but allocates
  8972. separate memory in the variable you copy to. The call looks like
  8973. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8974. @var{from} should be variables of type @code{va_list}. In principle,
  8975. do @code{va_end} on each of these variables before its scope ends.
  8976. Since the additional arguments' types are not specified in the
  8977. function's definition, the default argument promotions
  8978. (@pxref{Argument Promotions}) apply to them in function calls. The
  8979. function definition must take account of this; thus, if an argument
  8980. was passed as @code{short}, the function should get it as @code{int}.
  8981. If an argument was passed as @code{float}, the function should get it
  8982. as @code{double}.
  8983. C has no mechanism to tell the variadic function how many arguments
  8984. were passed to it, so its calling convention must give it a way to
  8985. determine this. That's why @code{add_multiple_values} takes a fixed
  8986. argument that says how many more arguments follow. Thus, you can
  8987. call the function like this:
  8988. @example
  8989. sum = add_multiple_values (3, 12, 34, 190);
  8990. /* @r{Value is 12+34+190.} */
  8991. @end example
  8992. In GNU C, there is no actual need to use the @code{va_end} function.
  8993. In fact, it does nothing. It's used for compatibility with other
  8994. compilers, when that matters.
  8995. It is a mistake to access variables declared as @code{va_list} except
  8996. in the specific ways described here. Just what that type consists of
  8997. is an implementation detail, which could vary from one platform to
  8998. another.
  8999. @node Nested Functions
  9000. @subsection Nested Functions
  9001. @cindex nested functions
  9002. @cindex functions, nested
  9003. @cindex downward funargs
  9004. @cindex thunks
  9005. A @dfn{nested function} is a function defined inside another function.
  9006. (The ability to do this indispensable for automatic translation of
  9007. certain programming languages into C.) The nested function's name is
  9008. local to the block where it is defined. For example, here we define a
  9009. nested function named @code{square}, then call it twice:
  9010. @example
  9011. @group
  9012. foo (double a, double b)
  9013. @{
  9014. double square (double z) @{ return z * z; @}
  9015. return square (a) + square (b);
  9016. @}
  9017. @end group
  9018. @end example
  9019. The nested function definition can access all the variables of the containing
  9020. function that are visible at the point of its definition. This is
  9021. called @dfn{lexical scoping}. For example, here we show a nested
  9022. function that uses an inherited variable named @code{offset}:
  9023. @example
  9024. @group
  9025. bar (int *array, int offset, int size)
  9026. @{
  9027. int access (int *array, int index)
  9028. @{ return array[index + offset]; @}
  9029. int i;
  9030. @r{@dots{}}
  9031. for (i = 0; i < size; i++)
  9032. @r{@dots{}} access (array, i) @r{@dots{}}
  9033. @}
  9034. @end group
  9035. @end example
  9036. Nested function definitions can appear wherever automatic variable
  9037. declarations are allowed; that is, in any block, interspersed with the
  9038. other declarations and statements in the block.
  9039. The nested function's name is visible only within the parent block;
  9040. the name's scope starts from its definition and continues to the end
  9041. of the containing block. If the nested function's name
  9042. is the same as the parent function's name, there will be
  9043. no way to refer to the parent function inside the scope of the
  9044. name of the nested function.
  9045. Using @code{extern} or @code{static} on a nested function definition
  9046. is an error.
  9047. It is possible to call the nested function from outside the scope of its
  9048. name by storing its address or passing the address to another function.
  9049. You can do this safely, but you must be careful:
  9050. @example
  9051. @group
  9052. hack (int *array, int size, int addition)
  9053. @{
  9054. void store (int index, int value)
  9055. @{ array[index] = value + addition; @}
  9056. intermediate (store, size);
  9057. @}
  9058. @end group
  9059. @end example
  9060. Here, the function @code{intermediate} receives the address of
  9061. @code{store} as an argument. If @code{intermediate} calls @code{store},
  9062. the arguments given to @code{store} are used to store into @code{array}.
  9063. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  9064. It is safe for @code{intermediate} to call @code{store} because
  9065. @code{hack}'s stack frame, with its arguments and local variables,
  9066. continues to exist during the call to @code{intermediate}.
  9067. Calling the nested function through its address after the containing
  9068. function has exited is asking for trouble. If it is called after a
  9069. containing scope level has exited, and if it refers to some of the
  9070. variables that are no longer in scope, it will refer to memory
  9071. containing junk or other data. It's not wise to take the risk.
  9072. The GNU C Compiler implements taking the address of a nested function
  9073. using a technique called @dfn{trampolines}. This technique was
  9074. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  9075. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  9076. A nested function can jump to a label inherited from a containing
  9077. function, provided the label was explicitly declared in the containing
  9078. function (@pxref{Local Labels}). Such a jump returns instantly to the
  9079. containing function, exiting the nested function that did the
  9080. @code{goto} and any intermediate function invocations as well. Here
  9081. is an example:
  9082. @example
  9083. @group
  9084. bar (int *array, int offset, int size)
  9085. @{
  9086. /* @r{Explicitly declare the label @code{failure}.} */
  9087. __label__ failure;
  9088. int access (int *array, int index)
  9089. @{
  9090. if (index > size)
  9091. /* @r{Exit this function,}
  9092. @r{and return to @code{bar}.} */
  9093. goto failure;
  9094. return array[index + offset];
  9095. @}
  9096. @end group
  9097. @group
  9098. int i;
  9099. @r{@dots{}}
  9100. for (i = 0; i < size; i++)
  9101. @r{@dots{}} access (array, i) @r{@dots{}}
  9102. @r{@dots{}}
  9103. return 0;
  9104. /* @r{Control comes here from @code{access}
  9105. if it does the @code{goto}.} */
  9106. failure:
  9107. return -1;
  9108. @}
  9109. @end group
  9110. @end example
  9111. To declare the nested function before its definition, use
  9112. @code{auto} (which is otherwise meaningless for function declarations;
  9113. @pxref{auto and register}). For example,
  9114. @example
  9115. bar (int *array, int offset, int size)
  9116. @{
  9117. auto int access (int *, int);
  9118. @r{@dots{}}
  9119. @r{@dots{}} access (array, i) @r{@dots{}}
  9120. @r{@dots{}}
  9121. int access (int *array, int index)
  9122. @{
  9123. @r{@dots{}}
  9124. @}
  9125. @r{@dots{}}
  9126. @}
  9127. @end example
  9128. @node Inline Function Definitions
  9129. @subsection Inline Function Definitions
  9130. @cindex inline function definitions
  9131. @cindex function definitions, inline
  9132. @findex inline
  9133. To declare a function inline, use the @code{inline} keyword in its
  9134. definition. Here's a simple function that takes a pointer-to-@code{int}
  9135. and increments the integer stored there---declared inline.
  9136. @example
  9137. struct list
  9138. @{
  9139. struct list *first, *second;
  9140. @};
  9141. inline struct list *
  9142. list_first (struct list *p)
  9143. @{
  9144. return p->first;
  9145. @}
  9146. inline struct list *
  9147. list_second (struct list *p)
  9148. @{
  9149. return p->second;
  9150. @}
  9151. @end example
  9152. optimized compilation can substitute the inline function's body for
  9153. any call to it. This is called @emph{inlining} the function. It
  9154. makes the code that contains the call run faster, significantly so if
  9155. the inline function is small.
  9156. Here's a function that uses @code{pair_second}:
  9157. @example
  9158. int
  9159. pairlist_length (struct list *l)
  9160. @{
  9161. int length = 0;
  9162. while (l)
  9163. @{
  9164. length++;
  9165. l = pair_second (l);
  9166. @}
  9167. return length;
  9168. @}
  9169. @end example
  9170. Substituting the code of @code{pair_second} into the definition of
  9171. @code{pairlist_length} results in this code, in effect:
  9172. @example
  9173. int
  9174. pairlist_length (struct list *l)
  9175. @{
  9176. int length = 0;
  9177. while (l)
  9178. @{
  9179. length++;
  9180. l = l->second;
  9181. @}
  9182. return length;
  9183. @}
  9184. @end example
  9185. Since the definition of @code{pair_second} does not say @code{extern}
  9186. or @code{static}, that definition is used only for inlining. It
  9187. doesn't generate code that can be called at run time. If not all the
  9188. calls to the function are inlined, there must be a definition of the
  9189. same function name in another module for them to call.
  9190. @cindex inline functions, omission of
  9191. @c @opindex fkeep-inline-functions
  9192. Adding @code{static} to an inline function definition means the
  9193. function definition is limited to this compilation module. Also, it
  9194. generates run-time code if necessary for the sake of any calls that
  9195. were not inlined. If all calls are inlined then the function
  9196. definition does not generate run-time code, but you can force
  9197. generation of run-time code with the option
  9198. @option{-fkeep-inline-functions}.
  9199. @cindex extern inline function
  9200. Specifying @code{extern} along with @code{inline} means the function is
  9201. external and generates run-time code to be called from other
  9202. separately compiled modules, as well as inlined. You can define the
  9203. function as @code{inline} without @code{extern} in other modules so as
  9204. to inline calls to the same function in those modules.
  9205. Why are some calls not inlined? First of all, inlining is an
  9206. optimization, so non-optimized compilation does not inline.
  9207. Some calls cannot be inlined for technical reasons. Also, certain
  9208. usages in a function definition can make it unsuitable for inline
  9209. substitution. Among these usages are: variadic functions, use of
  9210. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9211. use of nonlocal goto. The option @option{-Winline} requests a warning
  9212. when a function marked @code{inline} is unsuitable to be inlined. The
  9213. warning explains what obstacle makes it unsuitable.
  9214. Just because a call @emph{can} be inlined does not mean it
  9215. @emph{should} be inlined. The GNU C compiler weighs costs and
  9216. benefits to decide whether inlining a particular call is advantageous.
  9217. You can force inlining of all calls to a given function that can be
  9218. inlined, even in a non-optimized compilation. by specifying the
  9219. @samp{always_inline} attribute for the function, like this:
  9220. @example
  9221. /* @r{Prototype.} */
  9222. inline void foo (const char) __attribute__((always_inline));
  9223. @end example
  9224. @noindent
  9225. This is a GNU C extension. @xref{Attributes}.
  9226. A function call may be inlined even if not declared @code{inline} in
  9227. special cases where the compiler can determine this is correct and
  9228. desirable. For instance, when a static function is called only once,
  9229. it will very likely be inlined. With @option{-flto}, link-time
  9230. optimization, any function might be inlined. To absolutely prevent
  9231. inlining of a specific function, specify
  9232. @code{__attribute__((__noinline__))} in the function's definition.
  9233. @node Obsolete Definitions
  9234. @section Obsolete Function Features
  9235. These features of function definitions are still used in old
  9236. programs, but you shouldn't write code this way today.
  9237. If you are just learning C, you can skip this section.
  9238. @menu
  9239. * Old GNU Inlining:: An older inlining technique.
  9240. * Old-Style Function Definitions:: Original K&R style functions.
  9241. @end menu
  9242. @node Old GNU Inlining
  9243. @subsection Older GNU C Inlining
  9244. The GNU C spec for inline functions, before GCC version 5, defined
  9245. @code{extern inline} on a function definition to mean to inline calls
  9246. to it but @emph{not} generate code for the function that could be
  9247. called at run time. By contrast, @code{inline} without @code{extern}
  9248. specified to generate run-time code for the function. In effect, ISO
  9249. incompatibly flipped the meanings of these two cases. We changed GCC
  9250. in version 5 to adopt the ISO specification.
  9251. Many programs still use these cases with the previous GNU C meanings.
  9252. You can specify use of those meanings with the option
  9253. @option{-fgnu89-inline}. You can also specify this for a single
  9254. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9255. @example
  9256. inline __attribute__ ((gnu_inline))
  9257. int
  9258. inc (int *a)
  9259. @{
  9260. (*a)++;
  9261. @}
  9262. @end example
  9263. @node Old-Style Function Definitions
  9264. @subsection Old-Style Function Definitions
  9265. @cindex old-style function definitions
  9266. @cindex function definitions, old-style
  9267. @cindex K&R-style function definitions
  9268. The syntax of C traditionally allows omitting the data type in a
  9269. function declaration if it specifies a storage class or a qualifier.
  9270. Then the type defaults to @code{int}. For example:
  9271. @example
  9272. static foo (double x);
  9273. @end example
  9274. @noindent
  9275. defaults the return type to @code{int}. This is bad practice; if you
  9276. see it, fix it.
  9277. An @dfn{old-style} (or ``K&R'') function definition is the way
  9278. function definitions were written in the 1980s. It looks like this:
  9279. @example
  9280. @var{rettype}
  9281. @var{function} (@var{parmnames})
  9282. @var{parm_declarations}
  9283. @{
  9284. @var{body}
  9285. @}
  9286. @end example
  9287. In @var{parmnames}, only the parameter names are listed, separated by
  9288. commas. Then @var{parm_declarations} declares their data types; these
  9289. declarations look just like variable declarations. If a parameter is
  9290. listed in @var{parmnames} but has no declaration, it is implicitly
  9291. declared @code{int}.
  9292. There is no reason to write a definition this way nowadays, but they
  9293. can still be seen in older GNU programs.
  9294. An old-style variadic function definition looks like this:
  9295. @example
  9296. #include <varargs.h>
  9297. int
  9298. add_multiple_values (va_alist)
  9299. va_dcl
  9300. @{
  9301. int argcount;
  9302. int counter, total = 0;
  9303. /* @r{Declare a variable of type @code{va_list}.} */
  9304. va_list argptr;
  9305. /* @r{Initialize that variable.} */
  9306. va_start (argptr);
  9307. /* @r{Get the first argument (fixed).} */
  9308. argcount = va_arg (int);
  9309. for (counter = 0; counter < argcount; counter++)
  9310. @{
  9311. /* @r{Get the next additional argument.} */
  9312. total += va_arg (argptr, int);
  9313. @}
  9314. /* @r{End use of the @code{argptr} variable.} */
  9315. va_end (argptr);
  9316. return total;
  9317. @}
  9318. @end example
  9319. Note that the old-style variadic function definition has no fixed
  9320. parameter variables; all arguments must be obtained with
  9321. @code{va_arg}.
  9322. @node Compatible Types
  9323. @chapter Compatible Types
  9324. @cindex compatible types
  9325. @cindex types, compatible
  9326. Declaring a function or variable twice is valid in C only if the two
  9327. declarations specify @dfn{compatible} types. In addition, some
  9328. operations on pointers require operands to have compatible target
  9329. types.
  9330. In C, two different primitive types are never compatible. Likewise for
  9331. the defined types @code{struct}, @code{union} and @code{enum}: two
  9332. separately defined types are incompatible unless they are defined
  9333. exactly the same way.
  9334. However, there are a few cases where different types can be
  9335. compatible:
  9336. @itemize @bullet
  9337. @item
  9338. Every enumeration type is compatible with some integer type. In GNU
  9339. C, the choice of integer type depends on the largest enumeration
  9340. value.
  9341. @c ??? Which one, in GCC?
  9342. @c ??? ... it varies, depending on the enum values. Testing on
  9343. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9344. @c ??? then moves on to an 8-byte signed integer. These details
  9345. @c ??? might be platform-dependent, as the C standard says that even
  9346. @c ??? char could be used as an enum type, but it's at least true
  9347. @c ??? that GCC chooses a type that is at least large enough to
  9348. @c ??? hold the largest enum value.
  9349. @item
  9350. Array types are compatible if the element types are compatible
  9351. and the sizes (when specified) match.
  9352. @item
  9353. Pointer types are compatible if the pointer target types are
  9354. compatible.
  9355. @item
  9356. Function types that specify argument types are compatible if the
  9357. return types are compatible and the argument types are compatible,
  9358. argument by argument. In addition, they must all agree in whether
  9359. they use @code{...} to allow additional arguments.
  9360. @item
  9361. Function types that don't specify argument types are compatible if the
  9362. return types are.
  9363. @item
  9364. Function types that specify the argument types are compatible with
  9365. function types that omit them, if the return types are compatible and
  9366. the specified argument types are unaltered by the argument promotions
  9367. (@pxref{Argument Promotions}).
  9368. @end itemize
  9369. In order for types to be compatible, they must agree in their type
  9370. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9371. It follows that @code{const int *} and @code{int *} are incompatible
  9372. too (they are pointers to types that are not compatible).
  9373. If two types are compatible ignoring the qualifiers, we call them
  9374. @dfn{nearly compatible}. (If they are array types, we ignore
  9375. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9376. Comparison of pointers is valid if the pointers' target types are
  9377. nearly compatible. Likewise, the two branches of a conditional
  9378. expression may be pointers to nearly compatible target types.
  9379. If two types are compatible ignoring the qualifiers, and the first
  9380. type has all the qualifiers of the second type, we say the first is
  9381. @dfn{upward compatible} with the second. Assignment of pointers
  9382. requires the assigned pointer's target type to be upward compatible
  9383. with the right operand (the new value)'s target type.
  9384. @node Type Conversions
  9385. @chapter Type Conversions
  9386. @cindex type conversions
  9387. @cindex conversions, type
  9388. C converts between data types automatically when that seems clearly
  9389. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9390. @menu
  9391. * Explicit Type Conversion:: Casting a value from one type to another.
  9392. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9393. * Argument Promotions:: Automatic conversion of function parameters.
  9394. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9395. * Common Type:: When operand types differ, which one is used?
  9396. @end menu
  9397. @node Explicit Type Conversion
  9398. @section Explicit Type Conversion
  9399. @cindex cast
  9400. @cindex explicit type conversion
  9401. You can do explicit conversions using the unary @dfn{cast} operator,
  9402. which is written as a type designator (@pxref{Type Designators}) in
  9403. parentheses. For example, @code{(int)} is the operator to cast to
  9404. type @code{int}. Here's an example of using it:
  9405. @example
  9406. @{
  9407. double d = 5.5;
  9408. printf ("Floating point value: %f\n", d);
  9409. printf ("Rounded to integer: %d\n", (int) d);
  9410. @}
  9411. @end example
  9412. Using @code{(int) d} passes an @code{int} value as argument to
  9413. @code{printf}, so you can print it with @samp{%d}. Using just
  9414. @code{d} without the cast would pass the value as @code{double}.
  9415. That won't work at all with @samp{%d}; the results would be gibberish.
  9416. To divide one integer by another without rounding,
  9417. cast either of the integers to @code{double} first:
  9418. @example
  9419. (double) @var{dividend} / @var{divisor}
  9420. @var{dividend} / (double) @var{divisor}
  9421. @end example
  9422. It is enough to cast one of them, because that forces the common type
  9423. to @code{double} so the other will be converted automatically.
  9424. The valid cast conversions are:
  9425. @itemize @bullet
  9426. @item
  9427. One numerical type to another.
  9428. @item
  9429. One pointer type to another.
  9430. (Converting between pointers that point to functions
  9431. and pointers that point to data is not standard C.)
  9432. @item
  9433. A pointer type to an integer type.
  9434. @item
  9435. An integer type to a pointer type.
  9436. @item
  9437. To a union type, from the type of any alternative in the union
  9438. (@pxref{Unions}). (This is a GNU extension.)
  9439. @item
  9440. Anything, to @code{void}.
  9441. @end itemize
  9442. @node Assignment Type Conversions
  9443. @section Assignment Type Conversions
  9444. @cindex assignment type conversions
  9445. Certain type conversions occur automatically in assignments
  9446. and certain other contexts. These are the conversions
  9447. assignments can do:
  9448. @itemize @bullet
  9449. @item
  9450. Converting any numeric type to any other numeric type.
  9451. @item
  9452. Converting @code{void *} to any other pointer type
  9453. (except pointer-to-function types).
  9454. @item
  9455. Converting any other pointer type to @code{void *}.
  9456. (except pointer-to-function types).
  9457. @item
  9458. Converting 0 (a null pointer constant) to any pointer type.
  9459. @item
  9460. Converting any pointer type to @code{bool}. (The result is
  9461. 1 if the pointer is not null.)
  9462. @item
  9463. Converting between pointer types when the left-hand target type is
  9464. upward compatible with the right-hand target type. @xref{Compatible
  9465. Types}.
  9466. @end itemize
  9467. These type conversions occur automatically in certain contexts,
  9468. which are:
  9469. @itemize @bullet
  9470. @item
  9471. An assignment converts the type of the right-hand expression
  9472. to the type wanted by the left-hand expression. For example,
  9473. @example
  9474. double i;
  9475. i = 5;
  9476. @end example
  9477. @noindent
  9478. converts 5 to @code{double}.
  9479. @item
  9480. A function call, when the function specifies the type for that
  9481. argument, converts the argument value to that type. For example,
  9482. @example
  9483. void foo (double);
  9484. foo (5);
  9485. @end example
  9486. @noindent
  9487. converts 5 to @code{double}.
  9488. @item
  9489. A @code{return} statement converts the specified value to the type
  9490. that the function is declared to return. For example,
  9491. @example
  9492. double
  9493. foo ()
  9494. @{
  9495. return 5;
  9496. @}
  9497. @end example
  9498. @noindent
  9499. also converts 5 to @code{double}.
  9500. @end itemize
  9501. In all three contexts, if the conversion is impossible, that
  9502. constitutes an error.
  9503. @node Argument Promotions
  9504. @section Argument Promotions
  9505. @cindex argument promotions
  9506. @cindex promotion of arguments
  9507. When a function's definition or declaration does not specify the type
  9508. of an argument, that argument is passed without conversion in whatever
  9509. type it has, with these exceptions:
  9510. @itemize @bullet
  9511. @item
  9512. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9513. expression is a narrow integer, such as @code{char} or @code{short},
  9514. the call converts it automatically to @code{int} (@pxref{Integer
  9515. Types}).@footnote{On an embedded controller where @code{char}
  9516. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9517. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9518. never occurs in GNU C on real computers.}
  9519. In this example, the expression @code{c} is passed as an @code{int}:
  9520. @example
  9521. char c = '$';
  9522. printf ("Character c is '%c'\n", c);
  9523. @end example
  9524. @item
  9525. If the expression
  9526. has type @code{float}, the call converts it automatically to
  9527. @code{double}.
  9528. @item
  9529. An array as argument is converted to a pointer to its zeroth element.
  9530. @item
  9531. A function name as argument is converted to a pointer to that function.
  9532. @end itemize
  9533. @node Operand Promotions
  9534. @section Operand Promotions
  9535. @cindex operand promotions
  9536. The operands in arithmetic operations undergo type conversion automatically.
  9537. These @dfn{operand promotions} are the same as the argument promotions
  9538. except without converting @code{float} to @code{double}. In other words,
  9539. the operand promotions convert
  9540. @itemize @bullet
  9541. @item
  9542. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9543. @item
  9544. an array to a pointer to its zeroth element, and
  9545. @item
  9546. a function name to a pointer to that function.
  9547. @end itemize
  9548. @node Common Type
  9549. @section Common Type
  9550. @cindex common type
  9551. Arithmetic binary operators (except the shift operators) convert their
  9552. operands to the @dfn{common type} before operating on them.
  9553. Conditional expressions also convert the two possible results to their
  9554. common type. Here are the rules for determining the common type.
  9555. If one of the numbers has a floating-point type and the other is an
  9556. integer, the common type is that floating-point type. For instance,
  9557. @example
  9558. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9559. @end example
  9560. If both are floating point, the type with the larger range is the
  9561. common type.
  9562. If both are integers but of different widths, the common type
  9563. is the wider of the two.
  9564. If they are integer types of the same width, the common type is
  9565. unsigned if either operand is unsigned, and it's @code{long} if either
  9566. operand is @code{long}. It's @code{long long} if either operand is
  9567. @code{long long}.
  9568. These rules apply to addition, subtraction, multiplication, division,
  9569. remainder, comparisons, and bitwise operations. They also apply to
  9570. the two branches of a conditional expression, and to the arithmetic
  9571. done in a modifying assignment operation.
  9572. @node Scope
  9573. @chapter Scope
  9574. @cindex scope
  9575. @cindex block scope
  9576. @cindex function scope
  9577. @cindex function prototype scope
  9578. Each definition or declaration of an identifier is visible
  9579. in certain parts of the program, which is typically less than the whole
  9580. of the program. The parts where it is visible are called its @dfn{scope}.
  9581. Normally, declarations made at the top-level in the source -- that is,
  9582. not within any blocks and function definitions -- are visible for the
  9583. entire contents of the source file after that point. This is called
  9584. @dfn{file scope} (@pxref{File-Scope Variables}).
  9585. Declarations made within blocks of code, including within function
  9586. definitions, are visible only within those blocks. This is called
  9587. @dfn{block scope}. Here is an example:
  9588. @example
  9589. @group
  9590. void
  9591. foo (void)
  9592. @{
  9593. int x = 42;
  9594. @}
  9595. @end group
  9596. @end example
  9597. @noindent
  9598. In this example, the variable @code{x} has block scope; it is visible
  9599. only within the @code{foo} function definition block. Thus, other
  9600. blocks could have their own variables, also named @code{x}, without
  9601. any conflict between those variables.
  9602. A variable declared inside a subblock has a scope limited to
  9603. that subblock,
  9604. @example
  9605. @group
  9606. void
  9607. foo (void)
  9608. @{
  9609. @{
  9610. int x = 42;
  9611. @}
  9612. // @r{@code{x} is out of scope here.}
  9613. @}
  9614. @end group
  9615. @end example
  9616. If a variable declared within a block has the same name as a variable
  9617. declared outside of that block, the definition within the block
  9618. takes precedence during its scope:
  9619. @example
  9620. @group
  9621. int x = 42;
  9622. void
  9623. foo (void)
  9624. @{
  9625. int x = 17;
  9626. printf ("%d\n", x);
  9627. @}
  9628. @end group
  9629. @end example
  9630. @noindent
  9631. This prints 17, the value of the variable @code{x} declared in the
  9632. function body block, rather than the value of the variable @code{x} at
  9633. file scope. We say that the inner declaration of @code{x}
  9634. @dfn{shadows} the outer declaration, for the extent of the inner
  9635. declaration's scope.
  9636. A declaration with block scope can be shadowed by another declaration
  9637. with the same name in a subblock.
  9638. @example
  9639. @group
  9640. void
  9641. foo (void)
  9642. @{
  9643. char *x = "foo";
  9644. @{
  9645. int x = 42;
  9646. @r{@dots{}}
  9647. exit (x / 6);
  9648. @}
  9649. @}
  9650. @end group
  9651. @end example
  9652. A function parameter's scope is the entire function body, but it can
  9653. be shadowed. For example:
  9654. @example
  9655. @group
  9656. int x = 42;
  9657. void
  9658. foo (int x)
  9659. @{
  9660. printf ("%d\n", x);
  9661. @}
  9662. @end group
  9663. @end example
  9664. @noindent
  9665. This prints the value of @code{x} the function parameter, rather than
  9666. the value of the file-scope variable @code{x}.
  9667. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9668. is visible for the whole of the containing function body, both before
  9669. and after the label declaration:
  9670. @example
  9671. @group
  9672. void
  9673. foo (void)
  9674. @{
  9675. @r{@dots{}}
  9676. goto bar;
  9677. @r{@dots{}}
  9678. @{ // @r{Subblock does not affect labels.}
  9679. bar:
  9680. @r{@dots{}}
  9681. @}
  9682. goto bar;
  9683. @}
  9684. @end group
  9685. @end example
  9686. Except for labels, a declared identifier is not
  9687. visible to code before its declaration. For example:
  9688. @example
  9689. @group
  9690. int x = 5;
  9691. int y = x + 10;
  9692. @end group
  9693. @end example
  9694. @noindent
  9695. will work, but:
  9696. @example
  9697. @group
  9698. int x = y + 10;
  9699. int y = 5;
  9700. @end group
  9701. @end example
  9702. @noindent
  9703. cannot refer to the variable @code{y} before its declaration.
  9704. @include cpp.texi
  9705. @node Integers in Depth
  9706. @chapter Integers in Depth
  9707. This chapter explains the machine-level details of integer types: how
  9708. they are represented as bits in memory, and the range of possible
  9709. values for each integer type.
  9710. @menu
  9711. * Integer Representations:: How integer values appear in memory.
  9712. * Maximum and Minimum Values:: Value ranges of integer types.
  9713. @end menu
  9714. @node Integer Representations
  9715. @section Integer Representations
  9716. @cindex integer representations
  9717. @cindex representation of integers
  9718. Modern computers store integer values as binary (base-2) numbers that
  9719. occupy a single unit of storage, typically either as an 8-bit
  9720. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9721. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9722. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9723. any of these types could have some other size, bit it's not worth even
  9724. a minute to cater to that possibility. It never happens on
  9725. GNU/Linux.}
  9726. @cindex @code{CHAR_BIT}
  9727. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9728. of bits in type @code{char}. On any real operating system, the value
  9729. is 8.
  9730. The fixed sizes of numeric types necessarily limits their @dfn{range
  9731. of values}, and the particular encoding of integers decides what that
  9732. range is.
  9733. @cindex two's-complement representation
  9734. For unsigned integers, the entire space is used to represent a
  9735. nonnegative value. Signed integers are stored using
  9736. @dfn{two's-complement representation}: a signed integer with @var{n}
  9737. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9738. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9739. high-order, bit is called the @dfn{sign bit}.
  9740. @c ??? Needs correcting
  9741. There is only one value that means zero, and the most negative number
  9742. lacks a positive counterpart. As a result, negating that number
  9743. causes overflow; in practice, its result is that number back again.
  9744. For example, a two's-complement signed 8-bit integer can represent all
  9745. decimal numbers from @minus{}128 to +127. We will revisit that
  9746. peculiarity shortly.
  9747. Decades ago, there were computers that didn't use two's-complement
  9748. representation for integers (@pxref{Integers in Depth}), but they are
  9749. long gone and not worth any effort to support.
  9750. @c ??? Is this duplicate?
  9751. When an arithmetic operation produces a value that is too big to
  9752. represent, the operation is said to @dfn{overflow}. In C, integer
  9753. overflow does not interrupt the control flow or signal an error.
  9754. What it does depends on signedness.
  9755. For unsigned arithmetic, the result of an operation that overflows is
  9756. the @var{n} low-order bits of the correct value. If the correct value
  9757. is representable in @var{n} bits, that is always the result;
  9758. thus we often say that ``integer arithmetic is exact,'' omitting the
  9759. crucial qualifying phrase ``as long as the exact result is
  9760. representable.''
  9761. In principle, a C program should be written so that overflow never
  9762. occurs for signed integers, but in GNU C you can specify various ways
  9763. of handling such overflow (@pxref{Integer Overflow}).
  9764. Integer representations are best understood by looking at a table for
  9765. a tiny integer size; here are the possible values for an integer with
  9766. three bits:
  9767. @multitable @columnfractions .25 .25 .25 .25
  9768. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9769. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9770. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9771. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9772. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9773. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9774. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9775. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9776. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9777. @end multitable
  9778. The parenthesized decimal numbers in the last column represent the
  9779. signed meanings of the two's-complement of the line's value. Recall
  9780. that, in two's-complement encoding, the high-order bit is 0 when
  9781. the number is nonnegative.
  9782. We can now understand the peculiar behavior of negation of the
  9783. most negative two's-complement integer: start with 0b100,
  9784. invert the bits to get 0b011, and add 1: we get
  9785. 0b100, the value we started with.
  9786. We can also see overflow behavior in two's-complement:
  9787. @example
  9788. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9789. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9790. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9791. @end example
  9792. @noindent
  9793. A sum of two nonnegative signed values that overflows has a 1 in the
  9794. sign bit, so the exact positive result is truncated to a negative
  9795. value.
  9796. @c =====================================================================
  9797. @node Maximum and Minimum Values
  9798. @section Maximum and Minimum Values
  9799. @cindex maximum integer values
  9800. @cindex minimum integer values
  9801. @cindex integer ranges
  9802. @cindex ranges of integer types
  9803. @findex INT_MAX
  9804. @findex UINT_MAX
  9805. @findex SHRT_MAX
  9806. @findex LONG_MAX
  9807. @findex LLONG_MAX
  9808. @findex USHRT_MAX
  9809. @findex ULONG_MAX
  9810. @findex ULLONG_MAX
  9811. @findex CHAR_MAX
  9812. @findex SCHAR_MAX
  9813. @findex UCHAR_MAX
  9814. For each primitive integer type, there is a standard macro defined in
  9815. @file{limits.h} that gives the largest value that type can hold. For
  9816. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9817. On a 32-bit computer, that is equal to 2,147,483,647. The
  9818. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9819. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9820. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9821. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9822. @code{ULLONG_MAX}.
  9823. Since there are three ways to specify a @code{char} type, there are
  9824. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9825. @code{UCHAR_MAX}.
  9826. For each type that is or might be signed, there is another symbol that
  9827. gives the minimum value it can hold. (Just replace @code{MAX} with
  9828. @code{MIN} in the names listed above.) There is no minimum limit
  9829. symbol for types specified with @code{unsigned} because the
  9830. minimum for them is universally zero.
  9831. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9832. two's-complement representation, the most negative number is 1 less
  9833. than the negative of the most positive number. Thus, @code{INT_MIN}
  9834. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9835. actually write the value that way in C, since it would overflow.
  9836. That's a good reason to use @code{INT_MIN} to specify
  9837. that value. Its definition is written to avoid overflow.
  9838. @include fp.texi
  9839. @node Compilation
  9840. @chapter Compilation
  9841. @cindex object file
  9842. @cindex compilation module
  9843. @cindex make rules
  9844. @cindex link
  9845. Early in the manual we explained how to compile a simple C program
  9846. that consists of a single source file (@pxref{Compile Example}).
  9847. However, we handle only short programs that way. A typical C program
  9848. consists of many source files, each of which is usually a separate
  9849. @dfn{compilation module}---meaning that it has to be compiled
  9850. separately. (The source files that are not separate compilation
  9851. modules are those that are used via @code{#include}; see @ref{Header
  9852. Files}.)
  9853. To compile a multi-module program, you compile each of the program's
  9854. compilation modules, making an @dfn{object file} for that module. The
  9855. last step is to @dfn{link} the many object files together into a
  9856. single executable for the whole program.
  9857. The full details of how to compile C programs (and other programs)
  9858. with GCC are documented in xxxx.
  9859. @c ??? ref
  9860. Here we give only a simple introduction.
  9861. These commands compile two compilation modules, @file{foo.c} and
  9862. @file{bar.c}, running the compiler for each module:
  9863. @example
  9864. gcc -c -O -g foo.c
  9865. gcc -c -O -g bar.c
  9866. @end example
  9867. @noindent
  9868. In these commands, @option{-g} says to generate debugging information,
  9869. @option{-O} says to do some optimization, and @option{-c} says to put
  9870. the compiled code for that module into a corresponding object file and
  9871. go no further. The object file for @file{foo.c} is automatically
  9872. called @file{foo.o}, and so on.
  9873. If you wish, you can specify the additional compilation options. For
  9874. instance, @option{-Wformat -Wparenthesis -Wstrict-prototypes} request
  9875. additional warnings.
  9876. @cindex linking object files
  9877. After you compile all the program's modules, you link the object files
  9878. into a combined executable, like this:
  9879. @example
  9880. gcc -o foo foo.o bar.o
  9881. @end example
  9882. @noindent
  9883. In this command, @option{-o foo} species the file name for the
  9884. executable file, and the other arguments are the object files to link.
  9885. Always specify the executable file name in a command that generates
  9886. one.
  9887. One reason to divide a large program into multiple compilation modules
  9888. is to control how each module can access the internals of the others.
  9889. When a module declares a function or variable @code{extern}, other
  9890. modules can access it. The other functions and variables defined in a
  9891. module can't be accessed from outside that module.
  9892. The other reason for using multiple modules is so that changing one
  9893. source file does not require recompiling all of them in order to try
  9894. the modified program. It is sufficient to recompile the source file
  9895. that you changed, then link them all again. Dividing a large program
  9896. into many substantial modules in this way typically makes
  9897. recompilation much faster.
  9898. Normally we don't run any of these commands directly. Instead we
  9899. write a set of @dfn{make rules} for the program, then use the
  9900. @command{make} program to recompile only the source files that need to
  9901. be recompiled, by following those rules. @xref{Top, The GNU Make
  9902. Manual, , make, The GNU Make Manual}.
  9903. @node Directing Compilation
  9904. @chapter Directing Compilation
  9905. This chapter describes C constructs that don't alter the program's
  9906. meaning @emph{as such}, but rather direct the compiler how to treat
  9907. some aspects of the program.
  9908. @menu
  9909. * Pragmas:: Controlling compilation of some constructs.
  9910. * Static Assertions:: Compile-time tests for conditions.
  9911. @end menu
  9912. @node Pragmas
  9913. @section Pragmas
  9914. A @dfn{pragma} is an annotation in a program that gives direction to
  9915. the compiler.
  9916. @menu
  9917. * Pragma Basics:: Pragma syntax and usage.
  9918. * Severity Pragmas:: Settings for compile-time pragma output.
  9919. * Optimization Pragmas:: Controlling optimizations.
  9920. @end menu
  9921. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9922. @node Pragma Basics
  9923. @subsection Pragma Basics
  9924. C defines two syntactical forms for pragmas, the line form and the
  9925. token form. You can write any pragma in either form, with the same
  9926. meaning.
  9927. The line form is a line in the source code, like this:
  9928. @example
  9929. #pragma @var{line}
  9930. @end example
  9931. @noindent
  9932. The line pragma has no effect on the parsing of the lines around it.
  9933. This form has the drawback that it can't be generated by a macro expansion.
  9934. The token form is a series of tokens; it can appear anywhere in the
  9935. program between the other tokens.
  9936. @example
  9937. _Pragma (@var{stringconstant})
  9938. @end example
  9939. @noindent
  9940. The pragma has no effect on the syntax of the tokens that surround it;
  9941. thus, here's a pragma in the middle of an @code{if} statement:
  9942. @example
  9943. if _Pragma ("hello") (x > 1)
  9944. @end example
  9945. @noindent
  9946. However, that's an unclear thing to do; for the sake of
  9947. understandability, it is better to put a pragma on a line by itself
  9948. and not embedded in the middle of another construct.
  9949. Both forms of pragma have a textual argument. In a line pragma, the
  9950. text is the rest of the line. The textual argument to @code{_Pragma}
  9951. uses the same syntax as a C string constant: surround the text with
  9952. two @samp{"} characters, and add a backslash before each @samp{"} or
  9953. @samp{\} character in it.
  9954. With either syntax, the textual argument specifies what to do.
  9955. It begins with one or several words that specify the operation.
  9956. If the compiler does not recognize them, it ignores the pragma.
  9957. Here are the pragma operations supported in GNU C@.
  9958. @c ??? Verify font for []
  9959. @table @code
  9960. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9961. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9962. Declares that the current source file depends on @var{file}, so GNU C
  9963. compares the file times and gives a warning if @var{file} is newer
  9964. than the current source file.
  9965. This directive searches for @var{file} the way @code{#include}
  9966. searches for a non-system header file.
  9967. If @var{message} is given, the warning message includes that text.
  9968. Examples:
  9969. @example
  9970. #pragma GCC dependency "parse.y"
  9971. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9972. rerun fixincludes")
  9973. @end example
  9974. @item #pragma GCC poison @var{identifiers}
  9975. @itemx _Pragma ("GCC poison @var{identifiers}")
  9976. Poisons the identifiers listed in @var{identifiers}.
  9977. This is useful to make sure all mention of @var{identifiers} has been
  9978. deleted from the program and that no reference to them creeps back in.
  9979. If any of those identifiers appears anywhere in the source after the
  9980. directive, it causes a compilation error. For example,
  9981. @example
  9982. #pragma GCC poison printf sprintf fprintf
  9983. sprintf(some_string, "hello");
  9984. @end example
  9985. @noindent
  9986. generates an error.
  9987. If a poisoned identifier appears as part of the expansion of a macro
  9988. that was defined before the identifier was poisoned, it will @emph{not}
  9989. cause an error. Thus, system headers that define macros that use
  9990. the identifier will not cause errors.
  9991. For example,
  9992. @example
  9993. #define strrchr rindex
  9994. _Pragma ("GCC poison rindex")
  9995. strrchr(some_string, 'h');
  9996. @end example
  9997. @noindent
  9998. does not cause a compilation error.
  9999. @item #pragma GCC system_header
  10000. @itemx _Pragma ("GCC system_header")
  10001. Specify treating the rest of the current source file as if it came
  10002. from a system header file. @xref{System Headers, System Headers,
  10003. System Headers, gcc, Using the GNU Compiler Collection}.
  10004. @item #pragma GCC warning @var{message}
  10005. @itemx _Pragma ("GCC warning @var{message}")
  10006. Equivalent to @code{#warning}. Its advantage is that the
  10007. @code{_Pragma} form can be included in a macro definition.
  10008. @item #pragma GCC error @var{message}
  10009. @itemx _Pragma ("GCC error @var{message}")
  10010. Equivalent to @code{#error}. Its advantage is that the
  10011. @code{_Pragma} form can be included in a macro definition.
  10012. @item #pragma GCC message @var{message}
  10013. @itemx _Pragma ("GCC message @var{message}")
  10014. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  10015. informational message, and could be used to include additional warning
  10016. or error text without triggering more warnings or errors. (Note that
  10017. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  10018. @samp{GCC} as part of the pragma.)
  10019. @end table
  10020. @node Severity Pragmas
  10021. @subsection Severity Pragmas
  10022. These pragmas control the severity of classes of diagnostics.
  10023. You can specify the class of diagnostic with the GCC option that causes
  10024. those diagnostics to be generated.
  10025. @table @code
  10026. @item #pragma GCC diagnostic error @var{option}
  10027. @itemx _Pragma ("GCC diagnostic error @var{option}")
  10028. For code following this pragma, treat diagnostics of the variety
  10029. specified by @var{option} as errors. For example:
  10030. @example
  10031. _Pragma ("GCC diagnostic error -Wformat")
  10032. @end example
  10033. @noindent
  10034. specifies to treat diagnostics enabled by the @var{-Wformat} option
  10035. as errors rather than warnings.
  10036. @item #pragma GCC diagnostic warning @var{option}
  10037. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  10038. For code following this pragma, treat diagnostics of the variety
  10039. specified by @var{option} as warnings. This overrides the
  10040. @var{-Werror} option which says to treat warnings as errors.
  10041. @item #pragma GCC diagnostic ignore @var{option}
  10042. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  10043. For code following this pragma, refrain from reporting any diagnostics
  10044. of the variety specified by @var{option}.
  10045. @item #pragma GCC diagnostic push
  10046. @itemx _Pragma ("GCC diagnostic push")
  10047. @itemx #pragma GCC diagnostic pop
  10048. @itemx _Pragma ("GCC diagnostic pop")
  10049. These pragmas maintain a stack of states for severity settings.
  10050. @samp{GCC diagnostic push} saves the current settings on the stack,
  10051. and @samp{GCC diagnostic pop} pops the last stack item and restores
  10052. the current settings from that.
  10053. @samp{GCC diagnostic pop} when the severity setting stack is empty
  10054. restores the settings to what they were at the start of compilation.
  10055. Here is an example:
  10056. @example
  10057. _Pragma ("GCC diagnostic error -Wformat")
  10058. /* @r{@option{-Wformat} messages treated as errors. } */
  10059. _Pragma ("GCC diagnostic push")
  10060. _Pragma ("GCC diagnostic warning -Wformat")
  10061. /* @r{@option{-Wformat} messages treated as warnings. } */
  10062. _Pragma ("GCC diagnostic push")
  10063. _Pragma ("GCC diagnostic ignored -Wformat")
  10064. /* @r{@option{-Wformat} messages suppressed. } */
  10065. _Pragma ("GCC diagnostic pop")
  10066. /* @r{@option{-Wformat} messages treated as warnings again. } */
  10067. _Pragma ("GCC diagnostic pop")
  10068. /* @r{@option{-Wformat} messages treated as errors again. } */
  10069. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  10070. _Pragma ("GCC diagnostic pop")
  10071. /* @r{@option{-Wformat} messages treated once again}
  10072. @r{as specified by the GCC command-line options.} */
  10073. @end example
  10074. @end table
  10075. @node Optimization Pragmas
  10076. @subsection Optimization Pragmas
  10077. These pragmas enable a particular optimization for specific function
  10078. definitions. The settings take effect at the end of a function
  10079. definition, so the clean place to use these pragmas is between
  10080. function definitions.
  10081. @table @code
  10082. @item #pragma GCC optimize @var{optimization}
  10083. @itemx _Pragma ("GCC optimize @var{optimization}")
  10084. These pragmas enable the optimization @var{optimization} for the
  10085. following functions. For example,
  10086. @example
  10087. _Pragma ("GCC optimize -fforward-propagate")
  10088. @end example
  10089. @noindent
  10090. says to apply the @samp{forward-propagate} optimization to all
  10091. following function definitions. Specifying optimizations for
  10092. individual functions, rather than for the entire program, is rare but
  10093. can be useful for getting around a bug in the compiler.
  10094. If @var{optimization} does not correspond to a defined optimization
  10095. option, the pragma is erroneous. To turn off an optimization, use the
  10096. corresponding @samp{-fno-} option, such as
  10097. @samp{-fno-forward-propagate}.
  10098. @item #pragma GCC target @var{optimizations}
  10099. @itemx _Pragma ("GCC target @var{optimizations}")
  10100. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  10101. used for platform-specific optimizations. Thus,
  10102. @example
  10103. _Pragma ("GCC target popcnt")
  10104. @end example
  10105. @noindent
  10106. activates the optimization @samp{popcnt} for all
  10107. following function definitions. This optimization is supported
  10108. on a few common targets but not on others.
  10109. @item #pragma GCC push_options
  10110. @itemx _Pragma ("GCC push_options")
  10111. The @samp{push_options} pragma saves on a stack the current settings
  10112. specified with the @samp{target} and @samp{optimize} pragmas.
  10113. @item #pragma GCC pop_options
  10114. @itemx _Pragma ("GCC pop_options")
  10115. The @samp{pop_options} pragma pops saved settings from that stack.
  10116. Here's an example of using this stack.
  10117. @example
  10118. _Pragma ("GCC push_options")
  10119. _Pragma ("GCC optimize forward-propagate")
  10120. /* @r{Functions to compile}
  10121. @r{with the @code{forward-propagate} optimization.} */
  10122. _Pragma ("GCC pop_options")
  10123. /* @r{Ends enablement of @code{forward-propagate}.} */
  10124. @end example
  10125. @item #pragma GCC reset_options
  10126. @itemx _Pragma ("GCC reset_options")
  10127. Clears all pragma-defined @samp{target} and @samp{optimize}
  10128. optimization settings.
  10129. @end table
  10130. @node Static Assertions
  10131. @section Static Assertions
  10132. @cindex static assertions
  10133. @findex _Static_assert
  10134. You can add compiler-time tests for necessary conditions into your
  10135. code using @code{_Static_assert}. This can be useful, for example, to
  10136. check that the compilation target platform supports the type sizes
  10137. that the code expects. For example,
  10138. @example
  10139. _Static_assert ((sizeof (long int) >= 8),
  10140. "long int needs to be at least 8 bytes");
  10141. @end example
  10142. @noindent
  10143. reports a compile-time error if compiled on a system with long
  10144. integers smaller than 8 bytes, with @samp{long int needs to be at
  10145. least 8 bytes} as the error message.
  10146. Since calls @code{_Static_assert} are processed at compile time, the
  10147. expression must be computable at compile time and the error message
  10148. must be a literal string. The expression can refer to the sizes of
  10149. variables, but can't refer to their values. For example, the
  10150. following static assertion is invalid for two reasons:
  10151. @example
  10152. char *error_message
  10153. = "long int needs to be at least 8 bytes";
  10154. int size_of_long_int = sizeof (long int);
  10155. _Static_assert (size_of_long_int == 8, error_message);
  10156. @end example
  10157. @noindent
  10158. The expression @code{size_of_long_int == 8} isn't computable at
  10159. compile time, and the error message isn't a literal string.
  10160. You can, though, use preprocessor definition values with
  10161. @code{_Static_assert}:
  10162. @example
  10163. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10164. at least 8 bytes"
  10165. _Static_assert ((sizeof (long int) == 8),
  10166. LONG_INT_ERROR_MESSAGE);
  10167. @end example
  10168. Static assertions are permitted wherever a statement or declaration is
  10169. permitted, including at top level in the file, and also inside the
  10170. definition of a type.
  10171. @example
  10172. union y
  10173. @{
  10174. int i;
  10175. int *ptr;
  10176. _Static_assert (sizeof (int *) == sizeof (int),
  10177. "Pointer and int not same size");
  10178. @};
  10179. @end example
  10180. @node Type Alignment
  10181. @appendix Type Alignment
  10182. @cindex type alignment
  10183. @cindex alignment of type
  10184. @findex _Alignof
  10185. @findex __alignof__
  10186. Code for device drivers and other communication with low-level
  10187. hardware sometimes needs to be concerned with the alignment of
  10188. data objects in memory.
  10189. Each data type has a required @dfn{alignment}, always a power of 2,
  10190. that says at which memory addresses an object of that type can validly
  10191. start. A valid address for the type must be a multiple of its
  10192. alignment. If a type's alignment is 1, that means it can validly
  10193. start at any address. If a type's alignment is 2, that means it can
  10194. only start at an even address. If a type's alignment is 4, that means
  10195. it can only start at an address that is a multiple of 4.
  10196. The alignment of a type (except @code{char}) can vary depending on the
  10197. kind of computer in use. To refer to the alignment of a type in a C
  10198. program, use @code{_Alignof}, whose syntax parallels that of
  10199. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10200. operation, and it doesn't compute the value of the expression used
  10201. as its argument.
  10202. Nominally, each integer and floating-point type has an alignment equal to
  10203. the largest power of 2 that divides its size. Thus, @code{int} with
  10204. size 4 has a nominal alignment of 4, and @code{long long int} with
  10205. size 8 has a nominal alignment of 8.
  10206. However, each kind of computer generally has a maximum alignment, and
  10207. no type needs more alignment than that. If the computer's maximum
  10208. alignment is 4 (which is common), then no type's alignment is more
  10209. than 4.
  10210. The size of any type is always a multiple of its alignment; that way,
  10211. in an array whose elements have that type, all the elements are
  10212. properly aligned if the first one is.
  10213. These rules apply to all real computers today, but some embedded
  10214. controllers have odd exceptions. We don't have references to cite for
  10215. them.
  10216. @c We can't cite a nonfree manual as documentation.
  10217. Ordinary C code guarantees that every object of a given type is in
  10218. fact aligned as that type requires.
  10219. If the operand of @code{_Alignof} is a structure field, the value
  10220. is the alignment it requires. It may have a greater alignment by
  10221. coincidence, due to the other fields, but @code{_Alignof} is not
  10222. concerned about that. @xref{Structures}.
  10223. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10224. but now that the feature has been standardized, it is better
  10225. to use the standard keyword @code{_Alignof}.
  10226. @findex _Alignas
  10227. @findex __aligned__
  10228. You can explicitly specify an alignment requirement for a particular
  10229. variable or structure field by adding @code{_Alignas
  10230. (@var{alignment})} to the declaration, where @var{alignment} is a
  10231. power of 2 or a type name. For instance:
  10232. @example
  10233. char _Alignas (8) x;
  10234. @end example
  10235. @noindent
  10236. or
  10237. @example
  10238. char _Alignas (double) x;
  10239. @end example
  10240. @noindent
  10241. specifies that @code{x} must start on an address that is a multiple of
  10242. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10243. machine, that maximum is how much alignment @code{x} will get.
  10244. The older GNU C syntax for this feature looked like
  10245. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10246. declaration, and was added after the variable. For instance:
  10247. @example
  10248. char x __attribute__ ((__aligned__ 8));
  10249. @end example
  10250. @xref{Attributes}.
  10251. @node Aliasing
  10252. @appendix Aliasing
  10253. @cindex aliasing (of storage)
  10254. @cindex pointer type conversion
  10255. @cindex type conversion, pointer
  10256. We have already presented examples of casting a @code{void *} pointer
  10257. to another pointer type, and casting another pointer type to
  10258. @code{void *}.
  10259. One common kind of pointer cast is guaranteed safe: casting the value
  10260. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10261. Allocation}). It is safe because these functions do not save the
  10262. pointer anywhere else; the only way the program will access the newly
  10263. allocated memory is via the pointer just returned.
  10264. In fact, C allows casting any pointer type to any other pointer type.
  10265. Using this to access the same place in memory using two
  10266. different data types is called @dfn{aliasing}.
  10267. Aliasing is necessary in some programs that do sophisticated memory
  10268. management, such as GNU Emacs, but most C programs don't need to do
  10269. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10270. aliasing correctly requires following the rules stated below.
  10271. Otherwise, the aliasing may result in malfunctions when the program
  10272. runs.
  10273. The rest of this appendix explains the pitfalls and rules of aliasing.
  10274. @menu
  10275. * Aliasing Alignment:: Memory alignment considerations for
  10276. casting between pointer types.
  10277. * Aliasing Length:: Type size considerations for
  10278. casting between pointer types.
  10279. * Aliasing Type Rules:: Even when type alignment and size matches,
  10280. aliasing can still have surprising results.
  10281. @end menu
  10282. @node Aliasing Alignment
  10283. @appendixsection Aliasing and Alignment
  10284. In order for a type-converted pointer to be valid, it must have the
  10285. alignment that the new pointer type requires. For instance, on most
  10286. computers, @code{int} has alignment 4; the address of an @code{int}
  10287. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10288. address of a @code{char} is usually not a multiple of 4. Taking the
  10289. address of such a @code{char} and casting it to @code{int *} probably
  10290. results in an invalid pointer. Trying to dereference it may cause a
  10291. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10292. @example
  10293. foo ()
  10294. @{
  10295. char i[4];
  10296. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10297. return *p; /* @r{Crash!} */
  10298. @}
  10299. @end example
  10300. This requirement is never a problem when casting the return value
  10301. of @code{malloc} because that function always returns a pointer
  10302. with as much alignment as any type can require.
  10303. @node Aliasing Length
  10304. @appendixsection Aliasing and Length
  10305. When converting a pointer to a different pointer type, make sure the
  10306. object it really points to is at least as long as the target of the
  10307. converted pointer. For instance, suppose @code{p} has type @code{int
  10308. *} and it's cast as follows:
  10309. @example
  10310. int *p;
  10311. struct
  10312. @{
  10313. double d, e, f;
  10314. @} foo;
  10315. struct foo *q = (struct foo *)p;
  10316. q->f = 5.14159;
  10317. @end example
  10318. @noindent
  10319. the value @code{q->f} will run past the end of the @code{int} that
  10320. @code{p} points to. If @code{p} was initialized to the start of an
  10321. array of type @code{int[6]}, the object is long enough for three
  10322. @code{double}s. But if @code{p} points to something shorter,
  10323. @code{q->f} will run on beyond the end of that, overlaying some other
  10324. data. Storing that will garble that other data. Or it could extend
  10325. past the end of memory space and cause a @code{SIGSEGV} signal
  10326. (@pxref{Signals}).
  10327. @node Aliasing Type Rules
  10328. @appendixsection Type Rules for Aliasing
  10329. C code that converts a pointer to a different pointer type can use the
  10330. pointers to access the same memory locations with two different data
  10331. types. If the same address is accessed with different types in a
  10332. single control thread, optimization can make the code do surprising
  10333. things (in effect, make it malfunction).
  10334. Here's a concrete example where aliasing that can change the code's
  10335. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10336. long, like @code{int}, and so is every pointer. Thus, the structures
  10337. @code{struct a} and @code{struct b} are both 8 bytes.
  10338. @example
  10339. #include <stdio.h>
  10340. struct a @{ int size; char *data; @};
  10341. struct b @{ float size; char *data; @};
  10342. void sub (struct a *p, struct b *q)
  10343. @{
  10344.   int x;
  10345.   p->size = 0;
  10346.   q->size = 1;
  10347.   x = p->size;
  10348.   printf("x       =%d\n", x);
  10349.   printf("p->size =%d\n", (int)p->size);
  10350.   printf("q->size =%d\n", (int)q->size);
  10351. @}
  10352. int main(void)
  10353. @{
  10354.   struct a foo;
  10355.   struct a *p = &foo;
  10356.   struct b *q = (struct b *) &foo;
  10357.   sub (p, q);
  10358. @}
  10359. @end example
  10360. This code works as intended when compiled without optimization. All
  10361. the operations are carried out sequentially as written. The code
  10362. sets @code{x} to @code{p->size}, but what it actually gets is the
  10363. bits of the floating point number 1, as type @code{int}.
  10364. However, when optimizing, the compiler is allowed to assume
  10365. (mistakenly, here) that @code{q} does not point to the same storage as
  10366. @code{p}, because their data types are not allowed to alias.
  10367. From this assumption, the compiler can deduce (falsely, here) that the
  10368. assignment into @code{q->size} has no effect on the value of
  10369. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10370. be set to 0.
  10371. GNU C, following the C standard, @emph{defines} this optimization as
  10372. legitimate. Code that misbehaves when optimized following these rules
  10373. is, by definition, incorrect C code.
  10374. The rules for storage aliasing in C are based on the two data types:
  10375. the type of the object, and the type it is accessed through. The
  10376. rules permit accessing part of a storage object of type @var{t} using
  10377. only these types:
  10378. @itemize @bullet
  10379. @item
  10380. @var{t}.
  10381. @item
  10382. A type compatible with @var{t}. @xref{Compatible Types}.
  10383. @item
  10384. A signed or unsigned version of one of the above.
  10385. @item
  10386. A qualified version of one of the above.
  10387. @xref{Type Qualifiers}.
  10388. @item
  10389. An array, structure (@pxref{Structures}), or union type
  10390. (@code{Unions}) that contains one of the above, either directly as a
  10391. field or through multiple levels of fields. If @var{t} is
  10392. @code{double}, this would include @code{struct s @{ union @{ double
  10393. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10394. inside it somewhere.
  10395. @item
  10396. A character type.
  10397. @end itemize
  10398. What do these rules say about the example in this subsection?
  10399. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10400. @code{int}. The type @code{float} is not allowed as an aliasing type
  10401. by those rules, so @code{b->size} is not supposed to alias with
  10402. elements of @code{j}. Based on that assumption, GNU C makes a
  10403. permitted optimization that was not, in this case, consistent with
  10404. what the programmer intended the program to do.
  10405. Whether GCC actually performs type-based aliasing analysis depends on
  10406. the details of the code. GCC has other ways to determine (in some cases)
  10407. whether objects alias, and if it gets a reliable answer that way, it won't
  10408. fall back on type-based heuristics.
  10409. @c @opindex -fno-strict-aliasing
  10410. The importance of knowing the type-based aliasing rules is not so as
  10411. to ensure that the optimization is done where it would be safe, but so
  10412. as to ensure it is @emph{not} done in a way that would break the
  10413. program. You can turn off type-based aliasing analysis by giving GCC
  10414. the option @option{-fno-strict-aliasing}.
  10415. @node Digraphs
  10416. @appendix Digraphs
  10417. @cindex digraphs
  10418. C accepts aliases for certain characters. Apparently in the 1990s
  10419. some computer systems had trouble inputting these characters, or
  10420. trouble displaying them. These digraphs almost never appear in C
  10421. programs nowadays, but we mention them for completeness.
  10422. @table @samp
  10423. @item <:
  10424. An alias for @samp{[}.
  10425. @item :>
  10426. An alias for @samp{]}.
  10427. @item <%
  10428. An alias for @samp{@{}.
  10429. @item %>
  10430. An alias for @samp{@}}.
  10431. @item %:
  10432. An alias for @samp{#},
  10433. used for preprocessing directives (@pxref{Directives}) and
  10434. macros (@pxref{Macros}).
  10435. @end table
  10436. @node Attributes
  10437. @appendix Attributes in Declarations
  10438. @cindex attributes
  10439. @findex __attribute__
  10440. You can specify certain additional requirements in a declaration, to
  10441. get fine-grained control over code generation, and helpful
  10442. informational messages during compilation. We use a few attributes in
  10443. code examples throughout this manual, including
  10444. @table @code
  10445. @item aligned
  10446. The @code{aligned} attribute specifies a minimum alignment for a
  10447. variable or structure field, measured in bytes:
  10448. @example
  10449. int foo __attribute__ ((aligned (8))) = 0;
  10450. @end example
  10451. @noindent
  10452. This directs GNU C to allocate @code{foo} at an address that is a
  10453. multiple of 8 bytes. However, you can't force an alignment bigger
  10454. than the computer's maximum meaningful alignment.
  10455. @item packed
  10456. The @code{packed} attribute specifies to compact the fields of a
  10457. structure by not leaving gaps between fields. For example,
  10458. @example
  10459. struct __attribute__ ((packed)) bar
  10460. @{
  10461. char a;
  10462. int b;
  10463. @};
  10464. @end example
  10465. @noindent
  10466. allocates the integer field @code{b} at byte 1 in the structure,
  10467. immediately after the character field @code{a}. The packed structure
  10468. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10469. alignment is 1, that of @code{char}.
  10470. @item deprecated
  10471. Applicable to both variables and functions, the @code{deprecated}
  10472. attribute tells the compiler to issue a warning if the variable or
  10473. function is ever used in the source file.
  10474. @example
  10475. int old_foo __attribute__ ((deprecated));
  10476. int old_quux () __attribute__ ((deprecated));
  10477. @end example
  10478. @item __noinline__
  10479. The @code{__noinline__} attribute, in a function's declaration or
  10480. definition, specifies never to inline calls to that function. All
  10481. calls to that function, in a compilation unit where it has this
  10482. attribute, will be compiled to invoke the separately compiled
  10483. function. @xref{Inline Function Definitions}.
  10484. @item __noclone__
  10485. The @code{__noclone__} attribute, in a function's declaration or
  10486. definition, specifies never to clone that function. Thus, there will
  10487. be only one compiled version of the function. @xref{Label Value
  10488. Caveats}, for more information about cloning.
  10489. @item always_inline
  10490. The @code{always_inline} attribute, in a function's declaration or
  10491. definition, specifies to inline all calls to that function (unless
  10492. something about the function makes inlining impossible). This applies
  10493. to all calls to that function in a compilation unit where it has this
  10494. attribute. @xref{Inline Function Definitions}.
  10495. @item gnu_inline
  10496. The @code{gnu_inline} attribute, in a function's declaration or
  10497. definition, specifies to handle the @code{inline} keyword the way GNU
  10498. C originally implemented it, many years before ISO C said anything
  10499. about inlining. @xref{Inline Function Definitions}.
  10500. @end table
  10501. For full documentation of attributes, see the GCC manual.
  10502. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10503. the GNU Compiler Collection}.
  10504. @node Signals
  10505. @appendix Signals
  10506. @cindex signal
  10507. @cindex handler (for signal)
  10508. @cindex @code{SIGSEGV}
  10509. @cindex @code{SIGFPE}
  10510. @cindex @code{SIGBUS}
  10511. Some program operations bring about an error condition called a
  10512. @dfn{signal}. These signals terminate the program, by default.
  10513. There are various different kinds of signals, each with a name. We
  10514. have seen several such error conditions through this manual:
  10515. @table @code
  10516. @item SIGSEGV
  10517. This signal is generated when a program tries to read or write outside
  10518. the memory that is allocated for it, or to write memory that can only
  10519. be read. The name is an abbreviation for ``segmentation violation''.
  10520. @item SIGFPE
  10521. This signal indicates a fatal arithmetic error. The name is an
  10522. abbreviation for ``floating-point exception'', but covers all types of
  10523. arithmetic errors, including division by zero and overflow.
  10524. @item SIGBUS
  10525. This signal is generated when an invalid pointer is dereferenced,
  10526. typically the result of dereferencing an uninitialized pointer. It is
  10527. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10528. invalid access to valid memory, while @code{SIGBUS} indicates an
  10529. attempt to access an invalid address.
  10530. @end table
  10531. These kinds of signal allow the program to specify a function as a
  10532. @dfn{signal handler}. When a signal has a handler, it doesn't
  10533. terminate the program; instead it calls the handler.
  10534. There are many other kinds of signal; here we list only those that
  10535. come from run-time errors in C operations. The rest have to do with
  10536. the functioning of the operating system. The GNU C Library Reference
  10537. Manual gives more explanation about signals (@pxref{Program Signal
  10538. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10539. Manual}).
  10540. @node GNU Free Documentation License
  10541. @appendix GNU Free Documentation License
  10542. @include fdl.texi
  10543. @node Symbol Index
  10544. @unnumbered Index of Symbols and Keywords
  10545. @printindex fn
  10546. @node Concept Index
  10547. @unnumbered Concept Index
  10548. @printindex cp
  10549. @bye