c.texi 419 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018
  1. \input texinfo
  2. @c Copyright (C) 2022 Richard Stallman and Free Software Foundation, Inc.
  3. @c (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. @c licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Introduction}
  34. @center @titlefont{and Reference Manual}
  35. @sp 4
  36. @c @center @value{EDITION} Edition
  37. @sp 5
  38. @center Richard Stallman
  39. @center and
  40. @center Trevis Rothwell
  41. @center plus Nelson Beebe
  42. @center on floating point
  43. @page
  44. @vskip 0pt plus 1filll
  45. @insertcopying
  46. @sp 2
  47. @ignore
  48. WILL BE Published by the Free Software Foundation @*
  49. 51 Franklin Street, Fifth Floor @*
  50. Boston, MA 02110-1301 USA @*
  51. ISBN ?-??????-??-?
  52. @end ignore
  53. @ignore
  54. @sp 1
  55. Cover art by J. Random Artist
  56. @end ignore
  57. @end titlepage
  58. @summarycontents
  59. @contents
  60. @node Top
  61. @ifnottex
  62. @top GNU C Manual
  63. @end ifnottex
  64. @iftex
  65. @top Preface
  66. @end iftex
  67. This manual explains the C language for use with the GNU Compiler
  68. Collection (GCC) on the GNU/Linux system and other systems. We refer
  69. to this dialect as GNU C. If you already know C, you can use this as
  70. a reference manual.
  71. If you understand basic concepts of programming but know nothing about
  72. C, you can read this manual sequentially from the beginning to learn
  73. the C language.
  74. If you are a beginner to programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are defined in
  112. a standard library, which is automatically available in every C
  113. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  114. Reference Manual}.
  115. This manual incorporates the former GNU C Preprocessor Manual, which
  116. was among the earliest GNU Manuals. It also uses some text from the
  117. earlier GNU C Manual that was written by Trevis Rothwell and James
  118. Youngman.
  119. GNU C has many obscure features, each one either for historical
  120. compatibility or meant for very special situations. We have left them
  121. to a companion manual, the GNU C Obscurities Manual, which will be
  122. published digitally later.
  123. Please report errors and suggestions to c-manual@@gnu.org.
  124. @menu
  125. * The First Example:: Getting started with basic C code.
  126. * Complete Program:: A whole example program
  127. that can be compiled and run.
  128. * Storage:: Basic layout of storage; bytes.
  129. * Beyond Integers:: Exploring different numeric types.
  130. * Lexical Syntax:: The various lexical components of C programs.
  131. * Arithmetic:: Numeric computations.
  132. * Assignment Expressions:: Storing values in variables.
  133. * Execution Control Expressions:: Expressions combining values in various ways.
  134. * Binary Operator Grammar:: An overview of operator precedence.
  135. * Order of Execution:: The order of program execution.
  136. * Primitive Types:: More details about primitive data types.
  137. * Constants:: Explicit constant values:
  138. details and examples.
  139. * Type Size:: The memory space occupied by a type.
  140. * Pointers:: Creating and manipulating memory pointers.
  141. * Structures:: Compound data types built
  142. by grouping other types.
  143. * Arrays:: Creating and manipulating arrays.
  144. * Enumeration Types:: Sets of integers with named values.
  145. * Defining Typedef Names:: Using @code{typedef} to define type names.
  146. * Statements:: Controling program flow.
  147. * Variables:: Details about declaring, initializing,
  148. and using variables.
  149. * Type Qualifiers:: Mark variables for certain intended uses.
  150. * Functions:: Declaring, defining, and calling functions.
  151. * Compatible Types:: How to tell if two types are compatible
  152. with each other.
  153. * Type Conversions:: Converting between types.
  154. * Scope:: Different categories of identifier scope.
  155. * Preprocessing:: Using the GNU C preprocessor.
  156. * Integers in Depth:: How integer numbers are represented.
  157. * Floating Point in Depth:: How floating-point numbers are represented.
  158. * Compilation:: How to compile multi-file programs.
  159. * Directing Compilation:: Operations that affect compilation
  160. but don't change the program.
  161. Appendices
  162. * Type Alignment:: Where in memory a type can validly start.
  163. * Aliasing:: Accessing the same data in two types.
  164. * Digraphs:: Two-character aliases for some characters.
  165. * Attributes:: Specifying additional information
  166. in a declaration.
  167. * Signals:: Fatal errors triggered in various scenarios.
  168. * GNU Free Documentation License:: The license for this manual.
  169. * Symbol Index:: Keyword and symbol index.
  170. * Concept Index:: Detailed topical index.
  171. @detailmenu
  172. --- The Detailed Node Listing ---
  173. * Recursive Fibonacci:: Writing a simple function recursively.
  174. * Stack:: Each function call uses space in the stack.
  175. * Iterative Fibonacci:: Writing the same function iteratively.
  176. * Complete Example:: Turn the simple function into a full program.
  177. * Complete Explanation:: Explanation of each part of the example.
  178. * Complete Line-by-Line:: Explaining each line of the example.
  179. * Compile Example:: Using GCC to compile the example.
  180. * Float Example:: A function that uses floating-point numbers.
  181. * Array Example:: A function that works with arrays.
  182. * Array Example Call:: How to call that function.
  183. * Array Example Variations:: Different ways to write the call example.
  184. Lexical Syntax
  185. * English:: Write programs in English!
  186. * Characters:: The characters allowed in C programs.
  187. * Whitespace:: The particulars of whitespace characters.
  188. * Comments:: How to include comments in C code.
  189. * Identifiers:: How to form identifiers (names).
  190. * Operators/Punctuation:: Characters used as operators or punctuation.
  191. * Line Continuation:: Splitting one line into multiple lines.
  192. * Digraphs:: Two-character substitutes for some characters.
  193. Arithmetic
  194. * Basic Arithmetic:: Addition, subtraction, multiplication,
  195. and division.
  196. * Integer Arithmetic:: How C performs arithmetic with integer values.
  197. * Integer Overflow:: When an integer value exceeds the range
  198. of its type.
  199. * Mixed Mode:: Calculating with both integer values
  200. and floating-point values.
  201. * Division and Remainder:: How integer division works.
  202. * Numeric Comparisons:: Comparing numeric values for
  203. equality or order.
  204. * Shift Operations:: Shift integer bits left or right.
  205. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  206. Assignment Expressions
  207. * Simple Assignment:: The basics of storing a value.
  208. * Lvalues:: Expressions into which a value can be stored.
  209. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  210. * Increment/Decrement:: Shorthand for incrementing and decrementing
  211. an lvalue's contents.
  212. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  213. * Assignment in Subexpressions:: How to avoid ambiguity.
  214. * Write Assignments Separately:: Write assignments as separate statements.
  215. Execution Control Expressions
  216. * Logical Operators:: Logical conjunction, disjunction, negation.
  217. * Logicals and Comparison:: Logical operators with comparison operators.
  218. * Logicals and Assignments:: Assignments with logical operators.
  219. * Conditional Expression:: An if/else construct inside expressions.
  220. * Comma Operator:: Build a sequence of subexpressions.
  221. Order of Execution
  222. * Reordering of Operands:: Operations in C are not necessarily computed
  223. in the order they are written.
  224. * Associativity and Ordering:: Some associative operations are performed
  225. in a particular order; others are not.
  226. * Sequence Points:: Some guarantees about the order of operations.
  227. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  228. * Ordering of Operands:: Evaluation order of operands
  229. and function arguments.
  230. * Optimization and Ordering:: Compiler optimizations can reorder operations
  231. only if it has no impact on program results.
  232. Primitive Data Types
  233. * Integer Types:: Description of integer types.
  234. * Floating-Point Data Types:: Description of floating-point types.
  235. * Complex Data Types:: Description of complex number types.
  236. * The Void Type:: A type indicating no value at all.
  237. * Other Data Types:: A brief summary of other types.
  238. Constants
  239. * Integer Constants:: Literal integer values.
  240. * Integer Const Type:: Types of literal integer values.
  241. * Floating Constants:: Literal floating-point values.
  242. * Imaginary Constants:: Literal imaginary number values.
  243. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  244. * Character Constants:: Literal character values.
  245. * Unicode Character Codes:: Unicode characters represented
  246. in either UTF-16 or UTF-32.
  247. * Wide Character Constants:: Literal characters values larger than 8 bits.
  248. * String Constants:: Literal string values.
  249. * UTF-8 String Constants:: Literal UTF-8 string values.
  250. * Wide String Constants:: Literal string values made up of
  251. 16- or 32-bit characters.
  252. Pointers
  253. * Address of Data:: Using the ``address-of'' operator.
  254. * Pointer Types:: For each type, there is a pointer type.
  255. * Pointer Declarations:: Declaring variables with pointer types.
  256. * Pointer Type Designators:: Designators for pointer types.
  257. * Pointer Dereference:: Accessing what a pointer points at.
  258. * Null Pointers:: Pointers which do not point to any object.
  259. * Invalid Dereference:: Dereferencing null or invalid pointers.
  260. * Void Pointers:: Totally generic pointers, can cast to any.
  261. * Pointer Comparison:: Comparing memory address values.
  262. * Pointer Arithmetic:: Computing memory address values.
  263. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  264. * Pointer Arithmetic Low Level:: More about computing memory address values.
  265. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  266. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  267. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  268. * Printing Pointers:: Using @code{printf} for a pointer's value.
  269. Structures
  270. * Referencing Fields:: Accessing field values in a structure object.
  271. * Dynamic Memory Allocation:: Allocating space for objects
  272. while the program is running.
  273. * Field Offset:: Memory layout of fields within a structure.
  274. * Structure Layout:: Planning the memory layout of fields.
  275. * Packed Structures:: Packing structure fields as close as possible.
  276. * Bit Fields:: Dividing integer fields
  277. into fields with fewer bits.
  278. * Bit Field Packing:: How bit fields pack together in integers.
  279. * const Fields:: Making structure fields immutable.
  280. * Zero Length:: Zero-length array as a variable-length object.
  281. * Flexible Array Fields:: Another approach to variable-length objects.
  282. * Overlaying Structures:: Casting one structure type
  283. over an object of another structure type.
  284. * Structure Assignment:: Assigning values to structure objects.
  285. * Unions:: Viewing the same object in different types.
  286. * Packing With Unions:: Using a union type to pack various types into
  287. the same memory space.
  288. * Cast to Union:: Casting a value one of the union's alternative
  289. types to the type of the union itself.
  290. * Structure Constructors:: Building new structure objects.
  291. * Unnamed Types as Fields:: Fields' types do not always need names.
  292. * Incomplete Types:: Types which have not been fully defined.
  293. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  294. * Type Tags:: Scope of structure and union type tags.
  295. Arrays
  296. * Accessing Array Elements:: How to access individual elements of an array.
  297. * Declaring an Array:: How to name and reserve space for a new array.
  298. * Strings:: A string in C is a special case of array.
  299. * Incomplete Array Types:: Naming, but not allocating, a new array.
  300. * Limitations of C Arrays:: Arrays are not first-class objects.
  301. * Multidimensional Arrays:: Arrays of arrays.
  302. * Constructing Array Values:: Assigning values to an entire array at once.
  303. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  304. Statements
  305. * Expression Statement:: Evaluate an expression, as a statement,
  306. usually done for a side effect.
  307. * if Statement:: Basic conditional execution.
  308. * if-else Statement:: Multiple branches for conditional execution.
  309. * Blocks:: Grouping multiple statements together.
  310. * return Statement:: Return a value from a function.
  311. * Loop Statements:: Repeatedly executing a statement or block.
  312. * switch Statement:: Multi-way conditional choices.
  313. * switch Example:: A plausible example of using @code{switch}.
  314. * Duffs Device:: A special way to use @code{switch}.
  315. * Case Ranges:: Ranges of values for @code{switch} cases.
  316. * Null Statement:: A statement that does nothing.
  317. * goto Statement:: Jump to another point in the source code,
  318. identified by a label.
  319. * Local Labels:: Labels with limited scope.
  320. * Labels as Values:: Getting the address of a label.
  321. * Statement Exprs:: A series of statements used as an expression.
  322. Variables
  323. * Variable Declarations:: Name a variable and and reserve space for it.
  324. * Initializers:: Assigning inital values to variables.
  325. * Designated Inits:: Assigning initial values to array elements
  326. at particular array indices.
  327. * Auto Type:: Obtaining the type of a variable.
  328. * Local Variables:: Variables declared in function definitions.
  329. * File-Scope Variables:: Variables declared outside of
  330. function definitions.
  331. * Static Local Variables:: Variables declared within functions,
  332. but with permanent storage allocation.
  333. * Extern Declarations:: Declaring a variable
  334. which is allocated somewhere else.
  335. * Allocating File-Scope:: When is space allocated
  336. for file-scope variables?
  337. * auto and register:: Historically used storage directions.
  338. * Omitting Types:: The bad practice of declaring variables
  339. with implicit type.
  340. Type Qualifiers
  341. * const:: Variables whose values don't change.
  342. * volatile:: Variables whose values may be accessed
  343. or changed outside of the control of
  344. this program.
  345. * restrict Pointers:: Restricted pointers for code optimization.
  346. * restrict Pointer Example:: Example of how that works.
  347. Functions
  348. * Function Definitions:: Writing the body of a function.
  349. * Function Declarations:: Declaring the interface of a function.
  350. * Function Calls:: Using functions.
  351. * Function Call Semantics:: Call-by-value argument passing.
  352. * Function Pointers:: Using references to functions.
  353. * The main Function:: Where execution of a GNU C program begins.
  354. Type Conversions
  355. * Explicit Type Conversion:: Casting a value from one type to another.
  356. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  357. * Argument Promotions:: Automatic conversion of function parameters.
  358. * Operand Promotions:: Automatic conversion of arithmetic operands.
  359. * Common Type:: When operand types differ, which one is used?
  360. Scope
  361. * Scope:: Different categories of identifier scope.
  362. Preprocessing
  363. * Preproc Overview:: Introduction to the C preprocessor.
  364. * Directives:: The form of preprocessor directives.
  365. * Preprocessing Tokens:: The lexical elements of preprocessing.
  366. * Header Files:: Including one source file in another.
  367. * Macros:: Macro expansion by the preprocessor.
  368. * Conditionals:: Controling whether to compile some lines
  369. or ignore them.
  370. * Diagnostics:: Reporting warnings and errors.
  371. * Line Control:: Reporting source line numbers.
  372. * Null Directive:: A preprocessing no-op.
  373. Integers in Depth
  374. * Integer Representations:: How integer values appear in memory.
  375. * Maximum and Minimum Values:: Value ranges of integer types.
  376. Floating Point in Depth
  377. * Floating Representations:: How floating-point values appear in memory.
  378. * Floating Type Specs:: Precise details of memory representations.
  379. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  380. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  381. * Exception Flags:: Handling certain conditions in floating point.
  382. * Exact Floating-Point:: Not all floating calculations lose precision.
  383. * Rounding:: When a floating result can't be represented
  384. exactly in the floating-point type in use.
  385. * Rounding Issues:: Avoid magnifying rounding errors.
  386. * Significance Loss:: Subtracting numbers that are almost equal.
  387. * Fused Multiply-Add:: Taking advantage of a special floating-point
  388. instruction for faster execution.
  389. * Error Recovery:: Determining rounding errors.
  390. * Exact Floating Constants:: Precisely specified floating-point numbers.
  391. * Handling Infinity:: When floating calculation is out of range.
  392. * Handling NaN:: What floating calculation is undefined.
  393. * Signed Zeros:: Positive zero vs. negative zero.
  394. * Scaling by the Base:: A useful exact floating-point operation.
  395. * Rounding Control:: Specifying some rounding behaviors.
  396. * Machine Epsilon:: The smallest number you can add to 1.0
  397. and get a sum which is larger than 1.0.
  398. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  399. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  400. * Further Reading:: References for floating-point numbers.
  401. Directing Compilation
  402. * Pragmas:: Controling compilation of some constructs.
  403. * Static Assertions:: Compile-time tests for conditions.
  404. @end detailmenu
  405. @end menu
  406. @node The First Example
  407. @chapter The First Example
  408. This chapter presents the source code for a very simple C program and
  409. uses it to explain a few features of the language. If you already
  410. know the basic points of C presented in this chapter, you can skim it
  411. or skip it.
  412. @menu
  413. * Recursive Fibonacci:: Writing a simple function recursively.
  414. * Stack:: Each function call uses space in the stack.
  415. * Iterative Fibonacci:: Writing the same function iteratively.
  416. @end menu
  417. @node Recursive Fibonacci
  418. @section Example: Recursive Fibonacci
  419. @cindex recursive Fibonacci function
  420. @cindex Fibonacci function, recursive
  421. To introduce the most basic features of C, let's look at code for a
  422. simple mathematical function that does calculations on integers. This
  423. function calculates the @var{n}th number in the Fibonacci series, in
  424. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  425. 13, 21, 34, 55, @dots{}.
  426. @example
  427. int
  428. fib (int n)
  429. @{
  430. if (n <= 2) /* @r{This avoids infinite recursion.} */
  431. return 1;
  432. else
  433. return fib (n - 1) + fib (n - 2);
  434. @}
  435. @end example
  436. This very simple program illustrates several features of C:
  437. @itemize @bullet
  438. @item
  439. A function definition, whose first two lines constitute the function
  440. header. @xref{Function Definitions}.
  441. @item
  442. A function parameter @code{n}, referred to as the variable @code{n}
  443. inside the function body. @xref{Function Parameter Variables}.
  444. A function definition uses parameters to refer to the argument
  445. values provided in a call to that function.
  446. @item
  447. Arithmetic. C programs add with @samp{+} and subtract with
  448. @samp{-}. @xref{Arithmetic}.
  449. @item
  450. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  451. equal.'' @xref{Numeric Comparisons}.
  452. @item
  453. Integer constants written in base 10.
  454. @xref{Integer Constants}.
  455. @item
  456. A function call. The function call @code{fib (n - 1)} calls the
  457. function @code{fib}, passing as its argument the value @code{n - 1}.
  458. @xref{Function Calls}.
  459. @item
  460. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  461. comment has no effect on the execution of the program. Its purpose is
  462. to provide explanations to people reading the source code. Including
  463. comments in the code is tremendously important---they provide
  464. background information so others can understand the code more quickly.
  465. @xref{Comments}.
  466. @item
  467. Two kinds of statements, the @code{return} statement and the
  468. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  469. @item
  470. Recursion. The function @code{fib} calls itself; that is called a
  471. @dfn{recursive call}. These are valid in C, and quite common.
  472. The @code{fib} function would not be useful if it didn't return.
  473. Thus, recursive definitions, to be of any use, must avoid infinite
  474. recursion.
  475. This function definition prevents infinite recursion by specially
  476. handling the case where @code{n} is two or less. Thus the maximum
  477. depth of recursive calls is less than @code{n}.
  478. @end itemize
  479. @menu
  480. * Function Header:: The function's name and how it is called.
  481. * Function Body:: Declarations and statements that implement the function.
  482. @end menu
  483. @node Function Header
  484. @subsection Function Header
  485. @cindex function header
  486. In our example, the first two lines of the function definition are the
  487. @dfn{header}. Its purpose is to state the function's name and say how
  488. it is called:
  489. @example
  490. int
  491. fib (int n)
  492. @end example
  493. @noindent
  494. says that the function returns an integer (type @code{int}), its name is
  495. @code{fib}, and it takes one argument named @code{n} which is also an
  496. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  497. @node Function Body
  498. @subsection Function Body
  499. @cindex function body
  500. @cindex recursion
  501. The rest of the function definition is called the @dfn{function body}.
  502. Like every function body, this one starts with @samp{@{}, ends with
  503. @samp{@}}, and contains zero or more @dfn{statements} and
  504. @dfn{declarations}. Statements specify actions to take, whereas
  505. declarations define names of variables, functions, and so on. Each
  506. statement and each declaration ends with a semicolon (@samp{;}).
  507. Statements and declarations often contain @dfn{expressions}; an
  508. expression is a construct whose execution produces a @dfn{value} of
  509. some data type, but may also take actions through ``side effects''
  510. that alter subsequent execution. A statement, by contrast, does not
  511. have a value; it affects further execution of the program only through
  512. the actions it takes.
  513. This function body contains no declarations, and just one statement,
  514. but that one is a complex statement in that it contains nested
  515. statements. This function uses two kinds of statements:
  516. @table @code
  517. @item return
  518. The @code{return} statement makes the function return immediately.
  519. It looks like this:
  520. @example
  521. return @var{value};
  522. @end example
  523. Its meaning is to compute the expression @var{value} and exit the
  524. function, making it return whatever value that expression produced.
  525. For instance,
  526. @example
  527. return 1;
  528. @end example
  529. @noindent
  530. returns the integer 1 from the function, and
  531. @example
  532. return fib (n - 1) + fib (n - 2);
  533. @end example
  534. @noindent
  535. returns a value computed by performing two function calls
  536. as specified and adding their results.
  537. @item @code{if}@dots{}@code{else}
  538. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  539. Each time it executes, it chooses one of its two substatements to execute
  540. and ignores the other. It looks like this:
  541. @example
  542. if (@var{condition})
  543. @var{if-true-statement}
  544. else
  545. @var{if-false-statement}
  546. @end example
  547. Its meaning is to compute the expression @var{condition} and, if it's
  548. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  549. @var{if-false-statement}. @xref{if-else Statement}.
  550. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  551. simply an expression. It's considered ``true'' if its value is
  552. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  553. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  554. Comparisons}.) Thus,
  555. @example
  556. if (n <= 2)
  557. return 1;
  558. else
  559. return fib (n - 1) + fib (n - 2);
  560. @end example
  561. @noindent
  562. first tests whether the value of @code{n} is less than or equal to 2.
  563. If so, the expression @code{n <= 2} has the value 1. So execution
  564. continues with the statement
  565. @example
  566. return 1;
  567. @end example
  568. @noindent
  569. Otherwise, execution continues with this statement:
  570. @example
  571. return fib (n - 1) + fib (n - 2);
  572. @end example
  573. Each of these statements ends the execution of the function and
  574. provides a value for it to return. @xref{return Statement}.
  575. @end table
  576. Calculating @code{fib} using ordinary integers in C works only for
  577. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  578. in type @code{int}. The addition operation that tries to add
  579. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  580. This occurrence is called @dfn{integer overflow}.
  581. Overflow can manifest itself in various ways, but one thing that can't
  582. possibly happen is to produce the correct value, since that can't fit
  583. in the space for the value. @xref{Integer Overflow}.
  584. @xref{Functions}, for a full explanation about functions.
  585. @node Stack
  586. @section The Stack, And Stack Overflow
  587. @cindex stack
  588. @cindex stack frame
  589. @cindex stack overflow
  590. @cindex recursion, drawbacks of
  591. @cindex stack frame
  592. Recursion has a drawback: there are limits to how many nested function
  593. calls a program can make. In C, each function call allocates a block
  594. of memory which it uses until the call returns. C allocates these
  595. blocks consecutively within a large area of memory known as the
  596. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  597. The size of the stack is limited; if the program tries to use too
  598. much, that causes the program to fail because the stack is full. This
  599. is called @dfn{stack overflow}.
  600. @cindex crash
  601. @cindex segmentation fault
  602. Stack overflow on GNU/Linux typically manifests itself as the
  603. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  604. fault.'' By default, this signal terminates the program immediately,
  605. rather than letting the program try to recover, or reach an expected
  606. ending point. (We commonly say in this case that the program
  607. ``crashes''). @xref{Signals}.
  608. It is inconvenient to observe a crash by passing too large
  609. an argument to recursive Fibonacci, because the program would run a
  610. long time before it crashes. This algorithm is simple but
  611. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  612. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  613. the final result.
  614. However, you can observe stack overflow very quickly if you use
  615. this function instead:
  616. @example
  617. int
  618. fill_stack (int n)
  619. @{
  620. if (n <= 1) /* @r{This limits the depth of recursion.} */
  621. return 1;
  622. else
  623. return fill_stack (n - 1);
  624. @}
  625. @end example
  626. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  627. and using the default configuration, an experiment showed there is
  628. enough stack space to do 261906 nested calls to that function. One
  629. more, and the stack overflows and the program crashes. On another
  630. platform, with a different configuration, or with a different
  631. function, the limit might be bigger or smaller.
  632. @node Iterative Fibonacci
  633. @section Example: Iterative Fibonacci
  634. @cindex iterative Fibonacci function
  635. @cindex Fibonacci function, iterative
  636. Here's a much faster algorithm for computing the same Fibonacci
  637. series. It is faster for two reasons. First, it uses @dfn{iteration}
  638. (that is, repetition or looping) rather than recursion, so it doesn't
  639. take time for a large number of function calls. But mainly, it is
  640. faster because the number of repetitions is small---only @code{@var{n}}.
  641. @c If you change this, change the duplicate in node Example of for.
  642. @example
  643. int
  644. fib (int n)
  645. @{
  646. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  647. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  648. int i;
  649. for (i = 1; i < n; ++i)
  650. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  651. /* @r{since @code{i < n} is false the first time.} */
  652. @{
  653. /* @r{Now @code{last} is @code{fib (@code{i})}}
  654. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  655. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  656. int next = prev + last;
  657. /* @r{Shift the values down.} */
  658. prev = last;
  659. last = next;
  660. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  661. @r{and @code{prev} is @code{fib (@code{i})}.}
  662. @r{But that won't stay true for long,}
  663. @r{because we are about to increment @code{i}.} */
  664. @}
  665. return last;
  666. @}
  667. @end example
  668. This definition computes @code{fib (@var{n})} in a time proportional
  669. to @code{@var{n}}. The comments in the definition explain how it works: it
  670. advances through the series, always keeps the last two values in
  671. @code{last} and @code{prev}, and adds them to get the next value.
  672. Here are the additional C features that this definition uses:
  673. @table @asis
  674. @item Internal blocks
  675. Within a function, wherever a statement is called for, you can write a
  676. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  677. more statements and declarations. (You can also use additional
  678. blocks as statements in a block.)
  679. The function body also counts as a block, which is why it can contain
  680. statements and declarations.
  681. @xref{Blocks}.
  682. @item Declarations of local variables
  683. This function body contains declarations as well as statements. There
  684. are three declarations directly in the function body, as well as a
  685. fourth declaration in an internal block. Each starts with @code{int}
  686. because it declares a variable whose type is integer. One declaration
  687. can declare several variables, but each of these declarations is
  688. simple and declares just one variable.
  689. Variables declared inside a block (either a function body or an
  690. internal block) are @dfn{local variables}. These variables exist only
  691. within that block; their names are not defined outside the block, and
  692. exiting the block deallocates their storage. This example declares
  693. four local variables: @code{last}, @code{prev}, @code{i}, and
  694. @code{next}.
  695. The most basic local variable declaration looks like this:
  696. @example
  697. @var{type} @var{variablename};
  698. @end example
  699. For instance,
  700. @example
  701. int i;
  702. @end example
  703. @noindent
  704. declares the local variable @code{i} as an integer.
  705. @xref{Variable Declarations}.
  706. @item Initializers
  707. When you declare a variable, you can also specify its initial value,
  708. like this:
  709. @example
  710. @var{type} @var{variablename} = @var{value};
  711. @end example
  712. For instance,
  713. @example
  714. int last = 1;
  715. @end example
  716. @noindent
  717. declares the local variable @code{last} as an integer (type
  718. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  719. @item Assignment
  720. Assignment: a specific kind of expression, written with the @samp{=}
  721. operator, that stores a new value in a variable or other place. Thus,
  722. @example
  723. @var{variable} = @var{value}
  724. @end example
  725. @noindent
  726. is an expression that computes @code{@var{value}} and stores the value in
  727. @code{@var{variable}}. @xref{Assignment Expressions}.
  728. @item Expression statements
  729. An expression statement is an expression followed by a semicolon.
  730. That computes the value of the expression, then ignores the value.
  731. An expression statement is useful when the expression changes some
  732. data or has other side effects---for instance, with function calls, or
  733. with assignments as in this example. @xref{Expression Statement}.
  734. Using an expression with no side effects in an expression statement is
  735. pointless except in very special cases. For instance, the expression
  736. statement @code{x;} would examine the value of @code{x} and ignore it.
  737. That is not useful.
  738. @item Increment operator
  739. The increment operator is @samp{++}. @code{++i} is an
  740. expression that is short for @code{i = i + 1}.
  741. @xref{Increment/Decrement}.
  742. @item @code{for} statements
  743. A @code{for} statement is a clean way of executing a statement
  744. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  745. @example
  746. for (i = 1; i < n; ++i)
  747. @var{body}
  748. @end example
  749. @noindent
  750. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  751. for the loop. The loop itself consists of
  752. @itemize @bullet
  753. @item
  754. Testing @code{i < n} and exiting the loop if that's false.
  755. @item
  756. Executing @var{body}.
  757. @item
  758. Advancing the loop (executing @code{++i}, which increments @code{i}).
  759. @end itemize
  760. The net result is to execute @var{body} with 0 in @code{i},
  761. then with 1 in @code{i}, and so on, stopping just before the repetition
  762. where @code{i} would equal @code{n}.
  763. The body of the @code{for} statement must be one and only one
  764. statement. You can't write two statements in a row there; if you try
  765. to, only the first of them will be treated as part of the loop.
  766. The way to put multiple statements in those places is to group them
  767. with a block, and that's what we do in this example.
  768. @end table
  769. @node Complete Program
  770. @chapter A Complete Program
  771. @cindex complete example program
  772. @cindex example program, complete
  773. It's all very well to write a Fibonacci function, but you cannot run
  774. it by itself. It is a useful program, but it is not a complete
  775. program.
  776. In this chapter we present a complete program that contains the
  777. @code{fib} function. This example shows how to make the program
  778. start, how to make it finish, how to do computation, and how to print
  779. a result.
  780. @menu
  781. * Complete Example:: Turn the simple function into a full program.
  782. * Complete Explanation:: Explanation of each part of the example.
  783. * Complete Line-by-Line:: Explaining each line of the example.
  784. * Compile Example:: Using GCC to compile the example.
  785. @end menu
  786. @node Complete Example
  787. @section Complete Program Example
  788. Here is the complete program that uses the simple, recursive version
  789. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  790. @example
  791. #include <stdio.h>
  792. int
  793. fib (int n)
  794. @{
  795. if (n <= 2) /* @r{This avoids infinite recursion.} */
  796. return 1;
  797. else
  798. return fib (n - 1) + fib (n - 2);
  799. @}
  800. int
  801. main (void)
  802. @{
  803. printf ("Fibonacci series item %d is %d\n",
  804. 20, fib (20));
  805. return 0;
  806. @}
  807. @end example
  808. @noindent
  809. This program prints a message that shows the value of @code{fib (20)}.
  810. Now for an explanation of what that code means.
  811. @node Complete Explanation
  812. @section Complete Program Explanation
  813. @ifnottex
  814. Here's the explanation of the code of the example in the
  815. previous section.
  816. @end ifnottex
  817. This sample program prints a message that shows the value of @code{fib
  818. (20)}, and exits with code 0 (which stands for successful execution).
  819. Every C program is started by running the function named @code{main}.
  820. Therefore, the example program defines a function named @code{main} to
  821. provide a way to start it. Whatever that function does is what the
  822. program does. @xref{The main Function}.
  823. The @code{main} function is the first one called when the program
  824. runs, but it doesn't come first in the example code. The order of the
  825. function definitions in the source code makes no difference to the
  826. program's meaning.
  827. The initial call to @code{main} always passes certain arguments, but
  828. @code{main} does not have to pay attention to them. To ignore those
  829. arguments, define @code{main} with @code{void} as the parameter list.
  830. (@code{void} as a function's parameter list normally means ``call with
  831. no arguments,'' but @code{main} is a special case.)
  832. The function @code{main} returns 0 because that is
  833. the conventional way for @code{main} to indicate successful execution.
  834. It could instead return a positive integer to indicate failure, and
  835. some utility programs have specific conventions for the meaning of
  836. certain numeric @dfn{failure codes}. @xref{Values from main}.
  837. @cindex @code{printf}
  838. The simplest way to print text in C is by calling the @code{printf}
  839. function, so here we explain what that does.
  840. @cindex standard output
  841. The first argument to @code{printf} is a @dfn{string constant}
  842. (@pxref{String Constants}) that is a template for output. The
  843. function @code{printf} copies most of that string directly as output,
  844. including the newline character at the end of the string, which is
  845. written as @samp{\n}. The output goes to the program's @dfn{standard
  846. output} destination, which in the usual case is the terminal.
  847. @samp{%} in the template introduces a code that substitutes other text
  848. into the output. Specifically, @samp{%d} means to take the next
  849. argument to @code{printf} and substitute it into the text as a decimal
  850. number. (The argument for @samp{%d} must be of type @code{int}; if it
  851. isn't, @code{printf} will malfunction.) So the output is a line that
  852. looks like this:
  853. @example
  854. Fibonacci series item 20 is 6765
  855. @end example
  856. This program does not contain a definition for @code{printf} because
  857. it is defined by the C library, which makes it available in all C
  858. programs. However, each program does need to @dfn{declare}
  859. @code{printf} so it will be called correctly. The @code{#include}
  860. line takes care of that; it includes a @dfn{header file} called
  861. @file{stdio.h} into the program's code. That file is provided by the
  862. operating system and it contains declarations for the many standard
  863. input/output functions in the C library, one of which is
  864. @code{printf}.
  865. Don't worry about header files for now; we'll explain them later in
  866. @ref{Header Files}.
  867. The first argument of @code{printf} does not have to be a string
  868. constant; it can be any string (@pxref{Strings}). However, using a
  869. constant is the most common case.
  870. To learn more about @code{printf} and other facilities of the C
  871. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  872. Reference Manual}.
  873. @node Complete Line-by-Line
  874. @section Complete Program, Line by Line
  875. Here's the same example, explained line by line.
  876. @strong{Beginners, do you find this helpful or not?
  877. Would you prefer a different layout for the example?
  878. Please tell rms@@gnu.org.}
  879. @example
  880. #include <stdio.h> /* @r{Include declaration of usual} */
  881. /* @r{I/O functions such as @code{printf}.} */
  882. /* @r{Most programs need these.} */
  883. int /* @r{This function returns an @code{int}.} */
  884. fib (int n) /* @r{Its name is @code{fib};} */
  885. /* @r{its argument is called @code{n}.} */
  886. @{ /* @r{Start of function body.} */
  887. /* @r{This stops the recursion from being infinite.} */
  888. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  889. return 1; /* @r{make @code{fib} return 1.} */
  890. else /* @r{otherwise, add the two previous} */
  891. /* @r{fibonacci numbers.} */
  892. return fib (n - 1) + fib (n - 2);
  893. @}
  894. int /* @r{This function returns an @code{int}.} */
  895. main (void) /* @r{Start here; ignore arguments.} */
  896. @{ /* @r{Print message with numbers in it.} */
  897. printf ("Fibonacci series item %d is %d\n",
  898. 20, fib (20));
  899. return 0; /* @r{Terminate program, report success.} */
  900. @}
  901. @end example
  902. @node Compile Example
  903. @section Compiling the Example Program
  904. @cindex compiling
  905. @cindex executable file
  906. To run a C program requires converting the source code into an
  907. @dfn{executable file}. This is called @dfn{compiling} the program,
  908. and the command to do that using GNU C is @command{gcc}.
  909. This example program consists of a single source file. If we
  910. call that file @file{fib1.c}, the complete command to compile it is
  911. this:
  912. @example
  913. gcc -g -O -o fib1 fib1.c
  914. @end example
  915. @noindent
  916. Here, @option{-g} says to generate debugging information, @option{-O}
  917. says to optimize at the basic level, and @option{-o fib1} says to put
  918. the executable program in the file @file{fib1}.
  919. To run the program, use its file name as a shell command.
  920. For instance,
  921. @example
  922. ./fib1
  923. @end example
  924. @noindent
  925. However, unless you are sure the program is correct, you should
  926. expect to need to debug it. So use this command,
  927. @example
  928. gdb fib1
  929. @end example
  930. @noindent
  931. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  932. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  933. debug the executable program @code{fib1}.
  934. @xref{Compilation}, for an introduction to compiling more complex
  935. programs which consist of more than one source file.
  936. @node Storage
  937. @chapter Storage and Data
  938. @cindex bytes
  939. @cindex storage organization
  940. @cindex memory organization
  941. Storage in C programs is made up of units called @dfn{bytes}. On
  942. nearly all computers, a byte consists of 8 bits, but there are a few
  943. peculiar computers (mostly ``embedded controllers'' for very small
  944. systems) where a byte is longer than that. This manual does not try
  945. to explain the peculiarity of those computers; we assume that a byte
  946. is 8 bits.
  947. Every C data type is made up of a certain number of bytes; that number
  948. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  949. types @code{signed char} and @code{unsigned char} are one byte long;
  950. use those types to operate on data byte by byte. @xref{Signed and
  951. Unsigned Types}. You can refer to a series of consecutive bytes as an
  952. array of @code{char} elements; that's what an ASCII string looks like
  953. in memory. @xref{String Constants}.
  954. @node Beyond Integers
  955. @chapter Beyond Integers
  956. So far we've presented programs that operate on integers. In this
  957. chapter we'll present examples of handling non-integral numbers and
  958. arrays of numbers.
  959. @menu
  960. * Float Example:: A function that uses floating-point numbers.
  961. * Array Example:: A function that works with arrays.
  962. * Array Example Call:: How to call that function.
  963. * Array Example Variations:: Different ways to write the call example.
  964. @end menu
  965. @node Float Example
  966. @section An Example with Non-Integer Numbers
  967. @cindex floating point example
  968. Here's a function that operates on and returns @dfn{floating point}
  969. numbers that don't have to be integers. Floating point represents a
  970. number as a fraction together with a power of 2. (For more detail,
  971. @pxref{Floating-Point Data Types}.) This example calculates the
  972. average of three floating point numbers that are passed to it as
  973. arguments:
  974. @example
  975. double
  976. average_of_three (double a, double b, double c)
  977. @{
  978. return (a + b + c) / 3;
  979. @}
  980. @end example
  981. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  982. integers, and even when they happen to be integers, most likely their
  983. average is not an integer.
  984. @code{double} is the usual data type in C for calculations on
  985. floating-point numbers.
  986. To print a @code{double} with @code{printf}, we must use @samp{%f}
  987. instead of @samp{%d}:
  988. @example
  989. printf ("Average is %f\n",
  990. average_of_three (1.1, 9.8, 3.62));
  991. @end example
  992. The code that calls @code{printf} must pass a @code{double} for
  993. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  994. If the argument has the wrong type, @code{printf} will produce garbage
  995. output.
  996. Here's a complete program that computes the average of three
  997. specific numbers and prints the result:
  998. @example
  999. double
  1000. average_of_three (double a, double b, double c)
  1001. @{
  1002. return (a + b + c) / 3;
  1003. @}
  1004. int
  1005. main (void)
  1006. @{
  1007. printf ("Average is %f\n",
  1008. average_of_three (1.1, 9.8, 3.62));
  1009. return 0;
  1010. @}
  1011. @end example
  1012. From now on we will not present examples of calls to @code{main}.
  1013. Instead we encourage you to write them for yourself when you want
  1014. to test executing some code.
  1015. @node Array Example
  1016. @section An Example with Arrays
  1017. @cindex array example
  1018. A function to take the average of three numbers is very specific and
  1019. limited. A more general function would take the average of any number
  1020. of numbers. That requires passing the numbers in an array. An array
  1021. is an object in memory that contains a series of values of the same
  1022. data type. This chapter presents the basic concepts and use of arrays
  1023. through an example; for the full explanation, see @ref{Arrays}.
  1024. Here's a function definition to take the average of several
  1025. floating-point numbers, passed as type @code{double}. The first
  1026. parameter, @code{length}, specifies how many numbers are passed. The
  1027. second parameter, @code{input_data}, is an array that holds those
  1028. numbers.
  1029. @example
  1030. double
  1031. avg_of_double (int length, double input_data[])
  1032. @{
  1033. double sum = 0;
  1034. int i;
  1035. for (i = 0; i < length; i++)
  1036. sum = sum + input_data[i];
  1037. return sum / length;
  1038. @}
  1039. @end example
  1040. This introduces the expression to refer to an element of an array:
  1041. @code{input_data[i]} means the element at index @code{i} in
  1042. @code{input_data}. The index of the element can be any expression
  1043. with an integer value; in this case, the expression is @code{i}.
  1044. @xref{Accessing Array Elements}.
  1045. @cindex zero-origin indexing
  1046. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1047. valid index is one less than the number of elements. (This is known
  1048. as @dfn{zero-origin indexing}.)
  1049. This example also introduces the way to declare that a function
  1050. parameter is an array. Such declarations are modeled after the syntax
  1051. for an element of the array. Just as @code{double foo} declares that
  1052. @code{foo} is of type @code{double}, @code{double input_data[]}
  1053. declares that each element of @code{input_data} is of type
  1054. @code{double}. Therefore, @code{input_data} itself has type ``array
  1055. of @code{double}.''
  1056. When declaring an array parameter, it's not necessary to say how long
  1057. the array is. In this case, the parameter @code{input_data} has no
  1058. length information. That's why the function needs another parameter,
  1059. @code{length}, for the caller to provide that information to the
  1060. function @code{avg_of_double}.
  1061. @node Array Example Call
  1062. @section Calling the Array Example
  1063. To call the function @code{avg_of_double} requires making an
  1064. array and then passing it as an argument. Here is an example.
  1065. @example
  1066. @{
  1067. /* @r{The array of values to average.} */
  1068. double nums_to_average[5];
  1069. /* @r{The average, once we compute it.} */
  1070. double average;
  1071. /* @r{Fill in elements of @code{nums_to_average}.} */
  1072. nums_to_average[0] = 58.7;
  1073. nums_to_average[1] = 5.1;
  1074. nums_to_average[2] = 7.7;
  1075. nums_to_average[3] = 105.2;
  1076. nums_to_average[4] = -3.14159;
  1077. average = avg_of_double (5, nums_to_average);
  1078. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1079. @}
  1080. @end example
  1081. This shows an array subscripting expression again, this time
  1082. on the left side of an assignment, storing a value into an
  1083. element of an array.
  1084. It also shows how to declare a local variable that is an array:
  1085. @code{double nums_to_average[5];}. Since this declaration allocates the
  1086. space for the array, it needs to know the array's length. You can
  1087. specify the length with any expression whose value is an integer, but
  1088. in this declaration the length is a constant, the integer 5.
  1089. The name of the array, when used by itself as an expression, stands
  1090. for the address of the array's data, and that's what gets passed to
  1091. the function @code{avg_of_double} in @code{avg_of_double (5,
  1092. nums_to_average)}.
  1093. We can make the code easier to maintain by avoiding the need to write
  1094. 5, the array length, when calling @code{avg_of_double}. That way, if
  1095. we change the array to include more elements, we won't have to change
  1096. that call. One way to do this is with the @code{sizeof} operator:
  1097. @example
  1098. average = avg_of_double ((sizeof (nums_to_average)
  1099. / sizeof (nums_to_average[0])),
  1100. nums_to_average);
  1101. @end example
  1102. This computes the number of elements in @code{nums_to_average} by dividing
  1103. its total size by the size of one element. @xref{Type Size}, for more
  1104. details of using @code{sizeof}.
  1105. We don't show in this example what happens after storing the result of
  1106. @code{avg_of_double} in the variable @code{average}. Presumably
  1107. more code would follow that uses that result somehow. (Why compute
  1108. the average and not use it?) But that isn't part of this topic.
  1109. @node Array Example Variations
  1110. @section Variations for Array Example
  1111. The code to call @code{avg_of_double} has two declarations that
  1112. start with the same data type:
  1113. @example
  1114. /* @r{The array of values to average.} */
  1115. double nums_to_average[5];
  1116. /* @r{The average, once we compute it.} */
  1117. double average;
  1118. @end example
  1119. In C, you can combine the two, like this:
  1120. @example
  1121. double nums_to_average[5], average;
  1122. @end example
  1123. This declares @code{nums_to_average} so each of its elements is a
  1124. @code{double}, and @code{average} so that it simply is a
  1125. @code{double}.
  1126. However, while you @emph{can} combine them, that doesn't mean you
  1127. @emph{should}. If it is useful to write comments about the variables,
  1128. and usually it is, then it's clearer to keep the declarations separate
  1129. so you can put a comment on each one.
  1130. We set all of the elements of the array @code{nums_to_average} with
  1131. assignments, but it is more convenient to use an initializer in the
  1132. declaration:
  1133. @example
  1134. @{
  1135. /* @r{The array of values to average.} */
  1136. double nums_to_average[]
  1137. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1138. /* @r{The average, once we compute it.} */
  1139. average = avg_of_double ((sizeof (nums_to_average)
  1140. / sizeof (nums_to_average[0])),
  1141. nums_to_average);
  1142. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1143. @}
  1144. @end example
  1145. The array initializer is a comma-separated list of values, delimited
  1146. by braces. @xref{Initializers}.
  1147. Note that the declaration does not specify a size for
  1148. @code{nums_to_average}, so the size is determined from the
  1149. initializer. There are five values in the initializer, so
  1150. @code{nums_to_average} gets length 5. If we add another element to
  1151. the initializer, @code{nums_to_average} will have six elements.
  1152. Because the code computes the number of elements from the size of
  1153. the array, using @code{sizeof}, the program will operate on all the
  1154. elements in the initializer, regardless of how many those are.
  1155. @node Lexical Syntax
  1156. @chapter Lexical Syntax
  1157. @cindex lexical syntax
  1158. @cindex token
  1159. To start the full description of the C language, we explain the
  1160. lexical syntax and lexical units of C code. The lexical units of a
  1161. programming language are known as @dfn{tokens}. This chapter covers
  1162. all the tokens of C except for constants, which are covered in a later
  1163. chapter (@pxref{Constants}). One vital kind of token is the
  1164. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1165. kind.
  1166. @menu
  1167. * English:: Write programs in English!
  1168. * Characters:: The characters allowed in C programs.
  1169. * Whitespace:: The particulars of whitespace characters.
  1170. * Comments:: How to include comments in C code.
  1171. * Identifiers:: How to form identifiers (names).
  1172. * Operators/Punctuation:: Characters used as operators or punctuation.
  1173. * Line Continuation:: Splitting one line into multiple lines.
  1174. @end menu
  1175. @node English
  1176. @section Write Programs in English!
  1177. In principle, you can write the function and variable names in a
  1178. program, and the comments, in any human language. C allows any kinds
  1179. of characters in comments, and you can put non-ASCII characters into
  1180. identifiers with a special prefix. However, to enable programmers in
  1181. all countries to understand and develop the program, it is best given
  1182. today's circumstances to write identifiers and comments in
  1183. English.
  1184. English is the one language that programmers in all countries
  1185. generally study. If a program's names are in English, most
  1186. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1187. understand them. Most programmers in those countries can speak
  1188. English, or at least read it, but they do not read each other's
  1189. languages at all. In India, with so many languages, two programmers
  1190. may have no common language other than English.
  1191. If you don't feel confident in writing English, do the best you can,
  1192. and follow each English comment with a version in a language you
  1193. write better; add a note asking others to translate that to English.
  1194. Someone will eventually do that.
  1195. The program's user interface is a different matter. We don't need to
  1196. choose one language for that; it is easy to support multiple languages
  1197. and let each user choose the language to use. This requires writing
  1198. the program to support localization of its interface. (The
  1199. @code{gettext} package exists to support this; @pxref{Message
  1200. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1201. Manual}.) Then a community-based translation effort can provide
  1202. support for all the languages users want to use.
  1203. @node Characters
  1204. @section Characters
  1205. @cindex character set
  1206. @cindex Unicode
  1207. @c ??? How to express ¶?
  1208. GNU C source files are usually written in the
  1209. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1210. was defined in the 1960s for English. However, they can also include
  1211. Unicode characters represented in the
  1212. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1213. This makes it possible to represent accented letters such as @samp{á},
  1214. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1215. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1216. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1217. manual.}
  1218. In C source code, non-ASCII characters are valid in comments, in wide
  1219. character constants (@pxref{Wide Character Constants}), and in string
  1220. constants (@pxref{String Constants}).
  1221. @c ??? valid in identifiers?
  1222. Another way to specify non-ASCII characters in constants (character or
  1223. string) and identifiers is with an escape sequence starting with
  1224. backslash, specifying the intended Unicode character. (@xref{Unicode
  1225. Character Codes}.) This specifies non-ASCII characters without
  1226. putting a real non-ASCII character in the source file itself.
  1227. C accepts two-character aliases called @dfn{digraphs} for certain
  1228. characters. @xref{Digraphs}.
  1229. @node Whitespace
  1230. @section Whitespace
  1231. @cindex whitespace characters in source files
  1232. @cindex space character in source
  1233. @cindex tab character in source
  1234. @cindex formfeed in source
  1235. @cindex linefeed in source
  1236. @cindex newline in source
  1237. @cindex carriage return in source
  1238. @cindex vertical tab in source
  1239. Whitespace means characters that exist in a file but appear blank in a
  1240. printed listing of a file (or traditionally did appear blank, several
  1241. decades ago). The C language requires whitespace in order to separate
  1242. two consecutive identifiers, or to separate an identifier from a
  1243. numeric constant. Other than that, and a few special situations
  1244. described later, whitespace is optional; you can put it in when you
  1245. wish, to make the code easier to read.
  1246. Space and tab in C code are treated as whitespace characters. So are
  1247. line breaks. You can represent a line break with the newline
  1248. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1249. the CRLF sequence (two characters: carriage return followed by a
  1250. newline character).
  1251. The @dfn{formfeed} character, Control-L, was traditionally used to
  1252. divide a file into pages. It is still used this way in source code,
  1253. and the tools that generate nice printouts of source code still start
  1254. a new page after each ``formfeed'' character. Dividing code into
  1255. pages separated by formfeed characters is a good way to break it up
  1256. into comprehensible pieces and show other programmers where they start
  1257. and end.
  1258. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1259. make printing advance down to the next section of a page. We know of
  1260. no particular reason to use it in source code, but it is still
  1261. accepted as whitespace in C.
  1262. Comments are also syntactically equivalent to whitespace.
  1263. @ifinfo
  1264. @xref{Comments}.
  1265. @end ifinfo
  1266. @node Comments
  1267. @section Comments
  1268. @cindex comments
  1269. A comment encapsulates text that has no effect on the program's
  1270. execution or meaning.
  1271. The purpose of comments is to explain the code to people that read it.
  1272. Writing good comments for your code is tremendously important---they
  1273. should provide background information that helps programmers
  1274. understand the reasons why the code is written the way it is. You,
  1275. returning to the code six months from now, will need the help of these
  1276. comments to remember why you wrote it this way.
  1277. Outdated comments that become incorrect are counterproductive, so part
  1278. of the software developer's responsibility is to update comments as
  1279. needed to correspond with changes to the program code.
  1280. C allows two kinds of comment syntax, the traditional style and the
  1281. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1282. with @samp{*/}. For instance,
  1283. @example
  1284. /* @r{This is a comment in traditional C syntax.} */
  1285. @end example
  1286. A traditional comment can contain @samp{/*}, but these delimiters do
  1287. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1288. whether it contains @samp{/*} sequences.
  1289. @example
  1290. /* @r{This} /* @r{is a comment} */ But this is not! */
  1291. @end example
  1292. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1293. For instance,
  1294. @example
  1295. // @r{This is a comment in C@t{++} style.}
  1296. @end example
  1297. Line comments do nest, in effect, because @samp{//} inside a line
  1298. comment is part of that comment:
  1299. @example
  1300. // @r{this whole line is} // @r{one comment}
  1301. This is code, not comment.
  1302. @end example
  1303. It is safe to put line comments inside block comments, or vice versa.
  1304. @example
  1305. @group
  1306. /* @r{traditional comment}
  1307. // @r{contains line comment}
  1308. @r{more traditional comment}
  1309. */ text here is not a comment
  1310. // @r{line comment} /* @r{contains traditional comment} */
  1311. @end group
  1312. @end example
  1313. But beware of commenting out one end of a traditional comment with a line
  1314. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1315. inside an already-started comment.
  1316. @example
  1317. @group
  1318. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1319. Oops! The line comment has ended;
  1320. this isn't a comment any more. */
  1321. @end group
  1322. @end example
  1323. Comments are not recognized within string constants. @t{@w{"/* blah
  1324. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1325. string.
  1326. In this manual we show the text in comments in a variable-width font,
  1327. for readability, but this font distinction does not exist in source
  1328. files.
  1329. A comment is syntactically equivalent to whitespace, so it always
  1330. separates tokens. Thus,
  1331. @example
  1332. @group
  1333. int/* @r{comment} */foo;
  1334. @r{is equivalent to}
  1335. int foo;
  1336. @end group
  1337. @end example
  1338. @noindent
  1339. but clean code always uses real whitespace to separate the comment
  1340. visually from surrounding code.
  1341. @node Identifiers
  1342. @section Identifiers
  1343. @cindex identifiers
  1344. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1345. as well as @samp{_}, that does not start with a digit. Most compilers
  1346. also allow @samp{$}. An identifier can be as long as you like; for
  1347. example,
  1348. @example
  1349. int anti_dis_establishment_arian_ism;
  1350. @end example
  1351. @cindex case of letters in identifiers
  1352. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1353. and @code{A} are two different identifiers.
  1354. @cindex keyword
  1355. @cindex reserved words
  1356. Identifiers in C are used as variable names, function names, typedef
  1357. names, enumeration constants, type tags, field names, and labels.
  1358. Certain identifiers in C are @dfn{keywords}, which means they have
  1359. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1360. meaning you cannot use them in any other way. For instance, you can't
  1361. define a variable or function named @code{return} or @code{if}.
  1362. You can also include other characters, even non-ASCII characters, in
  1363. identifiers by writing their Unicode character names, which start with
  1364. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1365. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1366. characters in identifiers, and when they are written in English, they
  1367. never need non-ASCII characters. @xref{English}.
  1368. Whitespace is required to separate two consecutive identifiers, or to
  1369. separate an identifier from a preceding or following numeric
  1370. constant.
  1371. @node Operators/Punctuation
  1372. @section Operators and Punctuation
  1373. @cindex operators
  1374. @cindex punctuation
  1375. Here we describe the lexical syntax of operators and punctuation in C.
  1376. The specific operators of C and their meanings are presented in
  1377. subsequent chapters.
  1378. Most operators in C consist of one or two characters that can't be
  1379. used in identifiers. The characters used for operators in C are
  1380. @samp{!~^&|*/%+-=<>,.?:}.
  1381. Some operators are a single character. For instance, @samp{-} is the
  1382. operator for negation (with one operand) and the operator for
  1383. subtraction (with two operands).
  1384. Some operators are two characters. For example, @samp{++} is the
  1385. increment operator. Recognition of multicharacter operators works by
  1386. grouping together as many consecutive characters as can constitute one
  1387. operator.
  1388. For instance, the character sequence @samp{++} is always interpreted
  1389. as the increment operator; therefore, if we want to write two
  1390. consecutive instances of the operator @samp{+}, we must separate them
  1391. with a space so that they do not combine as one token. Applying the
  1392. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1393. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1394. of a valid C program and the former could not (since @code{a++}
  1395. is not an lvalue and thus can't be the operand of @code{++}).
  1396. A few C operators are keywords rather than special characters. They
  1397. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1398. (@pxref{Type Alignment}).
  1399. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1400. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1401. @samp{@}}) begin and end a block at the statement level
  1402. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1403. for a variable with multiple elements or components (such as arrays or
  1404. structures).
  1405. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1406. @code{array[5]}.
  1407. Parentheses are used in expressions for explicit nesting of
  1408. expressions (@pxref{Basic Arithmetic}), around the parameter
  1409. declarations in a function declaration or definition, and around the
  1410. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1411. (@pxref{Function Calls}). Several kinds of statements also use
  1412. parentheses as part of their syntax---for instance, @code{if}
  1413. statements, @code{for} statements, @code{while} statements, and
  1414. @code{switch} statements. @xref{if Statement}, and following
  1415. sections.
  1416. Parentheses are also required around the operand of the operator
  1417. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1418. type rather than a value. @xref{Type Size}.
  1419. @node Line Continuation
  1420. @section Line Continuation
  1421. @cindex line continuation
  1422. @cindex continuation of lines
  1423. The sequence of a backslash and a newline is ignored absolutely
  1424. anywhere in a C program. This makes it possible to split a single
  1425. source line into multiple lines in the source file. GNU C tolerates
  1426. and ignores other whitespace between the backslash and the newline.
  1427. In particular, it always ignores a CR (carriage return) character
  1428. there, in case some text editor decided to end the line with the CRLF
  1429. sequence.
  1430. The main use of line continuation in C is for macro definitions that
  1431. would be inconveniently long for a single line (@pxref{Macros}).
  1432. It is possible to continue a line comment onto another line with
  1433. backslash-newline. You can put backslash-newline in the middle of an
  1434. identifier, even a keyword, or an operator. You can even split
  1435. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1436. backslash-newline. Here's an ugly example:
  1437. @example
  1438. @group
  1439. /\
  1440. *
  1441. */ fo\
  1442. o +\
  1443. = 1\
  1444. 0;
  1445. @end group
  1446. @end example
  1447. @noindent
  1448. That's equivalent to @samp{/* */ foo += 10;}.
  1449. Don't do those things in real programs, since they make code hard to
  1450. read.
  1451. @strong{Note:} For the sake of using certain tools on the source code, it is
  1452. wise to end every source file with a newline character which is not
  1453. preceded by a backslash, so that it really ends the last line.
  1454. @node Arithmetic
  1455. @chapter Arithmetic
  1456. @cindex arithmetic operators
  1457. @cindex operators, arithmetic
  1458. @c ??? Duplication with other sections -- get rid of that?
  1459. Arithmetic operators in C attempt to be as similar as possible to the
  1460. abstract arithmetic operations, but it is impossible to do this
  1461. perfectly. Numbers in a computer have a finite range of possible
  1462. values, and non-integer values have a limit on their possible
  1463. accuracy. Nonetheless, in most cases you will encounter no surprises
  1464. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1465. for multiplication.
  1466. Each C operator has a @dfn{precedence}, which is its rank in the
  1467. grammatical order of the various operators. The operators with the
  1468. highest precedence grab adjoining operands first; these expressions
  1469. then become operands for operators of lower precedence. We give some
  1470. information about precedence of operators in this chapter where we
  1471. describe the operators; for the full explanation, see @ref{Binary
  1472. Operator Grammar}.
  1473. The arithmetic operators always @dfn{promote} their operands before
  1474. operating on them. This means converting narrow integer data types to
  1475. a wider data type (@pxref{Operand Promotions}). If you are just
  1476. learning C, don't worry about this yet.
  1477. Given two operands that have different types, most arithmetic
  1478. operations convert them both to their @dfn{common type}. For
  1479. instance, if one is @code{int} and the other is @code{double}, the
  1480. common type is @code{double}. (That's because @code{double} can
  1481. represent all the values that an @code{int} can hold, but not vice
  1482. versa.) For the full details, see @ref{Common Type}.
  1483. @menu
  1484. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1485. and division.
  1486. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1487. * Integer Overflow:: When an integer value exceeds the range
  1488. of its type.
  1489. * Mixed Mode:: Calculating with both integer values
  1490. and floating-point values.
  1491. * Division and Remainder:: How integer division works.
  1492. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1493. * Shift Operations:: Shift integer bits left or right.
  1494. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1495. @end menu
  1496. @node Basic Arithmetic
  1497. @section Basic Arithmetic
  1498. @cindex addition operator
  1499. @cindex subtraction operator
  1500. @cindex multiplication operator
  1501. @cindex division operator
  1502. @cindex negation operator
  1503. @cindex operator, addition
  1504. @cindex operator, subtraction
  1505. @cindex operator, multiplication
  1506. @cindex operator, division
  1507. @cindex operator, negation
  1508. Basic arithmetic in C is done with the usual binary operators of
  1509. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1510. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1511. used to change the sign of a number. The unary @code{+} operator also
  1512. exists; it yields its operand unaltered.
  1513. @samp{/} is the division operator, but dividing integers may not give
  1514. the result you expect. Its value is an integer, which is not equal to
  1515. the mathematical quotient when that is a fraction. Use @samp{%} to
  1516. get the corresponding integer remainder when necessary.
  1517. @xref{Division and Remainder}. Floating point division yields value
  1518. as close as possible to the mathematical quotient.
  1519. These operators use algebraic syntax with the usual algebraic
  1520. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1521. and division are done before addition and subtraction, but you can use
  1522. parentheses to explicitly specify how the operators nest. They are
  1523. left-associative (@pxref{Associativity and Ordering}). Thus,
  1524. @example
  1525. -a + b - c + d * e / f
  1526. @end example
  1527. @noindent
  1528. is equivalent to
  1529. @example
  1530. (((-a) + b) - c) + ((d * e) / f)
  1531. @end example
  1532. @node Integer Arithmetic
  1533. @section Integer Arithmetic
  1534. @cindex integer arithmetic
  1535. Each of the basic arithmetic operations in C has two variants for
  1536. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1537. by the data types of their operands.
  1538. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1539. A signed type can hold a range of positive and negative numbers, with
  1540. zero near the middle of the range. An unsigned type can hold only
  1541. nonnegative numbers; its range starts with zero and runs upward.
  1542. The most basic integer types are @code{int}, which normally can hold
  1543. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1544. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1545. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1546. computers but not always on embedded controllers.) @xref{Integer
  1547. Types}, for full information about integer types.
  1548. When a basic arithmetic operation is given two signed operands, it
  1549. does signed arithmetic. Given two unsigned operands, it does
  1550. unsigned arithmetic.
  1551. If one operand is @code{unsigned int} and the other is @code{int}, the
  1552. operator treats them both as unsigned. More generally, the common
  1553. type of the operands determines whether the operation is signed or
  1554. not. @xref{Common Type}.
  1555. Printing the results of unsigned arithmetic with @code{printf} using
  1556. @samp{%d} can produce surprising results for values far away from
  1557. zero. Even though the rules above say that the computation was done
  1558. with unsigned arithmetic, the printed result may appear to be signed!
  1559. The explanation is that the bit pattern resulting from addition,
  1560. subtraction or multiplication is actually the same for signed and
  1561. unsigned operations. The difference is only in the data type of the
  1562. result, which affects the @emph{interpretation} of the result bit pattern,
  1563. and whether the arithmetic operation can overflow (see the next section).
  1564. But @samp{%d} doesn't know its argument's data type. It sees only the
  1565. value's bit pattern, and it is defined to interpret that as
  1566. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1567. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1568. libc, The GNU C Library Reference Manual}.
  1569. Arithmetic in C never operates directly on narrow integer types (those
  1570. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1571. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1572. @node Integer Overflow
  1573. @section Integer Overflow
  1574. @cindex integer overflow
  1575. @cindex overflow, integer
  1576. When the mathematical value of an arithmetic operation doesn't fit in
  1577. the range of the data type in use, that's called @dfn{overflow}.
  1578. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1579. Integer overflow happens only in arithmetic operations. Type conversion
  1580. operations, by definition, do not cause overflow, not even when the
  1581. result can't fit in its new type. @xref{Integer Conversion}.
  1582. Signed numbers use two's-complement representation, in which the most
  1583. negative number lacks a positive counterpart (@pxref{Integers in
  1584. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1585. overflow.
  1586. @menu
  1587. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1588. * Signed Overflow:: Overlow in signed integer arithmetic.
  1589. @end menu
  1590. @node Unsigned Overflow
  1591. @subsection Overflow with Unsigned Integers
  1592. Unsigned arithmetic in C ignores overflow; it produces the true result
  1593. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1594. in the data type. We say it ``truncates'' the true result to the
  1595. lowest @var{n} bits.
  1596. A true result that is negative, when taken modulo the @var{n}th power
  1597. of 2, yields a positive number. For instance,
  1598. @example
  1599. unsigned int x = 1;
  1600. unsigned int y;
  1601. y = -x;
  1602. @end example
  1603. @noindent
  1604. causes overflow because the negative number @minus{}1 can't be stored
  1605. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1606. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1607. is the largest value that the unsigned data type can store. For a
  1608. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1609. and Minimum Values}.
  1610. Adding that number to itself, as here,
  1611. @example
  1612. unsigned int z;
  1613. z = y + y;
  1614. @end example
  1615. @noindent
  1616. ought to yield 8,489,934,590; however, that is again too large to fit,
  1617. so overflow truncates the value to 4,294,967,294. If that were a
  1618. signed integer, it would mean @minus{}2, which (not by coincidence)
  1619. equals @minus{}1 + @minus{}1.
  1620. @node Signed Overflow
  1621. @subsection Overflow with Signed Integers
  1622. @cindex compiler options for integer overflow
  1623. @cindex integer overflow, compiler options
  1624. @cindex overflow, compiler options
  1625. For signed integers, the result of overflow in C is @emph{in
  1626. principle} undefined, meaning that anything whatsoever could happen.
  1627. Therefore, C compilers can do optimizations that treat the overflow
  1628. case with total unconcern. (Since the result of overflow is undefined
  1629. in principle, one cannot claim that these optimizations are
  1630. erroneous.)
  1631. @strong{Watch out:} These optimizations can do surprising things. For
  1632. instance,
  1633. @example
  1634. int i;
  1635. @r{@dots{}}
  1636. if (i < i + 1)
  1637. x = 5;
  1638. @end example
  1639. @noindent
  1640. could be optimized to do the assignment unconditionally, because the
  1641. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1642. GCC offers compiler options to control handling signed integer
  1643. overflow. These options operate per module; that is, each module
  1644. behaves according to the options it was compiled with.
  1645. These two options specify particular ways to handle signed integer
  1646. overflow, other than the default way:
  1647. @table @option
  1648. @item -fwrapv
  1649. Make signed integer operations well-defined, like unsigned integer
  1650. operations: they produce the @var{n} low-order bits of the true
  1651. result. The highest of those @var{n} bits is the sign bit of the
  1652. result. With @option{-fwrapv}, these out-of-range operations are not
  1653. considered overflow, so (strictly speaking) integer overflow never
  1654. happens.
  1655. The option @option{-fwrapv} enables some optimizations based on the
  1656. defined values of out-of-range results. In GCC 8, it disables
  1657. optimizations that are based on assuming signed integer operations
  1658. will not overflow.
  1659. @item -ftrapv
  1660. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1661. This terminates the program unless the program handles the signal.
  1662. @xref{Signals}.
  1663. @end table
  1664. One other option is useful for finding where overflow occurs:
  1665. @ignore
  1666. @item -fno-strict-overflow
  1667. Disable optimizations that are based on assuming signed integer
  1668. operations will not overflow.
  1669. @end ignore
  1670. @table @option
  1671. @item -fsanitize=signed-integer-overflow
  1672. Output a warning message at run time when signed integer overflow
  1673. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1674. This takes priority over @option{-ftrapv}.
  1675. @end table
  1676. @node Mixed Mode
  1677. @section Mixed-Mode Arithmetic
  1678. Mixing integers and floating-point numbers in a basic arithmetic
  1679. operation converts the integers automatically to floating point.
  1680. In most cases, this gives exactly the desired results.
  1681. But sometimes it matters precisely where the conversion occurs.
  1682. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1683. as an integer, then converts the sum to floating point for the
  1684. multiplication. If the addition gets an overflow, that is not
  1685. equivalent to converting both integers to floating point and then
  1686. adding them. You can get the latter result by explicitly converting
  1687. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1688. @xref{Explicit Type Conversion}.
  1689. @c Eggert's report
  1690. Adding or multiplying several values, including some integers and some
  1691. floating point, does the operations left to right. Thus, @code{3.0 +
  1692. i + j} converts @code{i} to floating point, then adds 3.0, then
  1693. converts @code{j} to floating point and adds that. You can specify a
  1694. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1695. and @code{j} first and then adds that result (converting to floating
  1696. point) to 3.0. In this respect, C differs from other languages, such
  1697. as Fortran.
  1698. @node Division and Remainder
  1699. @section Division and Remainder
  1700. @cindex remainder operator
  1701. @cindex modulus
  1702. @cindex operator, remainder
  1703. Division of integers in C rounds the result to an integer. The result
  1704. is always rounded towards zero.
  1705. @example
  1706. 16 / 3 @result{} 5
  1707. -16 / 3 @result{} -5
  1708. 16 / -3 @result{} -5
  1709. -16 / -3 @result{} 5
  1710. @end example
  1711. @noindent
  1712. To get the corresponding remainder, use the @samp{%} operator:
  1713. @example
  1714. 16 % 3 @result{} 1
  1715. -16 % 3 @result{} -1
  1716. 16 % -3 @result{} 1
  1717. -16 % -3 @result{} -1
  1718. @end example
  1719. @noindent
  1720. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1721. From the rounded quotient and the remainder, you can reconstruct
  1722. the dividend, like this:
  1723. @example
  1724. int
  1725. original_dividend (int divisor, int quotient, int remainder)
  1726. @{
  1727. return divisor * quotient + remainder;
  1728. @}
  1729. @end example
  1730. To do unrounded division, use floating point. If only one operand is
  1731. floating point, @samp{/} converts the other operand to floating
  1732. point.
  1733. @example
  1734. 16.0 / 3 @result{} 5.333333333333333
  1735. 16 / 3.0 @result{} 5.333333333333333
  1736. 16.0 / 3.0 @result{} 5.333333333333333
  1737. 16 / 3 @result{} 5
  1738. @end example
  1739. The remainder operator @samp{%} is not allowed for floating-point
  1740. operands, because it is not needed. The concept of remainder makes
  1741. sense for integers because the result of division of integers has to
  1742. be an integer. For floating point, the result of division is a
  1743. floating-point number, in other words a fraction, which will differ
  1744. from the exact result only by a very small amount.
  1745. There are functions in the standard C library to calculate remainders
  1746. from integral-values division of floating-point numbers.
  1747. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1748. Reference Manual}.
  1749. Integer division overflows in one specific case: dividing the smallest
  1750. negative value for the data type (@pxref{Maximum and Minimum Values})
  1751. by @minus{}1. That's because the correct result, which is the
  1752. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1753. in the same number of bits. On some computers now in use, this always
  1754. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1755. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1756. Division by zero leads to unpredictable results---depending on the
  1757. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1758. produce a numeric result.
  1759. @cindex division by zero
  1760. @cindex zero, division by
  1761. @strong{Watch out:} Make sure the program does not divide by zero. If
  1762. you can't prove that the divisor is not zero, test whether it is zero,
  1763. and skip the division if so.
  1764. @node Numeric Comparisons
  1765. @section Numeric Comparisons
  1766. @cindex numeric comparisons
  1767. @cindex comparisons
  1768. @cindex operators, comparison
  1769. @cindex equal operator
  1770. @cindex not-equal operator
  1771. @cindex less-than operator
  1772. @cindex greater-than operator
  1773. @cindex less-or-equal operator
  1774. @cindex greater-or-equal operator
  1775. @cindex operator, equal
  1776. @cindex operator, not-equal
  1777. @cindex operator, less-than
  1778. @cindex operator, greater-than
  1779. @cindex operator, less-or-equal
  1780. @cindex operator, greater-or-equal
  1781. @cindex truth value
  1782. There are two kinds of comparison operators: @dfn{equality} and
  1783. @dfn{ordering}. Equality comparisons test whether two expressions
  1784. have the same value. The result is a @dfn{truth value}: a number that
  1785. is 1 for ``true'' and 0 for ``false.''
  1786. @example
  1787. a == b /* @r{Test for equal.} */
  1788. a != b /* @r{Test for not equal.} */
  1789. @end example
  1790. The equality comparison is written @code{==} because plain @code{=}
  1791. is the assignment operator.
  1792. Ordering comparisons test which operand is greater or less. Their
  1793. results are truth values. These are the ordering comparisons of C:
  1794. @example
  1795. a < b /* @r{Test for less-than.} */
  1796. a > b /* @r{Test for greater-than.} */
  1797. a <= b /* @r{Test for less-than-or-equal.} */
  1798. a >= b /* @r{Test for greater-than-or-equal.} */
  1799. @end example
  1800. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1801. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1802. mathematics. However, if @code{a} and @code{b} are special floating
  1803. point values (not ordinary numbers), all three can be false.
  1804. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1805. @node Shift Operations
  1806. @section Shift Operations
  1807. @cindex shift operators
  1808. @cindex operators, shift
  1809. @cindex operators, shift
  1810. @cindex shift count
  1811. @dfn{Shifting} an integer means moving the bit values to the left or
  1812. right within the bits of the data type. Shifting is defined only for
  1813. integers. Here's the way to write it:
  1814. @example
  1815. /* @r{Left shift.} */
  1816. 5 << 2 @result{} 20
  1817. /* @r{Right shift.} */
  1818. 5 >> 2 @result{} 1
  1819. @end example
  1820. @noindent
  1821. The left operand is the value to be shifted, and the right operand
  1822. says how many bits to shift it (the @dfn{shift count}). The left
  1823. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1824. operates on a narrow integer type; it's always either @code{int} or
  1825. wider. The value of the shift operator has the same type as the
  1826. promoted left operand.
  1827. @menu
  1828. * Bits Shifted In:: How shifting makes new bits to shift in.
  1829. * Shift Caveats:: Caveats of shift operations.
  1830. * Shift Hacks:: Clever tricks with shift operations.
  1831. @end menu
  1832. @node Bits Shifted In
  1833. @subsection Shifting Makes New Bits
  1834. A shift operation shifts towards one end of the number and has to
  1835. generate new bits at the other end.
  1836. Shifting left one bit must generate a new least significant bit. It
  1837. always brings in zero there. It is equivalent to multiplying by the
  1838. appropriate power of 2. For example,
  1839. @example
  1840. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1841. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1842. @end example
  1843. The meaning of shifting right depends on whether the data type is
  1844. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1845. data type, it performs ``arithmetic shift,'' which keeps the number's
  1846. sign unchanged by duplicating the sign bit. For an unsigned data
  1847. type, it performs ``logical shift,'' which always shifts in zeros at
  1848. the most significant bit.
  1849. In both cases, shifting right one bit is division by two, rounding
  1850. towards negative infinity. For example,
  1851. @example
  1852. (unsigned) 19 >> 2 @result{} 4
  1853. (unsigned) 20 >> 2 @result{} 5
  1854. (unsigned) 21 >> 2 @result{} 5
  1855. @end example
  1856. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1857. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1858. zero.
  1859. The shift count must be zero or greater. Shifting by a negative
  1860. number of bits gives machine-dependent results.
  1861. @node Shift Caveats
  1862. @subsection Caveats for Shift Operations
  1863. @strong{Warning:} If the shift count is greater than or equal to the
  1864. width in bits of the first operand, the results are machine-dependent.
  1865. Logically speaking, the ``correct'' value would be either -1 (for
  1866. right shift of a negative number) or 0 (in all other cases), but what
  1867. it really generates is whatever the machine's shift instruction does in
  1868. that case. So unless you can prove that the second operand is not too
  1869. large, write code to check it at run time.
  1870. @strong{Warning:} Never rely on how the shift operators relate in
  1871. precedence to other arithmetic binary operators. Programmers don't
  1872. remember these precedences, and won't understand the code. Always use
  1873. parentheses to explicitly specify the nesting, like this:
  1874. @example
  1875. a + (b << 5) /* @r{Shift first, then add.} */
  1876. (a + b) << 5 /* @r{Add first, then shift.} */
  1877. @end example
  1878. Note: according to the C standard, shifting of signed values isn't
  1879. guaranteed to work properly when the value shifted is negative, or
  1880. becomes negative during the operation of shifting left. However, only
  1881. pedants have a reason to be concerned about this; only computers with
  1882. strange shift instructions could plausibly do this wrong. In GNU C,
  1883. the operation always works as expected,
  1884. @node Shift Hacks
  1885. @subsection Shift Hacks
  1886. You can use the shift operators for various useful hacks. For
  1887. example, given a date specified by day of the month @code{d}, month
  1888. @code{m}, and year @code{y}, you can store the entire date in a single
  1889. integer @code{date}:
  1890. @example
  1891. unsigned int d = 12;
  1892. unsigned int m = 6;
  1893. unsigned int y = 1983;
  1894. unsigned int date = ((y << 4) + m) << 5) + d;
  1895. @end example
  1896. @noindent
  1897. To extract the original day, month, and year out of
  1898. @code{date}, use a combination of shift and remainder.
  1899. @example
  1900. d = date % 32;
  1901. m = (date >> 5) % 16;
  1902. y = date >> 9;
  1903. @end example
  1904. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1905. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1906. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1907. multiplication, since negating a value is equivalent to multiplying it
  1908. by @minus{}1.
  1909. @node Bitwise Operations
  1910. @section Bitwise Operations
  1911. @cindex bitwise operators
  1912. @cindex operators, bitwise
  1913. @cindex negation, bitwise
  1914. @cindex conjunction, bitwise
  1915. @cindex disjunction, bitwise
  1916. Bitwise operators operate on integers, treating each bit independently.
  1917. They are not allowed for floating-point types.
  1918. The examples in this section use binary constants, starting with
  1919. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1920. of type @code{int}.
  1921. @table @code
  1922. @item ~@code{a}
  1923. Unary operator for bitwise negation; this changes each bit of
  1924. @code{a} from 1 to 0 or from 0 to 1.
  1925. @example
  1926. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1927. ~0 @result{} 0b11111111111111111111111111111111
  1928. ~0b11111111111111111111111111111111 @result{} 0
  1929. ~ (-1) @result{} 0
  1930. @end example
  1931. It is useful to remember that @code{~@var{x} + 1} equals
  1932. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1933. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1934. as @var{x}.
  1935. @item @code{a} & @code{b}
  1936. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1937. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1938. @example
  1939. 0b10101010 & 0b11001100 @result{} 0b10001000
  1940. @end example
  1941. @item @code{a} | @code{b}
  1942. Binary operator for bitwise ``or'' (``inclusive or'' or
  1943. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1944. either @code{a} or @code{b}.
  1945. @example
  1946. 0b10101010 | 0b11001100 @result{} 0b11101110
  1947. @end example
  1948. @item @code{a} ^ @code{b}
  1949. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1950. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1951. @example
  1952. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1953. @end example
  1954. @end table
  1955. To understand the effect of these operators on signed integers, keep
  1956. in mind that all modern computers use two's-complement representation
  1957. (@pxref{Integer Representations}) for negative integers. This means
  1958. that the highest bit of the number indicates the sign; it is 1 for a
  1959. negative number and 0 for a positive number. In a negative number,
  1960. the value in the other bits @emph{increases} as the number gets closer
  1961. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1962. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1963. @strong{Warning:} C defines a precedence ordering for the bitwise
  1964. binary operators, but you should never rely on it. You should
  1965. never rely on how bitwise binary operators relate in precedence to the
  1966. arithmetic and shift binary operators. Other programmers don't
  1967. remember this precedence ordering, so always use parentheses to
  1968. explicitly specify the nesting.
  1969. For example, suppose @code{offset} is an integer that specifies
  1970. the offset within shared memory of a table, except that its bottom few
  1971. bits (@code{LOWBITS} says how many) are special flags. Here's
  1972. how to get just that offset and add it to the base address.
  1973. @example
  1974. shared_mem_base + (offset & (-1 << LOWBITS))
  1975. @end example
  1976. Thanks to the outer set of parentheses, we don't need to know whether
  1977. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1978. set, we don't need to know whether @samp{&} has higher precedence than
  1979. @samp{<<}. But we can rely on all unary operators to have higher
  1980. precedence than any binary operator, so we don't need parentheses
  1981. around the left operand of @samp{<<}.
  1982. @node Assignment Expressions
  1983. @chapter Assignment Expressions
  1984. @cindex assignment expressions
  1985. @cindex operators, assignment
  1986. As a general concept in programming, an @dfn{assignment} is a
  1987. construct that stores a new value into a place where values can be
  1988. stored---for instance, in a variable. Such places are called
  1989. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1990. An assignment in C is an expression because it has a value; we call
  1991. it an @dfn{assignment expression}. A simple assignment looks like
  1992. @example
  1993. @var{lvalue} = @var{value-to-store}
  1994. @end example
  1995. @noindent
  1996. We say it assigns the value of the expression @var{value-to-store} to
  1997. the location @var{lvalue}, or that it stores @var{value-to-store}
  1998. there. You can think of the ``l'' in ``lvalue'' as standing for
  1999. ``left,'' since that's what you put on the left side of the assignment
  2000. operator.
  2001. However, that's not the only way to use an lvalue, and not all lvalues
  2002. can be assigned to. To use the lvalue in the left side of an
  2003. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2004. not declared with the type qualifier @code{const} (@pxref{const}).
  2005. The value of the assignment expression is that of @var{lvalue} after
  2006. the new value is stored in it. This means you can use an assignment
  2007. inside other expressions. Assignment operators are right-associative
  2008. so that
  2009. @example
  2010. x = y = z = 0;
  2011. @end example
  2012. @noindent
  2013. is equivalent to
  2014. @example
  2015. x = (y = (z = 0));
  2016. @end example
  2017. This is the only useful way for them to associate;
  2018. the other way,
  2019. @example
  2020. ((x = y) = z) = 0;
  2021. @end example
  2022. @noindent
  2023. would be invalid since an assignment expression such as @code{x = y}
  2024. is not valid as an lvalue.
  2025. @strong{Warning:} Write parentheses around an assignment if you nest
  2026. it inside another expression, unless that is a conditional expression,
  2027. or comma-separated series, or another assignment.
  2028. @menu
  2029. * Simple Assignment:: The basics of storing a value.
  2030. * Lvalues:: Expressions into which a value can be stored.
  2031. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2032. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2033. an lvalue's contents.
  2034. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2035. * Assignment in Subexpressions:: How to avoid ambiguity.
  2036. * Write Assignments Separately:: Write assignments as separate statements.
  2037. @end menu
  2038. @node Simple Assignment
  2039. @section Simple Assignment
  2040. @cindex simple assignment
  2041. @cindex assignment, simple
  2042. A @dfn{simple assignment expression} computes the value of the right
  2043. operand and stores it into the lvalue on the left. Here is a simple
  2044. assignment expression that stores 5 in @code{i}:
  2045. @example
  2046. i = 5
  2047. @end example
  2048. @noindent
  2049. We say that this is an @dfn{assignment to} the variable @code{i} and
  2050. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2051. because it is an expression (so it has a value). Adding a semicolon
  2052. at the end would make it a statement (@pxref{Expression Statement}).
  2053. Here is another example of a simple assignment expression. Its
  2054. operands are not simple, but the kind of assignment done here is
  2055. simple assignment.
  2056. @example
  2057. x[foo ()] = y + 6
  2058. @end example
  2059. A simple assignment with two different numeric data types converts the
  2060. right operand value to the lvalue's type, if possible. It can convert
  2061. any numeric type to any other numeric type.
  2062. Simple assignment is also allowed on some non-numeric types: pointers
  2063. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2064. unions (@pxref{Unions}).
  2065. @strong{Warning:} Assignment is not allowed on arrays because
  2066. there are no array values in C; C variables can be arrays, but these
  2067. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2068. Arrays}.
  2069. @xref{Assignment Type Conversions}, for the complete rules about data
  2070. types used in assignments.
  2071. @node Lvalues
  2072. @section Lvalues
  2073. @cindex lvalues
  2074. An expression that identifies a memory space that holds a value is
  2075. called an @dfn{lvalue}, because it is a location that can hold a value.
  2076. The standard kinds of lvalues are:
  2077. @itemize @bullet
  2078. @item
  2079. A variable.
  2080. @item
  2081. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2082. unary @samp{*}.
  2083. @item
  2084. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2085. the structure value is an lvalue.
  2086. @item
  2087. A structure field reference using @samp{->}. This is always an lvalue
  2088. since @samp{->} implies pointer dereference.
  2089. @item
  2090. A union alternative reference (@pxref{Unions}), on the same conditions
  2091. as for structure fields.
  2092. @item
  2093. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2094. is an lvalue.
  2095. @end itemize
  2096. If an expression's outermost operation is any other operator, that
  2097. expression is not an lvalue. Thus, the variable @code{x} is an
  2098. lvalue, but @code{x + 0} is not, even though these two expressions
  2099. compute the same value (assuming @code{x} is a number).
  2100. An array can be an lvalue (the rules above determine whether it is
  2101. one), but using the array in an expression converts it automatically
  2102. to a pointer to the first element. The result of this conversion is
  2103. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2104. use @code{a} by itself as the left operand of an assignment. But you
  2105. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2106. lvalue since @code{a} is an lvalue.
  2107. @node Modifying Assignment
  2108. @section Modifying Assignment
  2109. @cindex modifying assignment
  2110. @cindex assignment, modifying
  2111. You can abbreviate the common construct
  2112. @example
  2113. @var{lvalue} = @var{lvalue} + @var{expression}
  2114. @end example
  2115. @noindent
  2116. as
  2117. @example
  2118. @var{lvalue} += @var{expression}
  2119. @end example
  2120. This is known as a @dfn{modifying assignment}. For instance,
  2121. @example
  2122. i = i + 5;
  2123. i += 5;
  2124. @end example
  2125. @noindent
  2126. shows two statements that are equivalent. The first uses
  2127. simple assignment; the second uses modifying assignment.
  2128. Modifying assignment works with any binary arithmetic operator. For
  2129. instance, you can subtract something from an lvalue like this,
  2130. @example
  2131. @var{lvalue} -= @var{expression}
  2132. @end example
  2133. @noindent
  2134. or multiply it by a certain amount like this,
  2135. @example
  2136. @var{lvalue} *= @var{expression}
  2137. @end example
  2138. @noindent
  2139. or shift it by a certain amount like this.
  2140. @example
  2141. @var{lvalue} <<= @var{expression}
  2142. @var{lvalue} >>= @var{expression}
  2143. @end example
  2144. In most cases, this feature adds no power to the language, but it
  2145. provides substantial convenience. Also, when @var{lvalue} contains
  2146. code that has side effects, the simple assignment performs those side
  2147. effects twice, while the modifying assignment performs them once. For
  2148. instance,
  2149. @example
  2150. x[foo ()] = x[foo ()] + 5;
  2151. @end example
  2152. @noindent
  2153. calls @code{foo} twice, and it could return different values each
  2154. time. If @code{foo ()} returns 1 the first time and 3 the second
  2155. time, then the effect could be to add @code{x[3]} and 5 and store the
  2156. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2157. result in @code{x[3]}. We don't know which of the two it will do,
  2158. because C does not specify which call to @code{foo} is computed first.
  2159. Such a statement is not well defined, and shouldn't be used.
  2160. By contrast,
  2161. @example
  2162. x[foo ()] += 5;
  2163. @end example
  2164. @noindent
  2165. is well defined: it calls @code{foo} only once to determine which
  2166. element of @code{x} to adjust, and it adjusts that element by adding 5
  2167. to it.
  2168. @node Increment/Decrement
  2169. @section Increment and Decrement Operators
  2170. @cindex increment operator
  2171. @cindex decrement operator
  2172. @cindex operator, increment
  2173. @cindex operator, decrement
  2174. @cindex preincrement expression
  2175. @cindex predecrement expression
  2176. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2177. @dfn{decrement} operators. When used on a numeric value, they add or
  2178. subtract 1. We don't consider them assignments, but they are
  2179. equivalent to assignments.
  2180. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2181. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2182. and the result becomes the expression's value. For instance,
  2183. @example
  2184. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2185. int
  2186. main (void)
  2187. @{
  2188. int i = 5;
  2189. printf ("%d\n", i);
  2190. printf ("%d\n", ++i);
  2191. printf ("%d\n", i);
  2192. return 0;
  2193. @}
  2194. @end example
  2195. @noindent
  2196. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2197. increments @code{i} from 5 to 6, and has the value 6, so the output
  2198. from @code{printf} on that line says @samp{6}.
  2199. Using @samp{--} instead, for predecrement,
  2200. @example
  2201. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2202. int
  2203. main (void)
  2204. @{
  2205. int i = 5;
  2206. printf ("%d\n", i);
  2207. printf ("%d\n", --i);
  2208. printf ("%d\n", i);
  2209. return 0;
  2210. @}
  2211. @end example
  2212. @noindent
  2213. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2214. again @samp{4}.
  2215. @node Postincrement/Postdecrement
  2216. @section Postincrement and Postdecrement
  2217. @cindex postincrement expression
  2218. @cindex postdecrement expression
  2219. @cindex operator, postincrement
  2220. @cindex operator, postdecrement
  2221. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2222. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2223. increments or decrement it. Thus, the value of @code{i++} is the same
  2224. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2225. little later.'' This is called @dfn{postincrement} or
  2226. @dfn{postdecrement}.
  2227. For example,
  2228. @example
  2229. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2230. int
  2231. main (void)
  2232. @{
  2233. int i = 5;
  2234. printf ("%d\n", i);
  2235. printf ("%d\n", i++);
  2236. printf ("%d\n", i);
  2237. return 0;
  2238. @}
  2239. @end example
  2240. @noindent
  2241. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2242. has the value 5, which is the value of @code{i} at the time,
  2243. but it increments @code{i} from 5 to 6 just a little later.
  2244. How much later is ``just a little later''? That is flexible. The
  2245. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2246. that means by the end of the statement. @xref{Sequence Points}.
  2247. If a unary operator precedes a postincrement or postincrement expression,
  2248. the increment nests inside:
  2249. @example
  2250. -a++ @r{is equivalent to} -(a++)
  2251. @end example
  2252. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2253. it can't be incremented.
  2254. @node Assignment in Subexpressions
  2255. @section Pitfall: Assignment in Subexpressions
  2256. @cindex assignment in subexpressions
  2257. @cindex subexpressions, assignment in
  2258. In C, the order of computing parts of an expression is not fixed.
  2259. Aside from a few special cases, the operations can be computed in any
  2260. order. If one part of the expression has an assignment to @code{x}
  2261. and another part of the expression uses @code{x}, the result is
  2262. unpredictable because that use might be computed before or after the
  2263. assignment.
  2264. Here's an example of ambiguous code:
  2265. @example
  2266. x = 20;
  2267. printf ("%d %d\n", x, x = 4);
  2268. @end example
  2269. @noindent
  2270. If the second argument, @code{x}, is computed before the third argument,
  2271. @code{x = 4}, the second argument's value will be 20. If they are
  2272. computed in the other order, the second argument's value will be 4.
  2273. Here's one way to make that code unambiguous:
  2274. @example
  2275. y = 20;
  2276. printf ("%d %d\n", y, x = 4);
  2277. @end example
  2278. Here's another way, with the other meaning:
  2279. @example
  2280. x = 4;
  2281. printf ("%d %d\n", x, x);
  2282. @end example
  2283. This issue applies to all kinds of assignments, and to the increment
  2284. and decrement operators, which are equivalent to assignments.
  2285. @xref{Order of Execution}, for more information about this.
  2286. However, it can be useful to write assignments inside an
  2287. @code{if}-condition or @code{while}-test along with logical operators.
  2288. @xref{Logicals and Assignments}.
  2289. @node Write Assignments Separately
  2290. @section Write Assignments in Separate Statements
  2291. It is often convenient to write an assignment inside an
  2292. @code{if}-condition, but that can reduce the readability of the
  2293. program. Here's an example of what to avoid:
  2294. @example
  2295. if (x = advance (x))
  2296. @r{@dots{}}
  2297. @end example
  2298. The idea here is to advance @code{x} and test if the value is nonzero.
  2299. However, readers might miss the fact that it uses @samp{=} and not
  2300. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2301. inside a condition is a common error, so GNU C can give warnings when
  2302. @samp{=} appears in a way that suggests it's an error.
  2303. It is much clearer to write the assignment as a separate statement, like this:
  2304. @example
  2305. x = advance (x);
  2306. if (x != 0)
  2307. @r{@dots{}}
  2308. @end example
  2309. @noindent
  2310. This makes it unmistakably clear that @code{x} is assigned a new value.
  2311. Another method is to use the comma operator (@pxref{Comma Operator}),
  2312. like this:
  2313. @example
  2314. if (x = advance (x), x != 0)
  2315. @r{@dots{}}
  2316. @end example
  2317. @noindent
  2318. However, putting the assignment in a separate statement is usually clearer
  2319. unless the assignment is very short, because it reduces nesting.
  2320. @node Execution Control Expressions
  2321. @chapter Execution Control Expressions
  2322. @cindex execution control expressions
  2323. @cindex expressions, execution control
  2324. This chapter describes the C operators that combine expressions to
  2325. control which of those expressions execute, or in which order.
  2326. @menu
  2327. * Logical Operators:: Logical conjunction, disjunction, negation.
  2328. * Logicals and Comparison:: Logical operators with comparison operators.
  2329. * Logicals and Assignments:: Assignments with logical operators.
  2330. * Conditional Expression:: An if/else construct inside expressions.
  2331. * Comma Operator:: Build a sequence of subexpressions.
  2332. @end menu
  2333. @node Logical Operators
  2334. @section Logical Operators
  2335. @cindex logical operators
  2336. @cindex operators, logical
  2337. @cindex conjunction operator
  2338. @cindex disjunction operator
  2339. @cindex negation operator, logical
  2340. The @dfn{logical operators} combine truth values, which are normally
  2341. represented in C as numbers. Any expression with a numeric value is a
  2342. valid truth value: zero means false, and any other value means true.
  2343. A pointer type is also meaningful as a truth value; a null pointer
  2344. (which is zero) means false, and a non-null pointer means true
  2345. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2346. or 0 and has type @code{int} (@pxref{Integer Types}).
  2347. The logical operators are used mainly in the condition of an @code{if}
  2348. statement, or in the end test in a @code{for} statement or
  2349. @code{while} statement (@pxref{Statements}). However, they are valid
  2350. in any context where an integer-valued expression is allowed.
  2351. @table @samp
  2352. @item ! @var{exp}
  2353. Unary operator for logical ``not.'' The value is 1 (true) if
  2354. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2355. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2356. function call, you should write parentheses around it.
  2357. @item @var{left} && @var{right}
  2358. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2359. @var{right}. If both of the operands are true, the @samp{&&} expression
  2360. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2361. gives the value 0 (false). If @var{left} yields a false value,
  2362. that determines the overall result, so @var{right} is not computed.
  2363. @item @var{left} || @var{right}
  2364. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2365. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2366. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2367. gives the value 0 (false). If @var{left} yields a true value,
  2368. that determines the overall result, so @var{right} is not computed.
  2369. @end table
  2370. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2371. and @samp{||}. When you use them together, always use parentheses to
  2372. specify explicitly how they nest, as shown here:
  2373. @example
  2374. if ((r != 0 && x % r == 0)
  2375. ||
  2376. (s != 0 && x % s == 0))
  2377. @end example
  2378. @node Logicals and Comparison
  2379. @section Logical Operators and Comparisons
  2380. The most common thing to use inside the logical operators is a
  2381. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2382. precedence than comparison operators and arithmetic operators, so we
  2383. can write expressions like this without parentheses and get the
  2384. nesting that is natural: two comparison operations that must both be
  2385. true.
  2386. @example
  2387. if (r != 0 && x % r == 0)
  2388. @end example
  2389. @noindent
  2390. This example also shows how it is useful that @samp{&&} guarantees to
  2391. skip the right operand if the left one turns out false. Because of
  2392. that, this code never tries to divide by zero.
  2393. This is equivalent:
  2394. @example
  2395. if (r && x % r == 0)
  2396. @end example
  2397. @noindent
  2398. A truth value is simply a number, so @code{r}
  2399. as a truth value tests whether it is nonzero.
  2400. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2401. So it is better style to write the explicit @code{!= 0}.
  2402. Here's another equivalent way to write it:
  2403. @example
  2404. if (!(r == 0) && x % r == 0)
  2405. @end example
  2406. @noindent
  2407. This illustrates the unary @samp{!} operator, and the need to
  2408. write parentheses around its operand.
  2409. @node Logicals and Assignments
  2410. @section Logical Operators and Assignments
  2411. There are cases where assignments nested inside the condition can
  2412. actually make a program @emph{easier} to read. Here is an example
  2413. using a hypothetical type @code{list} which represents a list; it
  2414. tests whether the list has at least two links, using hypothetical
  2415. functions, @code{nonempty} which is true of the argument is a nonempty
  2416. list, and @code{list_next} which advances from one list link to the
  2417. next. We assume that a list is never a null pointer, so that the
  2418. assignment expressions are always ``true.''
  2419. @example
  2420. if (nonempty (list)
  2421. && (temp1 = list_next (list))
  2422. && nonempty (temp1)
  2423. && (temp2 = list_next (temp1)))
  2424. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2425. @end example
  2426. @noindent
  2427. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2428. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2429. only natural place to put the assignments is among those calls.
  2430. It would be possible to rewrite this as several statements, but that
  2431. could make it much more cumbersome. On the other hand, when the test
  2432. is even more complex than this one, splitting it into multiple
  2433. statements might be necessary for clarity.
  2434. If an empty list is a null pointer, we can dispense with calling
  2435. @code{nonempty}:
  2436. @example
  2437. if ((temp1 = list_next (list))
  2438. && (temp2 = list_next (temp1)))
  2439. @r{@dots{}}
  2440. @end example
  2441. @node Conditional Expression
  2442. @section Conditional Expression
  2443. @cindex conditional expression
  2444. @cindex expression, conditional
  2445. C has a conditional expression that selects one of two expressions
  2446. to compute and get the value from. It looks like this:
  2447. @example
  2448. @var{condition} ? @var{iftrue} : @var{iffalse}
  2449. @end example
  2450. @menu
  2451. * Conditional Rules:: Rules for the conditional operator.
  2452. * Conditional Branches:: About the two branches in a conditional.
  2453. @end menu
  2454. @node Conditional Rules
  2455. @subsection Rules for Conditional Operator
  2456. The first operand, @var{condition}, should be a value that can be
  2457. compared with zero---a number or a pointer. If it is true (nonzero),
  2458. then the conditional expression computes @var{iftrue} and its value
  2459. becomes the value of the conditional expression. Otherwise the
  2460. conditional expression computes @var{iffalse} and its value becomes
  2461. the value of the conditional expression. The conditional expression
  2462. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2463. of them.
  2464. Here's an example: the absolute value of a number @code{x}
  2465. can be written as @code{(x >= 0 ? x : -x)}.
  2466. @strong{Warning:} The conditional expression operators have rather low
  2467. syntactic precedence. Except when the conditional expression is used
  2468. as an argument in a function call, write parentheses around it. For
  2469. clarity, always write parentheses around it if it extends across more
  2470. than one line.
  2471. Assignment operators and the comma operator (@pxref{Comma Operator})
  2472. have lower precedence than conditional expression operators, so write
  2473. parentheses around those when they appear inside a conditional
  2474. expression. @xref{Order of Execution}.
  2475. @node Conditional Branches
  2476. @subsection Conditional Operator Branches
  2477. @cindex branches of conditional expression
  2478. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2479. conditional.
  2480. The two branches should normally have the same type, but a few
  2481. exceptions are allowed. If they are both numeric types, the
  2482. conditional converts both to their common type (@pxref{Common Type}).
  2483. With pointers (@pxref{Pointers}), the two values can be pointers to
  2484. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2485. result type is a similar pointer whose target type combines all the
  2486. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2487. If one branch has type @code{void *} and the other is a pointer to an
  2488. object (not to a function), the conditional converts the @code{void *}
  2489. branch to the type of the other.
  2490. If one branch is an integer constant with value zero and the other is
  2491. a pointer, the conditional converts zero to the pointer's type.
  2492. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2493. that case, if @var{condition} is nonzero, its value becomes the value of
  2494. the conditional expression, after conversion to the common type.
  2495. Thus,
  2496. @example
  2497. x ? : y
  2498. @end example
  2499. @noindent
  2500. has the value of @code{x} if that is nonzero; otherwise, the value of
  2501. @code{y}.
  2502. @cindex side effect in ?:
  2503. @cindex ?: side effect
  2504. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2505. In that case, writing that expression twice would carry out the side
  2506. effects twice, but writing it once does them just once. For example,
  2507. if we suppose that the function @code{next_element} advances a pointer
  2508. variable to point to the next element in a list and returns the new
  2509. pointer,
  2510. @example
  2511. next_element () ? : default_pointer
  2512. @end example
  2513. @noindent
  2514. is a way to advance the pointer and use its new value if it isn't
  2515. null, but use @code{default_pointer} if that is null. We must not do
  2516. it this way,
  2517. @example
  2518. next_element () ? next_element () : default_pointer
  2519. @end example
  2520. @noindent
  2521. because it would advance the pointer a second time.
  2522. @node Comma Operator
  2523. @section Comma Operator
  2524. @cindex comma operator
  2525. @cindex operator, comma
  2526. The comma operator stands for sequential execution of expressions.
  2527. The value of the comma expression comes from the last expression in
  2528. the sequence; the previous expressions are computed only for their
  2529. side effects. It looks like this:
  2530. @example
  2531. @var{exp1}, @var{exp2} @r{@dots{}}
  2532. @end example
  2533. @noindent
  2534. You can bundle any number of expressions together this way, by putting
  2535. commas between them.
  2536. @menu
  2537. * Uses of Comma:: When to use the comma operator.
  2538. * Clean Comma:: Clean use of the comma operator.
  2539. * Avoid Comma:: When to not use the comma operator.
  2540. @end menu
  2541. @node Uses of Comma
  2542. @subsection The Uses of the Comma Operator
  2543. With commas, you can put several expressions into a place that
  2544. requires just one expression---for example, in the header of a
  2545. @code{for} statement. This statement
  2546. @example
  2547. for (i = 0, j = 10, k = 20; i < n; i++)
  2548. @end example
  2549. @noindent
  2550. contains three assignment expressions, to initialize @code{i}, @code{j}
  2551. and @code{k}. The syntax of @code{for} requires just one expression
  2552. for initialization; to include three assignments, we use commas to
  2553. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2554. 20}. This technique is also useful in the loop-advance expression,
  2555. the last of the three inside the @code{for} parentheses.
  2556. In the @code{for} statement and the @code{while} statement
  2557. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2558. effect before the loop-exit test. For example,
  2559. @example
  2560. while (printf ("At the test, x = %d\n", x), x != 0)
  2561. @end example
  2562. @node Clean Comma
  2563. @subsection Clean Use of the Comma Operator
  2564. Always write parentheses around a series of comma operators, except
  2565. when it is at top level in an expression statement, or within the
  2566. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2567. statement (@pxref{Statements}). For instance, in
  2568. @example
  2569. for (i = 0, j = 10, k = 20; i < n; i++)
  2570. @end example
  2571. @noindent
  2572. the commas between the assignments are clear because they are between
  2573. a parenthesis and a semicolon.
  2574. The arguments in a function call are also separated by commas, but that is
  2575. not an instance of the comma operator. Note the difference between
  2576. @example
  2577. foo (4, 5, 6)
  2578. @end example
  2579. @noindent
  2580. which passes three arguments to @code{foo} and
  2581. @example
  2582. foo ((4, 5, 6))
  2583. @end example
  2584. @noindent
  2585. which uses the comma operator and passes just one argument
  2586. (with value 6).
  2587. @strong{Warning:} don't use the comma operator around an argument
  2588. of a function unless it helps understand the code. When you do so,
  2589. don't put part of another argument on the same line. Instead, add a
  2590. line break to make the parentheses around the comma operator easier to
  2591. see, like this.
  2592. @example
  2593. foo ((mumble (x, y), frob (z)),
  2594. *p)
  2595. @end example
  2596. @node Avoid Comma
  2597. @subsection When Not to Use the Comma Operator
  2598. You can use a comma in any subexpression, but in most cases it only
  2599. makes the code confusing, and it is clearer to raise all but the last
  2600. of the comma-separated expressions to a higher level. Thus, instead
  2601. of this:
  2602. @example
  2603. x = (y += 4, 8);
  2604. @end example
  2605. @noindent
  2606. it is much clearer to write this:
  2607. @example
  2608. y += 4, x = 8;
  2609. @end example
  2610. @noindent
  2611. or this:
  2612. @example
  2613. y += 4;
  2614. x = 8;
  2615. @end example
  2616. Use commas only in the cases where there is no clearer alternative
  2617. involving multiple statements.
  2618. By contrast, don't hesitate to use commas in the expansion in a macro
  2619. definition. The trade-offs of code clarity are different in that
  2620. case, because the @emph{use} of the macro may improve overall clarity
  2621. so much that the ugliness of the macro's @emph{definition} is a small
  2622. price to pay. @xref{Macros}.
  2623. @node Binary Operator Grammar
  2624. @chapter Binary Operator Grammar
  2625. @cindex binary operator grammar
  2626. @cindex grammar, binary operator
  2627. @cindex operator precedence
  2628. @cindex precedence, operator
  2629. @cindex left-associative
  2630. @dfn{Binary operators} are those that take two operands, one
  2631. on the left and one on the right.
  2632. All the binary operators in C are syntactically left-associative.
  2633. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2634. @var{op} b) @var{op} c}}. However, you should only write repeated
  2635. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2636. @samp{/}, because those cases are clear from algebra. So it is ok to
  2637. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2638. c} or @code{a % b % c}.
  2639. Each C operator has a @dfn{precedence}, which is its rank in the
  2640. grammatical order of the various operators. The operators with the
  2641. highest precedence grab adjoining operands first; these expressions
  2642. then become operands for operators of lower precedence.
  2643. The precedence order of operators in C is fully specified, so any
  2644. combination of operations leads to a well-defined nesting. We state
  2645. only part of the full precedence ordering here because it is bad
  2646. practice for C code to depend on the other cases. For cases not
  2647. specified in this chapter, always use parentheses to make the nesting
  2648. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2649. remembering anything about the C precedence order beyond what's stated
  2650. here. I studied the full precedence table to write the parser, and
  2651. promptly forgot it again. If you need to look up the full precedence order
  2652. to understand some C code, fix the code with parentheses so nobody else
  2653. needs to do that.}
  2654. You can depend on this subsequence of the precedence ordering
  2655. (stated from highest precedence to lowest):
  2656. @enumerate
  2657. @item
  2658. Component access (@samp{.} and @samp{->}).
  2659. @item
  2660. Unary prefix operators.
  2661. @item
  2662. Unary postfix operators.
  2663. @item
  2664. Multiplication, division, and remainder (they have the same precedence).
  2665. @item
  2666. Addition and subtraction (they have the same precedence).
  2667. @item
  2668. Comparisons---but watch out!
  2669. @item
  2670. Logical operators @samp{&&} and @samp{||}---but watch out!
  2671. @item
  2672. Conditional expression with @samp{?} and @samp{:}.
  2673. @item
  2674. Assignments.
  2675. @item
  2676. Sequential execution (the comma operator, @samp{,}).
  2677. @end enumerate
  2678. Two of the lines in the above list say ``but watch out!'' That means
  2679. that the line covers operators with subtly different precedence.
  2680. Never depend on the grammar of C to decide how two comparisons nest;
  2681. instead, always use parentheses to specify their nesting.
  2682. You can let several @samp{&&} operators associate, or several
  2683. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2684. and @samp{||} nest with each other. @xref{Logical Operators}.
  2685. There is one other precedence ordering that code can depend on:
  2686. @enumerate
  2687. @item
  2688. Unary postfix operators.
  2689. @item
  2690. Bitwise and shift operators---but watch out!
  2691. @item
  2692. Conditional expression with @samp{?} and @samp{:}.
  2693. @end enumerate
  2694. The caveat for bitwise and shift operators is like that for logical
  2695. operators: you can let multiple uses of one bitwise operator
  2696. associate, but always use parentheses to control nesting of dissimilar
  2697. operators.
  2698. These lists do not specify any precedence ordering between the bitwise
  2699. and shift operators of the second list and the binary operators above
  2700. conditional expressions in the first list. When they come together,
  2701. parenthesize them. @xref{Bitwise Operations}.
  2702. @node Order of Execution
  2703. @chapter Order of Execution
  2704. @cindex order of execution
  2705. The order of execution of a C program is not always obvious, and not
  2706. necessarily predictable. This chapter describes what you can count on.
  2707. @menu
  2708. * Reordering of Operands:: Operations in C are not necessarily computed
  2709. in the order they are written.
  2710. * Associativity and Ordering:: Some associative operations are performed
  2711. in a particular order; others are not.
  2712. * Sequence Points:: Some guarantees about the order of operations.
  2713. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2714. * Ordering of Operands:: Evaluation order of operands
  2715. and function arguments.
  2716. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2717. only if it has no impact on program results.
  2718. @end menu
  2719. @node Reordering of Operands
  2720. @section Reordering of Operands
  2721. @cindex ordering of operands
  2722. @cindex reordering of operands
  2723. @cindex operand execution ordering
  2724. The C language does not necessarily carry out operations within an
  2725. expression in the order they appear in the code. For instance, in
  2726. this expression,
  2727. @example
  2728. foo () + bar ()
  2729. @end example
  2730. @noindent
  2731. @code{foo} might be called first or @code{bar} might be called first.
  2732. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2733. results can be unpredictable.
  2734. The unpredictable order of computation of subexpressions also makes a
  2735. difference when one of them contains an assignment. We already saw
  2736. this example of bad code,
  2737. @example
  2738. x = 20;
  2739. printf ("%d %d\n", x, x = 4);
  2740. @end example
  2741. @noindent
  2742. in which the second argument, @code{x}, has a different value
  2743. depending on whether it is computed before or after the assignment in
  2744. the third argument.
  2745. @node Associativity and Ordering
  2746. @section Associativity and Ordering
  2747. @cindex associativity and ordering
  2748. An associative binary operator, such as @code{+}, when used repeatedly
  2749. can combine any number of operands. The operands' values may be
  2750. computed in any order.
  2751. If the values are integers and overflow can be ignored, they may be
  2752. combined in any order. Thus, given four functions that return
  2753. @code{unsigned int}, calling them and adding their results as here
  2754. @example
  2755. (foo () + bar ()) + (baz () + quux ())
  2756. @end example
  2757. @noindent
  2758. may add up the results in any order.
  2759. By contrast, arithmetic on signed integers, with overflow significant,
  2760. is not really associative (@pxref{Integer Overflow}). Thus, the
  2761. additions must be done in the order specified, obeying parentheses and
  2762. left-association. That means computing @code{(foo () + bar ())} and
  2763. @code{(baz () + quux ())} first (in either order), then adding the
  2764. two.
  2765. The same applies to arithmetic on floating-point values, since that
  2766. too is not really associative. However, the GCC option
  2767. @option{-funsafe-math-optimizations} allows the compiler to change the
  2768. order of calculation when an associative operation (associative in
  2769. exact mathematics) combines several operands. The option takes effect
  2770. when compiling a module (@pxref{Compilation}). Changing the order
  2771. of association can enable the program to pipeline the floating point
  2772. operations.
  2773. In all these cases, the four function calls can be done in any order.
  2774. There is no right or wrong about that.
  2775. @node Sequence Points
  2776. @section Sequence Points
  2777. @cindex sequence points
  2778. @cindex full expression
  2779. There are some points in the code where C makes limited guarantees
  2780. about the order of operations. These are called @dfn{sequence
  2781. points}. Here is where they occur:
  2782. @itemize @bullet
  2783. @item
  2784. At the end of a @dfn{full expression}; that is to say, an expression
  2785. that is not part of a larger expression. All side effects specified
  2786. by that expression are carried out before execution moves
  2787. on to subsequent code.
  2788. @item
  2789. At the end of the first operand of certain operators: @samp{,},
  2790. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2791. that expression are carried out before any execution of the
  2792. next operand.
  2793. The commas that separate arguments in a function call are @emph{not}
  2794. comma operators, and they do not create sequence points. The rule
  2795. for function arguments and the rule for operands are different
  2796. (@pxref{Ordering of Operands}).
  2797. @item
  2798. Just before calling a function. All side effects specified by the
  2799. argument expressions are carried out before calling the function.
  2800. If the function to be called is not constant---that is, if it is
  2801. computed by an expression---all side effects in that expression are
  2802. carried out before calling the function.
  2803. @end itemize
  2804. The ordering imposed by a sequence point applies locally to a limited
  2805. range of code, as stated above in each case. For instance, the
  2806. ordering imposed by the comma operator does not apply to code outside
  2807. that comma operator. Thus, in this code,
  2808. @example
  2809. (x = 5, foo (x)) + x * x
  2810. @end example
  2811. @noindent
  2812. the sequence point of the comma operator orders @code{x = 5} before
  2813. @code{foo (x)}, but @code{x * x} could be computed before or after
  2814. them.
  2815. @node Postincrement and Ordering
  2816. @section Postincrement and Ordering
  2817. @cindex postincrement and ordering
  2818. @cindex ordering and postincrement
  2819. Ordering requirements are loose with the postincrement and
  2820. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2821. specify side effects to happen ``a little later.'' They must happen
  2822. before the next sequence point, but that still leaves room for various
  2823. meanings. In this expression,
  2824. @example
  2825. z = x++ - foo ()
  2826. @end example
  2827. @noindent
  2828. it's unpredictable whether @code{x} gets incremented before or after
  2829. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2830. it might see the old value or it might see the incremented value.
  2831. In this perverse expression,
  2832. @example
  2833. x = x++
  2834. @end example
  2835. @noindent
  2836. @code{x} will certainly be incremented but the incremented value may
  2837. not stick. If the incrementation of @code{x} happens after the
  2838. assignment to @code{x}, the incremented value will remain in place.
  2839. But if the incrementation happens first, the assignment will overwrite
  2840. that with the not-yet-incremented value, so the expression as a whole
  2841. will leave @code{x} unchanged.
  2842. @node Ordering of Operands
  2843. @section Ordering of Operands
  2844. @cindex ordering of operands
  2845. @cindex operand ordering
  2846. Operands and arguments can be computed in any order, but there are limits to
  2847. this intermixing in GNU C:
  2848. @itemize @bullet
  2849. @item
  2850. The operands of a binary arithmetic operator can be computed in either
  2851. order, but they can't be intermixed: one of them has to come first,
  2852. followed by the other. Any side effects in the operand that's computed
  2853. first are executed before the other operand is computed.
  2854. @item
  2855. That applies to assignment operators too, except that in simple assignment
  2856. the previous value of the left operand is unused.
  2857. @item
  2858. The arguments in a function call can be computed in any order, but
  2859. they can't be intermixed. Thus, one argument is fully computed, then
  2860. another, and so on until they are all done. Any side effects in one argument
  2861. are executed before computation of another argument begins.
  2862. @end itemize
  2863. These rules don't cover side effects caused by postincrement and
  2864. postdecrement operators---those can be deferred up to the next
  2865. sequence point.
  2866. If you want to get pedantic, the fact is that GCC can reorder the
  2867. computations in many other ways provided that doesn't alter the result
  2868. of running the program. However, because they don't alter the result
  2869. of running the program, they are negligible, unless you are concerned
  2870. with the values in certain variables at various times as seen by other
  2871. processes. In those cases, you can use @code{volatile} to prevent
  2872. optimizations that would make them behave strangely. @xref{volatile}.
  2873. @node Optimization and Ordering
  2874. @section Optimization and Ordering
  2875. @cindex optimization and ordering
  2876. @cindex ordering and optimization
  2877. Sequence points limit the compiler's freedom to reorder operations
  2878. arbitrarily, but optimizations can still reorder them if the compiler
  2879. concludes that this won't alter the results. Thus, in this code,
  2880. @example
  2881. x++;
  2882. y = z;
  2883. x++;
  2884. @end example
  2885. @noindent
  2886. there is a sequence point after each statement, so the code is
  2887. supposed to increment @code{x} once before the assignment to @code{y}
  2888. and once after. However, incrementing @code{x} has no effect on
  2889. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2890. the code could be optimized into this:
  2891. @example
  2892. y = z;
  2893. x += 2;
  2894. @end example
  2895. Normally that has no effect except to make the program faster. But
  2896. there are special situations where it can cause trouble due to things
  2897. that the compiler cannot know about, such as shared memory. To limit
  2898. optimization in those places, use the @code{volatile} type qualifier
  2899. (@pxref{volatile}).
  2900. @node Primitive Types
  2901. @chapter Primitive Data Types
  2902. @cindex primitive types
  2903. @cindex types, primitive
  2904. This chapter describes all the primitive data types of C---that is,
  2905. all the data types that aren't built up from other types. They
  2906. include the types @code{int} and @code{double} that we've already covered.
  2907. @menu
  2908. * Integer Types:: Description of integer types.
  2909. * Floating-Point Data Types:: Description of floating-point types.
  2910. * Complex Data Types:: Description of complex number types.
  2911. * The Void Type:: A type indicating no value at all.
  2912. * Other Data Types:: A brief summary of other types.
  2913. * Type Designators:: Referring to a data type abstractly.
  2914. @end menu
  2915. These types are all made up of bytes (@pxref{Storage}).
  2916. @node Integer Types
  2917. @section Integer Data Types
  2918. @cindex integer types
  2919. @cindex types, integer
  2920. Here we describe all the integer types and their basic
  2921. characteristics. @xref{Integers in Depth}, for more information about
  2922. the bit-level integer data representations and arithmetic.
  2923. @menu
  2924. * Basic Integers:: Overview of the various kinds of integers.
  2925. * Signed and Unsigned Types:: Integers can either hold both negative and
  2926. non-negative values, or only non-negative.
  2927. * Narrow Integers:: When to use smaller integer types.
  2928. * Integer Conversion:: Casting a value from one integer type
  2929. to another.
  2930. * Boolean Type:: An integer type for boolean values.
  2931. * Integer Variations:: Sizes of integer types can vary
  2932. across platforms.
  2933. @end menu
  2934. @node Basic Integers
  2935. @subsection Basic Integers
  2936. @findex char
  2937. @findex int
  2938. @findex short int
  2939. @findex long int
  2940. @findex long long int
  2941. Integer data types in C can be signed or unsigned. An unsigned type
  2942. can represent only positive numbers and zero. A signed type can
  2943. represent both positive and negative numbers, in a range spread almost
  2944. equally on both sides of zero.
  2945. Aside from signedness, the integer data types vary in size: how many
  2946. bytes long they are. The size determines how many different integer
  2947. values the type can hold.
  2948. Here's a list of the signed integer data types, with the sizes they
  2949. have on most computers. Each has a corresponding unsigned type; see
  2950. @ref{Signed and Unsigned Types}.
  2951. @table @code
  2952. @item signed char
  2953. One byte (8 bits). This integer type is used mainly for integers that
  2954. represent characters, as part of arrays or other data structures.
  2955. @item short
  2956. @itemx short int
  2957. Two bytes (16 bits).
  2958. @item int
  2959. Four bytes (32 bits).
  2960. @item long
  2961. @itemx long int
  2962. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2963. platform. Typically it is 32 bits on 32-bit computers
  2964. and 64 bits on 64-bit computers, but there are exceptions.
  2965. @item long long
  2966. @itemx long long int
  2967. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2968. incorporated into standard C as of ISO C99.
  2969. @end table
  2970. You can omit @code{int} when you use @code{long} or @code{short}.
  2971. This is harmless and customary.
  2972. @node Signed and Unsigned Types
  2973. @subsection Signed and Unsigned Types
  2974. @cindex signed types
  2975. @cindex unsigned types
  2976. @cindex types, signed
  2977. @cindex types, unsigned
  2978. @findex signed
  2979. @findex unsigned
  2980. An unsigned integer type can represent only positive numbers and zero.
  2981. A signed type can represent both positive and negative number, in a
  2982. range spread almost equally on both sides of zero. For instance,
  2983. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2984. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2985. these types holds 256 different possible values, since they are both 8
  2986. bits wide.
  2987. Write @code{signed} or @code{unsigned} before the type keyword to
  2988. specify a signed or an unsigned type. However, the integer types
  2989. other than @code{char} are signed by default; with them, @code{signed}
  2990. is a no-op.
  2991. Plain @code{char} may be signed or unsigned; this depends on the
  2992. compiler, the machine in use, and its operating system.
  2993. In many programs, it makes no difference whether @code{char} is
  2994. signed. When it does matter, don't leave it to chance; write
  2995. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2996. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2997. Arctic Char. When my meal arrived, I noted that the chef had not
  2998. signed it. So I complained, ``This char is unsigned---I wanted a
  2999. signed char!'' Or rather, I would have said this if I had thought of
  3000. it fast enough.}
  3001. @node Narrow Integers
  3002. @subsection Narrow Integers
  3003. The types that are narrower than @code{int} are rarely used for
  3004. ordinary variables---we declare them @code{int} instead. This is
  3005. because C converts those narrower types to @code{int} for any
  3006. arithmetic. There is literally no reason to declare a local variable
  3007. @code{char}, for instance.
  3008. In particular, if the value is really a character, you should declare
  3009. the variable @code{int}. Not @code{char}! Using that narrow type can
  3010. force the compiler to truncate values for conversion, which is a
  3011. waste. Furthermore, some functions return either a character value,
  3012. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3013. values distinct.
  3014. The narrow integer types are useful as parts of other objects, such as
  3015. arrays and structures. Compare these array declarations, whose sizes
  3016. on 32-bit processors are shown:
  3017. @example
  3018. signed char ac[1000]; /* @r{1000 bytes} */
  3019. short as[1000]; /* @r{2000 bytes} */
  3020. int ai[1000]; /* @r{4000 bytes} */
  3021. long long all[1000]; /* @r{8000 bytes} */
  3022. @end example
  3023. In addition, character strings must be made up of @code{char}s,
  3024. because that's what all the standard library string functions expect.
  3025. Thus, array @code{ac} could be used as a character string, but the
  3026. others could not be.
  3027. @node Integer Conversion
  3028. @subsection Conversion among Integer Types
  3029. C converts between integer types implicitly in many situations. It
  3030. converts the narrow integer types, @code{char} and @code{short}, to
  3031. @code{int} whenever they are used in arithmetic. Assigning a new
  3032. value to an integer variable (or other lvalue) converts the value to
  3033. the variable's type.
  3034. You can also convert one integer type to another explicitly with a
  3035. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3036. The process of conversion to a wider type is straightforward: the
  3037. value is unchanged. The only exception is when converting a negative
  3038. value (in a signed type, obviously) to a wider unsigned type. In that
  3039. case, the result is a positive value with the same bits
  3040. (@pxref{Integers in Depth}).
  3041. @cindex truncation
  3042. Converting to a narrower type, also called @dfn{truncation}, involves
  3043. discarding some of the value's bits. This is not considered overflow
  3044. (@pxref{Integer Overflow}) because loss of significant bits is a
  3045. normal consequence of truncation. Likewise for conversion between
  3046. signed and unsigned types of the same width.
  3047. More information about conversion for assignment is in
  3048. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3049. see @ref{Argument Promotions}.
  3050. @node Boolean Type
  3051. @subsection Boolean Type
  3052. @cindex boolean type
  3053. @cindex type, boolean
  3054. @findex bool
  3055. The unsigned integer type @code{bool} holds truth values: its possible
  3056. values are 0 and 1. Converting any nonzero value to @code{bool}
  3057. results in 1. For example:
  3058. @example
  3059. bool a = 0;
  3060. bool b = 1;
  3061. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3062. @end example
  3063. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3064. the header file @file{stdbool.h}.
  3065. @node Integer Variations
  3066. @subsection Integer Variations
  3067. The integer types of C have standard @emph{names}, but what they
  3068. @emph{mean} varies depending on the kind of platform in use:
  3069. which kind of computer, which operating system, and which compiler.
  3070. It may even depend on the compiler options used.
  3071. Plain @code{char} may be signed or unsigned; this depends on the
  3072. platform, too. Even for GNU C, there is no general rule.
  3073. In theory, all of the integer types' sizes can vary. @code{char} is
  3074. always considered one ``byte'' for C, but it is not necessarily an
  3075. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3076. specifies only that none of these types is narrower than the ones
  3077. above it in the list in @ref{Basic Integers}, and that @code{short}
  3078. has at least 16 bits.
  3079. It is possible that in the future GNU C will support platforms where
  3080. @code{int} is 64 bits long. In practice, however, on today's real
  3081. computers, there is little variation; you can rely on the table
  3082. given previously (@pxref{Basic Integers}).
  3083. To be completely sure of the size of an integer type,
  3084. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3085. Their corresponding unsigned types add @samp{u} at the front.
  3086. To define these, include the header file @file{stdint.h}.
  3087. The GNU C Compiler compiles for some embedded controllers that use two
  3088. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3089. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3090. 32 bits. These processors can't support an ordinary operating system
  3091. (they may have their own specialized operating systems), and most C
  3092. programs do not try to support them.
  3093. @node Floating-Point Data Types
  3094. @section Floating-Point Data Types
  3095. @cindex floating-point types
  3096. @cindex types, floating-point
  3097. @findex double
  3098. @findex float
  3099. @findex long double
  3100. @dfn{Floating point} is the binary analogue of scientific notation:
  3101. internally it represents a number as a fraction and a binary exponent; the
  3102. value is that fraction multiplied by the specified power of 2.
  3103. For instance, to represent 6, the fraction would be 0.75 and the
  3104. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3105. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3106. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3107. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3108. -1 as the exponent.
  3109. These binary exponents are used by machine instructions. You can
  3110. write a floating-point constant this way if you wish, using
  3111. hexadecimal; but normally we write floating-point numbers in decimal.
  3112. @xref{Floating Constants}.
  3113. C has three floating-point data types:
  3114. @table @code
  3115. @item double
  3116. ``Double-precision'' floating point, which uses 64 bits. This is the
  3117. normal floating-point type, and modern computers normally do
  3118. their floating-point computations in this type, or some wider type.
  3119. Except when there is a special reason to do otherwise, this is the
  3120. type to use for floating-point values.
  3121. @item float
  3122. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3123. for floating-point values stored in structures and arrays, to save
  3124. space when the full precision of @code{double} is not needed. In
  3125. addition, single-precision arithmetic is faster on some computers, and
  3126. occasionally that is useful. But not often---most programs don't use
  3127. the type @code{float}.
  3128. C would be cleaner if @code{float} were the name of the type we
  3129. use for most floating-point values; however, for historical reasons,
  3130. that's not so.
  3131. @item long double
  3132. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3133. precision, depending on the machine in use. On some machines, which
  3134. have no floating-point format wider than @code{double}, this is
  3135. equivalent to @code{double}.
  3136. @end table
  3137. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3138. Point in Depth}, for more information.
  3139. @node Complex Data Types
  3140. @section Complex Data Types
  3141. @cindex complex numbers
  3142. @cindex types, complex
  3143. @cindex @code{_Complex} keyword
  3144. @cindex @code{__complex__} keyword
  3145. @findex _Complex
  3146. @findex __complex__
  3147. Complex numbers can include both a real part and an imaginary part.
  3148. The numeric constants covered above have real-numbered values. An
  3149. imaginary-valued constant is an ordinary real-valued constant followed
  3150. by @samp{i}.
  3151. To declare numeric variables as complex, use the @code{_Complex}
  3152. keyword.@footnote{For compatibility with older versions of GNU C, the
  3153. keyword @code{__complex__} is also allowed. Going forward, however,
  3154. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3155. standard C complex data types are floating point,
  3156. @example
  3157. _Complex float foo;
  3158. _Complex double bar;
  3159. _Complex long double quux;
  3160. @end example
  3161. @noindent
  3162. but GNU C supports integer complex types as well.
  3163. Since @code{_Complex} is a keyword just like @code{float} and
  3164. @code{double} and @code{long}, the keywords can appear in any order,
  3165. but the order shown above seems most logical.
  3166. GNU C supports constants for complex values; for instance, @code{4.0 +
  3167. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3168. @xref{Imaginary Constants}.
  3169. To pull the real and imaginary parts of the number back out, GNU C
  3170. provides the keywords @code{__real__} and @code{__imag__}:
  3171. @example
  3172. _Complex double foo = 4.0 + 3.0i;
  3173. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3174. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3175. @end example
  3176. @noindent
  3177. Standard C does not include these keywords, and instead relies on
  3178. functions defined in @code{complex.h} for accessing the real and
  3179. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3180. @code{creall} extract the real part of a float, double, or long double
  3181. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3182. @code{cimagl} extract the imaginary part.
  3183. @cindex complex conjugation
  3184. GNU C also defines @samp{~} as an operator for complex conjugation,
  3185. which means negating the imaginary part of a complex number:
  3186. @example
  3187. _Complex double foo = 4.0 + 3.0i;
  3188. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3189. @end example
  3190. @noindent
  3191. For standard C compatibility, you can use the appropriate library
  3192. function: @code{conjf}, @code{conj}, or @code{confl}.
  3193. @node The Void Type
  3194. @section The Void Type
  3195. @cindex void type
  3196. @cindex type, void
  3197. @findex void
  3198. The data type @code{void} is a dummy---it allows no operations. It
  3199. really means ``no value at all.'' When a function is meant to return
  3200. no value, we write @code{void} for its return type. Then
  3201. @code{return} statements in that function should not specify a value
  3202. (@pxref{return Statement}). Here's an example:
  3203. @example
  3204. void
  3205. print_if_positive (double x, double y)
  3206. @{
  3207. if (x <= 0)
  3208. return;
  3209. if (y <= 0)
  3210. return;
  3211. printf ("Next point is (%f,%f)\n", x, y);
  3212. @}
  3213. @end example
  3214. A @code{void}-returning function is comparable to what some other languages
  3215. call a ``procedure'' instead of a ``function.''
  3216. @c ??? Already presented
  3217. @c @samp{%f} in an output template specifies to format a @code{double} value
  3218. @c as a decimal number, using a decimal point if needed.
  3219. @node Other Data Types
  3220. @section Other Data Types
  3221. Beyond the primitive types, C provides several ways to construct new
  3222. data types. For instance, you can define @dfn{pointers}, values that
  3223. represent the addresses of other data (@pxref{Pointers}). You can
  3224. define @dfn{structures}, as in many other languages
  3225. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3226. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3227. are collections of named integer codes (@pxref{Enumeration Types}).
  3228. @dfn{Array types} in C are used for allocating space for objects,
  3229. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3230. @node Type Designators
  3231. @section Type Designators
  3232. @cindex type designator
  3233. Some C constructs require a way to designate a specific data type
  3234. independent of any particular variable or expression which has that
  3235. type. The way to do this is with a @dfn{type designator}. The
  3236. constucts that need one include casts (@pxref{Explicit Type
  3237. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3238. We also use type designators to talk about the type of a value in C,
  3239. so you will see many type designators in this manual. When we say,
  3240. ``The value has type @code{int},'' @code{int} is a type designator.
  3241. To make the designator for any type, imagine a variable declaration
  3242. for a variable of that type and delete the variable name and the final
  3243. semicolon.
  3244. For example, to designate the type of full-word integers, we start
  3245. with the declaration for a variable @code{foo} with that type,
  3246. which is this:
  3247. @example
  3248. int foo;
  3249. @end example
  3250. @noindent
  3251. Then we delete the variable name @code{foo} and the semicolon, leaving
  3252. @code{int}---exactly the keyword used in such a declaration.
  3253. Therefore, the type designator for this type is @code{int}.
  3254. What about long unsigned integers? From the declaration
  3255. @example
  3256. unsigned long int foo;
  3257. @end example
  3258. @noindent
  3259. we determine that the designator is @code{unsigned long int}.
  3260. Following this procedure, the designator for any primitive type is
  3261. simply the set of keywords which specifies that type in a declaration.
  3262. The same is true for compound types such as structures, unions, and
  3263. enumerations.
  3264. Designators for pointer types do follow the rule of deleting the
  3265. variable name and semicolon, but the result is not so simple.
  3266. @xref{Pointer Type Designators}, as part of the chapter about
  3267. pointers. @xref{Array Type Designators}), for designators for array
  3268. types.
  3269. To understand what type a designator stands for, imagine a variable
  3270. name inserted into the right place in the designator to make a valid
  3271. declaration. What type would that variable be declared as? That is the
  3272. type the designator designates.
  3273. @node Constants
  3274. @chapter Constants
  3275. @cindex constants
  3276. A @dfn{constant} is an expression that stands for a specific value by
  3277. explicitly representing the desired value. C allows constants for
  3278. numbers, characters, and strings. We have already seen numeric and
  3279. string constants in the examples.
  3280. @menu
  3281. * Integer Constants:: Literal integer values.
  3282. * Integer Const Type:: Types of literal integer values.
  3283. * Floating Constants:: Literal floating-point values.
  3284. * Imaginary Constants:: Literal imaginary number values.
  3285. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3286. * Character Constants:: Literal character values.
  3287. * String Constants:: Literal string values.
  3288. * UTF-8 String Constants:: Literal UTF-8 string values.
  3289. * Unicode Character Codes:: Unicode characters represented
  3290. in either UTF-16 or UTF-32.
  3291. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3292. * Wide String Constants:: Literal string values made up of
  3293. 16- or 32-bit characters.
  3294. @end menu
  3295. @node Integer Constants
  3296. @section Integer Constants
  3297. @cindex integer constants
  3298. @cindex constants, integer
  3299. An integer constant consists of a number to specify the value,
  3300. followed optionally by suffix letters to specify the data type.
  3301. The simplest integer constants are numbers written in base 10
  3302. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3303. constant cannot start with the character @samp{0} (zero) because
  3304. that makes the constant octal.
  3305. You can get the effect of a negative integer constant by putting a
  3306. minus sign at the beginning. Grammatically speaking, that is an
  3307. arithmetic expression rather than a constant, but it behaves just like
  3308. a true constant.
  3309. Integer constants can also be written in octal (base 8), hexadecimal
  3310. (base 16), or binary (base 2). An octal constant starts with the
  3311. character @samp{0} (zero), followed by any number of octal digits
  3312. (@samp{0} to @samp{7}):
  3313. @example
  3314. 0 // @r{zero}
  3315. 077 // @r{63}
  3316. 0403 // @r{259}
  3317. @end example
  3318. @noindent
  3319. Pedantically speaking, the constant @code{0} is an octal constant, but
  3320. we can think of it as decimal; it has the same value either way.
  3321. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3322. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3323. through @samp{f} in upper or lower case):
  3324. @example
  3325. 0xff // @r{255}
  3326. 0XA0 // @r{160}
  3327. 0xffFF // @r{65535}
  3328. @end example
  3329. @cindex binary integer constants
  3330. A binary constant starts with @samp{0b} (upper or lower case) followed
  3331. by bits (each represented by the characters @samp{0} or @samp{1}):
  3332. @example
  3333. 0b101 // @r{5}
  3334. @end example
  3335. Binary constants are a GNU C extension, not part of the C standard.
  3336. Sometimes a space is needed after an integer constant to avoid
  3337. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3338. @node Integer Const Type
  3339. @section Integer Constant Data Types
  3340. @cindex integer constant data types
  3341. @cindex constant data types, integer
  3342. @cindex types of integer constants
  3343. The type of an integer constant is normally @code{int}, if the value
  3344. fits in that type, but here are the complete rules. The type
  3345. of an integer constant is the first one in this sequence that can
  3346. properly represent the value,
  3347. @enumerate
  3348. @item
  3349. @code{int}
  3350. @item
  3351. @code{unsigned int}
  3352. @item
  3353. @code{long int}
  3354. @item
  3355. @code{unsigned long int}
  3356. @item
  3357. @code{long long int}
  3358. @item
  3359. @code{unsigned long long int}
  3360. @end enumerate
  3361. @noindent
  3362. and that isn't excluded by the following rules.
  3363. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3364. first two types (non-@code{long}).
  3365. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3366. first four types (non-@code{long long}).
  3367. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3368. the signed types.
  3369. Otherwise, if the constant is decimal, that excludes the unsigned
  3370. types.
  3371. @c ### This said @code{unsigned int} is excluded.
  3372. @c ### See 17 April 2016
  3373. Here are some examples of the suffixes.
  3374. @example
  3375. 3000000000u // @r{three billion as @code{unsigned int}.}
  3376. 0LL // @r{zero as a @code{long long int}.}
  3377. 0403l // @r{259 as a @code{long int}.}
  3378. @end example
  3379. Suffixes in integer constants are rarely used. When the precise type
  3380. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3381. Type Conversion}).
  3382. @xref{Integer Types}.
  3383. @node Floating Constants
  3384. @section Floating-Point Constants
  3385. @cindex floating-point constants
  3386. @cindex constants, floating-point
  3387. A floating-point constant must have either a decimal point, an
  3388. exponent-of-ten, or both; they distinguish it from an integer
  3389. constant.
  3390. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3391. value follows. It is always written as a decimal number; it can
  3392. optionally start with a sign. The exponent @var{n} means to multiply
  3393. the constant's value by ten to the @var{n}th power.
  3394. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3395. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3396. writing a floating-point number whose value is 1500. They are all
  3397. equivalent.
  3398. Here are more examples with decimal points:
  3399. @example
  3400. 1.0
  3401. 1000.
  3402. 3.14159
  3403. .05
  3404. .0005
  3405. @end example
  3406. For each of them, here are some equivalent constants written with
  3407. exponents:
  3408. @example
  3409. 1e0, 1.0000e0
  3410. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3411. 3.14159e0
  3412. 5e-2, .0005e+2, 5E-2, .0005E2
  3413. .05e-2
  3414. @end example
  3415. A floating-point constant normally has type @code{double}. You can
  3416. force it to type @code{float} by adding @samp{f} or @samp{F}
  3417. at the end. For example,
  3418. @example
  3419. 3.14159f
  3420. 3.14159e0f
  3421. 1000.f
  3422. 100E1F
  3423. .0005f
  3424. .05e-2f
  3425. @end example
  3426. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3427. to type @code{long double}.
  3428. You can use exponents in hexadecimal floating constants, but since
  3429. @samp{e} would be interpreted as a hexadecimal digit, the character
  3430. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3431. The exponent in a hexadecimal floating constant is a possibly-signed
  3432. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3433. multiply into the number.
  3434. Here are some examples:
  3435. @example
  3436. @group
  3437. 0xAp2 // @r{40 in decimal}
  3438. 0xAp-1 // @r{5 in decimal}
  3439. 0x2.0Bp4 // @r{16.75 decimal}
  3440. 0xE.2p3 // @r{121 decimal}
  3441. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3442. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3443. 0x100p-8 // @r{1}
  3444. 0x10p-4 // @r{1}
  3445. 0x1p+4 // @r{16}
  3446. 0x1p+8 // @r{256}
  3447. @end group
  3448. @end example
  3449. @xref{Floating-Point Data Types}.
  3450. @node Imaginary Constants
  3451. @section Imaginary Constants
  3452. @cindex imaginary constants
  3453. @cindex complex constants
  3454. @cindex constants, imaginary
  3455. A complex number consists of a real part plus an imaginary part.
  3456. (Either or both parts may be zero.) This section explains how to
  3457. write numeric constants with imaginary values. By adding these to
  3458. ordinary real-valued numeric constants, we can make constants with
  3459. complex values.
  3460. The simple way to write an imaginary-number constant is to attach the
  3461. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3462. floating-point constant. For example, @code{2.5fi} has type
  3463. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3464. The four alternative suffix letters are all equivalent.
  3465. @cindex _Complex_I
  3466. The other way to write an imaginary constant is to multiply a real
  3467. constant by @code{_Complex_I}, which represents the imaginary number
  3468. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3469. this clunky way is needed.
  3470. To write a complex constant with a nonzero real part and a nonzero
  3471. imaginary part, write the two separately and add them, like this:
  3472. @example
  3473. 4.0 + 3.0i
  3474. @end example
  3475. @noindent
  3476. That gives the value 4 + 3i, with type @code{_Complex double}.
  3477. Such a sum can include multiple real constants, or none. Likewise, it
  3478. can include multiple imaginary constants, or none. For example:
  3479. @example
  3480. _Complex double foo, bar, quux;
  3481. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3482. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3483. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3484. @end example
  3485. @xref{Complex Data Types}.
  3486. @node Invalid Numbers
  3487. @section Invalid Numbers
  3488. Some number-like constructs which are not really valid as numeric
  3489. constants are treated as numbers in preprocessing directives. If
  3490. these constructs appear outside of preprocessing, they are erroneous.
  3491. @xref{Preprocessing Tokens}.
  3492. Sometimes we need to insert spaces to separate tokens so that they
  3493. won't be combined into a single number-like construct. For example,
  3494. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3495. constant, so it is a syntax error. If what we want is the three
  3496. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3497. @node Character Constants
  3498. @section Character Constants
  3499. @cindex character constants
  3500. @cindex constants, character
  3501. @cindex escape sequence
  3502. A @dfn{character constant} is written with single quotes, as in
  3503. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3504. character that the constant should represent. The constant has type
  3505. @code{int}, and its value is the character code of that character.
  3506. For instance, @code{'a'} represents the character code for the letter
  3507. @samp{a}: 97, that is.
  3508. To put the @samp{'} character (single quote) in the character
  3509. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3510. constant looks like @code{'\''}. This sort of sequence, starting with
  3511. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3512. here functions as a kind of @dfn{escape character}.
  3513. To put the @samp{\} character (backslash) in the character constant,
  3514. quote it likewise with @samp{\} (another backslash). This character
  3515. constant looks like @code{'\\'}.
  3516. @cindex bell character
  3517. @cindex @samp{\a}
  3518. @cindex backspace
  3519. @cindex @samp{\b}
  3520. @cindex tab (ASCII character)
  3521. @cindex @samp{\t}
  3522. @cindex vertical tab
  3523. @cindex @samp{\v}
  3524. @cindex formfeed
  3525. @cindex @samp{\f}
  3526. @cindex newline
  3527. @cindex @samp{\n}
  3528. @cindex return (ASCII character)
  3529. @cindex @samp{\r}
  3530. @cindex escape (ASCII character)
  3531. @cindex @samp{\e}
  3532. Here are all the escape sequences that represent specific
  3533. characters in a character constant. The numeric values shown are
  3534. the corresponding ASCII character codes, as decimal numbers.
  3535. @example
  3536. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3537. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3538. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3539. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3540. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3541. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3542. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3543. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3544. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3545. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3546. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3547. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3548. @end example
  3549. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3550. You can also write octal and hex character codes as
  3551. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3552. option here, so octal codes do not need to start with @samp{0}.
  3553. The character constant's value has type @code{int}. However, the
  3554. character code is treated initially as a @code{char} value, which is
  3555. then converted to @code{int}. If the character code is greater than
  3556. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3557. on a platform where the type @code{char} is 8 bits long and signed.
  3558. @node String Constants
  3559. @section String Constants
  3560. @cindex string constants
  3561. @cindex constants, string
  3562. A @dfn{string constant} represents a series of characters. It starts
  3563. with @samp{"} and ends with @samp{"}; in between are the contents of
  3564. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3565. newline in the contents works in string constants as in character
  3566. constants. In a string constant, @samp{'} does not need to be quoted.
  3567. A string constant defines an array of characters which contains the
  3568. specified characters followed by the null character (code 0). Using
  3569. the string constant is equivalent to using the name of an array with
  3570. those contents. In simple cases, the length in bytes of the string
  3571. constant is one greater than the number of characters written in it.
  3572. As with any array in C, using the string constant in an expression
  3573. converts the array to a pointer (@pxref{Pointers}) to the array's
  3574. first element (@pxref{Accessing Array Elements}). This pointer will
  3575. have type @code{char *} because it points to an element of type
  3576. @code{char}. @code{char *} is an example of a type designator for a
  3577. pointer type (@pxref{Pointer Type Designators}). That type is used
  3578. for strings generally, not just the strings expressed as constants
  3579. in a program.
  3580. Thus, the string constant @code{"Foo!"} is almost
  3581. equivalent to declaring an array like this
  3582. @example
  3583. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3584. @end example
  3585. @noindent
  3586. and then using @code{string_array_1} in the program. There
  3587. are two differences, however:
  3588. @itemize @bullet
  3589. @item
  3590. The string constant doesn't define a name for the array.
  3591. @item
  3592. The string constant is probably stored in a read-only area of memory.
  3593. @end itemize
  3594. Newlines are not allowed in the text of a string constant. The motive
  3595. for this prohibition is to catch the error of omitting the closing
  3596. @samp{"}. To put a newline in a constant string, write it as
  3597. @samp{\n} in the string constant.
  3598. A real null character in the source code inside a string constant
  3599. causes a warning. To put a null character in the middle of a string
  3600. constant, write @samp{\0} or @samp{\000}.
  3601. Consecutive string constants are effectively concatenated. Thus,
  3602. @example
  3603. "Fo" "o!" @r{is equivalent to} "Foo!"
  3604. @end example
  3605. This is useful for writing a string containing multiple lines,
  3606. like this:
  3607. @example
  3608. "This message is so long that it needs more than\n"
  3609. "a single line of text. C does not allow a newline\n"
  3610. "to represent itself in a string constant, so we have to\n"
  3611. "write \\n to put it in the string. For readability of\n"
  3612. "the source code, it is advisable to put line breaks in\n"
  3613. "the source where they occur in the contents of the\n"
  3614. "constant.\n"
  3615. @end example
  3616. The sequence of a backslash and a newline is ignored anywhere
  3617. in a C program, and that includes inside a string constant.
  3618. Thus, you can write multi-line string constants this way:
  3619. @example
  3620. "This is another way to put newlines in a string constant\n\
  3621. and break the line after them in the source code."
  3622. @end example
  3623. @noindent
  3624. However, concatenation is the recommended way to do this.
  3625. You can also write perverse string constants like this,
  3626. @example
  3627. "Fo\
  3628. o!"
  3629. @end example
  3630. @noindent
  3631. but don't do that---write it like this instead:
  3632. @example
  3633. "Foo!"
  3634. @end example
  3635. Be careful to avoid passing a string constant to a function that
  3636. modifies the string it receives. The memory where the string constant
  3637. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3638. signal that normally terminates the function (@pxref{Signals}. Even
  3639. worse, the memory may not be read-only. Then the function might
  3640. modify the string constant, thus spoiling the contents of other string
  3641. constants that are supposed to contain the same value and are unified
  3642. by the compiler.
  3643. @node UTF-8 String Constants
  3644. @section UTF-8 String Constants
  3645. @cindex UTF-8 String Constants
  3646. Writing @samp{u8} immediately before a string constant, with no
  3647. intervening space, means to represent that string in UTF-8 encoding as
  3648. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3649. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3650. as multibyte sequences. Here is an example of a UTF-8 constant:
  3651. @example
  3652. u8"A cónstàñt"
  3653. @end example
  3654. This constant occupies 13 bytes plus the terminating null,
  3655. because each of the accented letters is a two-byte sequence.
  3656. Concatenating an ordinary string with a UTF-8 string conceptually
  3657. produces another UTF-8 string. However, if the ordinary string
  3658. contains character codes 128 and up, the results cannot be relied on.
  3659. @node Unicode Character Codes
  3660. @section Unicode Character Codes
  3661. @cindex Unicode character codes
  3662. @cindex universal character names
  3663. You can specify Unicode characters, for individual character constants
  3664. or as part of string constants (@pxref{String Constants}), using
  3665. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3666. hexadecimal Unicode character code. If the code value is too big for
  3667. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3668. Unicode character code. (These codes are called @dfn{universal
  3669. character names}.) For example,
  3670. @example
  3671. \u6C34 /* @r{16-bit code (UTF-16)} */
  3672. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3673. @end example
  3674. @noindent
  3675. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3676. Constants}). For instance,
  3677. @example
  3678. u8"fóó \u6C34 \U0010ABCD"
  3679. @end example
  3680. You can also use them in wide character constants (@pxref{Wide
  3681. Character Constants}), like this:
  3682. @example
  3683. u'\u6C34' /* @r{16-bit code} */
  3684. U'\U0010ABCD' /* @r{32-bit code} */
  3685. @end example
  3686. @noindent
  3687. and in wide string constants (@pxref{Wide String Constants}), like
  3688. this:
  3689. @example
  3690. u"\u6C34\u6C33" /* @r{16-bit code} */
  3691. U"\U0010ABCD" /* @r{32-bit code} */
  3692. @end example
  3693. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3694. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3695. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3696. actually ASCII control characters, and you can specify them with other
  3697. escape sequences (@pxref{Character Constants}).
  3698. @node Wide Character Constants
  3699. @section Wide Character Constants
  3700. @cindex wide character constants
  3701. @cindex constants, wide character
  3702. A @dfn{wide character constant} represents characters with more than 8
  3703. bits of character code. This is an obscure feature that we need to
  3704. document but that you probably won't ever use. If you're just
  3705. learning C, you may as well skip this section.
  3706. The original C wide character constant looks like @samp{L} (upper
  3707. case!) followed immediately by an ordinary character constant (with no
  3708. intervening space). Its data type is @code{wchar_t}, which is an
  3709. alias defined in @file{stddef.h} for one of the standard integer
  3710. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3711. it is 16 bits, these character constants use the UTF-16 form of
  3712. Unicode; if 32 bits, UTF-32.
  3713. There are also Unicode wide character constants which explicitly
  3714. specify the width. These constants start with @samp{u} or @samp{U}
  3715. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3716. character constant, and @samp{U} a 32-bit Unicode wide character
  3717. constant. Their types are, respectively, @code{char16_t} and
  3718. @w{@code{char32_t}}; they are declared in the header file
  3719. @file{uchar.h}. These character constants are valid even if
  3720. @file{uchar.h} is not included, but some uses of them may be
  3721. inconvenient without including it to declare those type names.
  3722. The character represented in a wide character constant can be an
  3723. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3724. are all valid, and they are all equal to @code{'a'}.
  3725. In all three kinds of wide character constants, you can write a
  3726. non-ASCII Unicode character in the constant itself; the constant's
  3727. value is the character's Unicode character code. Or you can specify
  3728. the Unicode character with an escape sequence (@pxref{Unicode
  3729. Character Codes}).
  3730. @node Wide String Constants
  3731. @section Wide String Constants
  3732. @cindex wide string constants
  3733. @cindex constants, wide string
  3734. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3735. characters. They are rarely used; if you're just
  3736. learning C, you may as well skip this section.
  3737. There are three kinds of wide string constants, which differ in the
  3738. data type used for each character in the string. Each wide string
  3739. constant is equivalent to an array of integers, but the data type of
  3740. those integers depends on the kind of wide string. Using the constant
  3741. in an expression will convert the array to a pointer to its first
  3742. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3743. For each kind of wide string constant, we state here what type that
  3744. pointer will be.
  3745. @table @code
  3746. @item char16_t
  3747. This is a 16-bit Unicode wide string constant: each element is a
  3748. 16-bit Unicode character code with type @code{char16_t}, so the string
  3749. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3750. @pxref{Pointer Type Designators}.) The constant is written as
  3751. @samp{u} (which must be lower case) followed (with no intervening
  3752. space) by a string constant with the usual syntax.
  3753. @item char32_t
  3754. This is a 32-bit Unicode wide string constant: each element is a
  3755. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3756. It's written as @samp{U} (which must be upper case) followed (with no
  3757. intervening space) by a string constant with the usual syntax.
  3758. @item wchar_t
  3759. This is the original kind of wide string constant. It's written as
  3760. @samp{L} (which must be upper case) followed (with no intervening
  3761. space) by a string constant with the usual syntax, and the string has
  3762. type @code{wchar_t@ *}.
  3763. The width of the data type @code{wchar_t} depends on the target
  3764. platform, which makes this kind of wide string somewhat less useful
  3765. than the newer kinds.
  3766. @end table
  3767. @code{char16_t} and @code{char32_t} are declared in the header file
  3768. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3769. Consecutive wide string constants of the same kind concatenate, just
  3770. like ordinary string constants. A wide string constant concatenated
  3771. with an ordinary string constant results in a wide string constant.
  3772. You can't concatenate two wide string constants of different kinds.
  3773. You also can't concatenate a wide string constant (of any kind) with a
  3774. UTF-8 string constant.
  3775. @node Type Size
  3776. @chapter Type Size
  3777. @cindex type size
  3778. @cindex size of type
  3779. @findex sizeof
  3780. Each data type has a @dfn{size}, which is the number of bytes
  3781. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3782. a C program, use @code{sizeof}. There are two ways to use it:
  3783. @table @code
  3784. @item sizeof @var{expression}
  3785. This gives the size of @var{expression}, based on its data type. It
  3786. does not calculate the value of @var{expression}, only its size, so if
  3787. @var{expression} includes side effects or function calls, they do not
  3788. happen. Therefore, @code{sizeof} is always a compile-time operation
  3789. that has zero run-time cost.
  3790. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3791. operand of @code{sizeof}.
  3792. For example,
  3793. @example
  3794. double a;
  3795. i = sizeof a + 10;
  3796. @end example
  3797. @noindent
  3798. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3799. Here's how to determine the number of elements in an array
  3800. @code{array}:
  3801. @example
  3802. (sizeof array / sizeof array[0])
  3803. @end example
  3804. @noindent
  3805. The expression @code{sizeof array} gives the size of the array, not
  3806. the size of a pointer to an element. However, if @var{expression} is
  3807. a function parameter that was declared as an array, that
  3808. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3809. the result is the size of that pointer.
  3810. @item sizeof (@var{type})
  3811. This gives the size of @var{type}.
  3812. For example,
  3813. @example
  3814. i = sizeof (double) + 10;
  3815. @end example
  3816. @noindent
  3817. is equivalent to the previous example.
  3818. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3819. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3820. C, which makes adding an integer to a function pointer work as desired
  3821. (@pxref{Pointer Arithmetic}).
  3822. @end table
  3823. @strong{Warning}: When you use @code{sizeof} with a type
  3824. instead of an expression, you must write parentheses around the type.
  3825. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3826. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3827. the cast expression to avoid an ambiguity in the grammar of C@.
  3828. Specifically,
  3829. @example
  3830. sizeof (int) -x
  3831. @end example
  3832. @noindent
  3833. parses as
  3834. @example
  3835. (sizeof (int)) - x
  3836. @end example
  3837. @noindent
  3838. If what you want is
  3839. @example
  3840. sizeof ((int) -x)
  3841. @end example
  3842. @noindent
  3843. you must write it that way, with parentheses.
  3844. The data type of the value of the @code{sizeof} operator is always one
  3845. of the unsigned integer types; which one of those types depends on the
  3846. machine. The header file @code{stddef.h} defines the typedef name
  3847. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3848. Names}.
  3849. @node Pointers
  3850. @chapter Pointers
  3851. @cindex pointers
  3852. Among high-level languages, C is rather low level, close to the
  3853. machine. This is mainly because it has explicit @dfn{pointers}. A
  3854. pointer value is the numeric address of data in memory. The type of
  3855. data to be found at that address is specified by the data type of the
  3856. pointer itself. The unary operator @samp{*} gets the data that a
  3857. pointer points to---this is called @dfn{dereferencing the pointer}.
  3858. C also allows pointers to functions, but since there are some
  3859. differences in how they work, we treat them later. @xref{Function
  3860. Pointers}.
  3861. @menu
  3862. * Address of Data:: Using the ``address-of'' operator.
  3863. * Pointer Types:: For each type, there is a pointer type.
  3864. * Pointer Declarations:: Declaring variables with pointer types.
  3865. * Pointer Type Designators:: Designators for pointer types.
  3866. * Pointer Dereference:: Accessing what a pointer points at.
  3867. * Null Pointers:: Pointers which do not point to any object.
  3868. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3869. * Void Pointers:: Totally generic pointers, can cast to any.
  3870. * Pointer Comparison:: Comparing memory address values.
  3871. * Pointer Arithmetic:: Computing memory address values.
  3872. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3873. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3874. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3875. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3876. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3877. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3878. @end menu
  3879. @node Address of Data
  3880. @section Address of Data
  3881. @cindex address-of operator
  3882. The most basic way to make a pointer is with the ``address-of''
  3883. operator, @samp{&}. Let's suppose we have these variables available:
  3884. @example
  3885. int i;
  3886. double a[5];
  3887. @end example
  3888. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3889. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3890. address of the element 3 of @code{a}. (It is actually the fourth
  3891. element in the array, since the first element has index 0.)
  3892. The address-of operator is unusual because it operates on a place to
  3893. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3894. stored there. (The left argument of a simple assignment is unusual in
  3895. the same way.) You can use it on any lvalue except a bit field
  3896. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3897. Constructors}).
  3898. @node Pointer Types
  3899. @section Pointer Types
  3900. For each data type @var{t}, there is a type for pointers to type
  3901. @var{t}. For these variables,
  3902. @example
  3903. int i;
  3904. double a[5];
  3905. @end example
  3906. @itemize @bullet
  3907. @item
  3908. @code{i} has type @code{int}; we say
  3909. @code{&i} is a ``pointer to @code{int}.''
  3910. @item
  3911. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3912. arrays of five @code{double}s.''
  3913. @item
  3914. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3915. to @code{double}.''
  3916. @end itemize
  3917. @node Pointer Declarations
  3918. @section Pointer-Variable Declarations
  3919. The way to declare that a variable @code{foo} points to type @var{t} is
  3920. @example
  3921. @var{t} *foo;
  3922. @end example
  3923. To remember this syntax, think ``if you dereference @code{foo}, using
  3924. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3925. points to type @var{t}.''
  3926. Thus, we can declare variables that hold pointers to these three
  3927. types, like this:
  3928. @example
  3929. int *ptri; /* @r{Pointer to @code{int}.} */
  3930. double *ptrd; /* @r{Pointer to @code{double}.} */
  3931. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3932. @end example
  3933. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3934. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3935. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3936. @code{double}.'' The parentheses express the point that you would
  3937. dereference it first, then subscript it.
  3938. Contrast the last one with this:
  3939. @example
  3940. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3941. @end example
  3942. @noindent
  3943. Because @samp{*} has higher syntactic precedence than subscripting,
  3944. you would subscript @code{aptrd} then dereference it. Therefore, it
  3945. declares an array of pointers, not a pointer.
  3946. @node Pointer Type Designators
  3947. @section Pointer-Type Designators
  3948. Every type in C has a designator; you make it by deleting the variable
  3949. name and the semicolon from a declaration (@pxref{Type
  3950. Designators}). Here are the designators for the pointer
  3951. types of the example declarations in the previous section:
  3952. @example
  3953. int * /* @r{Pointer to @code{int}.} */
  3954. double * /* @r{Pointer to @code{double}.} */
  3955. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3956. @end example
  3957. Remember, to understand what type a designator stands for, imagine the
  3958. variable name that would be in the declaration, and figure out what
  3959. type it would declare that variable with. @code{double (*)[5]} can
  3960. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3961. which, when dereferenced, gives an array of 5 @code{double}s.
  3962. @node Pointer Dereference
  3963. @section Dereferencing Pointers
  3964. @cindex dereferencing pointers
  3965. @cindex pointer dereferencing
  3966. The main use of a pointer value is to @dfn{dereference it} (access the
  3967. data it points at) with the unary @samp{*} operator. For instance,
  3968. @code{*&i} is the value at @code{i}'s address---which is just
  3969. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3970. valid.
  3971. A pointer-dereference expression whose type is data (not a function)
  3972. is an lvalue.
  3973. Pointers become really useful when we store them somewhere and use
  3974. them later. Here's a simple example to illustrate the practice:
  3975. @example
  3976. @{
  3977. int i;
  3978. int *ptr;
  3979. ptr = &i;
  3980. i = 5;
  3981. @r{@dots{}}
  3982. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3983. @}
  3984. @end example
  3985. This shows how to declare the variable @code{ptr} as type
  3986. @code{int *} (pointer to @code{int}), store a pointer value into it
  3987. (pointing at @code{i}), and use it later to get the value of the
  3988. object it points at (the value in @code{i}).
  3989. If anyone can provide a useful example which is this basic,
  3990. I would be grateful.
  3991. @node Null Pointers
  3992. @section Null Pointers
  3993. @cindex null pointers
  3994. @cindex pointers, null
  3995. @c ???stdio loads sttddef
  3996. A pointer value can be @dfn{null}, which means it does not point to
  3997. any object. The cleanest way to get a null pointer is by writing
  3998. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3999. also do it by casting 0 to the desired pointer type, as in
  4000. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4001. @xref{Explicit Type Conversion}.)
  4002. You can store a null pointer in any lvalue whose data type
  4003. is a pointer type:
  4004. @example
  4005. char *foo;
  4006. foo = NULL;
  4007. @end example
  4008. These two, if consecutive, can be combined into a declaration with
  4009. initializer,
  4010. @example
  4011. char *foo = NULL;
  4012. @end example
  4013. You can also explicitly cast @code{NULL} to the specific pointer type
  4014. you want---it makes no difference.
  4015. @example
  4016. char *foo;
  4017. foo = (char *) NULL;
  4018. @end example
  4019. To test whether a pointer is null, compare it with zero or
  4020. @code{NULL}, as shown here:
  4021. @example
  4022. if (p != NULL)
  4023. /* @r{@code{p} is not null.} */
  4024. operate (p);
  4025. @end example
  4026. Since testing a pointer for not being null is basic and frequent, all
  4027. but beginners in C will understand the conditional without need for
  4028. @code{!= NULL}:
  4029. @example
  4030. if (p)
  4031. /* @r{@code{p} is not null.} */
  4032. operate (p);
  4033. @end example
  4034. @node Invalid Dereference
  4035. @section Dereferencing Null or Invalid Pointers
  4036. Trying to dereference a null pointer is an error. On most platforms,
  4037. it generally causes a signal, usually @code{SIGSEGV}
  4038. (@pxref{Signals}).
  4039. @example
  4040. char *foo = NULL;
  4041. c = *foo; /* @r{This causes a signal and terminates.} */
  4042. @end example
  4043. @noindent
  4044. Likewise a pointer that has the wrong alignment for the target data type
  4045. (on most types of computer), or points to a part of memory that has
  4046. not been allocated in the process's address space.
  4047. The signal terminates the program, unless the program has arranged to
  4048. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4049. The GNU C Library Reference Manual}).
  4050. However, the signal might not happen if the dereference is optimized
  4051. away. In the example above, if you don't subsequently use the value
  4052. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4053. can prevent such optimization using the @code{volatile} qualifier, as
  4054. shown here:
  4055. @example
  4056. volatile char *p;
  4057. volatile char c;
  4058. c = *p;
  4059. @end example
  4060. You can use this to test whether @code{p} points to unallocated
  4061. memory. Set up a signal handler first, so the signal won't terminate
  4062. the program.
  4063. @node Void Pointers
  4064. @section Void Pointers
  4065. @cindex void pointers
  4066. @cindex pointers, void
  4067. The peculiar type @code{void *}, a pointer whose target type is
  4068. @code{void}, is used often in C@. It represents a pointer to
  4069. we-don't-say-what. Thus,
  4070. @example
  4071. void *numbered_slot_pointer (int);
  4072. @end example
  4073. @noindent
  4074. declares a function @code{numbered_slot_pointer} that takes an
  4075. integer parameter and returns a pointer, but we don't say what type of
  4076. data it points to.
  4077. With type @code{void *}, you can pass the pointer around and test
  4078. whether it is null. However, dereferencing it gives a @code{void}
  4079. value that can't be used (@pxref{The Void Type}). To dereference the
  4080. pointer, first convert it to some other pointer type.
  4081. Assignments convert @code{void *} automatically to any other pointer
  4082. type, if the left operand has a pointer type; for instance,
  4083. @example
  4084. @{
  4085. int *p;
  4086. /* @r{Converts return value to @code{int *}.} */
  4087. p = numbered_slot_pointer (5);
  4088. @r{@dots{}}
  4089. @}
  4090. @end example
  4091. Passing an argument of type @code{void *} for a parameter that has a
  4092. pointer type also converts. For example, supposing the function
  4093. @code{hack} is declared to require type @code{float *} for its
  4094. argument, this will convert the null pointer to that type.
  4095. @example
  4096. /* @r{Declare @code{hack} that way.}
  4097. @r{We assume it is defined somewhere else.} */
  4098. void hack (float *);
  4099. @dots{}
  4100. /* @r{Now call @code{hack}.} */
  4101. @{
  4102. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4103. @r{to @code{float *} to pass it to @code{hack}.} */
  4104. hack (numbered_slot_pointer (5));
  4105. @r{@dots{}}
  4106. @}
  4107. @end example
  4108. You can also convert to another pointer type with an explicit cast
  4109. (@pxref{Explicit Type Conversion}), like this:
  4110. @example
  4111. (int *) numbered_slot_pointer (5)
  4112. @end example
  4113. Here is an example which decides at run time which pointer
  4114. type to convert to:
  4115. @example
  4116. void
  4117. extract_int_or_double (void *ptr, bool its_an_int)
  4118. @{
  4119. if (its_an_int)
  4120. handle_an_int (*(int *)ptr);
  4121. else
  4122. handle_a_double (*(double *)ptr);
  4123. @}
  4124. @end example
  4125. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4126. to type @code{int *}, then dereference it.
  4127. @node Pointer Comparison
  4128. @section Pointer Comparison
  4129. @cindex pointer comparison
  4130. @cindex comparison, pointer
  4131. Two pointer values are equal if they point to the same location, or if
  4132. they are both null. You can test for this with @code{==} and
  4133. @code{!=}. Here's a trivial example:
  4134. @example
  4135. @{
  4136. int i;
  4137. int *p, *q;
  4138. p = &i;
  4139. q = &i;
  4140. if (p == q)
  4141. printf ("This will be printed.\n");
  4142. if (p != q)
  4143. printf ("This won't be printed.\n");
  4144. @}
  4145. @end example
  4146. Ordering comparisons such as @code{>} and @code{>=} operate on
  4147. pointers by converting them to unsigned integers. The C standard says
  4148. the two pointers must point within the same object in memory, but on
  4149. GNU/Linux systems these operations simply compare the numeric values
  4150. of the pointers.
  4151. The pointer values to be compared should in principle have the same type, but
  4152. they are allowed to differ in limited cases. First of all, if the two
  4153. pointers' target types are nearly compatible (@pxref{Compatible
  4154. Types}), the comparison is allowed.
  4155. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4156. the other is another pointer type, the comparison operator converts
  4157. the @code{void *} pointer to the other type so as to compare them.
  4158. (In standard C, this is not allowed if the other type is a function
  4159. pointer type, but that works in GNU C@.)
  4160. Comparison operators also allow comparing the integer 0 with a pointer
  4161. value. Thus works by converting 0 to a null pointer of the same type
  4162. as the other operand.
  4163. @node Pointer Arithmetic
  4164. @section Pointer Arithmetic
  4165. @cindex pointer arithmetic
  4166. @cindex arithmetic, pointer
  4167. Adding an integer (positive or negative) to a pointer is valid in C@.
  4168. It assumes that the pointer points to an element in an array, and
  4169. advances or retracts the pointer across as many array elements as the
  4170. integer specifies. Here is an example, in which adding a positive
  4171. integer advances the pointer to a later element in the same array.
  4172. @example
  4173. void
  4174. incrementing_pointers ()
  4175. @{
  4176. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4177. int elt0, elt1, elt4;
  4178. int *p = &array[0];
  4179. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4180. elt0 = *p;
  4181. ++p;
  4182. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4183. elt1 = *p;
  4184. p += 3;
  4185. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4186. elt4 = *p;
  4187. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4188. elt0, elt1, elt4);
  4189. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4190. @}
  4191. @end example
  4192. Here's an example where adding a negative integer retracts the pointer
  4193. to an earlier element in the same array.
  4194. @example
  4195. void
  4196. decrementing_pointers ()
  4197. @{
  4198. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4199. int elt0, elt3, elt4;
  4200. int *p = &array[4];
  4201. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4202. elt4 = *p;
  4203. --p;
  4204. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4205. elt3 = *p;
  4206. p -= 3;
  4207. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4208. elt0 = *p;
  4209. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4210. elt0, elt3, elt4);
  4211. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4212. @}
  4213. @end example
  4214. If one pointer value was made by adding an integer to another
  4215. pointer value, it should be possible to subtract the pointer values
  4216. and recover that integer. That works too in C@.
  4217. @example
  4218. void
  4219. subtract_pointers ()
  4220. @{
  4221. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4222. int *p0, *p3, *p4;
  4223. int *p = &array[4];
  4224. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4225. p4 = p;
  4226. --p;
  4227. /* @r{Now @code{p} points at element 3. Save the value.} */
  4228. p3 = p;
  4229. p -= 3;
  4230. /* @r{Now @code{p} points at element 0. Save the value.} */
  4231. p0 = p;
  4232. printf ("%d, %d, %d, %d\n",
  4233. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4234. /* @r{Prints 4, 0, 3, -3.} */
  4235. @}
  4236. @end example
  4237. The addition operation does not know where arrays are. All it does is
  4238. add the integer (multiplied by object size) to the value of the
  4239. pointer. When the initial pointer and the result point into a single
  4240. array, the result is well-defined.
  4241. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4242. into different memory objects.
  4243. The difference between two pointers has type @code{int}, or
  4244. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4245. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4246. file @file{stddef.h}.
  4247. This definition of pointer subtraction is consistent with
  4248. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4249. @code{p3}, as in ordinary algebra.
  4250. In standard C, addition and subtraction are not allowed on @code{void
  4251. *}, since the target type's size is not defined in that case.
  4252. Likewise, they are not allowed on pointers to function types.
  4253. However, these operations work in GNU C, and the ``size of the target
  4254. type'' is taken as 1.
  4255. @node Pointers and Arrays
  4256. @section Pointers and Arrays
  4257. @cindex pointers and arrays
  4258. @cindex arrays and pointers
  4259. The clean way to refer to an array element is
  4260. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4261. same job is to get the address of that element as a pointer, then
  4262. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4263. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4264. pointer to element zero, then increments it with @code{+} to point to
  4265. the desired element, then gets the value from there.
  4266. That pointer-arithmetic construct is the @emph{definition} of square
  4267. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4268. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4269. symmetrically, so one must be a pointer and the other an integer; it
  4270. does not matter which comes first.
  4271. Since indexing with square brackets is defined in terms of addition
  4272. and dereference, that too is symmetrical. Thus, you can write
  4273. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4274. would be foolish to write @code{3[array]}, since it has no advantage
  4275. and could confuse people who read the code.
  4276. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4277. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4278. instead. Why is this valid? The name of the array, when used by
  4279. itself as an expression (other than in @code{sizeof}), stands for a
  4280. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4281. converts @code{array} implicitly to @code{&array[0]}, and the result
  4282. is a pointer to element 3, equivalent to @code{&array[3]}.
  4283. Since square brackets are defined in terms of such addition,
  4284. @code{array[3]} first converts @code{array} to a pointer. That's why
  4285. it works to use an array directly in that construct.
  4286. @node Pointer Arithmetic Low Level
  4287. @section Pointer Arithmetic at Low Level
  4288. @cindex pointer arithmetic, low level
  4289. @cindex low level pointer arithmetic
  4290. The behavior of pointer arithmetic is theoretically defined only when
  4291. the pointer values all point within one object allocated in memory.
  4292. But the addition and subtraction operators can't tell whether the
  4293. pointer values are all within one object. They don't know where
  4294. objects start and end. So what do they really do?
  4295. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4296. address, which is in fact an integer---call it @var{pint}. It treats
  4297. @var{i} as a number of elements of the type that @var{p} points to.
  4298. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4299. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4300. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4301. If the starting pointer value @var{p} and the result do not point at
  4302. parts of the same object, the operation is not officially legitimate,
  4303. and C code is not ``supposed'' to do it. But you can do it anyway,
  4304. and it gives precisely the results described by the procedure above.
  4305. In some special situations it can do something useful, but non-wizards
  4306. should avoid it.
  4307. Here's a function to offset a pointer value @emph{as if} it pointed to
  4308. an object of any given size, by explicitly performing that calculation:
  4309. @example
  4310. #include <stdint.h>
  4311. void *
  4312. ptr_add (void *p, int i, int objsize)
  4313. @{
  4314. intptr_t p_address = (long) p;
  4315. intptr_t totalsize = i * objsize;
  4316. intptr_t new_address = p_address + totalsize;
  4317. return (void *) new_address;
  4318. @}
  4319. @end example
  4320. @noindent
  4321. @cindex @code{intptr_t}
  4322. This does the same job as @code{@var{p} + @var{i}} with the proper
  4323. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4324. defined in the header file @file{stdint.h}. (In practice, @code{long
  4325. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4326. @node Pointer Increment/Decrement
  4327. @section Pointer Increment and Decrement
  4328. @cindex pointer increment and decrement
  4329. @cindex incrementing pointers
  4330. @cindex decrementing pointers
  4331. The @samp{++} operator adds 1 to a variable. We have seen it for
  4332. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4333. For instance, suppose we have a series of positive integers,
  4334. terminated by a zero, and we want to add them all up.
  4335. @example
  4336. int
  4337. sum_array_till_0 (int *p)
  4338. @{
  4339. int sum = 0;
  4340. for (;;)
  4341. @{
  4342. /* @r{Fetch the next integer.} */
  4343. int next = *p++;
  4344. /* @r{Exit the loop if it's 0.} */
  4345. if (next == 0)
  4346. break;
  4347. /* @r{Add it into running total.} */
  4348. sum += next;
  4349. @}
  4350. return sum;
  4351. @}
  4352. @end example
  4353. @noindent
  4354. The statement @samp{break;} will be explained further on (@pxref{break
  4355. Statement}). Used in this way, it immediately exits the surrounding
  4356. @code{for} statement.
  4357. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4358. takes precedence over a prefix operator. Therefore, it dereferences
  4359. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4360. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4361. pointer, adding 1 to it advances it by the width of the datum it
  4362. points to---in this case, one @code{int}. Therefore, each iteration
  4363. of the loop picks up the next integer from the series and puts it into
  4364. @code{next}.
  4365. This @code{for}-loop has no initialization expression since @code{p}
  4366. and @code{sum} are already initialized, it has no end-test since the
  4367. @samp{break;} statement will exit it, and needs no expression to
  4368. advance it since that's done within the loop by incrementing @code{p}
  4369. and @code{sum}. Thus, those three expressions after @code{for} are
  4370. left empty.
  4371. Another way to write this function is by keeping the parameter value unchanged
  4372. and using indexing to access the integers in the table.
  4373. @example
  4374. int
  4375. sum_array_till_0_indexing (int *p)
  4376. @{
  4377. int i;
  4378. int sum = 0;
  4379. for (i = 0; ; i++)
  4380. @{
  4381. /* @r{Fetch the next integer.} */
  4382. int next = p[i];
  4383. /* @r{Exit the loop if it's 0.} */
  4384. if (next == 0)
  4385. break;
  4386. /* @r{Add it into running total.} */
  4387. sum += next;
  4388. @}
  4389. return sum;
  4390. @}
  4391. @end example
  4392. In this program, instead of advancing @code{p}, we advance @code{i}
  4393. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4394. i)}.) Either way, it uses the same address to get the next integer.
  4395. It makes no difference in this program whether we write @code{i++} or
  4396. @code{++i}, because the value is not used. All that matters is the
  4397. effect, to increment @code{i}.
  4398. The @samp{--} operator also works on pointers; it can be used
  4399. to scan backwards through an array, like this:
  4400. @example
  4401. int
  4402. after_last_nonzero (int *p, int len)
  4403. @{
  4404. /* @r{Set up @code{q} to point just after the last array element.} */
  4405. int *q = p + len;
  4406. while (q != p)
  4407. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4408. if (*--q != 0)
  4409. /* @r{Return the index of the element after that nonzero.} */
  4410. return q - p + 1;
  4411. return 0;
  4412. @}
  4413. @end example
  4414. That function returns the length of the nonzero part of the
  4415. array specified by its arguments; that is, the index of the
  4416. first zero of the run of zeros at the end.
  4417. @node Pointer Arithmetic Drawbacks
  4418. @section Drawbacks of Pointer Arithmetic
  4419. @cindex drawbacks of pointer arithmetic
  4420. @cindex pointer arithmetic, drawbacks
  4421. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4422. major security flaw in the C language. Theoretically, it is only
  4423. valid to adjust a pointer within one object allocated as a unit in
  4424. memory. However, if you unintentionally adjust a pointer across the
  4425. bounds of the object and into some other object, the system has no way
  4426. to detect this error.
  4427. A bug which does that can easily result in clobbering part of another
  4428. object. For example, with @code{array[-1]} you can read or write the
  4429. nonexistent element before the beginning of an array---probably part
  4430. of some other data.
  4431. Combining pointer arithmetic with casts between pointer types, you can
  4432. create a pointer that fails to be properly aligned for its type. For
  4433. example,
  4434. @example
  4435. int a[2];
  4436. char *pa = (char *)a;
  4437. int *p = (int *)(pa + 1);
  4438. @end example
  4439. @noindent
  4440. gives @code{p} a value pointing to an ``integer'' that includes part
  4441. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4442. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4443. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4444. ``works,'' it may be quite slow. It can also cause aliasing
  4445. confusions (@pxref{Aliasing}).
  4446. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4447. unless it is really necessary.
  4448. @node Pointer-Integer Conversion
  4449. @section Pointer-Integer Conversion
  4450. @cindex pointer-integer conversion
  4451. @cindex conversion between pointers and integers
  4452. @cindex @code{uintptr_t}
  4453. On modern computers, an address is simply a number. It occupies the
  4454. same space as some size of integer. In C, you can convert a pointer
  4455. to the appropriate integer types and vice versa, without losing
  4456. information. The appropriate integer types are @code{uintptr_t} (an
  4457. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4458. in @file{stdint.h}.
  4459. For instance,
  4460. @example
  4461. #include <stdint.h>
  4462. #include <stdio.h>
  4463. void
  4464. print_pointer (void *ptr)
  4465. @{
  4466. uintptr_t converted = (uintptr_t) ptr;
  4467. printf ("Pointer value is 0x%x\n",
  4468. (unsigned int) converted);
  4469. @}
  4470. @end example
  4471. @noindent
  4472. The specification @samp{%x} in the template (the first argument) for
  4473. @code{printf} means to represent this argument using hexadecimal
  4474. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4475. printing treats the number as unsigned, but it won't actually matter:
  4476. all @code{printf} gets to see is the series of bits in the number.
  4477. @strong{Warning:} Converting pointers to integers is risky---don't do
  4478. it unless it is really necessary.
  4479. @node Printing Pointers
  4480. @section Printing Pointers
  4481. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4482. For example:
  4483. @example
  4484. void
  4485. print_pointer (void *ptr)
  4486. @{
  4487. printf ("Pointer value is %p\n", ptr);
  4488. @}
  4489. @end example
  4490. The specification @samp{%p} works with any pointer type. It prints
  4491. @samp{0x} followed by the address in hexadecimal, printed as the
  4492. appropriate unsigned integer type.
  4493. @node Structures
  4494. @chapter Structures
  4495. @cindex structures
  4496. @findex struct
  4497. @cindex fields in structures
  4498. A @dfn{structure} is a user-defined data type that holds various
  4499. @dfn{fields} of data. Each field has a name and a data type specified
  4500. in the structure's definition.
  4501. Here we define a structure suitable for storing a linked list of
  4502. integers. Each list item will hold one integer, plus a pointer
  4503. to the next item.
  4504. @example
  4505. struct intlistlink
  4506. @{
  4507. int datum;
  4508. struct intlistlink *next;
  4509. @};
  4510. @end example
  4511. The structure definition has a @dfn{type tag} so that the code can
  4512. refer to this structure. The type tag here is @code{intlistlink}.
  4513. The definition refers recursively to the same structure through that
  4514. tag.
  4515. You can define a structure without a type tag, but then you can't
  4516. refer to it again. That is useful only in some special contexts, such
  4517. as inside a @code{typedef} or a @code{union}.
  4518. The contents of the structure are specified by the @dfn{field
  4519. declarations} inside the braces. Each field in the structure needs a
  4520. declaration there. The fields in one structure definition must have
  4521. distinct names, but these names do not conflict with any other names
  4522. in the program.
  4523. A field declaration looks just like a variable declaration. You can
  4524. combine field declarations with the same beginning, just as you can
  4525. combine variable declarations.
  4526. This structure has two fields. One, named @code{datum}, has type
  4527. @code{int} and will hold one integer in the list. The other, named
  4528. @code{next}, is a pointer to another @code{struct intlistlink}
  4529. which would be the rest of the list. In the last list item, it would
  4530. be @code{NULL}.
  4531. This structure definition is recursive, since the type of the
  4532. @code{next} field refers to the structure type. Such recursion is not
  4533. a problem; in fact, you can use the type @code{struct intlistlink *}
  4534. before the definition of the type @code{struct intlistlink} itself.
  4535. That works because pointers to all kinds of structures really look the
  4536. same at the machine level.
  4537. After defining the structure, you can declare a variable of type
  4538. @code{struct intlistlink} like this:
  4539. @example
  4540. struct intlistlink foo;
  4541. @end example
  4542. The structure definition itself can serve as the beginning of a
  4543. variable declaration, so you can declare variables immediately after,
  4544. like this:
  4545. @example
  4546. struct intlistlink
  4547. @{
  4548. int datum;
  4549. struct intlistlink *next;
  4550. @} foo;
  4551. @end example
  4552. @noindent
  4553. But that is ugly. It is almost always clearer to separate the
  4554. definition of the structure from its uses.
  4555. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4556. the scope of the structure type name to that block. That means the
  4557. structure type is recognized only within that block. Declaring it in
  4558. a function parameter list, as here,
  4559. @example
  4560. int f (struct foo @{int a, b@} parm);
  4561. @end example
  4562. @noindent
  4563. (assuming that @code{struct foo} is not already defined) limits the
  4564. scope of the structure type @code{struct foo} to that parameter list;
  4565. that is basically useless, so it triggers a warning.
  4566. Standard C requires at least one field in a structure.
  4567. GNU C does not require this.
  4568. @menu
  4569. * Referencing Fields:: Accessing field values in a structure object.
  4570. * Dynamic Memory Allocation:: Allocating space for objects
  4571. while the program is running.
  4572. * Field Offset:: Memory layout of fields within a structure.
  4573. * Structure Layout:: Planning the memory layout of fields.
  4574. * Packed Structures:: Packing structure fields as close as possible.
  4575. * Bit Fields:: Dividing integer fields
  4576. into fields with fewer bits.
  4577. * Bit Field Packing:: How bit fields pack together in integers.
  4578. * const Fields:: Making structure fields immutable.
  4579. * Zero Length:: Zero-length array as a variable-length object.
  4580. * Flexible Array Fields:: Another approach to variable-length objects.
  4581. * Overlaying Structures:: Casting one structure type
  4582. over an object of another structure type.
  4583. * Structure Assignment:: Assigning values to structure objects.
  4584. * Unions:: Viewing the same object in different types.
  4585. * Packing With Unions:: Using a union type to pack various types into
  4586. the same memory space.
  4587. * Cast to Union:: Casting a value one of the union's alternative
  4588. types to the type of the union itself.
  4589. * Structure Constructors:: Building new structure objects.
  4590. * Unnamed Types as Fields:: Fields' types do not always need names.
  4591. * Incomplete Types:: Types which have not been fully defined.
  4592. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4593. * Type Tags:: Scope of structure and union type tags.
  4594. @end menu
  4595. @node Referencing Fields
  4596. @section Referencing Structure Fields
  4597. @cindex referencing structure fields
  4598. @cindex structure fields, referencing
  4599. To make a structure useful, there has to be a way to examine and store
  4600. its fields. The @samp{.} (period) operator does that; its use looks
  4601. like @code{@var{object}.@var{field}}.
  4602. Given this structure and variable,
  4603. @example
  4604. struct intlistlink
  4605. @{
  4606. int datum;
  4607. struct intlistlink *next;
  4608. @};
  4609. struct intlistlink foo;
  4610. @end example
  4611. @noindent
  4612. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4613. fields in the value of @code{foo}. These fields are lvalues, so you
  4614. can store values into them, and read the values out again.
  4615. Most often, structures are dynamically allocated (see the next
  4616. section), and we refer to the objects via pointers.
  4617. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4618. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4619. contains this declaration:
  4620. @example
  4621. struct intlistlink *ptr;
  4622. @end example
  4623. @noindent
  4624. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4625. to the two fields in the object that @code{ptr} points to.
  4626. If a unary operator precedes an expression using @samp{->},
  4627. the @samp{->} nests inside:
  4628. @example
  4629. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4630. @end example
  4631. You can intermix @samp{->} and @samp{.} without parentheses,
  4632. as shown here:
  4633. @example
  4634. struct @{ double d; struct intlistlink l; @} foo;
  4635. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4636. @end example
  4637. @node Dynamic Memory Allocation
  4638. @section Dynamic Memory Allocation
  4639. @cindex dynamic memory allocation
  4640. @cindex memory allocation, dynamic
  4641. @cindex allocating memory dynamically
  4642. To allocate an object dynamically, call the library function
  4643. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4644. Reference Manual}). Here is how to allocate an object of type
  4645. @code{struct intlistlink}. To make this code work, include the file
  4646. @file{stdlib.h}, like this:
  4647. @example
  4648. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4649. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4650. @dots{}
  4651. struct intlistlink *
  4652. alloc_intlistlink ()
  4653. @{
  4654. struct intlistlink *p;
  4655. p = malloc (sizeof (struct intlistlink));
  4656. if (p == NULL)
  4657. fatal ("Ran out of storage");
  4658. /* @r{Initialize the contents.} */
  4659. p->datum = 0;
  4660. p->next = NULL;
  4661. return p;
  4662. @}
  4663. @end example
  4664. @noindent
  4665. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4666. will automatically convert it to type @code{struct intlistlink *}.
  4667. The return value of @code{malloc} is always sufficiently aligned
  4668. (@pxref{Type Alignment}) that it is valid for any data type.
  4669. The test for @code{p == NULL} is necessary because @code{malloc}
  4670. returns a null pointer if it cannot get any storage. We assume that
  4671. the program defines the function @code{fatal} to report a fatal error
  4672. to the user.
  4673. Here's how to add one more integer to the front of such a list:
  4674. @example
  4675. struct intlistlink *my_list = NULL;
  4676. void
  4677. add_to_mylist (int my_int)
  4678. @{
  4679. struct intlistlink *p = alloc_intlistlink ();
  4680. p->datum = my_int;
  4681. p->next = mylist;
  4682. mylist = p;
  4683. @}
  4684. @end example
  4685. The way to free the objects is by calling @code{free}. Here's
  4686. a function to free all the links in one of these lists:
  4687. @example
  4688. void
  4689. free_intlist (struct intlistlink *p)
  4690. @{
  4691. while (p)
  4692. @{
  4693. struct intlistlink *q = p;
  4694. p = p->next;
  4695. free (q);
  4696. @}
  4697. @}
  4698. @end example
  4699. We must extract the @code{next} pointer from the object before freeing
  4700. it, because @code{free} can clobber the data that was in the object.
  4701. For the same reason, the program must not use the list any more after
  4702. freeing its elements. To make sure it won't, it is best to clear out
  4703. the variable where the list was stored, like this:
  4704. @example
  4705. free_intlist (mylist);
  4706. mylist = NULL;
  4707. @end example
  4708. @node Field Offset
  4709. @section Field Offset
  4710. @cindex field offset
  4711. @cindex structure field offset
  4712. @cindex offset of structure fields
  4713. To determine the offset of a given field @var{field} in a structure
  4714. type @var{type}, use the macro @code{offsetof}, which is defined in
  4715. the file @file{stddef.h}. It is used like this:
  4716. @example
  4717. offsetof (@var{type}, @var{field})
  4718. @end example
  4719. Here is an example:
  4720. @example
  4721. struct foo
  4722. @{
  4723. int element;
  4724. struct foo *next;
  4725. @};
  4726. offsetof (struct foo, next)
  4727. /* @r{On most machines that is 4. It may be 8.} */
  4728. @end example
  4729. @node Structure Layout
  4730. @section Structure Layout
  4731. @cindex structure layout
  4732. @cindex layout of structures
  4733. The rest of this chapter covers advanced topics about structures. If
  4734. you are just learning C, you can skip it.
  4735. The precise layout of a @code{struct} type is crucial when using it to
  4736. overlay hardware registers, to access data structures in shared
  4737. memory, or to assemble and disassemble packets for network
  4738. communication. It is also important for avoiding memory waste when
  4739. the program makes many objects of that type. However, the layout
  4740. depends on the target platform. Each platform has conventions for
  4741. structure layout, which compilers need to follow.
  4742. Here are the conventions used on most platforms.
  4743. The structure's fields appear in the structure layout in the order
  4744. they are declared. When possible, consecutive fields occupy
  4745. consecutive bytes within the structure. However, if a field's type
  4746. demands more alignment than it would get that way, C gives it the
  4747. alignment it requires by leaving a gap after the previous field.
  4748. Once all the fields have been laid out, it is possible to determine
  4749. the structure's alignment and size. The structure's alignment is the
  4750. maximum alignment of any of the fields in it. Then the structure's
  4751. size is rounded up to a multiple of its alignment. That may require
  4752. leaving a gap at the end of the structure.
  4753. Here are some examples, where we assume that @code{char} has size and
  4754. alignment 1 (always true), and @code{int} has size and alignment 4
  4755. (true on most kinds of computers):
  4756. @example
  4757. struct foo
  4758. @{
  4759. char a, b;
  4760. int c;
  4761. @};
  4762. @end example
  4763. @noindent
  4764. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4765. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4766. There is a gap of 2 bytes before @code{c}.
  4767. Contrast that with this structure:
  4768. @example
  4769. struct foo
  4770. @{
  4771. char a;
  4772. int c;
  4773. char b;
  4774. @};
  4775. @end example
  4776. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4777. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4778. gaps: three bytes before @code{c}, and three bytes at the end.
  4779. These two structures have the same contents at the C level, but one
  4780. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4781. fields. A reliable way to avoid this sort of wastage is to order the
  4782. fields by size, biggest fields first.
  4783. @node Packed Structures
  4784. @section Packed Structures
  4785. @cindex packed structures
  4786. @cindex @code{__attribute__((packed))}
  4787. In GNU C you can force a structure to be laid out with no gaps by
  4788. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4789. end of the structure type declaration). Here's an example:
  4790. @example
  4791. struct __attribute__((packed)) foo
  4792. @{
  4793. char a;
  4794. int c;
  4795. char b;
  4796. @};
  4797. @end example
  4798. Without @code{__attribute__((packed))}, this structure occupies 12
  4799. bytes (as described in the previous section), assuming 4-byte
  4800. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4801. only 6 bytes long---the sum of the lengths of its fields.
  4802. Use of @code{__attribute__((packed))} often results in fields that
  4803. don't have the normal alignment for their types. Taking the address
  4804. of such a field can result in an invalid pointer because of its
  4805. improper alignment. Dereferencing such a pointer can cause a
  4806. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4807. unaligned pointers.
  4808. @xref{Attributes}.
  4809. @node Bit Fields
  4810. @section Bit Fields
  4811. @cindex bit fields
  4812. A structure field declaration with an integer type can specify the
  4813. number of bits the field should occupy. We call that a @dfn{bit
  4814. field}. These are useful because consecutive bit fields are packed
  4815. into a larger storage unit. For instance,
  4816. @example
  4817. unsigned char opcode: 4;
  4818. @end example
  4819. @noindent
  4820. specifies that this field takes just 4 bits.
  4821. Since it is unsigned, its possible values range
  4822. from 0 to 15. A signed field with 4 bits, such as this,
  4823. @example
  4824. signed char small: 4;
  4825. @end example
  4826. @noindent
  4827. can hold values from -8 to 7.
  4828. You can subdivide a single byte into those two parts by writing
  4829. @example
  4830. unsigned char opcode: 4;
  4831. signed char small: 4;
  4832. @end example
  4833. @noindent
  4834. in the structure. With bit fields, these two numbers fit into
  4835. a single @code{char}.
  4836. Here's how to declare a one-bit field that can hold either 0 or 1:
  4837. @example
  4838. unsigned char special_flag: 1;
  4839. @end example
  4840. You can also use the @code{bool} type for bit fields:
  4841. @example
  4842. bool special_flag: 1;
  4843. @end example
  4844. Except when using @code{bool} (which is always unsigned,
  4845. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4846. for a bit field. There is a default, if that's not specified: the bit
  4847. field is signed if plain @code{char} is signed, except that the option
  4848. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4849. is cleaner not to depend on this default.
  4850. Bit fields are special in that you cannot take their address with
  4851. @samp{&}. They are not stored with the size and alignment appropriate
  4852. for the specified type, so they cannot be addressed through pointers
  4853. to that type.
  4854. @node Bit Field Packing
  4855. @section Bit Field Packing
  4856. Programs to communicate with low-level hardware interfaces need to
  4857. define bit fields laid out to match the hardware data. This section
  4858. explains how to do that.
  4859. Consecutive bit fields are packed together, but each bit field must
  4860. fit within a single object of its specified type. In this example,
  4861. @example
  4862. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4863. @end example
  4864. @noindent
  4865. all five fields fit consecutively into one two-byte @code{short}.
  4866. They need 15 bits, and one @code{short} provides 16. By contrast,
  4867. @example
  4868. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4869. @end example
  4870. @noindent
  4871. needs three bytes. It fits @code{a} and @code{b} into one
  4872. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4873. add up to 9 bits). So @code{c} and @code{d} go into a second
  4874. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4875. Then @code{e} needs a third @code{char}. By contrast,
  4876. @example
  4877. unsigned char a : 3, b : 3;
  4878. unsigned int c : 3;
  4879. unsigned char d : 3, e : 3;
  4880. @end example
  4881. @noindent
  4882. needs only two bytes: the type @code{unsigned int}
  4883. allows @code{c} to straddle bytes that are in the same word.
  4884. You can leave a gap of a specified number of bits by defining a
  4885. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4886. It is allocated space in the structure just as a named bit field would
  4887. be allocated.
  4888. You can force the following bit field to advance to the following
  4889. aligned memory object with @code{@var{type} : 0;}.
  4890. Both of these constructs can syntactically share @var{type} with
  4891. ordinary bit fields. This example illustrates both:
  4892. @example
  4893. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4894. @end example
  4895. @noindent
  4896. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4897. between them. Then @code{: 0} advances to the next @code{int},
  4898. so @code{c} and @code{d} fit into that one.
  4899. These rules for packing bit fields apply to most target platforms,
  4900. including all the usual real computers. A few embedded controllers
  4901. have special layout rules.
  4902. @node const Fields
  4903. @section @code{const} Fields
  4904. @cindex const fields
  4905. @cindex structure fields, constant
  4906. @c ??? Is this a C standard feature?
  4907. A structure field declared @code{const} cannot be assigned to
  4908. (@pxref{const}). For instance, let's define this modified version of
  4909. @code{struct intlistlink}:
  4910. @example
  4911. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4912. @{
  4913. const int datum;
  4914. struct intlistlink *next;
  4915. @};
  4916. @end example
  4917. This structure can be used to prevent part of the code from modifying
  4918. the @code{datum} field:
  4919. @example
  4920. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4921. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4922. struct intlistlink_ro *q
  4923. = (struct intlistlink_ro *) p;
  4924. q->datum = 5; /* @r{Error!} */
  4925. p->datum = 5; /* @r{Valid since @code{*p} is}
  4926. @r{not a @code{struct intlistlink_ro}.} */
  4927. @end example
  4928. A @code{const} field can get a value in two ways: by initialization of
  4929. the whole structure, and by making a pointer-to-structure point to an object
  4930. in which that field already has a value.
  4931. Any @code{const} field in a structure type makes assignment impossible
  4932. for structures of that type (@pxref{Structure Assignment}). That is
  4933. because structure assignment works by assigning the structure's
  4934. fields, one by one.
  4935. @node Zero Length
  4936. @section Arrays of Length Zero
  4937. @cindex array of length zero
  4938. @cindex zero-length arrays
  4939. @cindex length-zero arrays
  4940. GNU C allows zero-length arrays. They are useful as the last element
  4941. of a structure that is really a header for a variable-length object.
  4942. Here's an example, where we construct a variable-size structure
  4943. to hold a line which is @code{this_length} characters long:
  4944. @example
  4945. struct line @{
  4946. int length;
  4947. char contents[0];
  4948. @};
  4949. struct line *thisline
  4950. = ((struct line *)
  4951. malloc (sizeof (struct line)
  4952. + this_length));
  4953. thisline->length = this_length;
  4954. @end example
  4955. In ISO C90, we would have to give @code{contents} a length of 1, which
  4956. means either wasting space or complicating the argument to @code{malloc}.
  4957. @node Flexible Array Fields
  4958. @section Flexible Array Fields
  4959. @cindex flexible array fields
  4960. @cindex array fields, flexible
  4961. The C99 standard adopted a more complex equivalent of zero-length
  4962. array fields. It's called a @dfn{flexible array}, and it's indicated
  4963. by omitting the length, like this:
  4964. @example
  4965. struct line
  4966. @{
  4967. int length;
  4968. char contents[];
  4969. @};
  4970. @end example
  4971. The flexible array has to be the last field in the structure, and there
  4972. must be other fields before it.
  4973. Under the C standard, a structure with a flexible array can't be part
  4974. of another structure, and can't be an element of an array.
  4975. GNU C allows static initialization of flexible array fields. The effect
  4976. is to ``make the array long enough'' for the initializer.
  4977. @example
  4978. struct f1 @{ int x; int y[]; @} f1
  4979. = @{ 1, @{ 2, 3, 4 @} @};
  4980. @end example
  4981. @noindent
  4982. This defines a structure variable named @code{f1}
  4983. whose type is @code{struct f1}. In C, a variable name or function name
  4984. never conflicts with a structure type tag.
  4985. Omitting the flexible array field's size lets the initializer
  4986. determine it. This is allowed only when the flexible array is defined
  4987. in the outermost structure and you declare a variable of that
  4988. structure type. For example:
  4989. @example
  4990. struct foo @{ int x; int y[]; @};
  4991. struct bar @{ struct foo z; @};
  4992. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4993. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4994. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4995. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4996. @end example
  4997. @node Overlaying Structures
  4998. @section Overlaying Different Structures
  4999. @cindex overlaying structures
  5000. @cindex structures, overlaying
  5001. Be careful about using different structure types to refer to the same
  5002. memory within one function, because GNU C can optimize code assuming
  5003. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5004. aliasing that can cause the problem:
  5005. @example
  5006. struct a @{ int size; char *data; @};
  5007. struct b @{ int size; char *data; @};
  5008. struct a foo;
  5009. struct b *q = (struct b *) &foo;
  5010. @end example
  5011. Here @code{q} points to the same memory that the variable @code{foo}
  5012. occupies, but they have two different types. The two types
  5013. @code{struct a} and @code{struct b} are defined alike, but they are
  5014. not the same type. Interspersing references using the two types,
  5015. like this,
  5016. @example
  5017. p->size = 0;
  5018. q->size = 1;
  5019. x = p->size;
  5020. @end example
  5021. @noindent
  5022. allows GNU C to assume that @code{p->size} is still zero when it is
  5023. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5024. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5025. Other compilers might also do this optimization. The ISO C standard
  5026. considers such code erroneous, precisely so that this optimization
  5027. will be valid.
  5028. @node Structure Assignment
  5029. @section Structure Assignment
  5030. @cindex structure assignment
  5031. @cindex assigning structures
  5032. Assignment operating on a structure type copies the structure. The
  5033. left and right operands must have the same type. Here is an example:
  5034. @example
  5035. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5036. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5037. @r{@dots{}}
  5038. struct point @{ double x, y; @};
  5039. struct point *
  5040. copy_point (struct point point)
  5041. @{
  5042. struct point *p
  5043. = (struct point *) malloc (sizeof (struct point));
  5044. if (p == NULL)
  5045. fatal ("Out of memory");
  5046. *p = point;
  5047. return p;
  5048. @}
  5049. @end example
  5050. Notionally, assignment on a structure type works by copying each of
  5051. the fields. Thus, if any of the fields has the @code{const}
  5052. qualifier, that structure type does not allow assignment:
  5053. @example
  5054. struct point @{ const double x, y; @};
  5055. struct point a, b;
  5056. a = b; /* @r{Error!} */
  5057. @end example
  5058. @xref{Assignment Expressions}.
  5059. @node Unions
  5060. @section Unions
  5061. @cindex unions
  5062. @findex union
  5063. A @dfn{union type} defines alternative ways of looking at the same
  5064. piece of memory. Each alternative view is defined with a data type,
  5065. and identified by a name. A union definition looks like this:
  5066. @example
  5067. union @var{name}
  5068. @{
  5069. @var{alternative declarations}@r{@dots{}}
  5070. @};
  5071. @end example
  5072. Each alternative declaration looks like a structure field declaration,
  5073. except that it can't be a bit field. For instance,
  5074. @example
  5075. union number
  5076. @{
  5077. long int integer;
  5078. double float;
  5079. @}
  5080. @end example
  5081. @noindent
  5082. lets you store either an integer (type @code{long int}) or a floating
  5083. point number (type @code{double}) in the same place in memory. The
  5084. length and alignment of the union type are the maximum of all the
  5085. alternatives---they do not have to be the same. In this union
  5086. example, @code{double} probably takes more space than @code{long int},
  5087. but that doesn't cause a problem in programs that use the union in the
  5088. normal way.
  5089. The members don't have to be different in data type. Sometimes
  5090. each member pertains to a way the data will be used. For instance,
  5091. @example
  5092. union datum
  5093. @{
  5094. double latitude;
  5095. double longitude;
  5096. double height;
  5097. double weight;
  5098. int continent;
  5099. @}
  5100. @end example
  5101. This union holds one of several kinds of data; most kinds are floating
  5102. points, but the value can also be a code for a continent which is an
  5103. integer. You @emph{could} use one member of type @code{double} to
  5104. access all the values which have that type, but the different member
  5105. names will make the program clearer.
  5106. The alignment of a union type is the maximum of the alignments of the
  5107. alternatives. The size of the union type is the maximum of the sizes
  5108. of the alternatives, rounded up to a multiple of the alignment
  5109. (because every type's size must be a multiple of its alignment).
  5110. All the union alternatives start at the address of the union itself.
  5111. If an alternative is shorter than the union as a whole, it occupies
  5112. the first part of the union's storage, leaving the last part unused
  5113. @emph{for that alternative}.
  5114. @strong{Warning:} if the code stores data using one union alternative
  5115. and accesses it with another, the results depend on the kind of
  5116. computer in use. Only wizards should try to do this. However, when
  5117. you need to do this, a union is a clean way to do it.
  5118. Assignment works on any union type by copying the entire value.
  5119. @node Packing With Unions
  5120. @section Packing With Unions
  5121. Sometimes we design a union with the intention of packing various
  5122. kinds of objects into a certain amount of memory space. For example.
  5123. @example
  5124. union bytes8
  5125. @{
  5126. long long big_int_elt;
  5127. double double_elt;
  5128. struct @{ int first, second; @} two_ints;
  5129. struct @{ void *first, *second; @} two_ptrs;
  5130. @};
  5131. union bytes8 *p;
  5132. @end example
  5133. This union makes it possible to look at 8 bytes of data that @code{p}
  5134. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5135. single floating-point number (@code{p->double_elt}), as a pair of
  5136. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5137. as a pair of pointers (@code{p->two_ptrs.first} and
  5138. @code{p->two_ptrs.second}).
  5139. To pack storage with such a union makes assumptions about the sizes of
  5140. all the types involved. This particular union was written expecting a
  5141. pointer to have the same size as @code{int}. On a machine where one
  5142. pointer takes 8 bytes, the code using this union probably won't work
  5143. as expected. The union, as such, will function correctly---if you
  5144. store two values through @code{two_ints} and extract them through
  5145. @code{two_ints}, you will get the same integers back---but the part of
  5146. the program that expects the union to be 8 bytes long could
  5147. malfunction, or at least use too much space.
  5148. The above example shows one case where a @code{struct} type with no
  5149. tag can be useful. Another way to get effectively the same result
  5150. is with arrays as members of the union:
  5151. @example
  5152. union eight_bytes
  5153. @{
  5154. long long big_int_elt;
  5155. double double_elt;
  5156. int two_ints[2];
  5157. void *two_ptrs[2];
  5158. @};
  5159. @end example
  5160. @node Cast to Union
  5161. @section Cast to a Union Type
  5162. @cindex cast to a union
  5163. @cindex union, casting to a
  5164. In GNU C, you can explicitly cast any of the alternative types to the
  5165. union type; for instance,
  5166. @example
  5167. (union eight_bytes) (long long) 5
  5168. @end example
  5169. @noindent
  5170. makes a value of type @code{union eight_bytes} which gets its contents
  5171. through the alternative named @code{big_int_elt}.
  5172. The value being cast must exactly match the type of the alternative,
  5173. so this is not valid:
  5174. @example
  5175. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5176. @end example
  5177. A cast to union type looks like any other cast, except that the type
  5178. specified is a union type. You can specify the type either with
  5179. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5180. Typedef Names}).
  5181. Using the cast as the right-hand side of an assignment to a variable of
  5182. union type is equivalent to storing in an alternative of the union:
  5183. @example
  5184. union foo u;
  5185. u = (union foo) x @r{means} u.i = x
  5186. u = (union foo) y @r{means} u.d = y
  5187. @end example
  5188. You can also use the union cast as a function argument:
  5189. @example
  5190. void hack (union foo);
  5191. @r{@dots{}}
  5192. hack ((union foo) x);
  5193. @end example
  5194. @node Structure Constructors
  5195. @section Structure Constructors
  5196. @cindex structure constructors
  5197. @cindex constructors, structure
  5198. You can construct a structure value by writing its type in
  5199. parentheses, followed by an initializer that would be valid in a
  5200. declaration for that type. For instance, given this declaration,
  5201. @example
  5202. struct foo @{int a; char b[2];@} structure;
  5203. @end example
  5204. @noindent
  5205. you can create a @code{struct foo} value as follows:
  5206. @example
  5207. ((struct foo) @{x + y, 'a', 0@})
  5208. @end example
  5209. @noindent
  5210. This specifies @code{x + y} for field @code{a},
  5211. the character @samp{a} for field @code{b}'s element 0,
  5212. and the null character for field @code{b}'s element 1.
  5213. The parentheses around that constructor are to necessary, but we
  5214. recommend writing them to make the nesting of the containing
  5215. expression clearer.
  5216. You can also show the nesting of the two by writing it like
  5217. this:
  5218. @example
  5219. ((struct foo) @{x + y, @{'a', 0@} @})
  5220. @end example
  5221. Each of those is equivalent to writing the following statement
  5222. expression (@pxref{Statement Exprs}):
  5223. @example
  5224. (@{
  5225. struct foo temp = @{x + y, 'a', 0@};
  5226. temp;
  5227. @})
  5228. @end example
  5229. You can also create a union value this way, but it is not especially
  5230. useful since that is equivalent to doing a cast:
  5231. @example
  5232. ((union whosis) @{@var{value}@})
  5233. @r{is equivalent to}
  5234. ((union whosis) (@var{value}))
  5235. @end example
  5236. @node Unnamed Types as Fields
  5237. @section Unnamed Types as Fields
  5238. @cindex unnamed structures
  5239. @cindex unnamed unions
  5240. @cindex structures, unnamed
  5241. @cindex unions, unnamed
  5242. A structure or a union can contain, as fields,
  5243. unnamed structures and unions. Here's an example:
  5244. @example
  5245. struct
  5246. @{
  5247. int a;
  5248. union
  5249. @{
  5250. int b;
  5251. float c;
  5252. @};
  5253. int d;
  5254. @} foo;
  5255. @end example
  5256. @noindent
  5257. You can access the fields of the unnamed union within @code{foo} as if they
  5258. were individual fields at the same level as the union definition:
  5259. @example
  5260. foo.a = 42;
  5261. foo.b = 47;
  5262. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5263. foo.d = 314;
  5264. @end example
  5265. Avoid using field names that could cause ambiguity. For example, with
  5266. this definition:
  5267. @example
  5268. struct
  5269. @{
  5270. int a;
  5271. struct
  5272. @{
  5273. int a;
  5274. float b;
  5275. @};
  5276. @} foo;
  5277. @end example
  5278. @noindent
  5279. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5280. an error when a definition is ambiguous in this way.
  5281. @node Incomplete Types
  5282. @section Incomplete Types
  5283. @cindex incomplete types
  5284. @cindex types, incomplete
  5285. A type that has not been fully defined is called an @dfn{incomplete
  5286. type}. Structure and union types are incomplete when the code makes a
  5287. forward reference, such as @code{struct foo}, before defining the
  5288. type. An array type is incomplete when its length is unspecified.
  5289. You can't use an incomplete type to declare a variable or field, or
  5290. use it for a function parameter or return type. The operators
  5291. @code{sizeof} and @code{_Alignof} give errors when used on an
  5292. incomplete type.
  5293. However, you can define a pointer to an incomplete type, and declare a
  5294. variable or field with such a pointer type. In general, you can do
  5295. everything with such pointers except dereference them. For example:
  5296. @example
  5297. extern void bar (struct mysterious_value *);
  5298. void
  5299. foo (struct mysterious_value *arg)
  5300. @{
  5301. bar (arg);
  5302. @}
  5303. @r{@dots{}}
  5304. @{
  5305. struct mysterious_value *p, **q;
  5306. p = *q;
  5307. foo (p);
  5308. @}
  5309. @end example
  5310. @noindent
  5311. These examples are valid because the code doesn't try to understand
  5312. what @code{p} points to; it just passes the pointer around.
  5313. (Presumably @code{bar} is defined in some other file that really does
  5314. have a definition for @code{struct mysterious_value}.) However,
  5315. dereferencing the pointer would get an error; that requires a
  5316. definition for the structure type.
  5317. @node Intertwined Incomplete Types
  5318. @section Intertwined Incomplete Types
  5319. When several structure types contain pointers to each other, you can
  5320. define the types in any order because pointers to types that come
  5321. later are incomplete types. Thus,
  5322. Here is an example.
  5323. @example
  5324. /* @r{An employee record points to a group.} */
  5325. struct employee
  5326. @{
  5327. char *name;
  5328. @r{@dots{}}
  5329. struct group *group; /* @r{incomplete type.} */
  5330. @r{@dots{}}
  5331. @};
  5332. /* @r{An employee list points to employees.} */
  5333. struct employee_list
  5334. @{
  5335. struct employee *this_one;
  5336. struct employee_list *next; /* @r{incomplete type.} */
  5337. @r{@dots{}}
  5338. @};
  5339. /* @r{A group points to one employee_list.} */
  5340. struct group
  5341. @{
  5342. char *name;
  5343. @r{@dots{}}
  5344. struct employee_list *employees;
  5345. @r{@dots{}}
  5346. @};
  5347. @end example
  5348. @node Type Tags
  5349. @section Type Tags
  5350. @cindex type tags
  5351. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5352. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5353. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5354. name or function name; the type tags have a separate @dfn{name space}.
  5355. Thus, there is no name conflict in this code:
  5356. @example
  5357. struct pair @{ int a, b; @};
  5358. int pair = 1;
  5359. @end example
  5360. @noindent
  5361. nor in this one:
  5362. @example
  5363. struct pair @{ int a, b; @} pair;
  5364. @end example
  5365. @noindent
  5366. where @code{pair} is both a structure type tag and a variable name.
  5367. However, @code{struct}, @code{union}, and @code{enum} share the same
  5368. name space of tags, so this is a conflict:
  5369. @example
  5370. struct pair @{ int a, b; @};
  5371. enum pair @{ c, d @};
  5372. @end example
  5373. @noindent
  5374. and so is this:
  5375. @example
  5376. struct pair @{ int a, b; @};
  5377. struct pair @{ int c, d; @};
  5378. @end example
  5379. When the code defines a type tag inside a block, the tag's scope is
  5380. limited to that block (as for local variables). Two definitions for
  5381. one type tag do not conflict if they are in different scopes; rather,
  5382. each is valid in its scope. For example,
  5383. @example
  5384. struct pair @{ int a, b; @};
  5385. void
  5386. pair_up_doubles (int len, double array[])
  5387. @{
  5388. struct pair @{ double a, b; @};
  5389. @r{@dots{}}
  5390. @}
  5391. @end example
  5392. @noindent
  5393. has two definitions for @code{struct pair} which do not conflict. The
  5394. one inside the function applies only within the definition of
  5395. @code{pair_up_doubles}. Within its scope, that definition
  5396. @dfn{shadows} the outer definition.
  5397. If @code{struct pair} appears inside the function body, before the
  5398. inner definition, it refers to the outer definition---the only one
  5399. that has been seen at that point. Thus, in this code,
  5400. @example
  5401. struct pair @{ int a, b; @};
  5402. void
  5403. pair_up_doubles (int len, double array[])
  5404. @{
  5405. struct two_pairs @{ struct pair *p, *q; @};
  5406. struct pair @{ double a, b; @};
  5407. @r{@dots{}}
  5408. @}
  5409. @end example
  5410. @noindent
  5411. the structure @code{two_pairs} has pointers to the outer definition of
  5412. @code{struct pair}, which is probably not desirable.
  5413. To prevent that, you can write @code{struct pair;} inside the function
  5414. body as a variable declaration with no variables. This is a
  5415. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5416. type tag local to the current block, with the details of the type to
  5417. come later. Here's an example:
  5418. @example
  5419. void
  5420. pair_up_doubles (int len, double array[])
  5421. @{
  5422. /* @r{Forward declaration for @code{pair}.} */
  5423. struct pair;
  5424. struct two_pairs @{ struct pair *p, *q; @};
  5425. /* @r{Give the details.} */
  5426. struct pair @{ double a, b; @};
  5427. @r{@dots{}}
  5428. @}
  5429. @end example
  5430. However, the cleanest practice is to avoid shadowing type tags.
  5431. @node Arrays
  5432. @chapter Arrays
  5433. @cindex array
  5434. @cindex elements of arrays
  5435. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5436. all of the same data type. Each element is identified by its numeric
  5437. @var{index} within the array.
  5438. We presented arrays of numbers in the sample programs early in this
  5439. manual (@pxref{Array Example}). However, arrays can have elements of
  5440. any data type, including pointers, structures, unions, and other
  5441. arrays.
  5442. If you know another programming language, you may suppose that you know all
  5443. about arrays, but C arrays have special quirks, so in this chapter we
  5444. collect all the information about arrays in C@.
  5445. The elements of a C array are allocated consecutively in memory,
  5446. with no gaps between them. Each element is aligned as required
  5447. for its data type (@pxref{Type Alignment}).
  5448. @menu
  5449. * Accessing Array Elements:: How to access individual elements of an array.
  5450. * Declaring an Array:: How to name and reserve space for a new array.
  5451. * Strings:: A string in C is a special case of array.
  5452. * Array Type Designators:: Referring to a specific array type.
  5453. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5454. * Limitations of C Arrays:: Arrays are not first-class objects.
  5455. * Multidimensional Arrays:: Arrays of arrays.
  5456. * Constructing Array Values:: Assigning values to an entire array at once.
  5457. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5458. @end menu
  5459. @node Accessing Array Elements
  5460. @section Accessing Array Elements
  5461. @cindex accessing array elements
  5462. @cindex array elements, accessing
  5463. If the variable @code{a} is an array, the @var{n}th element of
  5464. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5465. an element's value or to assign to it:
  5466. @example
  5467. x = a[5];
  5468. a[6] = 1;
  5469. @end example
  5470. @noindent
  5471. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5472. lvalue.
  5473. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5474. valid index is one less than the number of elements.
  5475. The C language does not check whether array indices are in bounds, so
  5476. if the code uses an out-of-range index, it will access memory outside the
  5477. array.
  5478. @strong{Warning:} Using only valid index values in C is the
  5479. programmer's responsibility.
  5480. Array indexing in C is not a primitive operation: it is defined in
  5481. terms of pointer arithmetic and dereferencing. Now that we know
  5482. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5483. its job.
  5484. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5485. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5486. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5487. When an expression with array type (such as @code{a}) appears as part
  5488. of a larger C expression, it is converted automatically to a pointer
  5489. to element zero of that array. For instance, @code{a} in an
  5490. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5491. computed as @code{*(&a[0]+i)}.
  5492. Now we can analyze how that expression gives us the desired element of
  5493. the array. It makes a pointer to element 0 of @code{a}, advances it
  5494. by the value of @code{i}, and dereferences that pointer.
  5495. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5496. @node Declaring an Array
  5497. @section Declaring an Array
  5498. @cindex declaring an array
  5499. @cindex array, declaring
  5500. To make an array declaration, write @code{[@var{length}]} after the
  5501. name being declared. This construct is valid in the declaration of a
  5502. variable, a function parameter, a function value type (the value can't
  5503. be an array, but it can be a pointer to one), a structure field, or a
  5504. union alternative.
  5505. The surrounding declaration specifies the element type of the array;
  5506. that can be any type of data, but not @code{void} or a function type.
  5507. For instance,
  5508. @example
  5509. double a[5];
  5510. @end example
  5511. @noindent
  5512. declares @code{a} as an array of 5 @code{double}s.
  5513. @example
  5514. struct foo bstruct[length];
  5515. @end example
  5516. @noindent
  5517. declares @code{bstruct} as an array of @code{length} objects of type
  5518. @code{struct foo}. A variable array size like this is allowed when
  5519. the array is not file-scope.
  5520. Other declaration constructs can nest within the array declaration
  5521. construct. For instance:
  5522. @example
  5523. struct foo *b[length];
  5524. @end example
  5525. @noindent
  5526. declares @code{b} as an array of @code{length} pointers to
  5527. @code{struct foo}. This shows that the length need not be a constant
  5528. (@pxref{Arrays of Variable Length}).
  5529. @example
  5530. double (*c)[5];
  5531. @end example
  5532. @noindent
  5533. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5534. @example
  5535. char *(*f (int))[5];
  5536. @end example
  5537. @noindent
  5538. declares @code{f} as a function taking an @code{int} argument and
  5539. returning a pointer to an array of 5 strings (pointers to
  5540. @code{char}s).
  5541. @example
  5542. double aa[5][10];
  5543. @end example
  5544. @noindent
  5545. declares @code{aa} as an array of 5 elements, each of which is an
  5546. array of 10 @code{double}s. This shows how to declare a
  5547. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5548. All these declarations specify the array's length, which is needed in
  5549. these cases in order to allocate storage for the array.
  5550. @node Strings
  5551. @section Strings
  5552. @cindex string
  5553. A string in C is a sequence of elements of type @code{char},
  5554. terminated with the null character, the character with code zero.
  5555. Programs often need to use strings with specific, fixed contents. To
  5556. write one in a C program, use a @dfn{string constant} such as
  5557. @code{"Take me to your leader!"}. The data type of a string constant
  5558. is @code{char *}. For the full syntactic details of writing string
  5559. constants, @ref{String Constants}.
  5560. To declare a place to store a non-constant string, declare an array of
  5561. @code{char}. Keep in mind that it must include one extra @code{char}
  5562. for the terminating null. For instance,
  5563. @example
  5564. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5565. @end example
  5566. @noindent
  5567. declares an array named @samp{text} with six elements---five letters
  5568. and the terminating null character. An equivalent way to get the same
  5569. result is this,
  5570. @example
  5571. char text[] = "Hello";
  5572. @end example
  5573. @noindent
  5574. which copies the elements of the string constant, including @emph{its}
  5575. terminating null character.
  5576. @example
  5577. char message[200];
  5578. @end example
  5579. @noindent
  5580. declares an array long enough to hold a string of 199 ASCII characters
  5581. plus the terminating null character.
  5582. When you store a string into @code{message} be sure to check or prove
  5583. that the length does not exceed its size. For example,
  5584. @example
  5585. void
  5586. set_message (char *text)
  5587. @{
  5588. int i;
  5589. for (i = 0; i < sizeof (message); i++)
  5590. @{
  5591. message[i] = text[i];
  5592. if (text[i] == 0)
  5593. return;
  5594. @}
  5595. fatal_error ("Message is too long for `message');
  5596. @}
  5597. @end example
  5598. It's easy to do this with the standard library function
  5599. @code{strncpy}, which fills out the whole destination array (up to a
  5600. specified length) with null characters. Thus, if the last character
  5601. of the destination is not null, the string did not fit. Many system
  5602. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5603. to run faster than an explicit @code{for}-loop.
  5604. Here's what the code looks like:
  5605. @example
  5606. void
  5607. set_message (char *text)
  5608. @{
  5609. strncpy (message, text, sizeof (message));
  5610. if (message[sizeof (message) - 1] != 0)
  5611. fatal_error ("Message is too long for `message');
  5612. @}
  5613. @end example
  5614. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5615. Library Reference Manual}, for more information about the standard
  5616. library functions for operating on strings.
  5617. You can avoid putting a fixed length limit on strings you construct or
  5618. operate on by allocating the space for them dynamically.
  5619. @xref{Dynamic Memory Allocation}.
  5620. @node Array Type Designators
  5621. @section Array Type Designators
  5622. Every C type has a type designator, which you make by deleting the
  5623. variable name and the semicolon from a declaration (@pxref{Type
  5624. Designators}). The designators for array types follow this rule, but
  5625. they may appear surprising.
  5626. @example
  5627. @r{type} int a[5]; @r{designator} int [5]
  5628. @r{type} double a[5][3]; @r{designator} double [5][3]
  5629. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5630. @end example
  5631. @node Incomplete Array Types
  5632. @section Incomplete Array Types
  5633. @cindex incomplete array types
  5634. @cindex array types, incomplete
  5635. An array is equivalent, for most purposes, to a pointer to its zeroth
  5636. element. When that is true, the length of the array is irrelevant.
  5637. The length needs to be known only for allocating space for the array, or
  5638. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5639. contexts C allows
  5640. @itemize @bullet
  5641. @item
  5642. An @code{extern} declaration says how to refer to a variable allocated
  5643. elsewhere. It does not need to allocate space for the variable,
  5644. so if it is an array, you can omit the length. For example,
  5645. @example
  5646. extern int foo[];
  5647. @end example
  5648. @item
  5649. When declaring a function parameter as an array, the argument value
  5650. passed to the function is really a pointer to the array's zeroth
  5651. element. This value does not say how long the array really is, there
  5652. is no need to declare it. For example,
  5653. @example
  5654. int
  5655. func (int foo[])
  5656. @end example
  5657. @end itemize
  5658. These declarations are examples of @dfn{incomplete} array types, types
  5659. that are not fully specified. The incompleteness makes no difference
  5660. for accessing elements of the array, but it matters for some other
  5661. things. For instance, @code{sizeof} is not allowed on an incomplete
  5662. type.
  5663. With multidimensional arrays, only the first dimension can be omitted:
  5664. @example
  5665. extern struct chesspiece *funnyboard foo[][8];
  5666. @end example
  5667. In other words, the code doesn't have to say how many rows there are,
  5668. but it must state how big each row is.
  5669. @node Limitations of C Arrays
  5670. @section Limitations of C Arrays
  5671. @cindex limitations of C arrays
  5672. @cindex first-class object
  5673. Arrays have quirks in C because they are not ``first-class objects'':
  5674. there is no way in C to operate on an array as a unit.
  5675. The other composite objects in C, structures and unions, are
  5676. first-class objects: a C program can copy a structure or union value
  5677. in an assignment, or pass one as an argument to a function, or make a
  5678. function return one. You can't do those things with an array in C@.
  5679. That is because a value you can operate on never has an array type.
  5680. An expression in C can have an array type, but that doesn't produce
  5681. the array as a value. Instead it is converted automatically to a
  5682. pointer to the array's element at index zero. The code can operate
  5683. on the pointer, and through that on individual elements of the array,
  5684. but it can't get and operate on the array as a unit.
  5685. There are three exceptions to this conversion rule, but none of them
  5686. offers a way to operate on the array as a whole.
  5687. First, @samp{&} applied to an expression with array type gives you the
  5688. address of the array, as an array type. However, you can't operate on the
  5689. whole array that way---if you apply @samp{*} to get the array back,
  5690. that expression converts, as usual, to a pointer to its zeroth
  5691. element.
  5692. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5693. @code{typeof} do not convert the array to a pointer; they leave it as
  5694. an array. But they don't operate on the array's data---they only give
  5695. information about its type.
  5696. Third, a string constant used as an initializer for an array is not
  5697. converted to a pointer---rather, the declaration copies the
  5698. @emph{contents} of that string in that one special case.
  5699. You @emph{can} copy the contents of an array, just not with an
  5700. assignment operator. You can do it by calling the library function
  5701. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5702. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5703. when a structure contains just an array, you can copy that structure.
  5704. An array itself is an lvalue if it is a declared variable, or part of
  5705. a structure or union that is an lvalue. When you construct an array
  5706. from elements (@pxref{Constructing Array Values}), that array is not
  5707. an lvalue.
  5708. @node Multidimensional Arrays
  5709. @section Multidimensional Arrays
  5710. @cindex multidimensional arrays
  5711. @cindex array, multidimensional
  5712. Strictly speaking, all arrays in C are unidimensional. However, you
  5713. can create an array of arrays, which is more or less equivalent to a
  5714. multidimensional array. For example,
  5715. @example
  5716. struct chesspiece *board[8][8];
  5717. @end example
  5718. @noindent
  5719. declares an array of 8 arrays of 8 pointers to @code{struct
  5720. chesspiece}. This data type could represent the state of a chess
  5721. game. To access one square's contents requires two array index
  5722. operations, one for each dimension. For instance, you can write
  5723. @code{board[row][column]}, assuming @code{row} and @code{column}
  5724. are variables with integer values in the proper range.
  5725. How does C understand @code{board[row][column]}? First of all,
  5726. @code{board} is converted automatically to a pointer to the zeroth
  5727. element (at index zero) of @code{board}. Adding @code{row} to that
  5728. makes it point to the desired element. Thus, @code{board[row]}'s
  5729. value is an element of @code{board}---an array of 8 pointers.
  5730. However, as an expression with array type, it is converted
  5731. automatically to a pointer to the array's zeroth element. The second
  5732. array index operation, @code{[column]}, accesses the chosen element
  5733. from that array.
  5734. As this shows, pointer-to-array types are meaningful in C@.
  5735. You can declare a variable that points to a row in a chess board
  5736. like this:
  5737. @example
  5738. struct chesspiece *(*rowptr)[8];
  5739. @end example
  5740. @noindent
  5741. This points to an array of 8 pointers to @code{struct chesspiece}.
  5742. You can assign to it as follows:
  5743. @example
  5744. rowptr = &board[5];
  5745. @end example
  5746. The dimensions don't have to be equal in length. Here we declare
  5747. @code{statepop} as an array to hold the population of each state in
  5748. the United States for each year since 1900:
  5749. @example
  5750. #define NSTATES 50
  5751. @{
  5752. int nyears = current_year - 1900 + 1;
  5753. int statepop[NSTATES][nyears];
  5754. @r{@dots{}}
  5755. @}
  5756. @end example
  5757. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5758. each indexed by the year (counting from 1900). Thus, to get the
  5759. element for a particular state and year, we must subscript it first
  5760. by the number that indicates the state, and second by the index for
  5761. the year:
  5762. @example
  5763. statepop[state][year - 1900]
  5764. @end example
  5765. @cindex array, layout in memory
  5766. The subarrays within the multidimensional array are allocated
  5767. consecutively in memory, and within each subarray, its elements are
  5768. allocated consecutively in memory. The most efficient way to process
  5769. all the elements in the array is to scan the last subscript in the
  5770. innermost loop. This means consecutive accesses go to consecutive
  5771. memory locations, which optimizes use of the processor's memory cache.
  5772. For example:
  5773. @example
  5774. int total = 0;
  5775. float average;
  5776. for (int state = 0; state < NSTATES, ++state)
  5777. @{
  5778. for (int year = 0; year < nyears; ++year)
  5779. @{
  5780. total += statepop[state][year];
  5781. @}
  5782. @}
  5783. average = total / nyears;
  5784. @end example
  5785. C's layout for multidimensional arrays is different from Fortran's
  5786. layout. In Fortran, a multidimensional array is not an array of
  5787. arrays; rather, multidimensional arrays are a primitive feature, and
  5788. it is the first index that varies most rapidly between consecutive
  5789. memory locations. Thus, the memory layout of a 50x114 array in C
  5790. matches that of a 114x50 array in Fortran.
  5791. @node Constructing Array Values
  5792. @section Constructing Array Values
  5793. @cindex constructing array values
  5794. @cindex array values, constructing
  5795. You can construct an array from elements by writing them inside
  5796. braces, and preceding all that with the array type's designator in
  5797. parentheses. There is no need to specify the array length, since the
  5798. number of elements determines that. The constructor looks like this:
  5799. @example
  5800. (@var{elttype}[]) @{ @var{elements} @};
  5801. @end example
  5802. Here is an example, which constructs an array of string pointers:
  5803. @example
  5804. (char *[]) @{ "x", "y", "z" @};
  5805. @end example
  5806. That's equivalent in effect to declaring an array with the same
  5807. initializer, like this:
  5808. @example
  5809. char *array[] = @{ "x", "y", "z" @};
  5810. @end example
  5811. and then using the array.
  5812. If all the elements are simple constant expressions, or made up of
  5813. such, then the compound literal can be coerced to a pointer to its
  5814. zeroth element and used to initialize a file-scope variable
  5815. (@pxref{File-Scope Variables}), as shown here:
  5816. @example
  5817. char **foo = (char *[]) @{ "x", "y", "z" @};
  5818. @end example
  5819. @noindent
  5820. The data type of @code{foo} is @code{char **}, which is a pointer
  5821. type, not an array type. The declaration is equivalent to defining
  5822. and then using an array-type variable:
  5823. @example
  5824. char *nameless_array[] = @{ "x", "y", "z" @};
  5825. char **foo = &nameless_array[0];
  5826. @end example
  5827. @node Arrays of Variable Length
  5828. @section Arrays of Variable Length
  5829. @cindex array of variable length
  5830. @cindex variable-length arrays
  5831. In GNU C, you can declare variable-length arrays like any other
  5832. arrays, but with a length that is not a constant expression. The
  5833. storage is allocated at the point of declaration and deallocated when
  5834. the block scope containing the declaration exits. For example:
  5835. @example
  5836. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5837. #include <string.h> /* @r{Declares @code{str}.} */
  5838. FILE *
  5839. concat_fopen (char *s1, char *s2, char *mode)
  5840. @{
  5841. char str[strlen (s1) + strlen (s2) + 1];
  5842. strcpy (str, s1);
  5843. strcat (str, s2);
  5844. return fopen (str, mode);
  5845. @}
  5846. @end example
  5847. @noindent
  5848. (This uses some standard library functions; see @ref{String and Array
  5849. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5850. The length of an array is computed once when the storage is allocated
  5851. and is remembered for the scope of the array in case it is used in
  5852. @code{sizeof}.
  5853. @strong{Warning:} don't allocate a variable-length array if the size
  5854. might be very large (more than 100,000), or in a recursive function,
  5855. because that is likely to cause stack overflow. Allocate the array
  5856. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5857. Jumping or breaking out of the scope of the array name deallocates the
  5858. storage. Jumping into the scope is not allowed; that gives an error
  5859. message.
  5860. You can also use variable-length arrays as arguments to functions:
  5861. @example
  5862. struct entry
  5863. tester (int len, char data[len][len])
  5864. @{
  5865. @r{@dots{}}
  5866. @}
  5867. @end example
  5868. As usual, a function argument declared with an array type
  5869. is really a pointer to an array that already exists.
  5870. Calling the function does not allocate the array, so there's no
  5871. particular danger of stack overflow in using this construct.
  5872. To pass the array first and the length afterward, use a forward
  5873. declaration in the function's parameter list (another GNU extension).
  5874. For example,
  5875. @example
  5876. struct entry
  5877. tester (int len; char data[len][len], int len)
  5878. @{
  5879. @r{@dots{}}
  5880. @}
  5881. @end example
  5882. The @code{int len} before the semicolon is a @dfn{parameter forward
  5883. declaration}, and it serves the purpose of making the name @code{len}
  5884. known when the declaration of @code{data} is parsed.
  5885. You can write any number of such parameter forward declarations in the
  5886. parameter list. They can be separated by commas or semicolons, but
  5887. the last one must end with a semicolon, which is followed by the
  5888. ``real'' parameter declarations. Each forward declaration must match
  5889. a ``real'' declaration in parameter name and data type. ISO C11 does
  5890. not support parameter forward declarations.
  5891. @node Enumeration Types
  5892. @chapter Enumeration Types
  5893. @cindex enumeration types
  5894. @cindex types, enumeration
  5895. @cindex enumerator
  5896. An @dfn{enumeration type} represents a limited set of integer values,
  5897. each with a name. It is effectively equivalent to a primitive integer
  5898. type.
  5899. Suppose we have a list of possible emotional states to store in an
  5900. integer variable. We can give names to these alternative values with
  5901. an enumeration:
  5902. @example
  5903. enum emotion_state @{ neutral, happy, sad, worried,
  5904. calm, nervous @};
  5905. @end example
  5906. @noindent
  5907. (Never mind that this is a simplistic way to classify emotional states;
  5908. it's just a code example.)
  5909. The names inside the enumeration are called @dfn{enumerators}. The
  5910. enumeration type defines them as constants, and their values are
  5911. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5912. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5913. the enumerators explicitly like this:
  5914. @example
  5915. enum emotion_state @{ neutral = 2, happy = 5,
  5916. sad = 20, worried = 10,
  5917. calm = -5, nervous = -300 @};
  5918. @end example
  5919. Each enumerator which does not specify a value gets value zero
  5920. (if it is at the beginning) or the next consecutive integer.
  5921. @example
  5922. /* @r{@code{neutral} is 0 by default,}
  5923. @r{and @code{worried} is 21 by default.} */
  5924. enum emotion_state @{ neutral,
  5925. happy = 5, sad = 20, worried,
  5926. calm = -5, nervous = -300 @};
  5927. @end example
  5928. If an enumerator is obsolete, you can specify that using it should
  5929. cause a warning, by including an attribute in the enumerator's
  5930. declaration. Here is how @code{happy} would look with this
  5931. attribute:
  5932. @example
  5933. happy __attribute__
  5934. ((deprecated
  5935. ("impossible under plutocratic rule")))
  5936. = 5,
  5937. @end example
  5938. @xref{Attributes}.
  5939. You can declare variables with the enumeration type:
  5940. @example
  5941. enum emotion_state feelings_now;
  5942. @end example
  5943. In the C code itself, this is equivalent to declaring the variable
  5944. @code{int}. (If all the enumeration values are positive, it is
  5945. equivalent to @code{unsigned int}.) However, declaring it with the
  5946. enumeration type has an advantage in debugging, because GDB knows it
  5947. should display the current value of the variable using the
  5948. corresponding name. If the variable's type is @code{int}, GDB can
  5949. only show the value as a number.
  5950. The identifier that follows @code{enum} is called a @dfn{type tag}
  5951. since it distinguishes different enumeration types. Type tags are in
  5952. a separate name space and belong to scopes like most other names in C@.
  5953. @xref{Type Tags}, for explanation.
  5954. You can predeclare an @code{enum} type tag like a structure or union
  5955. type tag, like this:
  5956. @example
  5957. enum foo;
  5958. @end example
  5959. @noindent
  5960. The @code{enum} type is incomplete until you finish defining it.
  5961. You can optionally include a trailing comma at the end of a list of
  5962. enumeration values:
  5963. @example
  5964. enum emotion_state @{ neutral, happy, sad, worried,
  5965. calm, nervous, @};
  5966. @end example
  5967. @noindent
  5968. This is useful in some macro definitions, since it enables you to
  5969. assemble the list of enumerators without knowing which one is last.
  5970. The extra comma does not change the meaning of the enumeration in any
  5971. way.
  5972. @node Defining Typedef Names
  5973. @chapter Defining Typedef Names
  5974. @cindex typedef names
  5975. @findex typedef
  5976. You can define a data type keyword as an alias for any type, and then
  5977. use the alias syntactically like a built-in type keyword such as
  5978. @code{int}. You do this using @code{typedef}, so these aliases are
  5979. also called @dfn{typedef names}.
  5980. @code{typedef} is followed by text that looks just like a variable
  5981. declaration, but instead of declaring variables it defines data type
  5982. keywords.
  5983. Here's how to define @code{fooptr} as a typedef alias for the type
  5984. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5985. with that type:
  5986. @example
  5987. typedef struct foo *fooptr;
  5988. fooptr x, y;
  5989. @end example
  5990. @noindent
  5991. That declaration is equivalent to the following one:
  5992. @example
  5993. struct foo *x, *y;
  5994. @end example
  5995. You can define a typedef alias for any type. For instance, this makes
  5996. @code{frobcount} an alias for type @code{int}:
  5997. @example
  5998. typedef int frobcount;
  5999. @end example
  6000. @noindent
  6001. This doesn't define a new type distinct from @code{int}. Rather,
  6002. @code{frobcount} is another name for the type @code{int}. Once the
  6003. variable is declared, it makes no difference which name the
  6004. declaration used.
  6005. There is a syntactic difference, however, between @code{frobcount} and
  6006. @code{int}: A typedef name cannot be used with
  6007. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6008. to specify the type all by itself. So you can't write this:
  6009. @example
  6010. unsigned frobcount f1; /* @r{Error!} */
  6011. @end example
  6012. But you can write this:
  6013. @example
  6014. typedef unsigned int unsigned_frobcount;
  6015. unsigned_frobcount f1;
  6016. @end example
  6017. In other words, a typedef name is not an alias for @emph{a keyword}
  6018. such as @code{int}. It stands for a @emph{type}, and that could be
  6019. the type @code{int}.
  6020. Typedef names are in the same namespace as functions and variables, so
  6021. you can't use the same name for a typedef and a function, or a typedef
  6022. and a variable. When a typedef is declared inside a code block, it is
  6023. in scope only in that block.
  6024. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6025. because many of these have standard meanings.
  6026. You can redefine a typedef name to the exact same type as its first
  6027. definition, but you cannot redefine a typedef name to a
  6028. different type, even if the two types are compatible. For example, this
  6029. is valid:
  6030. @example
  6031. typedef int frobcount;
  6032. typedef int frotzcount;
  6033. typedef frotzcount frobcount;
  6034. typedef frobcount frotzcount;
  6035. @end example
  6036. @noindent
  6037. because each typedef name is always defined with the same type
  6038. (@code{int}), but this is not valid:
  6039. @example
  6040. enum foo @{f1, f2, f3@};
  6041. typedef enum foo frobcount;
  6042. typedef int frobcount;
  6043. @end example
  6044. @noindent
  6045. Even though the type @code{enum foo} is compatible with @code{int},
  6046. they are not the @emph{same} type.
  6047. @node Statements
  6048. @chapter Statements
  6049. @cindex statements
  6050. A @dfn{statement} specifies computations to be done for effect; it
  6051. does not produce a value, as an expression would. In general a
  6052. statement ends with a semicolon (@samp{;}), but blocks (which are
  6053. statements, more or less) are an exception to that rule.
  6054. @ifnottex
  6055. @xref{Blocks}.
  6056. @end ifnottex
  6057. The places to use statements are inside a block, and inside a
  6058. complex statement. A @dfn{complex statement} contains one or two
  6059. components that are nested statements. Each such component must
  6060. consist of one and only one statement. The way to put multiple
  6061. statements in such a component is to group them into a @dfn{block}
  6062. (@pxref{Blocks}), which counts as one statement.
  6063. The following sections describe the various kinds of statement.
  6064. @menu
  6065. * Expression Statement:: Evaluate an expression, as a statement,
  6066. usually done for a side effect.
  6067. * if Statement:: Basic conditional execution.
  6068. * if-else Statement:: Multiple branches for conditional execution.
  6069. * Blocks:: Grouping multiple statements together.
  6070. * return Statement:: Return a value from a function.
  6071. * Loop Statements:: Repeatedly executing a statement or block.
  6072. * switch Statement:: Multi-way conditional choices.
  6073. * switch Example:: A plausible example of using @code{switch}.
  6074. * Duffs Device:: A special way to use @code{switch}.
  6075. * Case Ranges:: Ranges of values for @code{switch} cases.
  6076. * Null Statement:: A statement that does nothing.
  6077. * goto Statement:: Jump to another point in the source code,
  6078. identified by a label.
  6079. * Local Labels:: Labels with limited scope.
  6080. * Labels as Values:: Getting the address of a label.
  6081. * Statement Exprs:: A series of statements used as an expression.
  6082. @end menu
  6083. @node Expression Statement
  6084. @section Expression Statement
  6085. @cindex expression statement
  6086. @cindex statement, expression
  6087. The most common kind of statement in C is an @dfn{expression statement}.
  6088. It consists of an expression followed by a
  6089. semicolon. The expression's value is discarded, so the expressions
  6090. that are useful are those that have side effects: assignment
  6091. expressions, increment and decrement expressions, and function calls.
  6092. Here are examples of expression statements:
  6093. @smallexample
  6094. x = 5; /* @r{Assignment expression.} */
  6095. p++; /* @r{Increment expression.} */
  6096. printf ("Done\n"); /* @r{Function call expression.} */
  6097. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6098. x + y; /* @r{Useless statement without effect.} */
  6099. @end smallexample
  6100. In very unusual circumstances we use an expression statement
  6101. whose purpose is to get a fault if an address is invalid:
  6102. @smallexample
  6103. volatile char *p;
  6104. @r{@dots{}}
  6105. *p; /* @r{Cause signal if @code{p} is null.} */
  6106. @end smallexample
  6107. If the target of @code{p} is not declared @code{volatile}, the
  6108. compiler might optimize away the memory access, since it knows that
  6109. the value isn't really used. @xref{volatile}.
  6110. @node if Statement
  6111. @section @code{if} Statement
  6112. @cindex @code{if} statement
  6113. @cindex statement, @code{if}
  6114. @findex if
  6115. An @code{if} statement computes an expression to decide
  6116. whether to execute the following statement or not.
  6117. It looks like this:
  6118. @example
  6119. if (@var{condition})
  6120. @var{execute-if-true}
  6121. @end example
  6122. The first thing this does is compute the value of @var{condition}. If
  6123. that is true (nonzero), then it executes the statement
  6124. @var{execute-if-true}. If the value of @var{condition} is false
  6125. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6126. nothing.
  6127. This is a @dfn{complex statement} because it contains a component
  6128. @var{if-true-substatement} that is a nested statement. It must be one
  6129. and only one statement. The way to put multiple statements there is
  6130. to group them into a @dfn{block} (@pxref{Blocks}).
  6131. @node if-else Statement
  6132. @section @code{if-else} Statement
  6133. @cindex @code{if}@dots{}@code{else} statement
  6134. @cindex statement, @code{if}@dots{}@code{else}
  6135. @findex else
  6136. An @code{if}-@code{else} statement computes an expression to decide
  6137. which of two nested statements to execute.
  6138. It looks like this:
  6139. @example
  6140. if (@var{condition})
  6141. @var{if-true-substatement}
  6142. else
  6143. @var{if-false-substatement}
  6144. @end example
  6145. The first thing this does is compute the value of @var{condition}. If
  6146. that is true (nonzero), then it executes the statement
  6147. @var{if-true-substatement}. If the value of @var{condition} is false
  6148. (zero), then it executes the statement @var{if-false-substatement} instead.
  6149. This is a @dfn{complex statement} because it contains components
  6150. @var{if-true-substatement} and @var{if-else-substatement} that are
  6151. nested statements. Each must be one and only one statement. The way
  6152. to put multiple statements in such a component is to group them into a
  6153. @dfn{block} (@pxref{Blocks}).
  6154. @node Blocks
  6155. @section Blocks
  6156. @cindex block
  6157. @cindex compound statement
  6158. A @dfn{block} is a construct that contains multiple statements of any
  6159. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6160. series of statements and declarations in between. Another name for
  6161. blocks is @dfn{compound statements}.
  6162. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6163. normal statement---it does not end with a semicolon. But you can
  6164. @emph{use} it like a statement; anywhere that a statement is required
  6165. or allowed, you can write a block and consider that block a statement.
  6166. So far it seems that a block is a kind of statement with an unusual
  6167. syntax. But that is not entirely true: a function body is also a
  6168. block, and that block is definitely not a statement. The text after a
  6169. function header is not treated as a statement; only a function body is
  6170. allowed there, and nothing else would be meaningful there.
  6171. In a formal grammar we would have to choose---either a block is a kind
  6172. of statement or it is not. But this manual is meant for humans, not
  6173. for parser generators. The clearest answer for humans is, ``a block
  6174. is a statement, in some ways.''
  6175. @cindex nested block
  6176. @cindex internal block
  6177. A block that isn't a function body is called an @dfn{internal block}
  6178. or a @dfn{nested block}. You can put a nested block directly inside
  6179. another block, but more often the nested block is inside some complex
  6180. statement, such as a @code{for} statement or an @code{if} statement.
  6181. There are two uses for nested blocks in C:
  6182. @itemize @bullet
  6183. @item
  6184. To specify the scope for local declarations. For instance, a local
  6185. variable's scope is the rest of the innermost containing block.
  6186. @item
  6187. To write a series of statements where, syntactically, one statement is
  6188. called for. For instance, the @var{execute-if-true} of an @code{if}
  6189. statement is one statement. To put multiple statements there, they
  6190. have to be wrapped in a block, like this:
  6191. @example
  6192. if (x < 0)
  6193. @{
  6194. printf ("x was negative\n");
  6195. x = -x;
  6196. @}
  6197. @end example
  6198. @end itemize
  6199. This example (repeated from above) shows a nested block which serves
  6200. both purposes: it includes two statements (plus a declaration) in the
  6201. body of a @code{while} statement, and it provides the scope for the
  6202. declaration of @code{q}.
  6203. @example
  6204. void
  6205. free_intlist (struct intlistlink *p)
  6206. @{
  6207. while (p)
  6208. @{
  6209. struct intlistlink *q = p;
  6210. p = p->next;
  6211. free (q);
  6212. @}
  6213. @}
  6214. @end example
  6215. @node return Statement
  6216. @section @code{return} Statement
  6217. @cindex @code{return} statement
  6218. @cindex statement, @code{return}
  6219. @findex return
  6220. The @code{return} statement makes the containing function return
  6221. immediately. It has two forms. This one specifies no value to
  6222. return:
  6223. @example
  6224. return;
  6225. @end example
  6226. @noindent
  6227. That form is meant for functions whose return type is @code{void}
  6228. (@pxref{The Void Type}). You can also use it in a function that
  6229. returns nonvoid data, but that's a bad idea, since it makes the
  6230. function return garbage.
  6231. The form that specifies a value looks like this:
  6232. @example
  6233. return @var{value};
  6234. @end example
  6235. @noindent
  6236. which computes the expression @var{value} and makes the function
  6237. return that. If necessary, the value undergoes type conversion to
  6238. the function's declared return value type, which works like
  6239. assigning the value to a variable of that type.
  6240. @node Loop Statements
  6241. @section Loop Statements
  6242. @cindex loop statements
  6243. @cindex statements, loop
  6244. @cindex iteration
  6245. You can use a loop statement when you need to execute a series of
  6246. statements repeatedly, making an @dfn{iteration}. C provides several
  6247. different kinds of loop statements, described in the following
  6248. subsections.
  6249. Every kind of loop statement is a complex statement because contains a
  6250. component, here called @var{body}, which is a nested statement.
  6251. Most often the body is a block.
  6252. @menu
  6253. * while Statement:: Loop as long as a test expression is true.
  6254. * do-while Statement:: Execute a loop once, with further looping
  6255. as long as a test expression is true.
  6256. * break Statement:: End a loop immediately.
  6257. * for Statement:: Iterative looping.
  6258. * Example of for:: An example of iterative looping.
  6259. * Omitted for-Expressions:: for-loop expression options.
  6260. * for-Index Declarations:: for-loop declaration options.
  6261. * continue Statement:: Begin the next cycle of a loop.
  6262. @end menu
  6263. @node while Statement
  6264. @subsection @code{while} Statement
  6265. @cindex @code{while} statement
  6266. @cindex statement, @code{while}
  6267. @findex while
  6268. The @code{while} statement is the simplest loop construct.
  6269. It looks like this:
  6270. @example
  6271. while (@var{test})
  6272. @var{body}
  6273. @end example
  6274. Here, @var{body} is a statement (often a nested block) to repeat, and
  6275. @var{test} is the test expression that controls whether to repeat it again.
  6276. Each iteration of the loop starts by computing @var{test} and, if it
  6277. is true (nonzero), that means the loop should execute @var{body} again
  6278. and then start over.
  6279. Here's an example of advancing to the last structure in a chain of
  6280. structures chained through the @code{next} field:
  6281. @example
  6282. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6283. @r{@dots{}}
  6284. while (chain->next != NULL)
  6285. chain = chain->next;
  6286. @end example
  6287. @noindent
  6288. This code assumes the chain isn't empty to start with; if the chain is
  6289. empty (that is, if @code{chain} is a null pointer), the code gets a
  6290. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6291. @node do-while Statement
  6292. @subsection @code{do-while} Statement
  6293. @cindex @code{do}--@code{while} statement
  6294. @cindex statement, @code{do}--@code{while}
  6295. @findex do
  6296. The @code{do}--@code{while} statement is a simple loop construct that
  6297. performs the test at the end of the iteration.
  6298. @example
  6299. do
  6300. @var{body}
  6301. while (@var{test});
  6302. @end example
  6303. Here, @var{body} is a statement (possibly a block) to repeat, and
  6304. @var{test} is an expression that controls whether to repeat it again.
  6305. Each iteration of the loop starts by executing @var{body}. Then it
  6306. computes @var{test} and, if it is true (nonzero), that means to go
  6307. back and start over with @var{body}. If @var{test} is false (zero),
  6308. then the loop stops repeating and execution moves on past it.
  6309. @node break Statement
  6310. @subsection @code{break} Statement
  6311. @cindex @code{break} statement
  6312. @cindex statement, @code{break}
  6313. @findex break
  6314. The @code{break} statement looks like @samp{break;}. Its effect is to
  6315. exit immediately from the innermost loop construct or @code{switch}
  6316. statement (@pxref{switch Statement}).
  6317. For example, this loop advances @code{p} until the next null
  6318. character or newline.
  6319. @example
  6320. while (*p)
  6321. @{
  6322. /* @r{End loop if we have reached a newline.} */
  6323. if (*p == '\n')
  6324. break;
  6325. p++
  6326. @}
  6327. @end example
  6328. When there are nested loops, the @code{break} statement exits from the
  6329. innermost loop containing it.
  6330. @example
  6331. struct list_if_tuples
  6332. @{
  6333. struct list_if_tuples next;
  6334. int length;
  6335. data *contents;
  6336. @};
  6337. void
  6338. process_all_elements (struct list_if_tuples *list)
  6339. @{
  6340. while (list)
  6341. @{
  6342. /* @r{Process all the elements in this node's vector,}
  6343. @r{stopping when we reach one that is null.} */
  6344. for (i = 0; i < list->length; i++
  6345. @{
  6346. /* @r{Null element terminates this node's vector.} */
  6347. if (list->contents[i] == NULL)
  6348. /* @r{Exit the @code{for} loop.} */
  6349. break;
  6350. /* @r{Operate on the next element.} */
  6351. process_element (list->contents[i]);
  6352. @}
  6353. list = list->next;
  6354. @}
  6355. @}
  6356. @end example
  6357. The only way in C to exit from an outer loop is with
  6358. @code{goto} (@pxref{goto Statement}).
  6359. @node for Statement
  6360. @subsection @code{for} Statement
  6361. @cindex @code{for} statement
  6362. @cindex statement, @code{for}
  6363. @findex for
  6364. A @code{for} statement uses three expressions written inside a
  6365. parenthetical group to define the repetition of the loop. The first
  6366. expression says how to prepare to start the loop. The second says how
  6367. to test, before each iteration, whether to continue looping. The
  6368. third says how to advance, at the end of an iteration, for the next
  6369. iteration. All together, it looks like this:
  6370. @example
  6371. for (@var{start}; @var{continue-test}; @var{advance})
  6372. @var{body}
  6373. @end example
  6374. The first thing the @code{for} statement does is compute @var{start}.
  6375. The next thing it does is compute the expression @var{continue-test}.
  6376. If that expression is false (zero), the @code{for} statement finishes
  6377. immediately, so @var{body} is executed zero times.
  6378. However, if @var{continue-test} is true (nonzero), the @code{for}
  6379. statement executes @var{body}, then @var{advance}. Then it loops back
  6380. to the not-quite-top to test @var{continue-test} again. But it does
  6381. not compute @var{start} again.
  6382. @node Example of for
  6383. @subsection Example of @code{for}
  6384. Here is the @code{for} statement from the iterative Fibonacci
  6385. function:
  6386. @example
  6387. int i;
  6388. for (i = 1; i < n; ++i)
  6389. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6390. /* @r{since @code{i < n} is false the first time.} */
  6391. @{
  6392. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6393. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6394. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6395. int next = prev + last;
  6396. /* @r{Shift the values down.} */
  6397. prev = last;
  6398. last = next;
  6399. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6400. @r{and @var{prev} is @code{fib (@var{i})}.}
  6401. @r{But that won't stay true for long,}
  6402. @r{because we are about to increment @var{i}.} */
  6403. @}
  6404. @end example
  6405. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6406. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6407. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6408. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6409. that contains a declaration and two statements.
  6410. @node Omitted for-Expressions
  6411. @subsection Omitted @code{for}-Expressions
  6412. A fully-fleshed @code{for} statement contains all these parts,
  6413. @example
  6414. for (@var{start}; @var{continue-test}; @var{advance})
  6415. @var{body}
  6416. @end example
  6417. @noindent
  6418. but you can omit any of the three expressions inside the parentheses.
  6419. The parentheses and the two semicolons are required syntactically, but
  6420. the expressions between them may be missing. A missing expression
  6421. means this loop doesn't use that particular feature of the @code{for}
  6422. statement.
  6423. Instead of using @var{start}, you can do the loop preparation
  6424. before the @code{for} statement: the effect is the same. So we
  6425. could have written the beginning of the previous example this way:
  6426. @example
  6427. int i = 0;
  6428. for (; i < n; ++i)
  6429. @end example
  6430. @noindent
  6431. instead of this way:
  6432. @example
  6433. int i;
  6434. for (i = 0; i < n; ++i)
  6435. @end example
  6436. Omitting @var{continue-test} means the loop runs forever (or until
  6437. something else causes exit from it). Statements inside the loop can
  6438. test conditions for termination and use @samp{break;} to exit. This
  6439. is more flexible since you can put those tests anywhere in the loop,
  6440. not solely at the beginning.
  6441. Putting an expression in @var{advance} is almost equivalent to writing
  6442. it at the end of the loop body; it does almost the same thing. The
  6443. only difference is for the @code{continue} statement (@pxref{continue
  6444. Statement}). So we could have written this:
  6445. @example
  6446. for (i = 0; i < n;)
  6447. @{
  6448. @r{@dots{}}
  6449. ++i;
  6450. @}
  6451. @end example
  6452. @noindent
  6453. instead of this:
  6454. @example
  6455. for (i = 0; i < n; ++i)
  6456. @{
  6457. @r{@dots{}}
  6458. @}
  6459. @end example
  6460. The choice is mainly a matter of what is more readable for
  6461. programmers. However, there is also a syntactic difference:
  6462. @var{advance} is an expression, not a statement. It can't include
  6463. loops, blocks, declarations, etc.
  6464. @node for-Index Declarations
  6465. @subsection @code{for}-Index Declarations
  6466. You can declare loop-index variables directly in the @var{start}
  6467. portion of the @code{for}-loop, like this:
  6468. @example
  6469. for (int i = 0; i < n; ++i)
  6470. @{
  6471. @r{@dots{}}
  6472. @}
  6473. @end example
  6474. This kind of @var{start} is limited to a single declaration; it can
  6475. declare one or more variables, separated by commas, all of which are
  6476. the same @var{basetype} (@code{int}, in this example):
  6477. @example
  6478. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6479. @{
  6480. @r{@dots{}}
  6481. @}
  6482. @end example
  6483. @noindent
  6484. The scope of these variables is the @code{for} statement as a whole.
  6485. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6486. Variables declared in @code{for} statements should have initializers.
  6487. Omitting the initialization gives the variables unpredictable initial
  6488. values, so this code is erroneous.
  6489. @example
  6490. for (int i; i < n; ++i)
  6491. @{
  6492. @r{@dots{}}
  6493. @}
  6494. @end example
  6495. @node continue Statement
  6496. @subsection @code{continue} Statement
  6497. @cindex @code{continue} statement
  6498. @cindex statement, @code{continue}
  6499. @findex continue
  6500. The @code{continue} statement looks like @samp{continue;}, and its
  6501. effect is to jump immediately to the end of the innermost loop
  6502. construct. If it is a @code{for}-loop, the next thing that happens
  6503. is to execute the loop's @var{advance} expression.
  6504. For example, this loop increments @code{p} until the next null character
  6505. or newline, and operates (in some way not shown) on all the characters
  6506. in the line except for spaces. All it does with spaces is skip them.
  6507. @example
  6508. for (;*p; ++p)
  6509. @{
  6510. /* @r{End loop if we have reached a newline.} */
  6511. if (*p == '\n')
  6512. break;
  6513. /* @r{Pay no attention to spaces.} */
  6514. if (*p == ' ')
  6515. continue;
  6516. /* @r{Operate on the next character.} */
  6517. @r{@dots{}}
  6518. @}
  6519. @end example
  6520. @noindent
  6521. Executing @samp{continue;} skips the loop body but it does not
  6522. skip the @var{advance} expression, @code{p++}.
  6523. We could also write it like this:
  6524. @example
  6525. for (;*p; ++p)
  6526. @{
  6527. /* @r{Exit if we have reached a newline.} */
  6528. if (*p == '\n')
  6529. break;
  6530. /* @r{Pay no attention to spaces.} */
  6531. if (*p != ' ')
  6532. @{
  6533. /* @r{Operate on the next character.} */
  6534. @r{@dots{}}
  6535. @}
  6536. @}
  6537. @end example
  6538. The advantage of using @code{continue} is that it reduces the
  6539. depth of nesting.
  6540. Contrast @code{continue} with the @code{break} statement. @xref{break
  6541. Statement}.
  6542. @node switch Statement
  6543. @section @code{switch} Statement
  6544. @cindex @code{switch} statement
  6545. @cindex statement, @code{switch}
  6546. @findex switch
  6547. @findex case
  6548. @findex default
  6549. The @code{switch} statement selects code to run according to the value
  6550. of an expression. The expression, in parentheses, follows the keyword
  6551. @code{switch}. After that come all the cases to select among,
  6552. inside braces. It looks like this:
  6553. @example
  6554. switch (@var{selector})
  6555. @{
  6556. @var{cases}@r{@dots{}}
  6557. @}
  6558. @end example
  6559. A case can look like this:
  6560. @example
  6561. case @var{value}:
  6562. @var{statements}
  6563. break;
  6564. @end example
  6565. @noindent
  6566. which means ``come here if @var{selector} happens to have the value
  6567. @var{value},'' or like this (a GNU C extension):
  6568. @example
  6569. case @var{rangestart} ... @var{rangeend}:
  6570. @var{statements}
  6571. break;
  6572. @end example
  6573. @noindent
  6574. which means ``come here if @var{selector} happens to have a value
  6575. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6576. Ranges}.
  6577. The values in @code{case} labels must reduce to integer constants.
  6578. They can use arithmetic, and @code{enum} constants, but they cannot
  6579. refer to data in memory, because they have to be computed at compile
  6580. time. It is an error if two @code{case} labels specify the same
  6581. value, or ranges that overlap, or if one is a range and the other is a
  6582. value in that range.
  6583. You can also define a default case to handle ``any other value,'' like
  6584. this:
  6585. @example
  6586. default:
  6587. @var{statements}
  6588. break;
  6589. @end example
  6590. If the @code{switch} statement has no @code{default:} label, then it
  6591. does nothing when the value matches none of the cases.
  6592. The brace-group inside the @code{switch} statement is a block, and you
  6593. can declare variables with that scope just as in any other block
  6594. (@pxref{Blocks}). However, initializers in these declarations won't
  6595. necessarily be executed every time the @code{switch} statement runs,
  6596. so it is best to avoid giving them initializers.
  6597. @code{break;} inside a @code{switch} statement exits immediately from
  6598. the @code{switch} statement. @xref{break Statement}.
  6599. If there is no @code{break;} at the end of the code for a case,
  6600. execution continues into the code for the following case. This
  6601. happens more often by mistake than intentionally, but since this
  6602. feature is used in real code, we cannot eliminate it.
  6603. @strong{Warning:} When one case is intended to fall through to the
  6604. next, write a comment like @samp{falls through} to say it's
  6605. intentional. That way, other programmers won't assume it was an error
  6606. and ``fix'' it erroneously.
  6607. Consecutive @code{case} statements could, pedantically, be considered
  6608. an instance of falling through, but we don't consider or treat them that
  6609. way because they won't confuse anyone.
  6610. @node switch Example
  6611. @section Example of @code{switch}
  6612. Here's an example of using the @code{switch} statement
  6613. to distinguish among characters:
  6614. @cindex counting vowels and punctuation
  6615. @example
  6616. struct vp @{ int vowels, punct; @};
  6617. struct vp
  6618. count_vowels_and_punct (char *string)
  6619. @{
  6620. int c;
  6621. int vowels = 0;
  6622. int punct = 0;
  6623. /* @r{Don't change the parameter itself.} */
  6624. /* @r{That helps in debugging.} */
  6625. char *p = string;
  6626. struct vp value;
  6627. while (c = *p++)
  6628. switch (c)
  6629. @{
  6630. case 'y':
  6631. case 'Y':
  6632. /* @r{We assume @code{y_is_consonant} will check surrounding
  6633. letters to determine whether this y is a vowel.} */
  6634. if (y_is_consonant (p - 1))
  6635. break;
  6636. /* @r{Falls through} */
  6637. case 'a':
  6638. case 'e':
  6639. case 'i':
  6640. case 'o':
  6641. case 'u':
  6642. case 'A':
  6643. case 'E':
  6644. case 'I':
  6645. case 'O':
  6646. case 'U':
  6647. vowels++;
  6648. break;
  6649. case '.':
  6650. case ',':
  6651. case ':':
  6652. case ';':
  6653. case '?':
  6654. case '!':
  6655. case '\"':
  6656. case '\'':
  6657. punct++;
  6658. break;
  6659. @}
  6660. value.vowels = vowels;
  6661. value.punct = punct;
  6662. return value;
  6663. @}
  6664. @end example
  6665. @node Duffs Device
  6666. @section Duff's Device
  6667. @cindex Duff's device
  6668. The cases in a @code{switch} statement can be inside other control
  6669. constructs. For instance, we can use a technique known as @dfn{Duff's
  6670. device} to optimize this simple function,
  6671. @example
  6672. void
  6673. copy (char *to, char *from, int count)
  6674. @{
  6675. while (count > 0)
  6676. *to++ = *from++, count--;
  6677. @}
  6678. @end example
  6679. @noindent
  6680. which copies memory starting at @var{from} to memory starting at
  6681. @var{to}.
  6682. Duff's device involves unrolling the loop so that it copies
  6683. several characters each time around, and using a @code{switch} statement
  6684. to enter the loop body at the proper point:
  6685. @example
  6686. void
  6687. copy (char *to, char *from, int count)
  6688. @{
  6689. if (count <= 0)
  6690. return;
  6691. int n = (count + 7) / 8;
  6692. switch (count % 8)
  6693. @{
  6694. do @{
  6695. case 0: *to++ = *from++;
  6696. case 7: *to++ = *from++;
  6697. case 6: *to++ = *from++;
  6698. case 5: *to++ = *from++;
  6699. case 4: *to++ = *from++;
  6700. case 3: *to++ = *from++;
  6701. case 2: *to++ = *from++;
  6702. case 1: *to++ = *from++;
  6703. @} while (--n > 0);
  6704. @}
  6705. @}
  6706. @end example
  6707. @node Case Ranges
  6708. @section Case Ranges
  6709. @cindex case ranges
  6710. @cindex ranges in case statements
  6711. You can specify a range of consecutive values in a single @code{case} label,
  6712. like this:
  6713. @example
  6714. case @var{low} ... @var{high}:
  6715. @end example
  6716. @noindent
  6717. This has the same effect as the proper number of individual @code{case}
  6718. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6719. This feature is especially useful for ranges of ASCII character codes:
  6720. @example
  6721. case 'A' ... 'Z':
  6722. @end example
  6723. @strong{Be careful:} with integers, write spaces around the @code{...}
  6724. to prevent it from being parsed wrong. For example, write this:
  6725. @example
  6726. case 1 ... 5:
  6727. @end example
  6728. @noindent
  6729. rather than this:
  6730. @example
  6731. case 1...5:
  6732. @end example
  6733. @node Null Statement
  6734. @section Null Statement
  6735. @cindex null statement
  6736. @cindex statement, null
  6737. A @dfn{null statement} is just a semicolon. It does nothing.
  6738. A null statement is a placeholder for use where a statement is
  6739. grammatically required, but there is nothing to be done. For
  6740. instance, sometimes all the work of a @code{for}-loop is done in the
  6741. @code{for}-header itself, leaving no work for the body. Here is an
  6742. example that searches for the first newline in @code{array}:
  6743. @example
  6744. for (p = array; *p != '\n'; p++)
  6745. ;
  6746. @end example
  6747. @node goto Statement
  6748. @section @code{goto} Statement and Labels
  6749. @cindex @code{goto} statement
  6750. @cindex statement, @code{goto}
  6751. @cindex label
  6752. @findex goto
  6753. The @code{goto} statement looks like this:
  6754. @example
  6755. goto @var{label};
  6756. @end example
  6757. @noindent
  6758. Its effect is to transfer control immediately to another part of the
  6759. current function---where the label named @var{label} is defined.
  6760. An ordinary label definition looks like this:
  6761. @example
  6762. @var{label}:
  6763. @end example
  6764. @noindent
  6765. and it can appear before any statement. You can't use @code{default}
  6766. as a label, since that has a special meaning for @code{switch}
  6767. statements.
  6768. An ordinary label doesn't need a separate declaration; defining it is
  6769. enough.
  6770. Here's an example of using @code{goto} to implement a loop
  6771. equivalent to @code{do}--@code{while}:
  6772. @example
  6773. @{
  6774. loop_restart:
  6775. @var{body}
  6776. if (@var{condition})
  6777. goto loop_restart;
  6778. @}
  6779. @end example
  6780. The name space of labels is separate from that of variables and functions.
  6781. Thus, there is no error in using a single name in both ways:
  6782. @example
  6783. @{
  6784. int foo; // @r{Variable @code{foo}.}
  6785. foo: // @r{Label @code{foo}.}
  6786. @var{body}
  6787. if (foo > 0) // @r{Variable @code{foo}.}
  6788. goto foo; // @r{Label @code{foo}.}
  6789. @}
  6790. @end example
  6791. Blocks have no effect on ordinary labels; each label name is defined
  6792. throughout the whole of the function it appears in. It looks strange to
  6793. jump into a block with @code{goto}, but it works. For example,
  6794. @example
  6795. if (x < 0)
  6796. goto negative;
  6797. if (y < 0)
  6798. @{
  6799. negative:
  6800. printf ("Negative\n");
  6801. return;
  6802. @}
  6803. @end example
  6804. If the goto jumps into the scope of a variable, it does not
  6805. initialize the variable. For example, if @code{x} is negative,
  6806. @example
  6807. if (x < 0)
  6808. goto negative;
  6809. if (y < 0)
  6810. @{
  6811. int i = 5;
  6812. negative:
  6813. printf ("Negative, and i is %d\n", i);
  6814. return;
  6815. @}
  6816. @end example
  6817. @noindent
  6818. prints junk because @code{i} was not initialized.
  6819. If the block declares a variable-length automatic array, jumping into
  6820. it gives a compilation error. However, jumping out of the scope of a
  6821. variable-length array works fine, and deallocates its storage.
  6822. A label can't come directly before a declaration, so the code can't
  6823. jump directly to one. For example, this is not allowed:
  6824. @example
  6825. @{
  6826. goto foo;
  6827. foo:
  6828. int x = 5;
  6829. bar(&x);
  6830. @}
  6831. @end example
  6832. @noindent
  6833. The workaround is to add a statement, even an empty statement,
  6834. directly after the label. For example:
  6835. @example
  6836. @{
  6837. goto foo;
  6838. foo:
  6839. ;
  6840. int x = 5;
  6841. bar(&x);
  6842. @}
  6843. @end example
  6844. Likewise, a label can't be the last thing in a block. The workaround
  6845. solution is the same: add a semicolon after the label.
  6846. These unnecessary restrictions on labels make no sense, and ought in
  6847. principle to be removed; but they do only a little harm since labels
  6848. and @code{goto} are rarely the best way to write a program.
  6849. These examples are all artificial; it would be more natural to
  6850. write them in other ways, without @code{goto}. For instance,
  6851. the clean way to write the example that prints @samp{Negative} is this:
  6852. @example
  6853. if (x < 0 || y < 0)
  6854. @{
  6855. printf ("Negative\n");
  6856. return;
  6857. @}
  6858. @end example
  6859. @noindent
  6860. It is hard to construct simple examples where @code{goto} is actually
  6861. the best way to write a program. Its rare good uses tend to be in
  6862. complex code, thus not apt for the purpose of explaining the meaning
  6863. of @code{goto}.
  6864. The only good time to use @code{goto} is when it makes the code
  6865. simpler than any alternative. Jumping backward is rarely desirable,
  6866. because usually the other looping and control constructs give simpler
  6867. code. Using @code{goto} to jump forward is more often desirable, for
  6868. instance when a function needs to do some processing in an error case
  6869. and errors can occur at various different places within the function.
  6870. @node Local Labels
  6871. @section Locally Declared Labels
  6872. @cindex local labels
  6873. @cindex macros, local labels
  6874. @findex __label__
  6875. In GNU C you can declare @dfn{local labels} in any nested block
  6876. scope. A local label is used in a @code{goto} statement just like an
  6877. ordinary label, but you can only reference it within the block in
  6878. which it was declared.
  6879. A local label declaration looks like this:
  6880. @example
  6881. __label__ @var{label};
  6882. @end example
  6883. @noindent
  6884. or
  6885. @example
  6886. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6887. @end example
  6888. Local label declarations must come at the beginning of the block,
  6889. before any ordinary declarations or statements.
  6890. The label declaration declares the label @emph{name}, but does not define
  6891. the label itself. That's done in the usual way, with
  6892. @code{@var{label}:}, before one of the statements in the block.
  6893. The local label feature is useful for complex macros. If a macro
  6894. contains nested loops, a @code{goto} can be useful for breaking out of
  6895. them. However, an ordinary label whose scope is the whole function
  6896. cannot be used: if the macro can be expanded several times in one
  6897. function, the label will be multiply defined in that function. A
  6898. local label avoids this problem. For example:
  6899. @example
  6900. #define SEARCH(value, array, target) \
  6901. do @{ \
  6902. __label__ found; \
  6903. __auto_type _SEARCH_target = (target); \
  6904. __auto_type _SEARCH_array = (array); \
  6905. int i, j; \
  6906. int value; \
  6907. for (i = 0; i < max; i++) \
  6908. for (j = 0; j < max; j++) \
  6909. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6910. @{ (value) = i; goto found; @} \
  6911. (value) = -1; \
  6912. found:; \
  6913. @} while (0)
  6914. @end example
  6915. This could also be written using a statement expression
  6916. (@pxref{Statement Exprs}):
  6917. @example
  6918. #define SEARCH(array, target) \
  6919. (@{ \
  6920. __label__ found; \
  6921. __auto_type _SEARCH_target = (target); \
  6922. __auto_type _SEARCH_array = (array); \
  6923. int i, j; \
  6924. int value; \
  6925. for (i = 0; i < max; i++) \
  6926. for (j = 0; j < max; j++) \
  6927. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6928. @{ value = i; goto found; @} \
  6929. value = -1; \
  6930. found: \
  6931. value; \
  6932. @})
  6933. @end example
  6934. Ordinary labels are visible throughout the function where they are
  6935. defined, and only in that function. However, explicitly declared
  6936. local labels of a block are visible in nested functions declared
  6937. within that block. @xref{Nested Functions}, for details.
  6938. @xref{goto Statement}.
  6939. @node Labels as Values
  6940. @section Labels as Values
  6941. @cindex labels as values
  6942. @cindex computed gotos
  6943. @cindex goto with computed label
  6944. @cindex address of a label
  6945. In GNU C, you can get the address of a label defined in the current
  6946. function (or a local label defined in the containing function) with
  6947. the unary operator @samp{&&}. The value has type @code{void *}. This
  6948. value is a constant and can be used wherever a constant of that type
  6949. is valid. For example:
  6950. @example
  6951. void *ptr;
  6952. @r{@dots{}}
  6953. ptr = &&foo;
  6954. @end example
  6955. To use these values requires a way to jump to one. This is done
  6956. with the computed goto statement@footnote{The analogous feature in
  6957. Fortran is called an assigned goto, but that name seems inappropriate in
  6958. C, since you can do more with label addresses than store them in special label
  6959. variables.}, @code{goto *@var{exp};}. For example,
  6960. @example
  6961. goto *ptr;
  6962. @end example
  6963. @noindent
  6964. Any expression of type @code{void *} is allowed.
  6965. @xref{goto Statement}.
  6966. @menu
  6967. * Label Value Uses:: Examples of using label values.
  6968. * Label Value Caveats:: Limitations of label values.
  6969. @end menu
  6970. @node Label Value Uses
  6971. @subsection Label Value Uses
  6972. One use for label-valued constants is to initialize a static array to
  6973. serve as a jump table:
  6974. @example
  6975. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6976. @end example
  6977. Then you can select a label with indexing, like this:
  6978. @example
  6979. goto *array[i];
  6980. @end example
  6981. @noindent
  6982. Note that this does not check whether the subscript is in bounds---array
  6983. indexing in C never checks that.
  6984. You can make the table entries offsets instead of addresses
  6985. by subtracting one label from the others. Here is an example:
  6986. @example
  6987. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6988. &&hack - &&foo @};
  6989. goto *(&&foo + array[i]);
  6990. @end example
  6991. @noindent
  6992. Using offsets is preferable in shared libraries, as it avoids the need
  6993. for dynamic relocation of the array elements; therefore, the array can
  6994. be read-only.
  6995. An array of label values or offsets serves a purpose much like that of
  6996. the @code{switch} statement. The @code{switch} statement is cleaner,
  6997. so use @code{switch} by preference when feasible.
  6998. Another use of label values is in an interpreter for threaded code.
  6999. The labels within the interpreter function can be stored in the
  7000. threaded code for super-fast dispatching.
  7001. @node Label Value Caveats
  7002. @subsection Label Value Caveats
  7003. Jumping to a label defined in another function does not work.
  7004. It can cause unpredictable results.
  7005. The best way to avoid this is to store label values only in
  7006. automatic variables, or static variables whose names are declared
  7007. within the function. Never pass them as arguments.
  7008. @cindex cloning
  7009. An optimization known as @dfn{cloning} generates multiple simplified
  7010. variants of a function's code, for use with specific fixed arguments.
  7011. Using label values in certain ways, such as saving the address in one
  7012. call to the function and using it again in another call, would make cloning
  7013. give incorrect results. These functions must disable cloning.
  7014. Inlining calls to the function would also result in multiple copies of
  7015. the code, each with its own value of the same label. Using the label
  7016. in a computed goto is no problem, because the computed goto inhibits
  7017. inlining. However, using the label value in some other way, such as
  7018. an indication of where an error occurred, would be optimized wrong.
  7019. These functions must disable inlining.
  7020. To prevent inlining or cloning of a function, specify
  7021. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7022. @xref{Attributes}.
  7023. When a function uses a label value in a static variable initializer,
  7024. that automatically prevents inlining or cloning the function.
  7025. @node Statement Exprs
  7026. @section Statements and Declarations in Expressions
  7027. @cindex statements inside expressions
  7028. @cindex declarations inside expressions
  7029. @cindex expressions containing statements
  7030. @c the above section title wrapped and causes an underfull hbox.. i
  7031. @c changed it from "within" to "in". --mew 4feb93
  7032. A block enclosed in parentheses can be used as an expression in GNU
  7033. C@. This provides a way to use local variables, loops and switches within
  7034. an expression. We call it a @dfn{statement expression}.
  7035. Recall that a block is a sequence of statements
  7036. surrounded by braces. In this construct, parentheses go around the
  7037. braces. For example:
  7038. @example
  7039. (@{ int y = foo (); int z;
  7040. if (y > 0) z = y;
  7041. else z = - y;
  7042. z; @})
  7043. @end example
  7044. @noindent
  7045. is a valid (though slightly more complex than necessary) expression
  7046. for the absolute value of @code{foo ()}.
  7047. The last statement in the block should be an expression statement; an
  7048. expression followed by a semicolon, that is. The value of this
  7049. expression serves as the value of statement expression. If the last
  7050. statement is anything else, the statement expression's value is
  7051. @code{void}.
  7052. This feature is mainly useful in making macro definitions compute each
  7053. operand exactly once. @xref{Macros and Auto Type}.
  7054. Statement expressions are not allowed in expressions that must be
  7055. constant, such as the value for an enumerator, the width of a
  7056. bit-field, or the initial value of a static variable.
  7057. Jumping into a statement expression---with @code{goto}, or using a
  7058. @code{switch} statement outside the statement expression---is an
  7059. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7060. compiler can't detect the error, but it still won't work.
  7061. Jumping out of a statement expression is permitted, but since
  7062. subexpressions in C are not computed in a strict order, it is
  7063. unpredictable which other subexpressions will have been computed by
  7064. then. For example,
  7065. @example
  7066. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7067. @end example
  7068. @noindent
  7069. calls @code{foo} and @code{bar1} before it jumps, and never
  7070. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7071. does get called, that occurs after @code{foo} and before @code{bar1}.
  7072. @node Variables
  7073. @chapter Variables
  7074. @cindex variables
  7075. Every variable used in a C program needs to be made known by a
  7076. @dfn{declaration}. It can be used only after it has been declared.
  7077. It is an error to declare a variable name more than once in the same
  7078. scope; an exception is that @code{extern} declarations and tentative
  7079. definitions can coexist with another declaration of the same
  7080. variable.
  7081. Variables can be declared anywhere within a block or file. (Older
  7082. versions of C required that all variable declarations within a block
  7083. occur before any statements.)
  7084. Variables declared within a function or block are @dfn{local} to
  7085. it. This means that the variable name is visible only until the end
  7086. of that function or block, and the memory space is allocated only
  7087. while control is within it.
  7088. Variables declared at the top level in a file are called @dfn{file-scope}.
  7089. They are assigned fixed, distinct memory locations, so they retain
  7090. their values for the whole execution of the program.
  7091. @menu
  7092. * Variable Declarations:: Name a variable and and reserve space for it.
  7093. * Initializers:: Assigning inital values to variables.
  7094. * Designated Inits:: Assigning initial values to array elements
  7095. at particular array indices.
  7096. * Auto Type:: Obtaining the type of a variable.
  7097. * Local Variables:: Variables declared in function definitions.
  7098. * File-Scope Variables:: Variables declared outside of
  7099. function definitions.
  7100. * Static Local Variables:: Variables declared within functions,
  7101. but with permanent storage allocation.
  7102. * Extern Declarations:: Declaring a variable
  7103. which is allocated somewhere else.
  7104. * Allocating File-Scope:: When is space allocated
  7105. for file-scope variables?
  7106. * auto and register:: Historically used storage directions.
  7107. * Omitting Types:: The bad practice of declaring variables
  7108. with implicit type.
  7109. @end menu
  7110. @node Variable Declarations
  7111. @section Variable Declarations
  7112. @cindex variable declarations
  7113. @cindex declaration of variables
  7114. Here's what a variable declaration looks like:
  7115. @example
  7116. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7117. @end example
  7118. The @var{keywords} specify how to handle the scope of the variable
  7119. name and the allocation of its storage. Most declarations have
  7120. no keywords because the defaults are right for them.
  7121. C allows these keywords to come before or after @var{basetype}, or
  7122. even in the middle of it as in @code{unsigned static int}, but don't
  7123. do that---it would surprise other programmers. Always write the
  7124. keywords first.
  7125. The @var{basetype} can be any of the predefined types of C, or a type
  7126. keyword defined with @code{typedef}. It can also be @code{struct
  7127. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7128. addition, it can include type qualifiers such as @code{const} and
  7129. @code{volatile} (@pxref{Type Qualifiers}).
  7130. In the simplest case, @var{decorated-variable} is just the variable
  7131. name. That declares the variable with the type specified by
  7132. @var{basetype}. For instance,
  7133. @example
  7134. int foo;
  7135. @end example
  7136. @noindent
  7137. uses @code{int} as the @var{basetype} and @code{foo} as the
  7138. @var{decorated-variable}. It declares @code{foo} with type
  7139. @code{int}.
  7140. @example
  7141. struct tree_node foo;
  7142. @end example
  7143. @noindent
  7144. declares @code{foo} with type @code{struct tree_node}.
  7145. @menu
  7146. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7147. array and pointer types.
  7148. * Combining Variable Declarations:: More than one variable declaration
  7149. in a single statement.
  7150. @end menu
  7151. @node Declaring Arrays and Pointers
  7152. @subsection Declaring Arrays and Pointers
  7153. @cindex declaring arrays and pointers
  7154. @cindex array, declaring
  7155. @cindex pointers, declaring
  7156. To declare a variable that is an array, write
  7157. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7158. @example
  7159. int foo[5];
  7160. @end example
  7161. To declare a variable that has a pointer type, write
  7162. @code{*@var{variable}} for @var{decorated-variable}:
  7163. @example
  7164. struct list_elt *foo;
  7165. @end example
  7166. These constructs nest. For instance,
  7167. @example
  7168. int foo[3][5];
  7169. @end example
  7170. @noindent
  7171. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7172. @example
  7173. struct list_elt *foo[5];
  7174. @end example
  7175. @noindent
  7176. declares @code{foo} as an array of 5 pointers to structures, and
  7177. @example
  7178. struct list_elt **foo;
  7179. @end example
  7180. @noindent
  7181. declares @code{foo} as a pointer to a pointer to a structure.
  7182. @example
  7183. int **(*foo[30])(int, double);
  7184. @end example
  7185. @noindent
  7186. declares @code{foo} as an array of 30 pointers to functions
  7187. (@pxref{Function Pointers}), each of which must accept two arguments
  7188. (one @code{int} and one @code{double}) and return type @code{int **}.
  7189. @example
  7190. void
  7191. bar (int size)
  7192. @{
  7193. int foo[size];
  7194. @r{@dots{}}
  7195. @}
  7196. @end example
  7197. @noindent
  7198. declares @code{foo} as an array of integers with a size specified at
  7199. run time when the function @code{bar} is called.
  7200. @node Combining Variable Declarations
  7201. @subsection Combining Variable Declarations
  7202. @cindex combining variable declarations
  7203. @cindex variable declarations, combining
  7204. @cindex declarations, combining
  7205. When multiple declarations have the same @var{keywords} and
  7206. @var{basetype}, you can combine them using commas. Thus,
  7207. @example
  7208. @var{keywords} @var{basetype}
  7209. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7210. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7211. @end example
  7212. @noindent
  7213. is equivalent to
  7214. @example
  7215. @var{keywords} @var{basetype}
  7216. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7217. @var{keywords} @var{basetype}
  7218. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7219. @end example
  7220. Here are some simple examples:
  7221. @example
  7222. int a, b;
  7223. int a = 1, b = 2;
  7224. int a, *p, array[5];
  7225. int a = 0, *p = &a, array[5] = @{1, 2@};
  7226. @end example
  7227. @noindent
  7228. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7229. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7230. Since the initializer for @code{array} specifies only two elements,
  7231. the other three elements are initialized to zero.
  7232. @node Initializers
  7233. @section Initializers
  7234. @cindex initializers
  7235. A variable's declaration, unless it is @code{extern}, should also
  7236. specify its initial value. For numeric and pointer-type variables,
  7237. the initializer is an expression for the value. If necessary, it is
  7238. converted to the variable's type, just as in an assignment.
  7239. You can also initialize a local structure-type (@pxref{Structures}) or
  7240. local union-type (@pxref{Unions}) variable this way, from an
  7241. expression whose value has the same type. But you can't initialize an
  7242. array this way (@pxref{Arrays}), since arrays are not first-class
  7243. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7244. assignment.
  7245. You can initialize arrays and structures componentwise,
  7246. with a list of the elements or components. You can initialize
  7247. a union with any one of its alternatives.
  7248. @itemize @bullet
  7249. @item
  7250. A component-wise initializer for an array consists of element values
  7251. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7252. don't cover all the elements in the array, the remaining elements are
  7253. initialized to zero.
  7254. You can omit the size of the array when you declare it, and let
  7255. the initializer specify the size:
  7256. @example
  7257. int array[] = @{ 3, 9, 12 @};
  7258. @end example
  7259. @item
  7260. A component-wise initializer for a structure consists of field values
  7261. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7262. order as the fields are declared in the structure. If the values in
  7263. the initializer don't cover all the fields in the structure, the
  7264. remaining fields are initialized to zero.
  7265. @item
  7266. The initializer for a union-type variable has the form @code{@{
  7267. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7268. in the union definition.
  7269. @end itemize
  7270. For an array of arrays, a structure containing arrays, an array of
  7271. structures, etc., you can nest these constructs. For example,
  7272. @example
  7273. struct point @{ double x, y; @};
  7274. struct point series[]
  7275. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7276. @end example
  7277. You can omit a pair of inner braces if they contain the right
  7278. number of elements for the sub-value they initialize, so that
  7279. no elements or fields need to be filled in with zeros.
  7280. But don't do that very much, as it gets confusing.
  7281. An array of @code{char} can be initialized using a string constant.
  7282. Recall that the string constant includes an implicit null character at
  7283. the end (@pxref{String Constants}). Using a string constant as
  7284. initializer means to use its contents as the initial values of the
  7285. array elements. Here are examples:
  7286. @example
  7287. char text[6] = "text!"; /* @r{Includes the null.} */
  7288. char text[5] = "text!"; /* @r{Excludes the null.} */
  7289. char text[] = "text!"; /* @r{Gets length 6.} */
  7290. char text[]
  7291. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7292. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7293. @end example
  7294. @noindent
  7295. and this kind of initializer can be nested inside braces to initialize
  7296. structures or arrays that contain a @code{char}-array.
  7297. In like manner, you can use a wide string constant to initialize
  7298. an array of @code{wchar_t}.
  7299. @node Designated Inits
  7300. @section Designated Initializers
  7301. @cindex initializers with labeled elements
  7302. @cindex labeled elements in initializers
  7303. @cindex case labels in initializers
  7304. @cindex designated initializers
  7305. In a complex structure or long array, it's useful to indicate
  7306. which field or element we are initializing.
  7307. To designate specific array elements during initialization, include
  7308. the array index in brackets, and an assignment operator, for each
  7309. element:
  7310. @example
  7311. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7312. @end example
  7313. @noindent
  7314. This does the same thing as:
  7315. @example
  7316. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7317. @end example
  7318. The array initialization can include non-designated element values
  7319. alongside designated indices; these follow the expected ordering
  7320. of the array initialization, so that
  7321. @example
  7322. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7323. @end example
  7324. @noindent
  7325. does the same thing as:
  7326. @example
  7327. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7328. @end example
  7329. Note that you can only use constant expressions as array index values,
  7330. not variables.
  7331. If you need to initialize a subsequence of sequential array elements to
  7332. the same value, you can specify a range:
  7333. @example
  7334. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7335. @end example
  7336. @noindent
  7337. Using a range this way is a GNU C extension.
  7338. When subsequence ranges overlap, each element is initialized by the
  7339. last specification that applies to it. Thus, this initialization is
  7340. equivalent to the previous one.
  7341. @example
  7342. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7343. @end example
  7344. @noindent
  7345. as the second overrides the first for elements 0 through 19.
  7346. The value used to initialize a range of elements is evaluated only
  7347. once, for the first element in the range. So for example, this code
  7348. @example
  7349. int random_values[100]
  7350. = @{ [0 ... 99] = get_random_number() @};
  7351. @end example
  7352. @noindent
  7353. would initialize all 100 elements of the array @code{random_values} to
  7354. the same value---probably not what is intended.
  7355. Similarly, you can initialize specific fields of a structure variable
  7356. by specifying the field name prefixed with a dot:
  7357. @example
  7358. struct point @{ int x; int y; @};
  7359. struct point foo = @{ .y = 42; @};
  7360. @end example
  7361. @noindent
  7362. The same syntax works for union variables as well:
  7363. @example
  7364. union int_double @{ int i; double d; @};
  7365. union int_double foo = @{ .d = 34 @};
  7366. @end example
  7367. @noindent
  7368. This casts the integer value 34 to a double and stores it
  7369. in the union variable @code{foo}.
  7370. You can designate both array elements and structure elements in
  7371. the same initialization; for example, here's an array of point
  7372. structures:
  7373. @example
  7374. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7375. @end example
  7376. Along with the capability to specify particular array and structure
  7377. elements to initialize comes the possibility of initializing the same
  7378. element more than once:
  7379. @example
  7380. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7381. @end example
  7382. @noindent
  7383. In such a case, the last initialization value is retained.
  7384. @node Auto Type
  7385. @section Referring to a Type with @code{__auto_type}
  7386. @findex __auto_type
  7387. @findex typeof
  7388. @cindex macros, types of arguments
  7389. You can declare a variable copying the type from
  7390. the initializer by using @code{__auto_type} instead of a particular type.
  7391. Here's an example:
  7392. @example
  7393. #define max(a,b) \
  7394. (@{ __auto_type _a = (a); \
  7395. __auto_type _b = (b); \
  7396. _a > _b ? _a : _b @})
  7397. @end example
  7398. This defines @code{_a} to be of the same type as @code{a}, and
  7399. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7400. to do in a macro that ought to be able to handle any type of data
  7401. (@pxref{Macros and Auto Type}).
  7402. The original GNU C method for obtaining the type of a value is to use
  7403. @code{typeof}, which takes as an argument either a value or the name of
  7404. a type. The previous example could also be written as:
  7405. @example
  7406. #define max(a,b) \
  7407. (@{ typeof(a) _a = (a); \
  7408. typeof(b) _b = (b); \
  7409. _a > _b ? _a : _b @})
  7410. @end example
  7411. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7412. principal use case for @code{typeof} is in variable declarations with
  7413. initialization, which is exactly what @code{__auto_type} handles.
  7414. @node Local Variables
  7415. @section Local Variables
  7416. @cindex local variables
  7417. @cindex variables, local
  7418. Declaring a variable inside a function definition (@pxref{Function
  7419. Definitions}) makes the variable name @dfn{local} to the containing
  7420. block---that is, the containing pair of braces. More precisely, the
  7421. variable's name is visible starting just after where it appears in the
  7422. declaration, and its visibility continues until the end of the block.
  7423. Local variables in C are generally @dfn{automatic} variables: each
  7424. variable's storage exists only from the declaration to the end of the
  7425. block. Execution of the declaration allocates the storage, computes
  7426. the initial value, and stores it in the variable. The end of the
  7427. block deallocates the storage.@footnote{Due to compiler optimizations,
  7428. allocation and deallocation don't necessarily really happen at
  7429. those times.}
  7430. @strong{Warning:} Two declarations for the same local variable
  7431. in the same scope are an error.
  7432. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7433. The total space for the program's stack may be limited; therefore,
  7434. in using very large arrays, it may be necessary to allocate
  7435. them in some other way to stop the program from crashing.
  7436. @strong{Warning:} If the declaration of an automatic variable does not
  7437. specify an initial value, the variable starts out containing garbage.
  7438. In this example, the value printed could be anything at all:
  7439. @example
  7440. @{
  7441. int i;
  7442. printf ("Print junk %d\n", i);
  7443. @}
  7444. @end example
  7445. In a simple test program, that statement is likely to print 0, simply
  7446. because every process starts with memory zeroed. But don't rely on it
  7447. to be zero---that is erroneous.
  7448. @strong{Note:} Make sure to store a value into each local variable (by
  7449. assignment, or by initialization) before referring to its value.
  7450. @node File-Scope Variables
  7451. @section File-Scope Variables
  7452. @cindex file-scope variables
  7453. @cindex global variables
  7454. @cindex variables, file-scope
  7455. @cindex variables, global
  7456. A variable declaration at the top level in a file (not inside a
  7457. function definition) declares a @dfn{file-scope variable}. Loading a
  7458. program allocates the storage for all the file-scope variables in it,
  7459. and initializes them too.
  7460. Each file-scope variable is either @dfn{static} (limited to one
  7461. compilation module) or @dfn{global} (shared with all compilation
  7462. modules in the program). To make the variable static, write the
  7463. keyword @code{static} at the start of the declaration. Omitting
  7464. @code{static} makes the variable global.
  7465. The initial value for a file-scope variable can't depend on the
  7466. contents of storage, and can't call any functions.
  7467. @example
  7468. int foo = 5; /* @r{Valid.} */
  7469. int bar = foo; /* @r{Invalid!} */
  7470. int bar = sin (1.0); /* @r{Invalid!} */
  7471. @end example
  7472. But it can use the address of another file-scope variable:
  7473. @example
  7474. int foo;
  7475. int *bar = &foo; /* @r{Valid.} */
  7476. int arr[5];
  7477. int *bar3 = &arr[3]; /* @r{Valid.} */
  7478. int *bar4 = arr + 4; /* @r{Valid.} */
  7479. @end example
  7480. It is valid for a module to have multiple declarations for a
  7481. file-scope variable, as long as they are all global or all static, but
  7482. at most one declaration can specify an initial value for it.
  7483. @node Static Local Variables
  7484. @section Static Local Variables
  7485. @cindex static local variables
  7486. @cindex variables, static local
  7487. @findex static
  7488. The keyword @code{static} in a local variable declaration says to
  7489. allocate the storage for the variable permanently, just like a
  7490. file-scope variable, even if the declaration is within a function.
  7491. Here's an example:
  7492. @example
  7493. int
  7494. increment_counter ()
  7495. @{
  7496. static int counter = 0;
  7497. return ++counter;
  7498. @}
  7499. @end example
  7500. The scope of the name @code{counter} runs from the declaration to the
  7501. end of the containing block, just like an automatic local variable,
  7502. but its storage is permanent, so the value persists from one call to
  7503. the next. As a result, each call to @code{increment_counter}
  7504. returns a different, unique value.
  7505. The initial value of a static local variable has the same limitations
  7506. as for file-scope variables: it can't depend on the contents of
  7507. storage or call any functions. It can use the address of a file-scope
  7508. variable or a static local variable, because those addresses are
  7509. determined before the program runs.
  7510. @node Extern Declarations
  7511. @section @code{extern} Declarations
  7512. @cindex @code{extern} declarations
  7513. @cindex declarations, @code{extern}
  7514. @findex extern
  7515. An @code{extern} declaration is used to refer to a global variable
  7516. whose principal declaration comes elsewhere---in the same module, or in
  7517. another compilation module. It looks like this:
  7518. @example
  7519. extern @var{basetype} @var{decorated-variable};
  7520. @end example
  7521. Its meaning is that, in the current scope, the variable name refers to
  7522. the file-scope variable of that name---which needs to be declared in a
  7523. non-@code{extern}, non-@code{static} way somewhere else.
  7524. For instance, if one compilation module has this global variable
  7525. declaration
  7526. @example
  7527. int error_count = 0;
  7528. @end example
  7529. @noindent
  7530. then other compilation modules can specify this
  7531. @example
  7532. extern int error_count;
  7533. @end example
  7534. @noindent
  7535. to allow reference to the same variable.
  7536. The usual place to write an @code{extern} declaration is at top level
  7537. in a source file, but you can write an @code{extern} declaration
  7538. inside a block to make a global or static file-scope variable
  7539. accessible in that block.
  7540. Since an @code{extern} declaration does not allocate space for the
  7541. variable, it can omit the size of an array:
  7542. @example
  7543. extern int array[];
  7544. @end example
  7545. You can use @code{array} normally in all contexts where it is
  7546. converted automatically to a pointer. However, to use it as the
  7547. operand of @code{sizeof} is an error, since the size is unknown.
  7548. It is valid to have multiple @code{extern} declarations for the same
  7549. variable, even in the same scope, if they give the same type. They do
  7550. not conflict---they agree. For an array, it is legitimate for some
  7551. @code{extern} declarations can specify the size while others omit it.
  7552. However, if two declarations give different sizes, that is an error.
  7553. Likewise, you can use @code{extern} declarations at file scope
  7554. (@pxref{File-Scope Variables}) followed by an ordinary global
  7555. (non-static) declaration of the same variable. They do not conflict,
  7556. because they say compatible things about the same meaning of the variable.
  7557. @node Allocating File-Scope
  7558. @section Allocating File-Scope Variables
  7559. @cindex allocation file-scope variables
  7560. @cindex file-scope variables, allocating
  7561. Some file-scope declarations allocate space for the variable, and some
  7562. don't.
  7563. A file-scope declaration with an initial value @emph{must} allocate
  7564. space for the variable; if there are two of such declarations for the
  7565. same variable, even in different compilation modules, they conflict.
  7566. An @code{extern} declaration @emph{never} allocates space for the variable.
  7567. If all the top-level declarations of a certain variable are
  7568. @code{extern}, the variable never gets memory space. If that variable
  7569. is used anywhere in the program, the use will be reported as an error,
  7570. saying that the variable is not defined.
  7571. @cindex tentative definition
  7572. A file-scope declaration without an initial value is called a
  7573. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7574. allocate space for the variable, but does not insist. So it causes no
  7575. conflict, no error, if the variable has another declaration that
  7576. allocates space for it, perhaps in another compilation module. But if
  7577. nothing else allocates space for the variable, the tentative
  7578. definition will do it. Any number of compilation modules can declare
  7579. the same variable in this way, and that is sufficient for all of them
  7580. to use the variable.
  7581. @c @opindex -fno-common
  7582. @c @opindex --warn_common
  7583. In programs that are very large or have many contributors, it may be
  7584. wise to adopt the convention of never using tentative definitions.
  7585. You can use the compilation option @option{-fno-common} to make them
  7586. an error, or @option{--warn-common} to warn about them.
  7587. If a file-scope variable gets its space through a tentative
  7588. definition, it starts out containing all zeros.
  7589. @node auto and register
  7590. @section @code{auto} and @code{register}
  7591. @cindex @code{auto} declarations
  7592. @cindex @code{register} declarations
  7593. @findex auto
  7594. @findex register
  7595. For historical reasons, you can write @code{auto} or @code{register}
  7596. before a local variable declaration. @code{auto} merely emphasizes
  7597. that the variable isn't static; it changes nothing.
  7598. @code{register} suggests to the compiler storing this variable in a
  7599. register. However, GNU C ignores this suggestion, since it can
  7600. choose the best variables to store in registers without any hints.
  7601. It is an error to take the address of a variable declared
  7602. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7603. If the variable is an array, you can't use it at all (other than as
  7604. the operand of @code{sizeof}), which makes it rather useless.
  7605. @node Omitting Types
  7606. @section Omitting Types in Declarations
  7607. @cindex omitting types in declarations
  7608. The syntax of C traditionally allows omitting the data type in a
  7609. declaration if it specifies a storage class, a type qualifier (see the
  7610. next chapter), or @code{auto} or @code{register}. Then the type
  7611. defaults to @code{int}. For example:
  7612. @example
  7613. auto foo = 42;
  7614. @end example
  7615. This is bad practice; if you see it, fix it.
  7616. @node Type Qualifiers
  7617. @chapter Type Qualifiers
  7618. A declaration can include type qualifiers to advise the compiler
  7619. about how the variable will be used. There are three different
  7620. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7621. pertain to different issues, so you can use more than one together.
  7622. For instance, @code{const volatile} describes a value that the
  7623. program is not allowed to change, but might have a different value
  7624. each time the program examines it. (This might perhaps be a special
  7625. hardware register, or part of shared memory.)
  7626. If you are just learning C, you can skip this chapter.
  7627. @menu
  7628. * const:: Variables whose values don't change.
  7629. * volatile:: Variables whose values may be accessed
  7630. or changed outside of the control of
  7631. this program.
  7632. * restrict Pointers:: Restricted pointers for code optimization.
  7633. * restrict Pointer Example:: Example of how that works.
  7634. @end menu
  7635. @node const
  7636. @section @code{const} Variables and Fields
  7637. @cindex @code{const} variables and fields
  7638. @cindex variables, @code{const}
  7639. @findex const
  7640. You can mark a variable as ``constant'' by writing @code{const} in
  7641. front of the declaration. This says to treat any assignment to that
  7642. variable as an error. It may also permit some compiler
  7643. optimizations---for instance, to fetch the value only once to satisfy
  7644. multiple references to it. The construct looks like this:
  7645. @example
  7646. const double pi = 3.14159;
  7647. @end example
  7648. After this definition, the code can use the variable @code{pi}
  7649. but cannot assign a different value to it.
  7650. @example
  7651. pi = 3.0; /* @r{Error!} */
  7652. @end example
  7653. Simple variables that are constant can be used for the same purposes
  7654. as enumeration constants, and they are not limited to integers. The
  7655. constantness of the variable propagates into pointers, too.
  7656. A pointer type can specify that the @emph{target} is constant. For
  7657. example, the pointer type @code{const double *} stands for a pointer
  7658. to a constant @code{double}. That's the typethat results from taking
  7659. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7660. left side of an assignment.
  7661. @example
  7662. *(&pi) = 3.0; /* @r{Error!} */
  7663. @end example
  7664. Nonconstant pointers can be converted automatically to constant
  7665. pointers, but not vice versa. For instance,
  7666. @example
  7667. const double *cptr;
  7668. double *ptr;
  7669. cptr = &pi; /* @r{Valid.} */
  7670. cptr = ptr; /* @r{Valid.} */
  7671. ptr = cptr; /* @r{Error!} */
  7672. ptr = &pi; /* @r{Error!} */
  7673. @end example
  7674. This is not an ironclad protection against modifying the value. You
  7675. can always cast the constant pointer to a nonconstant pointer type:
  7676. @example
  7677. ptr = (double *)cptr; /* @r{Valid.} */
  7678. ptr = (double *)&pi; /* @r{Valid.} */
  7679. @end example
  7680. However, @code{const} provides a way to show that a certain function
  7681. won't modify the data structure whose address is passed to it. Here's
  7682. an example:
  7683. @example
  7684. int
  7685. string_length (const char *string)
  7686. @{
  7687. int count = 0;
  7688. while (*string++)
  7689. count++;
  7690. return count;
  7691. @}
  7692. @end example
  7693. @noindent
  7694. Using @code{const char *} for the parameter is a way of saying this
  7695. function never modifies the memory of the string itself.
  7696. In calling @code{string_length}, you can specify an ordinary
  7697. @code{char *} since that can be converted automatically to @code{const
  7698. char *}.
  7699. @node volatile
  7700. @section @code{volatile} Variables and Fields
  7701. @cindex @code{volatile} variables and fields
  7702. @cindex variables, @code{volatile}
  7703. @findex volatile
  7704. The GNU C compiler often performs optimizations that eliminate the
  7705. need to write or read a variable. For instance,
  7706. @example
  7707. int foo;
  7708. foo = 1;
  7709. foo++;
  7710. @end example
  7711. @noindent
  7712. might simply store the value 2 into @code{foo}, without ever storing 1.
  7713. These optimizations can also apply to structure fields in some cases.
  7714. If the memory containing @code{foo} is shared with another program,
  7715. or if it is examined asynchronously by hardware, such optimizations
  7716. could confuse the communication. Using @code{volatile} is one way
  7717. to prevent them.
  7718. Writing @code{volatile} with the type in a variable or field declaration
  7719. says that the value may be examined or changed for reasons outside the
  7720. control of the program at any moment. Therefore, the program must
  7721. execute in a careful way to assure correct interaction with those
  7722. accesses, whenever they may occur.
  7723. The simplest use looks like this:
  7724. @example
  7725. volatile int lock;
  7726. @end example
  7727. This directs the compiler not to do certain common optimizations on
  7728. use of the variable @code{lock}. All the reads and writes for a volatile
  7729. variable or field are really done, and done in the order specified
  7730. by the source code. Thus, this code:
  7731. @example
  7732. lock = 1;
  7733. list = list->next;
  7734. if (lock)
  7735. lock_broken (&lock);
  7736. lock = 0;
  7737. @end example
  7738. @noindent
  7739. really stores the value 1 in @code{lock}, even though there is no
  7740. sign it is really used, and the @code{if} statement reads and
  7741. checks the value of @code{lock}, rather than assuming it is still 1.
  7742. A limited amount of optimization can be done, in principle, on
  7743. @code{volatile} variables and fields: multiple references between two
  7744. sequence points (@pxref{Sequence Points}) can be simplified together.
  7745. Use of @code{volatile} does not eliminate the flexibility in ordering
  7746. the computation of the operands of most operators. For instance, in
  7747. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7748. @code{foo} is not specified, so they may be done in either order; the
  7749. fact that @code{lock} is @code{volatile} has no effect on that.
  7750. @node restrict Pointers
  7751. @section @code{restrict}-Qualified Pointers
  7752. @cindex @code{restrict} pointers
  7753. @cindex pointers, @code{restrict}-qualified
  7754. @findex restrict
  7755. You can declare a pointer as ``restricted'' using the @code{restrict}
  7756. type qualifier, like this:
  7757. @example
  7758. int *restrict p = x;
  7759. @end example
  7760. @noindent
  7761. This enables better optimization of code that uses the pointer.
  7762. If @code{p} is declared with @code{restrict}, and then the code
  7763. references the object that @code{p} points to (using @code{*p} or
  7764. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7765. code will not access that object in any other way---only through
  7766. @code{p}.
  7767. For instance, it means the code must not use another pointer
  7768. to access the same space, as shown here:
  7769. @example
  7770. int *restrict p = @var{whatever};
  7771. int *q = p;
  7772. foo (*p, *q);
  7773. @end example
  7774. @noindent
  7775. That contradicts the @code{restrict} promise by accessing the object
  7776. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7777. Likewise, it must not do this:
  7778. @example
  7779. int *restrict p = @var{whatever};
  7780. struct @{ int *a, *b; @} s;
  7781. s.a = p;
  7782. foo (*p, *s.a);
  7783. @end example
  7784. @noindent
  7785. This example uses a structure field instead of the variable @code{q}
  7786. to hold the other pointer, and that contradicts the promise just the
  7787. same.
  7788. The keyword @code{restrict} also promises that @code{p} won't point to
  7789. the allocated space of any automatic or static variable. So the code
  7790. must not do this:
  7791. @example
  7792. int a;
  7793. int *restrict p = &a;
  7794. foo (*p, a);
  7795. @end example
  7796. @noindent
  7797. because that does direct access to the object (@code{a}) that @code{p}
  7798. points to, which bypasses @code{p}.
  7799. If the code makes such promises with @code{restrict} then breaks them,
  7800. execution is unpredictable.
  7801. @node restrict Pointer Example
  7802. @section @code{restrict} Pointer Example
  7803. Here are examples where @code{restrict} enables real optimization.
  7804. In this example, @code{restrict} assures GCC that the array @code{out}
  7805. points to does not overlap with the array @code{in} points to.
  7806. @example
  7807. void
  7808. process_data (const char *in,
  7809. char * restrict out,
  7810. size_t size)
  7811. @{
  7812. for (i = 0; i < size; i++)
  7813. out[i] = in[i] + in[i + 1];
  7814. @}
  7815. @end example
  7816. Here's a simple tree structure, where each tree node holds data of
  7817. type @code{PAYLOAD} plus two subtrees.
  7818. @example
  7819. struct foo
  7820. @{
  7821. PAYLOAD payload;
  7822. struct foo *left;
  7823. struct foo *right;
  7824. @};
  7825. @end example
  7826. Now here's a function to null out both pointers in the @code{left}
  7827. subtree.
  7828. @example
  7829. void
  7830. null_left (struct foo *a)
  7831. @{
  7832. a->left->left = NULL;
  7833. a->left->right = NULL;
  7834. @}
  7835. @end example
  7836. Since @code{*a} and @code{*a->left} have the same data type,
  7837. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7838. the compiled code for @code{null_left} must read @code{a->left}
  7839. again from memory when executing the second assignment statement.
  7840. We can enable optimization, so that it does not need to read
  7841. @code{a->left} again, by writing @code{null_left} this in a less
  7842. obvious way.
  7843. @example
  7844. void
  7845. null_left (struct foo *a)
  7846. @{
  7847. struct foo *b = a->left;
  7848. b->left = NULL;
  7849. b->right = NULL;
  7850. @}
  7851. @end example
  7852. A more elegant way to fix this is with @code{restrict}.
  7853. @example
  7854. void
  7855. null_left (struct foo *restrict a)
  7856. @{
  7857. a->left->left = NULL;
  7858. a->left->right = NULL;
  7859. @}
  7860. @end example
  7861. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7862. as @code{a->left} will not point to the same memory space as @code{a}.
  7863. Therefore, the memory location @code{a->left->left} cannot be the same
  7864. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7865. reloading @code{a->left} for the second statement.
  7866. @node Functions
  7867. @chapter Functions
  7868. @cindex functions
  7869. We have already presented many examples of functions, so if you've
  7870. read this far, you basically understand the concept of a function. It
  7871. is vital, nonetheless, to have a chapter in the manual that collects
  7872. all the information about functions.
  7873. @menu
  7874. * Function Definitions:: Writing the body of a function.
  7875. * Function Declarations:: Declaring the interface of a function.
  7876. * Function Calls:: Using functions.
  7877. * Function Call Semantics:: Call-by-value argument passing.
  7878. * Function Pointers:: Using references to functions.
  7879. * The main Function:: Where execution of a GNU C program begins.
  7880. * Advanced Definitions:: Advanced features of function definitions.
  7881. * Obsolete Definitions:: Obsolete features still used
  7882. in function definitions in old code.
  7883. @end menu
  7884. @node Function Definitions
  7885. @section Function Definitions
  7886. @cindex function definitions
  7887. @cindex defining functions
  7888. We have already presented many examples of function definitions. To
  7889. summarize the rules, a function definition looks like this:
  7890. @example
  7891. @var{returntype}
  7892. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7893. @{
  7894. @var{body}
  7895. @}
  7896. @end example
  7897. The part before the open-brace is called the @dfn{function header}.
  7898. Write @code{void} as the @var{returntype} if the function does
  7899. not return a value.
  7900. @menu
  7901. * Function Parameter Variables:: Syntax and semantics
  7902. of function parameters.
  7903. * Forward Function Declarations:: Functions can only be called after
  7904. they have been defined or declared.
  7905. * Static Functions:: Limiting visibility of a function.
  7906. * Arrays as Parameters:: Functions that accept array arguments.
  7907. * Structs as Parameters:: Functions that accept structure arguments.
  7908. @end menu
  7909. @node Function Parameter Variables
  7910. @subsection Function Parameter Variables
  7911. @cindex function parameter variables
  7912. @cindex parameter variables in functions
  7913. @cindex parameter list
  7914. A function parameter variable is a local variable (@pxref{Local
  7915. Variables}) used within the function to store the value passed as an
  7916. argument in a call to the function. Usually we say ``function
  7917. parameter'' or ``parameter'' for short, not mentioning the fact that
  7918. it's a variable.
  7919. We declare these variables in the beginning of the function
  7920. definition, in the @dfn{parameter list}. For example,
  7921. @example
  7922. fib (int n)
  7923. @end example
  7924. @noindent
  7925. has a parameter list with one function parameter @code{n}, which has
  7926. type @code{int}.
  7927. Function parameter declarations differ from ordinary variable
  7928. declarations in several ways:
  7929. @itemize @bullet
  7930. @item
  7931. Inside the function definition header, commas separate parameter
  7932. declarations, and each parameter needs a complete declaration
  7933. including the type. For instance, if a function @code{foo} has two
  7934. @code{int} parameters, write this:
  7935. @example
  7936. foo (int a, int b)
  7937. @end example
  7938. You can't share the common @code{int} between the two declarations:
  7939. @example
  7940. foo (int a, b) /* @r{Invalid!} */
  7941. @end example
  7942. @item
  7943. A function parameter variable is initialized to whatever value is
  7944. passed in the function call, so its declaration cannot specify an
  7945. initial value.
  7946. @item
  7947. Writing an array type in a function parameter declaration has the
  7948. effect of declaring it as a pointer. The size specified for the array
  7949. has no effect at all, and we normally omit the size. Thus,
  7950. @example
  7951. foo (int a[5])
  7952. foo (int a[])
  7953. foo (int *a)
  7954. @end example
  7955. @noindent
  7956. are equivalent.
  7957. @item
  7958. The scope of the parameter variables is the entire function body,
  7959. notwithstanding the fact that they are written in the function header,
  7960. which is just outside the function body.
  7961. @end itemize
  7962. If a function has no parameters, it would be most natural for the
  7963. list of parameters in its definition to be empty. But that, in C, has
  7964. a special meaning for historical reasons: ``Do not check that calls to
  7965. this function have the right number of arguments.'' Thus,
  7966. @example
  7967. int
  7968. foo ()
  7969. @{
  7970. return 5;
  7971. @}
  7972. int
  7973. bar (int x)
  7974. @{
  7975. return foo (x);
  7976. @}
  7977. @end example
  7978. @noindent
  7979. would not report a compilation error in passing @code{x} as an
  7980. argument to @code{foo}. By contrast,
  7981. @example
  7982. int
  7983. foo (void)
  7984. @{
  7985. return 5;
  7986. @}
  7987. int
  7988. bar (int x)
  7989. @{
  7990. return foo (x);
  7991. @}
  7992. @end example
  7993. @noindent
  7994. would report an error because @code{foo} is supposed to receive
  7995. no arguments.
  7996. @node Forward Function Declarations
  7997. @subsection Forward Function Declarations
  7998. @cindex forward function declarations
  7999. @cindex function declarations, forward
  8000. The order of the function definitions in the source code makes no
  8001. difference, except that each function needs to be defined or declared
  8002. before code uses it.
  8003. The definition of a function also declares its name for the rest of
  8004. the containing scope. But what if you want to call the function
  8005. before its definition? To permit that, write a compatible declaration
  8006. of the same function, before the first call. A declaration that
  8007. prefigures a subsequent definition in this way is called a
  8008. @dfn{forward declaration}. The function declaration can be at top
  8009. @c ??? file scope
  8010. level or within a block, and it applies until the end of the containing
  8011. scope.
  8012. @xref{Function Declarations}, for more information about these
  8013. declarations.
  8014. @node Static Functions
  8015. @subsection Static Functions
  8016. @cindex static functions
  8017. @cindex functions, static
  8018. @findex static
  8019. The keyword @code{static} in a function definition limits the
  8020. visibility of the name to the current compilation module. (That's the
  8021. same thing @code{static} does in variable declarations;
  8022. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8023. contains this code:
  8024. @example
  8025. static int
  8026. foo (void)
  8027. @{
  8028. @r{@dots{}}
  8029. @}
  8030. @end example
  8031. @noindent
  8032. then the code of that compilation module can call @code{foo} anywhere
  8033. after the definition, but other compilation modules cannot refer to it
  8034. at all.
  8035. @cindex forward declaration
  8036. @cindex static function, declaration
  8037. To call @code{foo} before its definition, it needs a forward
  8038. declaration, which should use @code{static} since the function
  8039. definition does. For this function, it looks like this:
  8040. @example
  8041. static int foo (void);
  8042. @end example
  8043. It is generally wise to use @code{static} on the definitions of
  8044. functions that won't be called from outside the same compilation
  8045. module. This makes sure that calls are not added in other modules.
  8046. If programmers decide to change the function's calling convention, or
  8047. understand all the consequences of its use, they will only have to
  8048. check for calls in the same compilation module.
  8049. @node Arrays as Parameters
  8050. @subsection Arrays as Parameters
  8051. @cindex array as parameters
  8052. @cindex functions with array parameters
  8053. Arrays in C are not first-class objects: it is impossible to copy
  8054. them. So they cannot be passed as arguments like other values.
  8055. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8056. a special way.
  8057. @menu
  8058. * Array Parm Pointer::
  8059. * Passing Array Args::
  8060. * Array Parm Qualifiers::
  8061. @end menu
  8062. @node Array Parm Pointer
  8063. @subsubsection Array parameters are pointers
  8064. Declaring a function parameter variable as an array really gives it a
  8065. pointer type. C does this because an expression with array type, if
  8066. used as an argument in a function call, is converted automatically to
  8067. a pointer (to the zeroth element of the array). If you declare the
  8068. corresponding parameter as an ``array'', it will work correctly with
  8069. the pointer value that really gets passed.
  8070. This relates to the fact that C does not check array bounds in access
  8071. to elements of the array (@pxref{Accessing Array Elements}).
  8072. For example, in this function,
  8073. @example
  8074. void
  8075. clobber4 (int array[20])
  8076. @{
  8077. array[4] = 0;
  8078. @}
  8079. @end example
  8080. @noindent
  8081. the parameter @code{array}'s real type is @code{int *}; the specified
  8082. length, 20, has no effect on the program. You can leave out the length
  8083. and write this:
  8084. @example
  8085. void
  8086. clobber4 (int array[])
  8087. @{
  8088. array[4] = 0;
  8089. @}
  8090. @end example
  8091. @noindent
  8092. or write the parameter declaration explicitly as a pointer:
  8093. @example
  8094. void
  8095. clobber4 (int *array)
  8096. @{
  8097. array[4] = 0;
  8098. @}
  8099. @end example
  8100. They are all equivalent.
  8101. @node Passing Array Args
  8102. @subsubsection Passing array arguments
  8103. The function call passes this pointer by
  8104. value, like all argument values in C@. However, the result is
  8105. paradoxical in that the array itself is passed by reference: its
  8106. contents are treated as shared memory---shared between the caller and
  8107. the called function, that is. When @code{clobber4} assigns to element
  8108. 4 of @code{array}, the effect is to alter element 4 of the array
  8109. specified in the call.
  8110. @example
  8111. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8112. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8113. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8114. int
  8115. main (void)
  8116. @{
  8117. int data[] = @{1, 2, 3, 4, 5, 6@};
  8118. int i;
  8119. /* @r{Show the initial value of element 4.} */
  8120. for (i = 0; i < 6; i++)
  8121. printf ("data[%d] = %d\n", i, data[i]);
  8122. printf ("\n");
  8123. clobber4 (data);
  8124. /* @r{Show that element 4 has been changed.} */
  8125. for (i = 0; i < 6; i++)
  8126. printf ("data[%d] = %d\n", i, data[i]);
  8127. printf ("\n");
  8128. return EXIT_SUCCESS;
  8129. @}
  8130. @end example
  8131. @noindent
  8132. shows that @code{data[4]} has become zero after the call to
  8133. @code{clobber4}.
  8134. The array @code{data} has 6 elements, but passing it to a function
  8135. whose argument type is written as @code{int [20]} is not an error,
  8136. because that really stands for @code{int *}. The pointer that is the
  8137. real argument carries no indication of the length of the array it
  8138. points into. It is not required to point to the beginning of the
  8139. array, either. For instance,
  8140. @example
  8141. clobber4 (data+1);
  8142. @end example
  8143. @noindent
  8144. passes an ``array'' that starts at element 1 of @code{data}, and the
  8145. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8146. If all calls to the function will provide an array of a particular
  8147. size, you can specify the size of the array to be @code{static}:
  8148. @example
  8149. void
  8150. clobber4 (int array[static 20])
  8151. @r{@dots{}}
  8152. @end example
  8153. @noindent
  8154. This is a promise to the compiler that the function will always be
  8155. called with an array of 20 elements, so that the compiler can optimize
  8156. code accordingly. If the code breaks this promise and calls the
  8157. function with, for example, a shorter array, unpredictable things may
  8158. happen.
  8159. @node Array Parm Qualifiers
  8160. @subsubsection Type qualifiers on array parameters
  8161. You can use the type qualifiers @code{const}, @code{restrict}, and
  8162. @code{volatile} with array parameters; for example:
  8163. @example
  8164. void
  8165. clobber4 (volatile int array[20])
  8166. @r{@dots{}}
  8167. @end example
  8168. @noindent
  8169. denotes that @code{array} is equivalent to a pointer to a volatile
  8170. @code{int}. Alternatively:
  8171. @example
  8172. void
  8173. clobber4 (int array[const 20])
  8174. @r{@dots{}}
  8175. @end example
  8176. @noindent
  8177. makes the array parameter equivalent to a constant pointer to an
  8178. @code{int}. If we want the @code{clobber4} function to succeed, it
  8179. would not make sense to write
  8180. @example
  8181. void
  8182. clobber4 (const int array[20])
  8183. @r{@dots{}}
  8184. @end example
  8185. @noindent
  8186. as this would tell the compiler that the parameter should point to an
  8187. array of constant @code{int} values, and then we would not be able to
  8188. store zeros in them.
  8189. In a function with multiple array parameters, you can use @code{restrict}
  8190. to tell the compiler that each array parameter passed in will be distinct:
  8191. @example
  8192. void
  8193. foo (int array1[restrict 10], int array2[restrict 10])
  8194. @r{@dots{}}
  8195. @end example
  8196. @noindent
  8197. Using @code{restrict} promises the compiler that callers will
  8198. not pass in the same array for more than one @code{restrict} array
  8199. parameter. Knowing this enables the compiler to perform better code
  8200. optimization. This is the same effect as using @code{restrict}
  8201. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8202. the code that an array of a specific size is expected.
  8203. @node Structs as Parameters
  8204. @subsection Functions That Accept Structure Arguments
  8205. Structures in GNU C are first-class objects, so using them as function
  8206. parameters and arguments works in the natural way. This function
  8207. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8208. and returns a structure of the same type but with the fields
  8209. exchanged.
  8210. @example
  8211. struct foo @{ int a, b; @};
  8212. struct foo x;
  8213. struct foo
  8214. swapfoo (struct foo inval)
  8215. @{
  8216. struct foo outval;
  8217. outval.a = inval.b;
  8218. outval.b = inval.a;
  8219. return outval;
  8220. @}
  8221. @end example
  8222. This simpler definition of @code{swapfoo} avoids using a local
  8223. variable to hold the result about to be return, by using a structure
  8224. constructor (@pxref{Structure Constructors}), like this:
  8225. @example
  8226. struct foo
  8227. swapfoo (struct foo inval)
  8228. @{
  8229. return (struct foo) @{ inval.b, inval.a @};
  8230. @}
  8231. @end example
  8232. It is valid to define a structure type in a function's parameter list,
  8233. as in
  8234. @example
  8235. int
  8236. frob_bar (struct bar @{ int a, b; @} inval)
  8237. @{
  8238. @var{body}
  8239. @}
  8240. @end example
  8241. @noindent
  8242. and @var{body} can access the fields of @var{inval} since the
  8243. structure type @code{struct bar} is defined for the whole function
  8244. body. However, there is no way to create a @code{struct bar} argument
  8245. to pass to @code{frob_bar}, except with kludges. As a result,
  8246. defining a structure type in a parameter list is useless in practice.
  8247. @node Function Declarations
  8248. @section Function Declarations
  8249. @cindex function declarations
  8250. @cindex declararing functions
  8251. To call a function, or use its name as a pointer, a @dfn{function
  8252. declaration} for the function name must be in effect at that point in
  8253. the code. The function's definition serves as a declaration of that
  8254. function for the rest of the containing scope, but to use the function
  8255. in code before the definition, or from another compilation module, a
  8256. separate function declaration must precede the use.
  8257. A function declaration looks like the start of a function definition.
  8258. It begins with the return value type (@code{void} if none) and the
  8259. function name, followed by argument declarations in parentheses
  8260. (though these can sometimes be omitted). But that's as far as the
  8261. similarity goes: instead of the function body, the declaration uses a
  8262. semicolon.
  8263. @cindex function prototype
  8264. @cindex prototype of a function
  8265. A declaration that specifies argument types is called a @dfn{function
  8266. prototype}. You can include the argument names or omit them. The
  8267. names, if included in the declaration, have no effect, but they may
  8268. serve as documentation.
  8269. This form of prototype specifies fixed argument types:
  8270. @example
  8271. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8272. @end example
  8273. @noindent
  8274. This form says the function takes no arguments:
  8275. @example
  8276. @var{rettype} @var{function} (void);
  8277. @end example
  8278. @noindent
  8279. This form declares types for some arguments, and allows additional
  8280. arguments whose types are not specified:
  8281. @example
  8282. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8283. @end example
  8284. For a parameter that's an array of variable length, you can write
  8285. its declaration with @samp{*} where the ``length'' of the array would
  8286. normally go; for example, these are all equivalent.
  8287. @example
  8288. double maximum (int n, int m, double a[n][m]);
  8289. double maximum (int n, int m, double a[*][*]);
  8290. double maximum (int n, int m, double a[ ][*]);
  8291. double maximum (int n, int m, double a[ ][m]);
  8292. @end example
  8293. @noindent
  8294. The old-fashioned form of declaration, which is not a prototype, says
  8295. nothing about the types of arguments or how many they should be:
  8296. @example
  8297. @var{rettype} @var{function} ();
  8298. @end example
  8299. @strong{Warning:} Arguments passed to a function declared without a
  8300. prototype are converted with the default argument promotions
  8301. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8302. types are unspecified.
  8303. Function declarations are usually written at the top level in a source file,
  8304. but you can also put them inside code blocks. Then the function name
  8305. is visible for the rest of the containing scope. For example:
  8306. @example
  8307. void
  8308. foo (char *file_name)
  8309. @{
  8310. void save_file (char *);
  8311. save_file (file_name);
  8312. @}
  8313. @end example
  8314. If another part of the code tries to call the function
  8315. @code{save_file}, this declaration won't be in effect there. So the
  8316. function will get an implicit declaration of the form @code{extern int
  8317. save_file ();}. That conflicts with the explicit declaration
  8318. here, and the discrepancy generates a warning.
  8319. The syntax of C traditionally allows omitting the data type in a
  8320. function declaration if it specifies a storage class or a qualifier.
  8321. Then the type defaults to @code{int}. For example:
  8322. @example
  8323. static foo (double x);
  8324. @end example
  8325. @noindent
  8326. defaults the return type to @code{int}.
  8327. This is bad practice; if you see it, fix it.
  8328. Calling a function that is undeclared has the effect of an creating
  8329. @dfn{implicit} declaration in the innermost containing scope,
  8330. equivalent to this:
  8331. @example
  8332. extern int @dfn{function} ();
  8333. @end example
  8334. @noindent
  8335. This declaration says that the function returns @code{int} but leaves
  8336. its argument types unspecified. If that does not accurately fit the
  8337. function, then the program @strong{needs} an explicit declaration of
  8338. the function with argument types in order to call it correctly.
  8339. Implicit declarations are deprecated, and a function call that creates one
  8340. causes a warning.
  8341. @node Function Calls
  8342. @section Function Calls
  8343. @cindex function calls
  8344. @cindex calling functions
  8345. Starting a program automatically calls the function named @code{main}
  8346. (@pxref{The main Function}). Aside from that, a function does nothing
  8347. except when it is @dfn{called}. That occurs during the execution of a
  8348. function-call expression specifying that function.
  8349. A function-call expression looks like this:
  8350. @example
  8351. @var{function} (@var{arguments}@r{@dots{}})
  8352. @end example
  8353. Most of the time, @var{function} is a function name. However, it can
  8354. also be an expression with a function pointer value; that way, the
  8355. program can determine at run time which function to call.
  8356. The @var{arguments} are a series of expressions separated by commas.
  8357. Each expression specifies one argument to pass to the function.
  8358. The list of arguments in a function call looks just like use of the
  8359. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8360. the parentheses of a function call gives it a different meaning.
  8361. Here's an example of a function call, taken from an example near the
  8362. beginning (@pxref{Complete Program}).
  8363. @example
  8364. printf ("Fibonacci series item %d is %d\n",
  8365. 19, fib (19));
  8366. @end example
  8367. The three arguments given to @code{printf} are a constant string, the
  8368. integer 19, and the integer returned by @code{fib (19)}.
  8369. @node Function Call Semantics
  8370. @section Function Call Semantics
  8371. @cindex function call semantics
  8372. @cindex semantics of function calls
  8373. @cindex call-by-value
  8374. The meaning of a function call is to compute the specified argument
  8375. expressions, convert their values according to the function's
  8376. declaration, then run the function giving it copies of the converted
  8377. values. (This method of argument passing is known as
  8378. @dfn{call-by-value}.) When the function finishes, the value it
  8379. returns becomes the value of the function-call expression.
  8380. Call-by-value implies that an assignment to the function argument
  8381. variable has no direct effect on the caller. For instance,
  8382. @example
  8383. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8384. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8385. void
  8386. subroutine (int x)
  8387. @{
  8388. x = 5;
  8389. @}
  8390. void
  8391. main (void)
  8392. @{
  8393. int y = 20;
  8394. subroutine (y);
  8395. printf ("y is %d\n", y);
  8396. return EXIT_SUCCESS;
  8397. @}
  8398. @end example
  8399. @noindent
  8400. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8401. from the value of @code{y}, but this does not establish any other
  8402. relationship between the two variables. Thus, the assignment to
  8403. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8404. If an argument's type is specified by the function's declaration, the
  8405. function call converts the argument expression to that type if
  8406. possible. If the conversion is impossible, that is an error.
  8407. If the function's declaration doesn't specify the type of that
  8408. argument, then the @emph{default argument promotions} apply.
  8409. @xref{Argument Promotions}.
  8410. @node Function Pointers
  8411. @section Function Pointers
  8412. @cindex function pointers
  8413. @cindex pointers to functions
  8414. A function name refers to a fixed function. Sometimes it is useful to
  8415. call a function to be determined at run time; to do this, you can use
  8416. a @dfn{function pointer value} that points to the chosen function
  8417. (@pxref{Pointers}).
  8418. Pointer-to-function types can be used to declare variables and other
  8419. data, including array elements, structure fields, and union
  8420. alternatives. They can also be used for function arguments and return
  8421. values. These types have the peculiarity that they are never
  8422. converted automatically to @code{void *} or vice versa. However, you
  8423. can do that conversion with a cast.
  8424. @menu
  8425. * Declaring Function Pointers:: How to declare a pointer to a function.
  8426. * Assigning Function Pointers:: How to assign values to function pointers.
  8427. * Calling Function Pointers:: How to call functions through pointers.
  8428. @end menu
  8429. @node Declaring Function Pointers
  8430. @subsection Declaring Function Pointers
  8431. @cindex declaring function pointers
  8432. @cindex function pointers, declaring
  8433. The declaration of a function pointer variable (or structure field)
  8434. looks almost like a function declaration, except it has an additional
  8435. @samp{*} just before the variable name. Proper nesting requires a
  8436. pair of parentheses around the two of them. For instance, @code{int
  8437. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8438. an @code{int}-returning function.''
  8439. Contrast these three declarations:
  8440. @example
  8441. /* @r{Declare a function returning @code{char *}.} */
  8442. char *a (char *);
  8443. /* @r{Declare a pointer to a function returning @code{char}.} */
  8444. char (*a) (char *);
  8445. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8446. char *(*a) (char *);
  8447. @end example
  8448. The possible argument types of the function pointed to are the same
  8449. as in a function declaration. You can write a prototype
  8450. that specifies all the argument types:
  8451. @example
  8452. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8453. @end example
  8454. @noindent
  8455. or one that specifies some and leaves the rest unspecified:
  8456. @example
  8457. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8458. @end example
  8459. @noindent
  8460. or one that says there are no arguments:
  8461. @example
  8462. @var{rettype} (*@var{function}) (void);
  8463. @end example
  8464. You can also write a non-prototype declaration that says
  8465. nothing about the argument types:
  8466. @example
  8467. @var{rettype} (*@var{function}) ();
  8468. @end example
  8469. For example, here's a declaration for a variable that should
  8470. point to some arithmetic function that operates on two @code{double}s:
  8471. @example
  8472. double (*binary_op) (double, double);
  8473. @end example
  8474. Structure fields, union alternatives, and array elements can be
  8475. function pointers; so can parameter variables. The function pointer
  8476. declaration construct can also be combined with other operators
  8477. allowed in declarations. For instance,
  8478. @example
  8479. int **(*foo)();
  8480. @end example
  8481. @noindent
  8482. declares @code{foo} as a pointer to a function that returns
  8483. type @code{int **}, and
  8484. @example
  8485. int **(*foo[30])();
  8486. @end example
  8487. @noindent
  8488. declares @code{foo} as an array of 30 pointers to functions that
  8489. return type @code{int **}.
  8490. @example
  8491. int **(**foo)();
  8492. @end example
  8493. @noindent
  8494. declares @code{foo} as a pointer to a pointer to a function that
  8495. returns type @code{int **}.
  8496. @node Assigning Function Pointers
  8497. @subsection Assigning Function Pointers
  8498. @cindex assigning function pointers
  8499. @cindex function pointers, assigning
  8500. Assuming we have declared the variable @code{binary_op} as in the
  8501. previous section, giving it a value requires a suitable function to
  8502. use. So let's define a function suitable for the variable to point
  8503. to. Here's one:
  8504. @example
  8505. double
  8506. double_add (double a, double b)
  8507. @{
  8508. return a+b;
  8509. @}
  8510. @end example
  8511. Now we can give it a value:
  8512. @example
  8513. binary_op = double_add;
  8514. @end example
  8515. The target type of the function pointer must be upward compatible with
  8516. the type of the function (@pxref{Compatible Types}).
  8517. There is no need for @samp{&} in front of @code{double_add}.
  8518. Using a function name such as @code{double_add} as an expression
  8519. automatically converts it to the function's address, with the
  8520. appropriate function pointer type. However, it is ok to use
  8521. @samp{&} if you feel that is clearer:
  8522. @example
  8523. binary_op = &double_add;
  8524. @end example
  8525. @node Calling Function Pointers
  8526. @subsection Calling Function Pointers
  8527. @cindex calling function pointers
  8528. @cindex function pointers, calling
  8529. To call the function specified by a function pointer, just write the
  8530. function pointer value in a function call. For instance, here's a
  8531. call to the function @code{binary_op} points to:
  8532. @example
  8533. binary_op (x, 5)
  8534. @end example
  8535. Since the data type of @code{binary_op} explicitly specifies type
  8536. @code{double} for the arguments, the call converts @code{x} and 5 to
  8537. @code{double}.
  8538. The call conceptually dereferences the pointer @code{binary_op} to
  8539. ``get'' the function it points to, and calls that function. If you
  8540. wish, you can explicitly represent the derefence by writing the
  8541. @code{*} operator:
  8542. @example
  8543. (*binary_op) (x, 5)
  8544. @end example
  8545. The @samp{*} reminds people reading the code that @code{binary_op} is
  8546. a function pointer rather than the name of a specific function.
  8547. @node The main Function
  8548. @section The @code{main} Function
  8549. @cindex @code{main} function
  8550. @findex main
  8551. Every complete executable program requires at least one function,
  8552. called @code{main}, which is where execution begins. You do not have
  8553. to explicitly declare @code{main}, though GNU C permits you to do so.
  8554. Conventionally, @code{main} should be defined to follow one of these
  8555. calling conventions:
  8556. @example
  8557. int main (void) @{@r{@dots{}}@}
  8558. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8559. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8560. @end example
  8561. @noindent
  8562. Using @code{void} as the parameter list means that @code{main} does
  8563. not use the arguments. You can write @code{char **argv} instead of
  8564. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8565. constructs are equivalent.
  8566. @ignore @c Not so at present
  8567. Defining @code{main} in any other way generates a warning. Your
  8568. program will still compile, but you may get unexpected results when
  8569. executing it.
  8570. @end ignore
  8571. You can call @code{main} from C code, as you can call any other
  8572. function, though that is an unusual thing to do. When you do that,
  8573. you must write the call to pass arguments that match the parameters in
  8574. the definition of @code{main}.
  8575. The @code{main} function is not actually the first code that runs when
  8576. a program starts. In fact, the first code that runs is system code
  8577. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8578. code, but in GNU we replaced it with C code. Its job is to find
  8579. the arguments for @code{main} and call that.
  8580. @menu
  8581. * Values from main:: Returning values from the main function.
  8582. * Command-line Parameters:: Accessing command-line parameters
  8583. provided to the program.
  8584. * Environment Variables:: Accessing system environment variables.
  8585. @end menu
  8586. @node Values from main
  8587. @subsection Returning Values from @code{main}
  8588. @cindex returning values from @code{main}
  8589. @cindex success
  8590. @cindex failure
  8591. @cindex exit status
  8592. When @code{main} returns, the process terminates. Whatever value
  8593. @code{main} returns becomes the exit status which is reported to the
  8594. parent process. While nominally the return value is of type
  8595. @code{int}, in fact the exit status gets truncated to eight bits; if
  8596. @code{main} returns the value 256, the exit status is 0.
  8597. Normally, programs return only one of two values: 0 for success,
  8598. and 1 for failure. For maximum portability, use the macro
  8599. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8600. @code{stdlib.h}. Here's an example:
  8601. @cindex @code{EXIT_FAILURE}
  8602. @cindex @code{EXIT_SUCCESS}
  8603. @example
  8604. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8605. /* @r{and @code{EXIT_FAILURE}.} */
  8606. int
  8607. main (void)
  8608. @{
  8609. @r{@dots{}}
  8610. if (foo)
  8611. return EXIT_SUCCESS;
  8612. else
  8613. return EXIT_FAILURE;
  8614. @}
  8615. @end example
  8616. Some types of programs maintain special conventions for various return
  8617. values; for example, comparison programs including @code{cmp} and
  8618. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8619. the comparison couldn't be performed.
  8620. @node Command-line Parameters
  8621. @subsection Accessing Command-line Parameters
  8622. @cindex command-line parameters
  8623. @cindex parameters, command-line
  8624. If the program was invoked with any command-line arguments, it can
  8625. access them through the arguments of @code{main}, @code{argc} and
  8626. @code{argv}. (You can give these arguments any names, but the names
  8627. @code{argc} and @code{argv} are customary.)
  8628. The value of @code{argv} is an array containing all of the
  8629. command-line arguments as strings, with the name of the command
  8630. invoked as the first string. @code{argc} is an integer that says how
  8631. many strings @code{argv} contains. Here is an example of accessing
  8632. the command-line parameters, retrieving the program's name and
  8633. checking for the standard @option{--version} and @option{--help} options:
  8634. @example
  8635. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8636. int
  8637. main (int argc, char *argv[])
  8638. @{
  8639. char *program_name = argv[0];
  8640. for (int i = 1; i < argc; i++)
  8641. @{
  8642. if (!strcmp (argv[i], "--version"))
  8643. @{
  8644. /* @r{Print version information and exit.} */
  8645. @r{@dots{}}
  8646. @}
  8647. else if (!strcmp (argv[i], "--help"))
  8648. @{
  8649. /* @r{Print help information and exit.} */
  8650. @r{@dots{}}
  8651. @}
  8652. @}
  8653. @r{@dots{}}
  8654. @}
  8655. @end example
  8656. @node Environment Variables
  8657. @subsection Accessing Environment Variables
  8658. @cindex environment variables
  8659. You can optionally include a third parameter to @code{main}, another
  8660. array of strings, to capture the environment variables available to
  8661. the program. Unlike what happens with @code{argv}, there is no
  8662. additional parameter for the count of environment variables; rather,
  8663. the array of environment variables concludes with a null pointer.
  8664. @example
  8665. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8666. int
  8667. main (int argc, char *argv[], char *envp[])
  8668. @{
  8669. /* @r{Print out all environment variables.} */
  8670. int i = 0;
  8671. while (envp[i])
  8672. @{
  8673. printf ("%s\n", envp[i]);
  8674. i++;
  8675. @}
  8676. @}
  8677. @end example
  8678. Another method of retrieving environment variables is to use the
  8679. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8680. Using @code{getenv} does not require defining @code{main} to accept the
  8681. @code{envp} pointer. For example, here is a program that fetches and prints
  8682. the user's home directory (if defined):
  8683. @example
  8684. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8685. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8686. int
  8687. main (void)
  8688. @{
  8689. char *home_directory = getenv ("HOME");
  8690. if (home_directory)
  8691. printf ("My home directory is: %s\n", home_directory);
  8692. else
  8693. printf ("My home directory is not defined!\n");
  8694. @}
  8695. @end example
  8696. @node Advanced Definitions
  8697. @section Advanced Function Features
  8698. This section describes some advanced or obscure features for GNU C
  8699. function definitions. If you are just learning C, you can skip the
  8700. rest of this chapter.
  8701. @menu
  8702. * Variable-Length Array Parameters:: Functions that accept arrays
  8703. of variable length.
  8704. * Variable Number of Arguments:: Variadic functions.
  8705. * Nested Functions:: Defining functions within functions.
  8706. * Inline Function Definitions:: A function call optimization technique.
  8707. @end menu
  8708. @node Variable-Length Array Parameters
  8709. @subsection Variable-Length Array Parameters
  8710. @cindex variable-length array parameters
  8711. @cindex array parameters, variable-length
  8712. @cindex functions that accept variable-length arrays
  8713. An array parameter can have variable length: simply declare the array
  8714. type with a size that isn't constant. In a nested function, the
  8715. length can refer to a variable defined in a containing scope. In any
  8716. function, it can refer to a previous parameter, like this:
  8717. @example
  8718. struct entry
  8719. tester (int len, char data[len][len])
  8720. @{
  8721. @r{@dots{}}
  8722. @}
  8723. @end example
  8724. Alternatively, in function declarations (but not in function
  8725. definitions), you can use @code{[*]} to denote that the array
  8726. parameter is of a variable length, such that these two declarations
  8727. mean the same thing:
  8728. @example
  8729. struct entry
  8730. tester (int len, char data[len][len]);
  8731. @end example
  8732. @example
  8733. struct entry
  8734. tester (int len, char data[*][*]);
  8735. @end example
  8736. @noindent
  8737. The two forms of input are equivalent in GNU C, but emphasizing that
  8738. the array parameter is variable-length may be helpful to those
  8739. studying the code.
  8740. You can also omit the length parameter, and instead use some other
  8741. in-scope variable for the length in the function definition:
  8742. @example
  8743. struct entry
  8744. tester (char data[*][*]);
  8745. @r{@dots{}}
  8746. int dataLength = 20;
  8747. @r{@dots{}}
  8748. struct entry
  8749. tester (char data[dataLength][dataLength])
  8750. @{
  8751. @r{@dots{}}
  8752. @}
  8753. @end example
  8754. @c ??? check text above
  8755. @cindex parameter forward declaration
  8756. In GNU C, to pass the array first and the length afterward, you can
  8757. use a @dfn{parameter forward declaration}, like this:
  8758. @example
  8759. struct entry
  8760. tester (int len; char data[len][len], int len)
  8761. @{
  8762. @r{@dots{}}
  8763. @}
  8764. @end example
  8765. The @samp{int len} before the semicolon is the parameter forward
  8766. declaration; it serves the purpose of making the name @code{len} known
  8767. when the declaration of @code{data} is parsed.
  8768. You can write any number of such parameter forward declarations in the
  8769. parameter list. They can be separated by commas or semicolons, but
  8770. the last one must end with a semicolon, which is followed by the
  8771. ``real'' parameter declarations. Each forward declaration must match
  8772. a subsequent ``real'' declaration in parameter name and data type.
  8773. Standard C does not support parameter forward declarations.
  8774. @node Variable Number of Arguments
  8775. @subsection Variable-Length Parameter Lists
  8776. @cindex variable-length parameter lists
  8777. @cindex parameters lists, variable length
  8778. @cindex function parameter lists, variable length
  8779. @cindex variadic function
  8780. A function that takes a variable number of arguments is called a
  8781. @dfn{variadic function}. In C, a variadic function must specify at
  8782. least one fixed argument with an explicitly declared data type.
  8783. Additional arguments can follow, and can vary in both quantity and
  8784. data type.
  8785. In the function header, declare the fixed parameters in the normal
  8786. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8787. example of a variadic function header:
  8788. @example
  8789. int add_multiple_values (int number, ...)
  8790. @end example
  8791. @cindex @code{va_list}
  8792. @cindex @code{va_start}
  8793. @cindex @code{va_end}
  8794. The function body can refer to fixed arguments by their parameter
  8795. names, but the additional arguments have no names. Accessing them in
  8796. the function body uses certain standard macros. They are defined in
  8797. the library header file @file{stdarg.h}, so the code must
  8798. @code{#include} that file.
  8799. In the body, write
  8800. @example
  8801. va_list ap;
  8802. va_start (ap, @var{last_fixed_parameter});
  8803. @end example
  8804. @noindent
  8805. This declares the variable @code{ap} (you can use any name for it)
  8806. and then sets it up to point before the first additional argument.
  8807. Then, to fetch the next consecutive additional argument, write this:
  8808. @example
  8809. va_arg (ap, @var{type})
  8810. @end example
  8811. After fetching all the additional arguments (or as many as need to be
  8812. used), write this:
  8813. @example
  8814. va_end (ap);
  8815. @end example
  8816. Here's an example of a variadic function definition that adds any
  8817. number of @code{int} arguments. The first (fixed) argument says how
  8818. many more arguments follow.
  8819. @example
  8820. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8821. @r{@dots{}}
  8822. int
  8823. add_multiple_values (int argcount, ...)
  8824. @{
  8825. int counter, total = 0;
  8826. /* @r{Declare a variable of type @code{va_list}.} */
  8827. va_list argptr;
  8828. /* @r{Initialize that variable..} */
  8829. va_start (argptr, argcount);
  8830. for (counter = 0; counter < argcount; counter++)
  8831. @{
  8832. /* @r{Get the next additional argument.} */
  8833. total += va_arg (argptr, int);
  8834. @}
  8835. /* @r{End use of the @code{argptr} variable.} */
  8836. va_end (argptr);
  8837. return total;
  8838. @}
  8839. @end example
  8840. With GNU C, @code{va_end} is superfluous, but some other compilers
  8841. might make @code{va_start} allocate memory so that calling
  8842. @code{va_end} is necessary to avoid a memory leak. Before doing
  8843. @code{va_start} again with the same variable, do @code{va_end}
  8844. first.
  8845. @cindex @code{va_copy}
  8846. Because of this possible memory allocation, it is risky (in principle)
  8847. to copy one @code{va_list} variable to another with assignment.
  8848. Instead, use @code{va_copy}, which copies the substance but allocates
  8849. separate memory in the variable you copy to. The call looks like
  8850. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8851. @var{from} should be variables of type @code{va_list}. In principle,
  8852. do @code{va_end} on each of these variables before its scope ends.
  8853. Since the additional arguments' types are not specified in the
  8854. function's definition, the default argument promotions
  8855. (@pxref{Argument Promotions}) apply to them in function calls. The
  8856. function definition must take account of this; thus, if an argument
  8857. was passed as @code{short}, the function should get it as @code{int}.
  8858. If an argument was passed as @code{float}, the function should get it
  8859. as @code{double}.
  8860. C has no mechanism to tell the variadic function how many arguments
  8861. were passed to it, so its calling convention must give it a way to
  8862. determine this. That's why @code{add_multiple_values} takes a fixed
  8863. argument that says how many more arguments follow. Thus, you can
  8864. call the function like this:
  8865. @example
  8866. sum = add_multiple_values (3, 12, 34, 190);
  8867. /* @r{Value is 12+34+190.} */
  8868. @end example
  8869. In GNU C, there is no actual need to use the @code{va_end} function.
  8870. In fact, it does nothing. It's used for compatibility with other
  8871. compilers, when that matters.
  8872. It is a mistake to access variables declared as @code{va_list} except
  8873. in the specific ways described here. Just what that type consists of
  8874. is an implementation detail, which could vary from one platform to
  8875. another.
  8876. @node Nested Functions
  8877. @subsection Nested Functions
  8878. @cindex nested functions
  8879. @cindex functions, nested
  8880. @cindex downward funargs
  8881. @cindex thunks
  8882. A @dfn{nested function} is a function defined inside another function.
  8883. The nested function's name is local to the block where it is defined.
  8884. For example, here we define a nested function named @code{square}, and
  8885. call it twice:
  8886. @example
  8887. @group
  8888. foo (double a, double b)
  8889. @{
  8890. double square (double z) @{ return z * z; @}
  8891. return square (a) + square (b);
  8892. @}
  8893. @end group
  8894. @end example
  8895. The nested function can access all the variables of the containing
  8896. function that are visible at the point of its definition. This is
  8897. called @dfn{lexical scoping}. For example, here we show a nested
  8898. function that uses an inherited variable named @code{offset}:
  8899. @example
  8900. @group
  8901. bar (int *array, int offset, int size)
  8902. @{
  8903. int access (int *array, int index)
  8904. @{ return array[index + offset]; @}
  8905. int i;
  8906. @r{@dots{}}
  8907. for (i = 0; i < size; i++)
  8908. @r{@dots{}} access (array, i) @r{@dots{}}
  8909. @}
  8910. @end group
  8911. @end example
  8912. Nested function definitions can appear wherever automatic variable
  8913. declarations are allowed; that is, in any block, interspersed with the
  8914. other declarations and statements in the block.
  8915. The nested function's name is visible only within the parent block;
  8916. the name's scope starts from its definition and continues to the end
  8917. of the containing block. If the nested function's name
  8918. is the same as the parent function's name, there wil be
  8919. no way to refer to the parent function inside the scope of the
  8920. name of the nested function.
  8921. Using @code{extern} or @code{static} on a nested function definition
  8922. is an error.
  8923. It is possible to call the nested function from outside the scope of its
  8924. name by storing its address or passing the address to another function.
  8925. You can do this safely, but you must be careful:
  8926. @example
  8927. @group
  8928. hack (int *array, int size, int addition)
  8929. @{
  8930. void store (int index, int value)
  8931. @{ array[index] = value + addition; @}
  8932. intermediate (store, size);
  8933. @}
  8934. @end group
  8935. @end example
  8936. Here, the function @code{intermediate} receives the address of
  8937. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8938. the arguments given to @code{store} are used to store into @code{array}.
  8939. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8940. It is safe for @code{intermediate} to call @code{store} because
  8941. @code{hack}'s stack frame, with its arguments and local variables,
  8942. continues to exist during the call to @code{intermediate}.
  8943. Calling the nested function through its address after the containing
  8944. function has exited is asking for trouble. If it is called after a
  8945. containing scope level has exited, and if it refers to some of the
  8946. variables that are no longer in scope, it will refer to memory
  8947. containing junk or other data. It's not wise to take the risk.
  8948. The GNU C Compiler implements taking the address of a nested function
  8949. using a technique called @dfn{trampolines}. This technique was
  8950. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8951. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8952. A nested function can jump to a label inherited from a containing
  8953. function, provided the label was explicitly declared in the containing
  8954. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8955. containing function, exiting the nested function that did the
  8956. @code{goto} and any intermediate function invocations as well. Here
  8957. is an example:
  8958. @example
  8959. @group
  8960. bar (int *array, int offset, int size)
  8961. @{
  8962. /* @r{Explicitly declare the label @code{failure}.} */
  8963. __label__ failure;
  8964. int access (int *array, int index)
  8965. @{
  8966. if (index > size)
  8967. /* @r{Exit this function,}
  8968. @r{and return to @code{bar}.} */
  8969. goto failure;
  8970. return array[index + offset];
  8971. @}
  8972. @end group
  8973. @group
  8974. int i;
  8975. @r{@dots{}}
  8976. for (i = 0; i < size; i++)
  8977. @r{@dots{}} access (array, i) @r{@dots{}}
  8978. @r{@dots{}}
  8979. return 0;
  8980. /* @r{Control comes here from @code{access}
  8981. if it does the @code{goto}.} */
  8982. failure:
  8983. return -1;
  8984. @}
  8985. @end group
  8986. @end example
  8987. To declare the nested function before its definition, use
  8988. @code{auto} (which is otherwise meaningless for function declarations;
  8989. @pxref{auto and register}). For example,
  8990. @example
  8991. bar (int *array, int offset, int size)
  8992. @{
  8993. auto int access (int *, int);
  8994. @r{@dots{}}
  8995. @r{@dots{}} access (array, i) @r{@dots{}}
  8996. @r{@dots{}}
  8997. int access (int *array, int index)
  8998. @{
  8999. @r{@dots{}}
  9000. @}
  9001. @r{@dots{}}
  9002. @}
  9003. @end example
  9004. @node Inline Function Definitions
  9005. @subsection Inline Function Definitions
  9006. @cindex inline function definitions
  9007. @cindex function definitions, inline
  9008. @findex inline
  9009. To declare a function inline, use the @code{inline} keyword in its
  9010. definition. Here's a simple function that takes a pointer-to-@code{int}
  9011. and increments the integer stored there---declared inline.
  9012. @example
  9013. struct list
  9014. @{
  9015. struct list *first, *second;
  9016. @};
  9017. inline struct list *
  9018. list_first (struct list *p)
  9019. @{
  9020. return p->first;
  9021. @}
  9022. inline struct list *
  9023. list_second (struct list *p)
  9024. @{
  9025. return p->second;
  9026. @}
  9027. @end example
  9028. optimized compilation can substitute the inline function's body for
  9029. any call to it. This is called @emph{inlining} the function. It
  9030. makes the code that contains the call run faster, significantly so if
  9031. the inline function is small.
  9032. Here's a function that uses @code{pair_second}:
  9033. @example
  9034. int
  9035. pairlist_length (struct list *l)
  9036. @{
  9037. int length = 0;
  9038. while (l)
  9039. @{
  9040. length++;
  9041. l = pair_second (l);
  9042. @}
  9043. return length;
  9044. @}
  9045. @end example
  9046. Substituting the code of @code{pair_second} into the definition of
  9047. @code{pairlist_length} results in this code, in effect:
  9048. @example
  9049. int
  9050. pairlist_length (struct list *l)
  9051. @{
  9052. int length = 0;
  9053. while (l)
  9054. @{
  9055. length++;
  9056. l = l->second;
  9057. @}
  9058. return length;
  9059. @}
  9060. @end example
  9061. Since the definition of @code{pair_second} does not say @code{extern}
  9062. or @code{static}, that definition is used only for inlining. It
  9063. doesn't generate code that can be called at run time. If not all the
  9064. calls to the function are inlined, there must be a definition of the
  9065. same function name in another module for them to call.
  9066. @cindex inline functions, omission of
  9067. @c @opindex fkeep-inline-functions
  9068. Adding @code{static} to an inline function definition means the
  9069. function definition is limited to this compilation module. Also, it
  9070. generates run-time code if necessary for the sake of any calls that
  9071. were not inlined. If all calls are inlined then the function
  9072. definition does not generate run-time code, but you can force
  9073. generation of run-time code with the option
  9074. @option{-fkeep-inline-functions}.
  9075. @cindex extern inline function
  9076. Specifying @code{extern} along with @code{inline} means the function is
  9077. external and generates run-time code to be called from other
  9078. separately compiled modules, as well as inlined. You can define the
  9079. function as @code{inline} without @code{extern} in other modules so as
  9080. to inline calls to the same function in those modules.
  9081. Why are some calls not inlined? First of all, inlining is an
  9082. optimization, so non-optimized compilation does not inline.
  9083. Some calls cannot be inlined for technical reasons. Also, certain
  9084. usages in a function definition can make it unsuitable for inline
  9085. substitution. Among these usages are: variadic functions, use of
  9086. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9087. use of nonlocal goto. The option @option{-Winline} requests a warning
  9088. when a function marked @code{inline} is unsuitable to be inlined. The
  9089. warning explains what obstacle makes it unsuitable.
  9090. Just because a call @emph{can} be inlined does not mean it
  9091. @emph{should} be inlined. The GNU C compiler weighs costs and
  9092. benefits to decide whether inlining a particular call is advantageous.
  9093. You can force inlining of all calls to a given function that can be
  9094. inlined, even in a non-optimized compilation. by specifying the
  9095. @samp{always_inline} attribute for the function, like this:
  9096. @example
  9097. /* @r{Prototype.} */
  9098. inline void foo (const char) __attribute__((always_inline));
  9099. @end example
  9100. @noindent
  9101. This is a GNU C extension. @xref{Attributes}.
  9102. A function call may be inlined even if not declared @code{inline} in
  9103. special cases where the compiler can determine this is correct and
  9104. desirable. For instance, when a static function is called only once,
  9105. it will very likely be inlined. With @option{-flto}, link-time
  9106. optimization, any function might be inlined. To absolutely prevent
  9107. inlining of a specific function, specify
  9108. @code{__attribute__((__noinline__))} in the function's definition.
  9109. @node Obsolete Definitions
  9110. @section Obsolete Function Features
  9111. These features of function definitions are still used in old
  9112. programs, but you shouldn't write code this way today.
  9113. If you are just learning C, you can skip this section.
  9114. @menu
  9115. * Old GNU Inlining:: An older inlining technique.
  9116. * Old-Style Function Definitions:: Original K&R style functions.
  9117. @end menu
  9118. @node Old GNU Inlining
  9119. @subsection Older GNU C Inlining
  9120. The GNU C spec for inline functions, before GCC version 5, defined
  9121. @code{extern inline} on a function definition to mean to inline calls
  9122. to it but @emph{not} generate code for the function that could be
  9123. called at run time. By contrast, @code{inline} without @code{extern}
  9124. specified to generate run-time code for the function. In effect, ISO
  9125. incompatibly flipped the meanings of these two cases. We changed GCC
  9126. in version 5 to adopt the ISO specification.
  9127. Many programs still use these cases with the previous GNU C meanings.
  9128. You can specify use of those meanings with the option
  9129. @option{-fgnu89-inline}. You can also specify this for a single
  9130. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9131. @example
  9132. inline __attribute__ ((gnu_inline))
  9133. int
  9134. inc (int *a)
  9135. @{
  9136. (*a)++;
  9137. @}
  9138. @end example
  9139. @node Old-Style Function Definitions
  9140. @subsection Old-Style Function Definitions
  9141. @cindex old-style function definitions
  9142. @cindex function definitions, old-style
  9143. @cindex K&R-style function definitions
  9144. The syntax of C traditionally allows omitting the data type in a
  9145. function declaration if it specifies a storage class or a qualifier.
  9146. Then the type defaults to @code{int}. For example:
  9147. @example
  9148. static foo (double x);
  9149. @end example
  9150. @noindent
  9151. defaults the return type to @code{int}. This is bad practice; if you
  9152. see it, fix it.
  9153. An @dfn{old-style} (or ``K&R'') function definition is the way
  9154. function definitions were written in the 1980s. It looks like this:
  9155. @example
  9156. @var{rettype}
  9157. @var{function} (@var{parmnames})
  9158. @var{parm_declarations}
  9159. @{
  9160. @var{body}
  9161. @}
  9162. @end example
  9163. In @var{parmnames}, only the parameter names are listed, separated by
  9164. commas. Then @var{parm_declarations} declares their data types; these
  9165. declarations look just like variable declarations. If a parameter is
  9166. listed in @var{parmnames} but has no declaration, it is implicitly
  9167. declared @code{int}.
  9168. There is no reason to write a definition this way nowadays, but they
  9169. can still be seen in older GNU programs.
  9170. An old-style variadic function definition looks like this:
  9171. @example
  9172. #include <varargs.h>
  9173. int
  9174. add_multiple_values (va_alist)
  9175. va_dcl
  9176. @{
  9177. int argcount;
  9178. int counter, total = 0;
  9179. /* @r{Declare a variable of type @code{va_list}.} */
  9180. va_list argptr;
  9181. /* @r{Initialize that variable.} */
  9182. va_start (argptr);
  9183. /* @r{Get the first argument (fixed).} */
  9184. argcount = va_arg (int);
  9185. for (counter = 0; counter < argcount; counter++)
  9186. @{
  9187. /* @r{Get the next additional argument.} */
  9188. total += va_arg (argptr, int);
  9189. @}
  9190. /* @r{End use of the @code{argptr} variable.} */
  9191. va_end (argptr);
  9192. return total;
  9193. @}
  9194. @end example
  9195. Note that the old-style variadic function definition has no fixed
  9196. parameter variables; all arguments must be obtained with
  9197. @code{va_arg}.
  9198. @node Compatible Types
  9199. @chapter Compatible Types
  9200. @cindex compatible types
  9201. @cindex types, compatible
  9202. Declaring a function or variable twice is valid in C only if the two
  9203. declarations specify @dfn{compatible} types. In addition, some
  9204. operations on pointers require operands to have compatible target
  9205. types.
  9206. In C, two different primitive types are never compatible. Likewise for
  9207. the defined types @code{struct}, @code{union} and @code{enum}: two
  9208. separately defined types are incompatible unless they are defined
  9209. exactly the same way.
  9210. However, there are a few cases where different types can be
  9211. compatible:
  9212. @itemize @bullet
  9213. @item
  9214. Every enumeration type is compatible with some integer type. In GNU
  9215. C, the choice of integer type depends on the largest enumeration
  9216. value.
  9217. @c ??? Which one, in GCC?
  9218. @c ??? ... it varies, depending on the enum values. Testing on
  9219. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9220. @c ??? then moves on to an 8-byte signed integer. These details
  9221. @c ??? might be platform-dependent, as the C standard says that even
  9222. @c ??? char could be used as an enum type, but it's at least true
  9223. @c ??? that GCC chooses a type that is at least large enough to
  9224. @c ??? hold the largest enum value.
  9225. @item
  9226. Array types are compatible if the element types are compatible
  9227. and the sizes (when specified) match.
  9228. @item
  9229. Pointer types are compatible if the pointer target types are
  9230. compatible.
  9231. @item
  9232. Function types that specify argument types are compatible if the
  9233. return types are compatible and the argument types are compatible,
  9234. argument by argument. In addition, they must all agree in whether
  9235. they use @code{...} to allow additional arguments.
  9236. @item
  9237. Function types that don't specify argument types are compatible if the
  9238. return types are.
  9239. @item
  9240. Function types that specify the argument types are compatible with
  9241. function types that omit them, if the return types are compatible and
  9242. the specified argument types are unaltered by the argument promotions
  9243. (@pxref{Argument Promotions}).
  9244. @end itemize
  9245. In order for types to be compatible, they must agree in their type
  9246. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9247. It follows that @code{const int *} and @code{int *} are incompatible
  9248. too (they are pointers to types that are not compatible).
  9249. If two types are compatible ignoring the qualifiers, we call them
  9250. @dfn{nearly compatible}. (If they are array types, we ignore
  9251. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9252. Comparison of pointers is valid if the pointers' target types are
  9253. nearly compatible. Likewise, the two branches of a conditional
  9254. expression may be pointers to nearly compatible target types.
  9255. If two types are compatible ignoring the qualifiers, and the first
  9256. type has all the qualifiers of the second type, we say the first is
  9257. @dfn{upward compatible} with the second. Assignment of pointers
  9258. requires the assigned pointer's target type to be upward compatible
  9259. with the right operand (the new value)'s target type.
  9260. @node Type Conversions
  9261. @chapter Type Conversions
  9262. @cindex type conversions
  9263. @cindex conversions, type
  9264. C converts between data types automatically when that seems clearly
  9265. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9266. @menu
  9267. * Explicit Type Conversion:: Casting a value from one type to another.
  9268. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9269. * Argument Promotions:: Automatic conversion of function parameters.
  9270. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9271. * Common Type:: When operand types differ, which one is used?
  9272. @end menu
  9273. @node Explicit Type Conversion
  9274. @section Explicit Type Conversion
  9275. @cindex cast
  9276. @cindex explicit type conversion
  9277. You can do explicit conversions using the unary @dfn{cast} operator,
  9278. which is written as a type designator (@pxref{Type Designators}) in
  9279. parentheses. For example, @code{(int)} is the operator to cast to
  9280. type @code{int}. Here's an example of using it:
  9281. @example
  9282. @{
  9283. double d = 5.5;
  9284. printf ("Floating point value: %f\n", d);
  9285. printf ("Rounded to integer: %d\n", (int) d);
  9286. @}
  9287. @end example
  9288. Using @code{(int) d} passes an @code{int} value as argument to
  9289. @code{printf}, so you can print it with @samp{%d}. Using just
  9290. @code{d} without the cast would pass the value as @code{double}.
  9291. That won't work at all with @samp{%d}; the results would be gibberish.
  9292. To divide one integer by another without rounding,
  9293. cast either of the integers to @code{double} first:
  9294. @example
  9295. (double) @var{dividend} / @var{divisor}
  9296. @var{dividend} / (double) @var{divisor}
  9297. @end example
  9298. It is enough to cast one of them, because that forces the common type
  9299. to @code{double} so the other will be converted automatically.
  9300. The valid cast conversions are:
  9301. @itemize @bullet
  9302. @item
  9303. One numerical type to another.
  9304. @item
  9305. One pointer type to another.
  9306. (Converting between pointers that point to functions
  9307. and pointers that point to data is not standard C.)
  9308. @item
  9309. A pointer type to an integer type.
  9310. @item
  9311. An integer type to a pointer type.
  9312. @item
  9313. To a union type, from the type of any alternative in the union
  9314. (@pxref{Unions}). (This is a GNU extension.)
  9315. @item
  9316. Anything, to @code{void}.
  9317. @end itemize
  9318. @node Assignment Type Conversions
  9319. @section Assignment Type Conversions
  9320. @cindex assignment type conversions
  9321. Certain type conversions occur automatically in assignments
  9322. and certain other contexts. These are the conversions
  9323. assignments can do:
  9324. @itemize @bullet
  9325. @item
  9326. Converting any numeric type to any other numeric type.
  9327. @item
  9328. Converting @code{void *} to any other pointer type
  9329. (except pointer-to-function types).
  9330. @item
  9331. Converting any other pointer type to @code{void *}.
  9332. (except pointer-to-function types).
  9333. @item
  9334. Converting 0 (a null pointer constant) to any pointer type.
  9335. @item
  9336. Converting any pointer type to @code{bool}. (The result is
  9337. 1 if the pointer is not null.)
  9338. @item
  9339. Converting between pointer types when the left-hand target type is
  9340. upward compatible with the right-hand target type. @xref{Compatible
  9341. Types}.
  9342. @end itemize
  9343. These type conversions occur automatically in certain contexts,
  9344. which are:
  9345. @itemize @bullet
  9346. @item
  9347. An assignment converts the type of the right-hand expression
  9348. to the type wanted by the left-hand expression. For example,
  9349. @example
  9350. double i;
  9351. i = 5;
  9352. @end example
  9353. @noindent
  9354. converts 5 to @code{double}.
  9355. @item
  9356. A function call, when the function specifies the type for that
  9357. argument, converts the argument value to that type. For example,
  9358. @example
  9359. void foo (double);
  9360. foo (5);
  9361. @end example
  9362. @noindent
  9363. converts 5 to @code{double}.
  9364. @item
  9365. A @code{return} statement converts the specified value to the type
  9366. that the function is declared to return. For example,
  9367. @example
  9368. double
  9369. foo ()
  9370. @{
  9371. return 5;
  9372. @}
  9373. @end example
  9374. @noindent
  9375. also converts 5 to @code{double}.
  9376. @end itemize
  9377. In all three contexts, if the conversion is impossible, that
  9378. constitutes an error.
  9379. @node Argument Promotions
  9380. @section Argument Promotions
  9381. @cindex argument promotions
  9382. @cindex promotion of arguments
  9383. When a function's definition or declaration does not specify the type
  9384. of an argument, that argument is passed without conversion in whatever
  9385. type it has, with these exceptions:
  9386. @itemize @bullet
  9387. @item
  9388. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9389. expression is a narrow integer, such as @code{char} or @code{short},
  9390. the call converts it automatically to @code{int} (@pxref{Integer
  9391. Types}).@footnote{On an embedded controller where @code{char}
  9392. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9393. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9394. never occurs in GNU C on real computers.}
  9395. In this example, the expression @code{c} is passed as an @code{int}:
  9396. @example
  9397. char c = '$';
  9398. printf ("Character c is '%c'\n", c);
  9399. @end example
  9400. @item
  9401. If the expression
  9402. has type @code{float}, the call converts it automatically to
  9403. @code{double}.
  9404. @item
  9405. An array as argument is converted to a pointer to its zeroth element.
  9406. @item
  9407. A function name as argument is converted to a pointer to that function.
  9408. @end itemize
  9409. @node Operand Promotions
  9410. @section Operand Promotions
  9411. @cindex operand promotions
  9412. The operands in arithmetic operations undergo type conversion automatically.
  9413. These @dfn{operand promotions} are the same as the argument promotions
  9414. except without converting @code{float} to @code{double}. In other words,
  9415. the operand promotions convert
  9416. @itemize @bullet
  9417. @item
  9418. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9419. @item
  9420. an array to a pointer to its zeroth element, and
  9421. @item
  9422. a function name to a pointer to that function.
  9423. @end itemize
  9424. @node Common Type
  9425. @section Common Type
  9426. @cindex common type
  9427. Arithmetic binary operators (except the shift operators) convert their
  9428. operands to the @dfn{common type} before operating on them.
  9429. Conditional expressions also convert the two possible results to their
  9430. common type. Here are the rules for determining the common type.
  9431. If one of the numbers has a floating-point type and the other is an
  9432. integer, the common type is that floating-point type. For instance,
  9433. @example
  9434. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9435. @end example
  9436. If both are floating point, the type with the larger range is the
  9437. common type.
  9438. If both are integers but of different widths, the common type
  9439. is the wider of the two.
  9440. If they are integer types of the same width, the common type is
  9441. unsigned if either operand is unsigned, and it's @code{long} if either
  9442. operand is @code{long}. It's @code{long long} if either operand is
  9443. @code{long long}.
  9444. These rules apply to addition, subtraction, multiplication, division,
  9445. remainder, comparisons, and bitwise operations. They also apply to
  9446. the two branches of a conditional expression, and to the arithmetic
  9447. done in a modifying assignment operation.
  9448. @node Scope
  9449. @chapter Scope
  9450. @cindex scope
  9451. @cindex block scope
  9452. @cindex function scope
  9453. @cindex function prototype scope
  9454. Each definition or declaration of an identifier is visible
  9455. in certain parts of the program, which is typically less than the whole
  9456. of the program. The parts where it is visible are called its @dfn{scope}.
  9457. Normally, declarations made at the top-level in the source -- that is,
  9458. not within any blocks and function definitions -- are visible for the
  9459. entire contents of the source file after that point. This is called
  9460. @dfn{file scope} (@pxref{File-Scope Variables}).
  9461. Declarations made within blocks of code, including within function
  9462. definitions, are visible only within those blocks. This is called
  9463. @dfn{block scope}. Here is an example:
  9464. @example
  9465. @group
  9466. void
  9467. foo (void)
  9468. @{
  9469. int x = 42;
  9470. @}
  9471. @end group
  9472. @end example
  9473. @noindent
  9474. In this example, the variable @code{x} has block scope; it is visible
  9475. only within the @code{foo} function definition block. Thus, other
  9476. blocks could have their own variables, also named @code{x}, without
  9477. any conflict between those variables.
  9478. A variable declared inside a subblock has a scope limited to
  9479. that subblock,
  9480. @example
  9481. @group
  9482. void
  9483. foo (void)
  9484. @{
  9485. @{
  9486. int x = 42;
  9487. @}
  9488. // @r{@code{x} is out of scope here.}
  9489. @}
  9490. @end group
  9491. @end example
  9492. If a variable declared within a block has the same name as a variable
  9493. declared outside of that block, the definition within the block
  9494. takes precedence during its scope:
  9495. @example
  9496. @group
  9497. int x = 42;
  9498. void
  9499. foo (void)
  9500. @{
  9501. int x = 17;
  9502. printf ("%d\n", x);
  9503. @}
  9504. @end group
  9505. @end example
  9506. @noindent
  9507. This prints 17, the value of the variable @code{x} declared in the
  9508. function body block, rather than the value of the variable @code{x} at
  9509. file scope. We say that the inner declaration of @code{x}
  9510. @dfn{shadows} the outer declaration, for the extent of the inner
  9511. declaration's scope.
  9512. A declaration with block scope can be shadowed by another declaration
  9513. with the same name in a subblock.
  9514. @example
  9515. @group
  9516. void
  9517. foo (void)
  9518. @{
  9519. char *x = "foo";
  9520. @{
  9521. int x = 42;
  9522. @r{@dots{}}
  9523. exit (x / 6);
  9524. @}
  9525. @}
  9526. @end group
  9527. @end example
  9528. A function parameter's scope is the entire function body, but it can
  9529. be shadowed. For example:
  9530. @example
  9531. @group
  9532. int x = 42;
  9533. void
  9534. foo (int x)
  9535. @{
  9536. printf ("%d\n", x);
  9537. @}
  9538. @end group
  9539. @end example
  9540. @noindent
  9541. This prints the value of @code{x} the function parameter, rather than
  9542. the value of the file-scope variable @code{x}. However,
  9543. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9544. is visible for the whole of the containing function body, both before
  9545. and after the label declaration:
  9546. @example
  9547. @group
  9548. void
  9549. foo (void)
  9550. @{
  9551. @r{@dots{}}
  9552. goto bar;
  9553. @r{@dots{}}
  9554. @{ // @r{Subblock does not affect labels.}
  9555. bar:
  9556. @r{@dots{}}
  9557. @}
  9558. goto bar;
  9559. @}
  9560. @end group
  9561. @end example
  9562. Except for labels, a declared identifier is not
  9563. visible to code before its declaration. For example:
  9564. @example
  9565. @group
  9566. int x = 5;
  9567. int y = x + 10;
  9568. @end group
  9569. @end example
  9570. @noindent
  9571. will work, but:
  9572. @example
  9573. @group
  9574. int x = y + 10;
  9575. int y = 5;
  9576. @end group
  9577. @end example
  9578. @noindent
  9579. cannot refer to the variable @code{y} before its declaration.
  9580. @include cpp.texi
  9581. @node Integers in Depth
  9582. @chapter Integers in Depth
  9583. This chapter explains the machine-level details of integer types: how
  9584. they are represented as bits in memory, and the range of possible
  9585. values for each integer type.
  9586. @menu
  9587. * Integer Representations:: How integer values appear in memory.
  9588. * Maximum and Minimum Values:: Value ranges of integer types.
  9589. @end menu
  9590. @node Integer Representations
  9591. @section Integer Representations
  9592. @cindex integer representations
  9593. @cindex representation of integers
  9594. Modern computers store integer values as binary (base-2) numbers that
  9595. occupy a single unit of storage, typically either as an 8-bit
  9596. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9597. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9598. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9599. any of these types could have some other size, bit it's not worth even
  9600. a minute to cater to that possibility. It never happens on
  9601. GNU/Linux.}
  9602. @cindex @code{CHAR_BIT}
  9603. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9604. of bits in type @code{char}. On any real operating system, the value
  9605. is 8.
  9606. The fixed sizes of numeric types necessarily limits their @dfn{range
  9607. of values}, and the particular encoding of integers decides what that
  9608. range is.
  9609. @cindex two's-complement representation
  9610. For unsigned integers, the entire space is used to represent a
  9611. nonnegative value. Signed integers are stored using
  9612. @dfn{two's-complement representation}: a signed integer with @var{n}
  9613. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9614. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9615. high-order, bit is called the @dfn{sign bit}.
  9616. @c ??? Needs correcting
  9617. There is only one value that means zero, and the most negative number
  9618. lacks a positive counterpart. As a result, negating that number
  9619. causes overflow; in practice, its result is that number back again.
  9620. For example, a two's-complement signed 8-bit integer can represent all
  9621. decimal numbers from @minus{}128 to +127. We will revisit that
  9622. peculiarity shortly.
  9623. Decades ago, there were computers that didn't use two's-complement
  9624. representation for integers (@pxref{Integers in Depth}), but they are
  9625. long gone and not worth any effort to support.
  9626. @c ??? Is this duplicate?
  9627. When an arithmetic operation produces a value that is too big to
  9628. represent, the operation is said to @dfn{overflow}. In C, integer
  9629. overflow does not interrupt the control flow or signal an error.
  9630. What it does depends on signedness.
  9631. For unsigned arithmetic, the result of an operation that overflows is
  9632. the @var{n} low-order bits of the correct value. If the correct value
  9633. is representable in @var{n} bits, that is always the result;
  9634. thus we often say that ``integer arithmetic is exact,'' omitting the
  9635. crucial qualifying phrase ``as long as the exact result is
  9636. representable.''
  9637. In principle, a C program should be written so that overflow never
  9638. occurs for signed integers, but in GNU C you can specify various ways
  9639. of handling such overflow (@pxref{Integer Overflow}).
  9640. Integer representations are best understood by looking at a table for
  9641. a tiny integer size; here are the possible values for an integer with
  9642. three bits:
  9643. @multitable @columnfractions .25 .25 .25 .25
  9644. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9645. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9646. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9647. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9648. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9649. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9650. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9651. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9652. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9653. @end multitable
  9654. The parenthesized decimal numbers in the last column represent the
  9655. signed meanings of the two's-complement of the line's value. Recall
  9656. that, in two's-complement encoding, the high-order bit is 0 when
  9657. the number is nonnegative.
  9658. We can now understand the peculiar behavior of negation of the
  9659. most negative two's-complement integer: start with 0b100,
  9660. invert the bits to get 0b011, and add 1: we get
  9661. 0b100, the value we started with.
  9662. We can also see overflow behavior in two's-complement:
  9663. @example
  9664. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9665. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9666. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9667. @end example
  9668. @noindent
  9669. A sum of two nonnegative signed values that overflows has a 1 in the
  9670. sign bit, so the exact positive result is truncated to a negative
  9671. value.
  9672. @c =====================================================================
  9673. @node Maximum and Minimum Values
  9674. @section Maximum and Minimum Values
  9675. @cindex maximum integer values
  9676. @cindex minimum integer values
  9677. @cindex integer ranges
  9678. @cindex ranges of integer types
  9679. @findex INT_MAX
  9680. @findex UINT_MAX
  9681. @findex SHRT_MAX
  9682. @findex LONG_MAX
  9683. @findex LLONG_MAX
  9684. @findex USHRT_MAX
  9685. @findex ULONG_MAX
  9686. @findex ULLONG_MAX
  9687. @findex CHAR_MAX
  9688. @findex SCHAR_MAX
  9689. @findex UCHAR_MAX
  9690. For each primitive integer type, there is a standard macro defined in
  9691. @file{limits.h} that gives the largest value that type can hold. For
  9692. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9693. On a 32-bit computer, that is equal to 2,147,483,647. The
  9694. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9695. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9696. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9697. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9698. @code{ULLONG_MAX}.
  9699. Since there are three ways to specify a @code{char} type, there are
  9700. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9701. @code{UCHAR_MAX}.
  9702. For each type that is or might be signed, there is another symbol that
  9703. gives the minimum value it can hold. (Just replace @code{MAX} with
  9704. @code{MIN} in the names listed above.) There is no minimum limit
  9705. symbol for types specified with @code{unsigned} because the
  9706. minimum for them is universally zero.
  9707. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9708. two's-complement representation, the most negative number is 1 less
  9709. than the negative of the most positive number. Thus, @code{INT_MIN}
  9710. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9711. actually write the value that way in C, since it would overflow.
  9712. That's a good reason to use @code{INT_MIN} to specify
  9713. that value. Its definition is written to avoid overflow.
  9714. @include fp.texi
  9715. @node Compilation
  9716. @chapter Compilation
  9717. @cindex object file
  9718. @cindex compilation module
  9719. @cindex make rules
  9720. Early in the manual we explained how to compile a simple C program
  9721. that consists of a single source file (@pxref{Compile Example}).
  9722. However, we handle only short programs that way. A typical C program
  9723. consists of many source files, each of which is a separate
  9724. @dfn{compilation module}---meaning that it has to be compiled
  9725. separately.
  9726. The full details of how to compile with GCC are documented in xxxx.
  9727. @c ??? ref
  9728. Here we give only a simple introduction.
  9729. These are the commands to compile two compilation modules,
  9730. @file{foo.c} and @file{bar.c}, with a command for each module:
  9731. @example
  9732. gcc -c -O -g foo.c
  9733. gcc -c -O -g bar.c
  9734. @end example
  9735. @noindent
  9736. In these commands, @option{-g} says to generate debugging information,
  9737. @option{-O} says to do some optimization, and @option{-c} says to put
  9738. the compiled code for that module into a corresponding @dfn{object
  9739. file} and go no further. The object file for @file{foo.c} is called
  9740. @file{foo.o}, and so on.
  9741. If you wish, you can specify the additional options @option{-Wformat
  9742. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9743. One reason to divide a large program into multiple compilation modules
  9744. is to control how each module can access the internals of the others.
  9745. When a module declares a function or variable @code{extern}, other
  9746. modules can access it. The other functions and variables in
  9747. a module can't be accessed from outside that module.
  9748. The other reason for using multiple modules is so that changing
  9749. one source file does not require recompiling all of them in order
  9750. to try the modified program. Dividing a large program into many
  9751. substantial modules in this way typically makes recompilation much faster.
  9752. @cindex linking object files
  9753. After you compile all the program's modules, in order to run the
  9754. program you must @dfn{link} the object files into a combined
  9755. executable, like this:
  9756. @example
  9757. gcc -o foo foo.o bar.o
  9758. @end example
  9759. @noindent
  9760. In this command, @option{-o foo} species the file name for the
  9761. executable file, and the other arguments are the object files to link.
  9762. Always specify the executable file name in a command that generates
  9763. one.
  9764. Normally we don't run any of these commands directly. Instead we
  9765. write a set of @dfn{make rules} for the program, then use the
  9766. @command{make} program to recompile only the source files that need to
  9767. be recompiled.
  9768. @c ??? ref to make manual
  9769. @node Directing Compilation
  9770. @chapter Directing Compilation
  9771. This chapter describes C constructs that don't alter the program's
  9772. meaning @emph{as such}, but rather direct the compiler how to treat
  9773. some aspects of the program.
  9774. @menu
  9775. * Pragmas:: Controling compilation of some constructs.
  9776. * Static Assertions:: Compile-time tests for conditions.
  9777. @end menu
  9778. @node Pragmas
  9779. @section Pragmas
  9780. A @dfn{pragma} is an annotation in a program that gives direction to
  9781. the compiler.
  9782. @menu
  9783. * Pragma Basics:: Pragma syntax and usage.
  9784. * Severity Pragmas:: Settings for compile-time pragma output.
  9785. * Optimization Pragmas:: Controlling optimizations.
  9786. @end menu
  9787. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9788. @node Pragma Basics
  9789. @subsection Pragma Basics
  9790. C defines two syntactical forms for pragmas, the line form and the
  9791. token form. You can write any pragma in either form, with the same
  9792. meaning.
  9793. The line form is a line in the source code, like this:
  9794. @example
  9795. #pragma @var{line}
  9796. @end example
  9797. @noindent
  9798. The line pragma has no effect on the parsing of the lines around it.
  9799. This form has the drawback that it can't be generated by a macro expansion.
  9800. The token form is a series of tokens; it can appear anywhere in the
  9801. program between the other tokens.
  9802. @example
  9803. _Pragma (@var{stringconstant})
  9804. @end example
  9805. @noindent
  9806. The pragma has no effect on the syntax of the tokens that surround it;
  9807. thus, here's a pragma in the middle of an @code{if} statement:
  9808. @example
  9809. if _Pragma ("hello") (x > 1)
  9810. @end example
  9811. @noindent
  9812. However, that's an unclear thing to do; for the sake of
  9813. understandability, it is better to put a pragma on a line by itself
  9814. and not embedded in the middle of another construct.
  9815. Both forms of pragma have a textual argument. In a line pragma, the
  9816. text is the rest of the line. The textual argument to @code{_Pragma}
  9817. uses the same syntax as a C string constant: surround the text with
  9818. two @samp{"} characters, and add a backslash before each @samp{"} or
  9819. @samp{\} character in it.
  9820. With either syntax, the textual argument specifies what to do.
  9821. It begins with one or several words that specify the operation.
  9822. If the compiler does not recognize them, it ignores the pragma.
  9823. Here are the pragma operations supported in GNU C@.
  9824. @c ??? Verify font for []
  9825. @table @code
  9826. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9827. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9828. Declares that the current source file depends on @var{file}, so GNU C
  9829. compares the file times and gives a warning if @var{file} is newer
  9830. than the current source file.
  9831. This directive searches for @var{file} the way @code{#include}
  9832. searches for a non-system header file.
  9833. If @var{message} is given, the warning message includes that text.
  9834. Examples:
  9835. @example
  9836. #pragma GCC dependency "parse.y"
  9837. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9838. rerun fixincludes")
  9839. @end example
  9840. @item #pragma GCC poison @var{identifiers}
  9841. @itemx _Pragma ("GCC poison @var{identifiers}")
  9842. Poisons the identifiers listed in @var{identifiers}.
  9843. This is useful to make sure all mention of @var{identifiers} has been
  9844. deleted from the program and that no reference to them creeps back in.
  9845. If any of those identifiers appears anywhere in the source after the
  9846. directive, it causes a compilation error. For example,
  9847. @example
  9848. #pragma GCC poison printf sprintf fprintf
  9849. sprintf(some_string, "hello");
  9850. @end example
  9851. @noindent
  9852. generates an error.
  9853. If a poisoned identifier appears as part of the expansion of a macro
  9854. that was defined before the identifier was poisoned, it will @emph{not}
  9855. cause an error. Thus, system headers that define macros that use
  9856. the identifier will not cause errors.
  9857. For example,
  9858. @example
  9859. #define strrchr rindex
  9860. _Pragma ("GCC poison rindex")
  9861. strrchr(some_string, 'h');
  9862. @end example
  9863. @noindent
  9864. does not cause a compilation error.
  9865. @item #pragma GCC system_header
  9866. @itemx _Pragma ("GCC system_header")
  9867. Specify treating the rest of the current source file as if it came
  9868. from a system header file. @xref{System Headers, System Headers,
  9869. System Headers, gcc, Using the GNU Compiler Collection}.
  9870. @item #pragma GCC warning @var{message}
  9871. @itemx _Pragma ("GCC warning @var{message}")
  9872. Equivalent to @code{#warning}. Its advantage is that the
  9873. @code{_Pragma} form can be included in a macro definition.
  9874. @item #pragma GCC error @var{message}
  9875. @itemx _Pragma ("GCC error @var{message}")
  9876. Equivalent to @code{#error}. Its advantage is that the
  9877. @code{_Pragma} form can be included in a macro definition.
  9878. @item #pragma GCC message @var{message}
  9879. @itemx _Pragma ("GCC message @var{message}")
  9880. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9881. informational message, and could be used to include additional warning
  9882. or error text without triggering more warnings or errors. (Note that
  9883. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9884. @samp{GCC} as part of the pragma.)
  9885. @end table
  9886. @node Severity Pragmas
  9887. @subsection Severity Pragmas
  9888. These pragmas control the severity of classes of diagnostics.
  9889. You can specify the class of diagnostic with the GCC option that causes
  9890. those diagnostics to be generated.
  9891. @table @code
  9892. @item #pragma GCC diagnostic error @var{option}
  9893. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9894. For code following this pragma, treat diagnostics of the variety
  9895. specified by @var{option} as errors. For example:
  9896. @example
  9897. _Pragma ("GCC diagnostic error -Wformat")
  9898. @end example
  9899. @noindent
  9900. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9901. as errors rather than warnings.
  9902. @item #pragma GCC diagnostic warning @var{option}
  9903. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9904. For code following this pragma, treat diagnostics of the variety
  9905. specified by @var{option} as warnings. This overrides the
  9906. @var{-Werror} option which says to treat warnings as errors.
  9907. @item #pragma GCC diagnostic ignore @var{option}
  9908. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9909. For code following this pragma, refrain from reporting any diagnostics
  9910. of the variety specified by @var{option}.
  9911. @item #pragma GCC diagnostic push
  9912. @itemx _Pragma ("GCC diagnostic push")
  9913. @itemx #pragma GCC diagnostic pop
  9914. @itemx _Pragma ("GCC diagnostic pop")
  9915. These pragmas maintain a stack of states for severity settings.
  9916. @samp{GCC diagnostic push} saves the current settings on the stack,
  9917. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9918. the current settings from that.
  9919. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9920. restores the settings to what they were at the start of compilation.
  9921. Here is an example:
  9922. @example
  9923. _Pragma ("GCC diagnostic error -Wformat")
  9924. /* @r{@option{-Wformat} messages treated as errors. } */
  9925. _Pragma ("GCC diagnostic push")
  9926. _Pragma ("GCC diagnostic warning -Wformat")
  9927. /* @r{@option{-Wformat} messages treated as warnings. } */
  9928. _Pragma ("GCC diagnostic push")
  9929. _Pragma ("GCC diagnostic ignored -Wformat")
  9930. /* @r{@option{-Wformat} messages suppressed. } */
  9931. _Pragma ("GCC diagnostic pop")
  9932. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9933. _Pragma ("GCC diagnostic pop")
  9934. /* @r{@option{-Wformat} messages treated as errors again. } */
  9935. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9936. _Pragma ("GCC diagnostic pop")
  9937. /* @r{@option{-Wformat} messages treated once again}
  9938. @r{as specified by the GCC command-line options.} */
  9939. @end example
  9940. @end table
  9941. @node Optimization Pragmas
  9942. @subsection Optimization Pragmas
  9943. These pragmas enable a particular optimization for specific function
  9944. definitions. The settings take effect at the end of a function
  9945. definition, so the clean place to use these pragmas is between
  9946. function definitions.
  9947. @table @code
  9948. @item #pragma GCC optimize @var{optimization}
  9949. @itemx _Pragma ("GCC optimize @var{optimization}")
  9950. These pragmas enable the optimization @var{optimization} for the
  9951. following functions. For example,
  9952. @example
  9953. _Pragma ("GCC optimize -fforward-propagate")
  9954. @end example
  9955. @noindent
  9956. says to apply the @samp{forward-propagate} optimization to all
  9957. following function definitions. Specifying optimizations for
  9958. individual functions, rather than for the entire program, is rare but
  9959. can be useful for getting around a bug in the compiler.
  9960. If @var{optimization} does not correspond to a defined optimization
  9961. option, the pragma is erroneous. To turn off an optimization, use the
  9962. corresponding @samp{-fno-} option, such as
  9963. @samp{-fno-forward-propagate}.
  9964. @item #pragma GCC target @var{optimizations}
  9965. @itemx _Pragma ("GCC target @var{optimizations}")
  9966. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9967. used for platform-specific optimizations. Thus,
  9968. @example
  9969. _Pragma ("GCC target popcnt")
  9970. @end example
  9971. @noindent
  9972. activates the optimization @samp{popcnt} for all
  9973. following function definitions. This optimization is supported
  9974. on a few common targets but not on others.
  9975. @item #pragma GCC push_options
  9976. @itemx _Pragma ("GCC push_options")
  9977. The @samp{push_options} pragma saves on a stack the current settings
  9978. specified with the @samp{target} and @samp{optimize} pragmas.
  9979. @item #pragma GCC pop_options
  9980. @itemx _Pragma ("GCC pop_options")
  9981. The @samp{pop_options} pragma pops saved settings from that stack.
  9982. Here's an example of using this stack.
  9983. @example
  9984. _Pragma ("GCC push_options")
  9985. _Pragma ("GCC optimize forward-propagate")
  9986. /* @r{Functions to compile}
  9987. @r{with the @code{forward-propagate} optimization.} */
  9988. _Pragma ("GCC pop_options")
  9989. /* @r{Ends enablement of @code{forward-propagate}.} */
  9990. @end example
  9991. @item #pragma GCC reset_options
  9992. @itemx _Pragma ("GCC reset_options")
  9993. Clears all pragma-defined @samp{target} and @samp{optimize}
  9994. optimization settings.
  9995. @end table
  9996. @node Static Assertions
  9997. @section Static Assertions
  9998. @cindex static assertions
  9999. @findex _Static_assert
  10000. You can add compiler-time tests for necessary conditions into your
  10001. code using @code{_Static_assert}. This can be useful, for example, to
  10002. check that the compilation target platform supports the type sizes
  10003. that the code expects. For example,
  10004. @example
  10005. _Static_assert ((sizeof (long int) >= 8),
  10006. "long int needs to be at least 8 bytes");
  10007. @end example
  10008. @noindent
  10009. reports a compile-time error if compiled on a system with long
  10010. integers smaller than 8 bytes, with @samp{long int needs to be at
  10011. least 8 bytes} as the error message.
  10012. Since calls @code{_Static_assert} are processed at compile time, the
  10013. expression must be computable at compile time and the error message
  10014. must be a literal string. The expression can refer to the sizes of
  10015. variables, but can't refer to their values. For example, the
  10016. following static assertion is invalid for two reasons:
  10017. @example
  10018. char *error_message
  10019. = "long int needs to be at least 8 bytes";
  10020. int size_of_long_int = sizeof (long int);
  10021. _Static_assert (size_of_long_int == 8, error_message);
  10022. @end example
  10023. @noindent
  10024. The expression @code{size_of_long_int == 8} isn't computable at
  10025. compile time, and the error message isn't a literal string.
  10026. You can, though, use preprocessor definition values with
  10027. @code{_Static_assert}:
  10028. @example
  10029. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10030. at least 8 bytes"
  10031. _Static_assert ((sizeof (long int) == 8),
  10032. LONG_INT_ERROR_MESSAGE);
  10033. @end example
  10034. Static assertions are permitted wherever a statement or declaration is
  10035. permitted, including at top level in the file, and also inside the
  10036. definition of a type.
  10037. @example
  10038. union y
  10039. @{
  10040. int i;
  10041. int *ptr;
  10042. _Static_assert (sizeof (int *) == sizeof (int),
  10043. "Pointer and int not same size");
  10044. @};
  10045. @end example
  10046. @node Type Alignment
  10047. @appendix Type Alignment
  10048. @cindex type alignment
  10049. @cindex alignment of type
  10050. @findex _Alignof
  10051. @findex __alignof__
  10052. Code for device drivers and other communication with low-level
  10053. hardware sometimes needs to be concerned with the alignment of
  10054. data objects in memory.
  10055. Each data type has a required @dfn{alignment}, always a power of 2,
  10056. that says at which memory addresses an object of that type can validly
  10057. start. A valid address for the type must be a multiple of its
  10058. alignment. If a type's alignment is 1, that means it can validly
  10059. start at any address. If a type's alignment is 2, that means it can
  10060. only start at an even address. If a type's alignment is 4, that means
  10061. it can only start at an address that is a multiple of 4.
  10062. The alignment of a type (except @code{char}) can vary depending on the
  10063. kind of computer in use. To refer to the alignment of a type in a C
  10064. program, use @code{_Alignof}, whose syntax parallels that of
  10065. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10066. operation, and it doesn't compute the value of the expression used
  10067. as its argument.
  10068. Nominally, each integer and floating-point type has an alignment equal to
  10069. the largest power of 2 that divides its size. Thus, @code{int} with
  10070. size 4 has a nominal alignment of 4, and @code{long long int} with
  10071. size 8 has a nominal alignment of 8.
  10072. However, each kind of computer generally has a maximum alignment, and
  10073. no type needs more alignment than that. If the computer's maximum
  10074. alignment is 4 (which is common), then no type's alignment is more
  10075. than 4.
  10076. The size of any type is always a multiple of its alignment; that way,
  10077. in an array whose elements have that type, all the elements are
  10078. properly aligned if the first one is.
  10079. These rules apply to all real computers today, but some embedded
  10080. controllers have odd exceptions. We don't have references to cite for
  10081. them.
  10082. @c We can't cite a nonfree manual as documentation.
  10083. Ordinary C code guarantees that every object of a given type is in
  10084. fact aligned as that type requires.
  10085. If the operand of @code{_Alignof} is a structure field, the value
  10086. is the alignment it requires. It may have a greater alignment by
  10087. coincidence, due to the other fields, but @code{_Alignof} is not
  10088. concerned about that. @xref{Structures}.
  10089. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10090. but now that the feature has been standardized, it is better
  10091. to use the standard keyword @code{_Alignof}.
  10092. @findex _Alignas
  10093. @findex __aligned__
  10094. You can explicitly specify an alignment requirement for a particular
  10095. variable or structure field by adding @code{_Alignas
  10096. (@var{alignment})} to the declaration, where @var{alignment} is a
  10097. power of 2 or a type name. For instance:
  10098. @example
  10099. char _Alignas (8) x;
  10100. @end example
  10101. @noindent
  10102. or
  10103. @example
  10104. char _Alignas (double) x;
  10105. @end example
  10106. @noindent
  10107. specifies that @code{x} must start on an address that is a multiple of
  10108. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10109. machine, that maximum is how much alignment @code{x} will get.
  10110. The older GNU C syntax for this feature looked like
  10111. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10112. declaration, and was added after the variable. For instance:
  10113. @example
  10114. char x __attribute__ ((__aligned__ 8));
  10115. @end example
  10116. @xref{Attributes}.
  10117. @node Aliasing
  10118. @appendix Aliasing
  10119. @cindex aliasing (of storage)
  10120. @cindex pointer type conversion
  10121. @cindex type conversion, pointer
  10122. We have already presented examples of casting a @code{void *} pointer
  10123. to another pointer type, and casting another pointer type to
  10124. @code{void *}.
  10125. One common kind of pointer cast is guaranteed safe: casting the value
  10126. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10127. Allocation}). It is safe because these functions do not save the
  10128. pointer anywhere else; the only way the program will access the newly
  10129. allocated memory is via the pointer just returned.
  10130. In fact, C allows casting any pointer type to any other pointer type.
  10131. Using this to access the same place in memory using two
  10132. different data types is called @dfn{aliasing}.
  10133. Aliasing is necessary in some programs that do sophisticated memory
  10134. management, such as GNU Emacs, but most C programs don't need to do
  10135. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10136. aliasing correctly requires following the rules stated below.
  10137. Otherwise, the aliasing may result in malfunctions when the program
  10138. runs.
  10139. The rest of this appendix explains the pitfalls and rules of aliasing.
  10140. @menu
  10141. * Aliasing Alignment:: Memory alignment considerations for
  10142. casting between pointer types.
  10143. * Aliasing Length:: Type size considerations for
  10144. casting between pointer types.
  10145. * Aliasing Type Rules:: Even when type alignment and size matches,
  10146. aliasing can still have surprising results.
  10147. @end menu
  10148. @node Aliasing Alignment
  10149. @appendixsection Aliasing and Alignment
  10150. In order for a type-converted pointer to be valid, it must have the
  10151. alignment that the new pointer type requires. For instance, on most
  10152. computers, @code{int} has alignment 4; the address of an @code{int}
  10153. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10154. address of a @code{char} is usually not a multiple of 4. Taking the
  10155. address of such a @code{char} and casting it to @code{int *} probably
  10156. results in an invalid pointer. Trying to dereference it may cause a
  10157. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10158. @example
  10159. foo ()
  10160. @{
  10161. char i[4];
  10162. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10163. return *p; /* @r{Crash!} */
  10164. @}
  10165. @end example
  10166. This requirement is never a problem when casting the return value
  10167. of @code{malloc} because that function always returns a pointer
  10168. with as much alignment as any type can require.
  10169. @node Aliasing Length
  10170. @appendixsection Aliasing and Length
  10171. When converting a pointer to a different pointer type, make sure the
  10172. object it really points to is at least as long as the target of the
  10173. converted pointer. For instance, suppose @code{p} has type @code{int
  10174. *} and it's cast as follows:
  10175. @example
  10176. int *p;
  10177. struct
  10178. @{
  10179. double d, e, f;
  10180. @} foo;
  10181. struct foo *q = (struct foo *)p;
  10182. q->f = 5.14159;
  10183. @end example
  10184. @noindent
  10185. the value @code{q->f} will run past the end of the @code{int} that
  10186. @code{p} points to. If @code{p} was initialized to the start of an
  10187. array of type @code{int[6]}, the object is long enough for three
  10188. @code{double}s. But if @code{p} points to something shorter,
  10189. @code{q->f} will run on beyond the end of that, overlaying some other
  10190. data. Storing that will garble that other data. Or it could extend
  10191. past the end of memory space and cause a @code{SIGSEGV} signal
  10192. (@pxref{Signals}).
  10193. @node Aliasing Type Rules
  10194. @appendixsection Type Rules for Aliasing
  10195. C code that converts a pointer to a different pointer type can use the
  10196. pointers to access the same memory locations with two different data
  10197. types. If the same address is accessed with different types in a
  10198. single control thread, optimization can make the code do surprising
  10199. things (in effect, make it malfunction).
  10200. Here's a concrete example where aliasing that can change the code's
  10201. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10202. long, like @code{int}, and so is every pointer. Thus, the structures
  10203. @code{struct a} and @code{struct b} are both 8 bytes.
  10204. @example
  10205. #include <stdio.h>
  10206. struct a @{ int size; char *data; @};
  10207. struct b @{ float size; char *data; @};
  10208. void sub (struct a *p, struct b *q)
  10209. @{
  10210.   int x;
  10211.   p->size = 0;
  10212.   q->size = 1;
  10213.   x = p->size;
  10214.   printf("x       =%d\n", x);
  10215.   printf("p->size =%d\n", (int)p->size);
  10216.   printf("q->size =%d\n", (int)q->size);
  10217. @}
  10218. int main(void)
  10219. @{
  10220.   struct a foo;
  10221.   struct a *p = &foo;
  10222.   struct b *q = (struct b *) &foo;
  10223.   sub (p, q);
  10224. @}
  10225. @end example
  10226. This code works as intended when compiled without optimization. All
  10227. the operations are carried out sequentially as written. The code
  10228. sets @code{x} to @code{p->size}, but what it actually gets is the
  10229. bits of the floating point number 1, as type @code{int}.
  10230. However, when optimizing, the compiler is allowed to assume
  10231. (mistakenly, here) that @code{q} does not point to the same storage as
  10232. @code{p}, because their data types are not allowed to alias.
  10233. From this assumption, the compiler can deduce (falsely, here) that the
  10234. assignment into @code{q->size} has no effect on the value of
  10235. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10236. be set to 0.
  10237. GNU C, following the C standard, @emph{defines} this optimization as
  10238. legitimate. Code that misbehaves when optimized following these rules
  10239. is, by definition, incorrect C code.
  10240. The rules for storage aliasing in C are based on the two data types:
  10241. the type of the object, and the type it is accessed through. The
  10242. rules permit accessing part of a storage object of type @var{t} using
  10243. only these types:
  10244. @itemize @bullet
  10245. @item
  10246. @var{t}.
  10247. @item
  10248. A type compatible with @var{t}. @xref{Compatible Types}.
  10249. @item
  10250. A signed or unsigned version of one of the above.
  10251. @item
  10252. A qualifed version of one of the above.
  10253. @xref{Type Qualifiers}.
  10254. @item
  10255. An array, structure (@pxref{Structures}), or union type
  10256. (@code{Unions}) that contains one of the above, either directly as a
  10257. field or through multiple levels of fields. If @var{t} is
  10258. @code{double}, this would include @code{struct s @{ union @{ double
  10259. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10260. inside it somewhere.
  10261. @item
  10262. A character type.
  10263. @end itemize
  10264. What do these rules say about the example in this subsection?
  10265. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10266. @code{int}. The type @code{float} is not allowed as an aliasing type
  10267. by those rules, so @code{b->size} is not supposed to alias with
  10268. elements of @code{j}. Based on that assumption, GNU C makes a
  10269. permitted optimization that was not, in this case, consistent with
  10270. what the programmer intended the program to do.
  10271. Whether GCC actually performs type-based aliasing analysis depends on
  10272. the details of the code. GCC has other ways to determine (in some cases)
  10273. whether objects alias, and if it gets a reliable answer that way, it won't
  10274. fall back on type-based heuristics.
  10275. @c @opindex -fno-strict-aliasing
  10276. The importance of knowing the type-based aliasing rules is not so as
  10277. to ensure that the optimization is done where it would be safe, but so
  10278. as to ensure it is @emph{not} done in a way that would break the
  10279. program. You can turn off type-based aliasing analysis by giving GCC
  10280. the option @option{-fno-strict-aliasing}.
  10281. @node Digraphs
  10282. @appendix Digraphs
  10283. @cindex digraphs
  10284. C accepts aliases for certain characters. Apparently in the 1990s
  10285. some computer systems had trouble inputting these characters, or
  10286. trouble displaying them. These digraphs almost never appear in C
  10287. programs nowadays, but we mention them for completeness.
  10288. @table @samp
  10289. @item <:
  10290. An alias for @samp{[}.
  10291. @item :>
  10292. An alias for @samp{]}.
  10293. @item <%
  10294. An alias for @samp{@{}.
  10295. @item %>
  10296. An alias for @samp{@}}.
  10297. @item %:
  10298. An alias for @samp{#},
  10299. used for preprocessing directives (@pxref{Directives}) and
  10300. macros (@pxref{Macros}).
  10301. @end table
  10302. @node Attributes
  10303. @appendix Attributes in Declarations
  10304. @cindex attributes
  10305. @findex __attribute__
  10306. You can specify certain additional requirements in a declaration, to
  10307. get fine-grained control over code generation, and helpful
  10308. informational messages during compilation. We use a few attributes in
  10309. code examples throughout this manual, including
  10310. @table @code
  10311. @item aligned
  10312. The @code{aligned} attribute specifies a minimum alignment for a
  10313. variable or structure field, measured in bytes:
  10314. @example
  10315. int foo __attribute__ ((aligned (8))) = 0;
  10316. @end example
  10317. @noindent
  10318. This directs GNU C to allocate @code{foo} at an address that is a
  10319. multiple of 8 bytes. However, you can't force an alignment bigger
  10320. than the computer's maximum meaningful alignment.
  10321. @item packed
  10322. The @code{packed} attribute specifies to compact the fields of a
  10323. structure by not leaving gaps between fields. For example,
  10324. @example
  10325. struct __attribute__ ((packed)) bar
  10326. @{
  10327. char a;
  10328. int b;
  10329. @};
  10330. @end example
  10331. @noindent
  10332. allocates the integer field @code{b} at byte 1 in the structure,
  10333. immediately after the character field @code{a}. The packed structure
  10334. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10335. alignment is 1, that of @code{char}.
  10336. @item deprecated
  10337. Applicable to both variables and functions, the @code{deprecated}
  10338. attribute tells the compiler to issue a warning if the variable or
  10339. function is ever used in the source file.
  10340. @example
  10341. int old_foo __attribute__ ((deprecated));
  10342. int old_quux () __attribute__ ((deprecated));
  10343. @end example
  10344. @item __noinline__
  10345. The @code{__noinline__} attribute, in a function's declaration or
  10346. definition, specifies never to inline calls to that function. All
  10347. calls to that function, in a compilation unit where it has this
  10348. attribute, will be compiled to invoke the separately compiled
  10349. function. @xref{Inline Function Definitions}.
  10350. @item __noclone__
  10351. The @code{__noclone__} attribute, in a function's declaration or
  10352. definition, specifies never to clone that function. Thus, there will
  10353. be only one compiled version of the function. @xref{Label Value
  10354. Caveats}, for more information about cloning.
  10355. @item always_inline
  10356. The @code{always_inline} attribute, in a function's declaration or
  10357. definition, specifies to inline all calls to that function (unless
  10358. something about the function makes inlining impossible). This applies
  10359. to all calls to that function in a compilation unit where it has this
  10360. attribute. @xref{Inline Function Definitions}.
  10361. @item gnu_inline
  10362. The @code{gnu_inline} attribute, in a function's declaration or
  10363. definition, specifies to handle the @code{inline} keywprd the way GNU
  10364. C originally implemented it, many years before ISO C said anything
  10365. about inlining. @xref{Inline Function Definitions}.
  10366. @end table
  10367. For full documentation of attributes, see the GCC manual.
  10368. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10369. the GNU Compiler Collection}.
  10370. @node Signals
  10371. @appendix Signals
  10372. @cindex signal
  10373. @cindex handler (for signal)
  10374. @cindex @code{SIGSEGV}
  10375. @cindex @code{SIGFPE}
  10376. @cindex @code{SIGBUS}
  10377. Some program operations bring about an error condition called a
  10378. @dfn{signal}. These signals terminate the program, by default.
  10379. There are various different kinds of signals, each with a name. We
  10380. have seen several such error conditions through this manual:
  10381. @table @code
  10382. @item SIGSEGV
  10383. This signal is generated when a program tries to read or write outside
  10384. the memory that is allocated for it, or to write memory that can only
  10385. be read. The name is an abbreviation for ``segmentation violation''.
  10386. @item SIGFPE
  10387. This signal indicates a fatal arithmetic error. The name is an
  10388. abbreviation for ``floating-point exception'', but covers all types of
  10389. arithmetic errors, including division by zero and overflow.
  10390. @item SIGBUS
  10391. This signal is generated when an invalid pointer is dereferenced,
  10392. typically the result of dereferencing an uninintalized pointer. It is
  10393. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10394. invalid access to valid memory, while @code{SIGBUS} indicates an
  10395. attempt to access an invalid address.
  10396. @end table
  10397. These kinds of signal allow the program to specify a function as a
  10398. @dfn{signal handler}. When a signal has a handler, it doesn't
  10399. terminate the program; instead it calls the handler.
  10400. There are many other kinds of signal; here we list only those that
  10401. come from run-time errors in C operations. The rest have to do with
  10402. the functioning of the operating system. The GNU C Library Reference
  10403. Manual gives more explanation about signals (@pxref{Program Signal
  10404. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10405. Manual}).
  10406. @node GNU Free Documentation License
  10407. @appendix GNU Free Documentation License
  10408. @include fdl.texi
  10409. @node Symbol Index
  10410. @unnumbered Index of Symbols and Keywords
  10411. @printindex fn
  10412. @node Concept Index
  10413. @unnumbered Concept Index
  10414. @printindex cp
  10415. @bye