c.texi 419 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006
  1. \input texinfo
  2. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  3. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. 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 Intro and Reference Manual}
  34. @sp 4
  35. @c @center @value{EDITION} Edition
  36. @sp 5
  37. @center Richard Stallman
  38. @center and
  39. @center Trevis Rothwell
  40. @center plus Nelson Beebe
  41. @center on floating point
  42. @page
  43. @vskip 0pt plus 1filll
  44. @insertcopying
  45. @sp 2
  46. WILL BE Published by the Free Software Foundation @*
  47. 51 Franklin Street, Fifth Floor @*
  48. Boston, MA 02110-1301 USA @*
  49. ISBN ?-??????-??-?
  50. @ignore
  51. @sp 1
  52. Cover art by J. Random Artist
  53. @end ignore
  54. @end titlepage
  55. @summarycontents
  56. @contents
  57. @node Top
  58. @ifnottex
  59. @top GNU C Manual
  60. @end ifnottex
  61. @iftex
  62. @top Preface
  63. @end iftex
  64. This manual explains the C language for use with the GNU Compiler
  65. Collection (GCC) on the GNU/Linux system and other systems. We refer
  66. to this dialect as GNU C. If you already know C, you can use this as
  67. a reference manual.
  68. If you understand basic concepts of programming but know nothing about
  69. C, you can read this manual sequentially from the beginning to learn
  70. the C language.
  71. If you are a beginner to programming, we recommend you first learn a
  72. language with automatic garbage collection and no explicit pointers,
  73. rather than starting with C@. Good choices include Lisp, Scheme,
  74. Python and Java. C's explicit pointers mean that programmers must be
  75. careful to avoid certain kinds of errors.
  76. C is a venerable language; it was first used in 1973. The GNU C
  77. Compiler, which was subsequently extended into the GNU Compiler
  78. Collection, was first released in 1987. Other important languages
  79. were designed based on C: once you know C, it gives you a useful base
  80. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  81. The special advantage of C is that it is fairly simple while allowing
  82. close access to the computer's hardware, which previously required
  83. writing in assembler language to describe the individual machine
  84. instructions. Some have called C a ``high-level assembler language''
  85. because of its explicit pointers and lack of automatic management of
  86. storage. As one wag put it, ``C combines the power of assembler
  87. language with the convenience of assembler language.'' However, C is
  88. far more portable, and much easier to read and write, than assembler
  89. language.
  90. This manual focuses on the GNU C language supported by the GNU
  91. Compiler Collection, version ???. When a construct may be absent or
  92. work differently in other C compilers, we say so. When it is not part
  93. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  94. useful to know that; however, other dialects and standards are not the
  95. focus of this manual. We keep those notes short, unless it is vital
  96. to say more. For the same reason, we hardly mention C@t{++} or other
  97. languages that the GNU Compiler Collection supports.
  98. Some aspects of the meaning of C programs depend on the target
  99. platform: which computer, and which operating system, the compiled
  100. code will run on. Where this is the case, we say so.
  101. The C language provides no built-in facilities for performing such
  102. common operations as input/output, memory management, string
  103. manipulation, and the like. Instead, these facilities are defined in
  104. a standard library, which is automatically available in every C
  105. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  106. Reference Manual}.
  107. This manual incorporates the former GNU C Preprocessor Manual, which
  108. was among the earliest GNU Manuals. It also uses some text from the
  109. earlier GNU C Manual that was written by Trevis Rothwell and James
  110. Youngman.
  111. GNU C has many obscure features, each one either for historical
  112. compatibility or meant for very special situations. We have left them
  113. to a companion manual, the GNU C Obscurities Manual, which will be
  114. published digitally later.
  115. @menu
  116. * The First Example:: Getting started with basic C code.
  117. * Complete Program:: A whole example program
  118. that can be compiled and run.
  119. * Storage:: Basic layout of storage; bytes.
  120. * Beyond Integers:: Exploring different numeric types.
  121. * Lexical Syntax:: The various lexical components of C programs.
  122. * Arithmetic:: Numeric computations.
  123. * Assignment Expressions:: Storing values in variables.
  124. * Execution Control Expressions:: Expressions combining values in various ways.
  125. * Binary Operator Grammar:: An overview of operator precedence.
  126. * Order of Execution:: The order of program execution.
  127. * Primitive Types:: More details about primitive data types.
  128. * Constants:: Explicit constant values:
  129. details and examples.
  130. * Type Size:: The memory space occupied by a type.
  131. * Pointers:: Creating and manipulating memory pointers.
  132. * Structures:: Compound data types built
  133. by grouping other types.
  134. * Arrays:: Creating and manipulating arrays.
  135. * Enumeration Types:: Sets of integers with named values.
  136. * Defining Typedef Names:: Using @code{typedef} to define type names.
  137. * Statements:: Controling program flow.
  138. * Variables:: Details about declaring, initializing,
  139. and using variables.
  140. * Type Qualifiers:: Mark variables for certain intended uses.
  141. * Functions:: Declaring, defining, and calling functions.
  142. * Compatible Types:: How to tell if two types are compatible
  143. with each other.
  144. * Type Conversions:: Converting between types.
  145. * Scope:: Different categories of identifier scope.
  146. * Preprocessing:: Using the GNU C preprocessor.
  147. * Integers in Depth:: How integer numbers are represented.
  148. * Floating Point in Depth:: How floating-point numbers are represented.
  149. * Compilation:: How to compile multi-file programs.
  150. * Directing Compilation:: Operations that affect compilation
  151. but don't change the program.
  152. Appendices
  153. * Type Alignment:: Where in memory a type can validly start.
  154. * Aliasing:: Accessing the same data in two types.
  155. * Digraphs:: Two-character aliases for some characters.
  156. * Attributes:: Specifying additional information
  157. in a declaration.
  158. * Signals:: Fatal errors triggered in various scenarios.
  159. * GNU Free Documentation License:: The license for this manual.
  160. * Symbol Index:: Keyword and symbol index.
  161. * Concept Index:: Detailed topical index.
  162. @detailmenu
  163. --- The Detailed Node Listing ---
  164. * Recursive Fibonacci:: Writing a simple function recursively.
  165. * Stack:: Each function call uses space in the stack.
  166. * Iterative Fibonacci:: Writing the same function iteratively.
  167. * Complete Example:: Turn the simple function into a full program.
  168. * Complete Explanation:: Explanation of each part of the example.
  169. * Complete Line-by-Line:: Explaining each line of the example.
  170. * Compile Example:: Using GCC to compile the example.
  171. * Float Example:: A function that uses floating-point numbers.
  172. * Array Example:: A function that works with arrays.
  173. * Array Example Call:: How to call that function.
  174. * Array Example Variations:: Different ways to write the call example.
  175. Lexical Syntax
  176. * English:: Write programs in English!
  177. * Characters:: The characters allowed in C programs.
  178. * Whitespace:: The particulars of whitespace characters.
  179. * Comments:: How to include comments in C code.
  180. * Identifiers:: How to form identifiers (names).
  181. * Operators/Punctuation:: Characters used as operators or punctuation.
  182. * Line Continuation:: Splitting one line into multiple lines.
  183. * Digraphs:: Two-character substitutes for some characters.
  184. Arithmetic
  185. * Basic Arithmetic:: Addition, subtraction, multiplication,
  186. and division.
  187. * Integer Arithmetic:: How C performs arithmetic with integer values.
  188. * Integer Overflow:: When an integer value exceeds the range
  189. of its type.
  190. * Mixed Mode:: Calculating with both integer values
  191. and floating-point values.
  192. * Division and Remainder:: How integer division works.
  193. * Numeric Comparisons:: Comparing numeric values for
  194. equality or order.
  195. * Shift Operations:: Shift integer bits left or right.
  196. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  197. Assignment Expressions
  198. * Simple Assignment:: The basics of storing a value.
  199. * Lvalues:: Expressions into which a value can be stored.
  200. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  201. * Increment/Decrement:: Shorthand for incrementing and decrementing
  202. an lvalue's contents.
  203. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  204. * Assignment in Subexpressions:: How to avoid ambiguity.
  205. * Write Assignments Separately:: Write assignments as separate statements.
  206. Execution Control Expressions
  207. * Logical Operators:: Logical conjunction, disjunction, negation.
  208. * Logicals and Comparison:: Logical operators with comparison operators.
  209. * Logicals and Assignments:: Assignments with logical operators.
  210. * Conditional Expression:: An if/else construct inside expressions.
  211. * Comma Operator:: Build a sequence of subexpressions.
  212. Order of Execution
  213. * Reordering of Operands:: Operations in C are not necessarily computed
  214. in the order they are written.
  215. * Associativity and Ordering:: Some associative operations are performed
  216. in a particular order; others are not.
  217. * Sequence Points:: Some guarantees about the order of operations.
  218. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  219. * Ordering of Operands:: Evaluation order of operands
  220. and function arguments.
  221. * Optimization and Ordering:: Compiler optimizations can reorder operations
  222. only if it has no impact on program results.
  223. Primitive Data Types
  224. * Integer Types:: Description of integer types.
  225. * Floating-Point Data Types:: Description of floating-point types.
  226. * Complex Data Types:: Description of complex number types.
  227. * The Void Type:: A type indicating no value at all.
  228. * Other Data Types:: A brief summary of other types.
  229. Constants
  230. * Integer Constants:: Literal integer values.
  231. * Integer Const Type:: Types of literal integer values.
  232. * Floating Constants:: Literal floating-point values.
  233. * Imaginary Constants:: Literal imaginary number values.
  234. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  235. * Character Constants:: Literal character values.
  236. * Unicode Character Codes:: Unicode characters represented
  237. in either UTF-16 or UTF-32.
  238. * Wide Character Constants:: Literal characters values larger than 8 bits.
  239. * String Constants:: Literal string values.
  240. * UTF-8 String Constants:: Literal UTF-8 string values.
  241. * Wide String Constants:: Literal string values made up of
  242. 16- or 32-bit characters.
  243. Pointers
  244. * Address of Data:: Using the ``address-of'' operator.
  245. * Pointer Types:: For each type, there is a pointer type.
  246. * Pointer Declarations:: Declaring variables with pointer types.
  247. * Pointer Type Designators:: Designators for pointer types.
  248. * Pointer Dereference:: Accessing what a pointer points at.
  249. * Null Pointers:: Pointers which do not point to any object.
  250. * Invalid Dereference:: Dereferencing null or invalid pointers.
  251. * Void Pointers:: Totally generic pointers, can cast to any.
  252. * Pointer Comparison:: Comparing memory address values.
  253. * Pointer Arithmetic:: Computing memory address values.
  254. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  255. * Pointer Arithmetic Low Level:: More about computing memory address values.
  256. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  257. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  258. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  259. * Printing Pointers:: Using @code{printf} for a pointer's value.
  260. Structures
  261. * Referencing Fields:: Accessing field values in a structure object.
  262. * Dynamic Memory Allocation:: Allocating space for objects
  263. while the program is running.
  264. * Field Offset:: Memory layout of fields within a structure.
  265. * Structure Layout:: Planning the memory layout of fields.
  266. * Packed Structures:: Packing structure fields as close as possible.
  267. * Bit Fields:: Dividing integer fields
  268. into fields with fewer bits.
  269. * Bit Field Packing:: How bit fields pack together in integers.
  270. * const Fields:: Making structure fields immutable.
  271. * Zero Length:: Zero-length array as a variable-length object.
  272. * Flexible Array Fields:: Another approach to variable-length objects.
  273. * Overlaying Structures:: Casting one structure type
  274. over an object of another structure type.
  275. * Structure Assignment:: Assigning values to structure objects.
  276. * Unions:: Viewing the same object in different types.
  277. * Packing With Unions:: Using a union type to pack various types into
  278. the same memory space.
  279. * Cast to Union:: Casting a value one of the union's alternative
  280. types to the type of the union itself.
  281. * Structure Constructors:: Building new structure objects.
  282. * Unnamed Types as Fields:: Fields' types do not always need names.
  283. * Incomplete Types:: Types which have not been fully defined.
  284. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  285. * Type Tags:: Scope of structure and union type tags.
  286. Arrays
  287. * Accessing Array Elements:: How to access individual elements of an array.
  288. * Declaring an Array:: How to name and reserve space for a new array.
  289. * Strings:: A string in C is a special case of array.
  290. * Incomplete Array Types:: Naming, but not allocating, a new array.
  291. * Limitations of C Arrays:: Arrays are not first-class objects.
  292. * Multidimensional Arrays:: Arrays of arrays.
  293. * Constructing Array Values:: Assigning values to an entire array at once.
  294. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  295. Statements
  296. * Expression Statement:: Evaluate an expression, as a statement,
  297. usually done for a side effect.
  298. * if Statement:: Basic conditional execution.
  299. * if-else Statement:: Multiple branches for conditional execution.
  300. * Blocks:: Grouping multiple statements together.
  301. * return Statement:: Return a value from a function.
  302. * Loop Statements:: Repeatedly executing a statement or block.
  303. * switch Statement:: Multi-way conditional choices.
  304. * switch Example:: A plausible example of using @code{switch}.
  305. * Duffs Device:: A special way to use @code{switch}.
  306. * Case Ranges:: Ranges of values for @code{switch} cases.
  307. * Null Statement:: A statement that does nothing.
  308. * goto Statement:: Jump to another point in the source code,
  309. identified by a label.
  310. * Local Labels:: Labels with limited scope.
  311. * Labels as Values:: Getting the address of a label.
  312. * Statement Exprs:: A series of statements used as an expression.
  313. Variables
  314. * Variable Declarations:: Name a variable and and reserve space for it.
  315. * Initializers:: Assigning inital values to variables.
  316. * Designated Inits:: Assigning initial values to array elements
  317. at particular array indices.
  318. * Auto Type:: Obtaining the type of a variable.
  319. * Local Variables:: Variables declared in function definitions.
  320. * File-Scope Variables:: Variables declared outside of
  321. function definitions.
  322. * Static Local Variables:: Variables declared within functions,
  323. but with permanent storage allocation.
  324. * Extern Declarations:: Declaring a variable
  325. which is allocated somewhere else.
  326. * Allocating File-Scope:: When is space allocated
  327. for file-scope variables?
  328. * auto and register:: Historically used storage directions.
  329. * Omitting Types:: The bad practice of declaring variables
  330. with implicit type.
  331. Type Qualifiers
  332. * const:: Variables whose values don't change.
  333. * volatile:: Variables whose values may be accessed
  334. or changed outside of the control of
  335. this program.
  336. * restrict Pointers:: Restricted pointers for code optimization.
  337. * restrict Pointer Example:: Example of how that works.
  338. Functions
  339. * Function Definitions:: Writing the body of a function.
  340. * Function Declarations:: Declaring the interface of a function.
  341. * Function Calls:: Using functions.
  342. * Function Call Semantics:: Call-by-value argument passing.
  343. * Function Pointers:: Using references to functions.
  344. * The main Function:: Where execution of a GNU C program begins.
  345. Type Conversions
  346. * Explicit Type Conversion:: Casting a value from one type to another.
  347. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  348. * Argument Promotions:: Automatic conversion of function parameters.
  349. * Operand Promotions:: Automatic conversion of arithmetic operands.
  350. * Common Type:: When operand types differ, which one is used?
  351. Scope
  352. * Scope:: Different categories of identifier scope.
  353. Preprocessing
  354. * Preproc Overview:: Introduction to the C preprocessor.
  355. * Directives:: The form of preprocessor directives.
  356. * Preprocessing Tokens:: The lexical elements of preprocessing.
  357. * Header Files:: Including one source file in another.
  358. * Macros:: Macro expansion by the preprocessor.
  359. * Conditionals:: Controling whether to compile some lines
  360. or ignore them.
  361. * Diagnostics:: Reporting warnings and errors.
  362. * Line Control:: Reporting source line numbers.
  363. * Null Directive:: A preprocessing no-op.
  364. Integers in Depth
  365. * Integer Representations:: How integer values appear in memory.
  366. * Maximum and Minimum Values:: Value ranges of integer types.
  367. Floating Point in Depth
  368. * Floating Representations:: How floating-point values appear in memory.
  369. * Floating Type Specs:: Precise details of memory representations.
  370. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  371. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  372. * Exception Flags:: Handling certain conditions in floating point.
  373. * Exact Floating-Point:: Not all floating calculations lose precision.
  374. * Rounding:: When a floating result can't be represented
  375. exactly in the floating-point type in use.
  376. * Rounding Issues:: Avoid magnifying rounding errors.
  377. * Significance Loss:: Subtracting numbers that are almost equal.
  378. * Fused Multiply-Add:: Taking advantage of a special floating-point
  379. instruction for faster execution.
  380. * Error Recovery:: Determining rounding errors.
  381. * Exact Floating Constants:: Precisely specified floating-point numbers.
  382. * Handling Infinity:: When floating calculation is out of range.
  383. * Handling NaN:: What floating calculation is undefined.
  384. * Signed Zeros:: Positive zero vs. negative zero.
  385. * Scaling by the Base:: A useful exact floating-point operation.
  386. * Rounding Control:: Specifying some rounding behaviors.
  387. * Machine Epsilon:: The smallest number you can add to 1.0
  388. and get a sum which is larger than 1.0.
  389. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  390. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  391. * Further Reading:: References for floating-point numbers.
  392. Directing Compilation
  393. * Pragmas:: Controling compilation of some constructs.
  394. * Static Assertions:: Compile-time tests for conditions.
  395. @end detailmenu
  396. @end menu
  397. @node The First Example
  398. @chapter The First Example
  399. This chapter presents the source code for a very simple C program and
  400. uses it to explain a few features of the language. If you already
  401. know the basic points of C presented in this chapter, you can skim it
  402. or skip it.
  403. @menu
  404. * Recursive Fibonacci:: Writing a simple function recursively.
  405. * Stack:: Each function call uses space in the stack.
  406. * Iterative Fibonacci:: Writing the same function iteratively.
  407. @end menu
  408. @node Recursive Fibonacci
  409. @section Example: Recursive Fibonacci
  410. @cindex recursive Fibonacci function
  411. @cindex Fibonacci function, recursive
  412. To introduce the most basic features of C, let's look at code for a
  413. simple mathematical function that does calculations on integers. This
  414. function calculates the @var{n}th number in the Fibonacci series, in
  415. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  416. 13, 21, 34, 55, @dots{}.
  417. @example
  418. int
  419. fib (int n)
  420. @{
  421. if (n <= 2) /* @r{This avoids infinite recursion.} */
  422. return 1;
  423. else
  424. return fib (n - 1) + fib (n - 2);
  425. @}
  426. @end example
  427. This very simple program illustrates several features of C:
  428. @itemize @bullet
  429. @item
  430. A function definition, whose first two lines constitute the function
  431. header. @xref{Function Definitions}.
  432. @item
  433. A function parameter @code{n}, referred to as the variable @code{n}
  434. inside the function body. @xref{Function Parameter Variables}.
  435. A function definition uses parameters to refer to the argument
  436. values provided in a call to that function.
  437. @item
  438. Arithmetic. C programs add with @samp{+} and subtract with
  439. @samp{-}. @xref{Arithmetic}.
  440. @item
  441. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  442. equal.'' @xref{Numeric Comparisons}.
  443. @item
  444. Integer constants written in base 10.
  445. @xref{Integer Constants}.
  446. @item
  447. A function call. The function call @code{fib (n - 1)} calls the
  448. function @code{fib}, passing as its argument the value @code{n - 1}.
  449. @xref{Function Calls}.
  450. @item
  451. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  452. comment has no effect on the execution of the program. Its purpose is
  453. to provide explanations to people reading the source code. Including
  454. comments in the code is tremendously important---they provide
  455. background information so others can understand the code more quickly.
  456. @xref{Comments}.
  457. @item
  458. Two kinds of statements, the @code{return} statement and the
  459. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  460. @item
  461. Recursion. The function @code{fib} calls itself; that is called a
  462. @dfn{recursive call}. These are valid in C, and quite common.
  463. The @code{fib} function would not be useful if it didn't return.
  464. Thus, recursive definitions, to be of any use, must avoid infinite
  465. recursion.
  466. This function definition prevents infinite recursion by specially
  467. handling the case where @code{n} is two or less. Thus the maximum
  468. depth of recursive calls is less than @code{n}.
  469. @end itemize
  470. @menu
  471. * Function Header:: The function's name and how it is called.
  472. * Function Body:: Declarations and statements that implement the function.
  473. @end menu
  474. @node Function Header
  475. @subsection Function Header
  476. @cindex function header
  477. In our example, the first two lines of the function definition are the
  478. @dfn{header}. Its purpose is to state the function's name and say how
  479. it is called:
  480. @example
  481. int
  482. fib (int n)
  483. @end example
  484. @noindent
  485. says that the function returns an integer (type @code{int}), its name is
  486. @code{fib}, and it takes one argument named @code{n} which is also an
  487. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  488. @node Function Body
  489. @subsection Function Body
  490. @cindex function body
  491. @cindex recursion
  492. The rest of the function definition is called the @dfn{function body}.
  493. Like every function body, this one starts with @samp{@{}, ends with
  494. @samp{@}}, and contains zero or more @dfn{statements} and
  495. @dfn{declarations}. Statements specify actions to take, whereas
  496. declarations define names of variables, functions, and so on. Each
  497. statement and each declaration ends with a semicolon (@samp{;}).
  498. Statements and declarations often contain @dfn{expressions}; an
  499. expression is a construct whose execution produces a @dfn{value} of
  500. some data type, but may also take actions through ``side effects''
  501. that alter subsequent execution. A statement, by contrast, does not
  502. have a value; it affects further execution of the program only through
  503. the actions it takes.
  504. This function body contains no declarations, and just one statement,
  505. but that one is a complex statement in that it contains nested
  506. statements. This function uses two kinds of statements:
  507. @table @code
  508. @item return
  509. The @code{return} statement makes the function return immediately.
  510. It looks like this:
  511. @example
  512. return @var{value};
  513. @end example
  514. Its meaning is to compute the expression @var{value} and exit the
  515. function, making it return whatever value that expression produced.
  516. For instance,
  517. @example
  518. return 1;
  519. @end example
  520. @noindent
  521. returns the integer 1 from the function, and
  522. @example
  523. return fib (n - 1) + fib (n - 2);
  524. @end example
  525. @noindent
  526. returns a value computed by performing two function calls
  527. as specified and adding their results.
  528. @item @code{if}@dots{}@code{else}
  529. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  530. Each time it executes, it chooses one of its two substatements to execute
  531. and ignores the other. It looks like this:
  532. @example
  533. if (@var{condition})
  534. @var{if-true-statement}
  535. else
  536. @var{if-false-statement}
  537. @end example
  538. Its meaning is to compute the expression @var{condition} and, if it's
  539. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  540. @var{if-false-statement}. @xref{if-else Statement}.
  541. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  542. simply an expression. It's considered ``true'' if its value is
  543. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  544. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  545. Comparisons}.) Thus,
  546. @example
  547. if (n <= 2)
  548. return 1;
  549. else
  550. return fib (n - 1) + fib (n - 2);
  551. @end example
  552. @noindent
  553. first tests whether the value of @code{n} is less than or equal to 2.
  554. If so, the expression @code{n <= 2} has the value 1. So execution
  555. continues with the statement
  556. @example
  557. return 1;
  558. @end example
  559. @noindent
  560. Otherwise, execution continues with this statement:
  561. @example
  562. return fib (n - 1) + fib (n - 2);
  563. @end example
  564. Each of these statements ends the execution of the function and
  565. provides a value for it to return. @xref{return Statement}.
  566. @end table
  567. Calculating @code{fib} using ordinary integers in C works only for
  568. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  569. in type @code{int}. The addition operation that tries to add
  570. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  571. This occurrence is called @dfn{integer overflow}.
  572. Overflow can manifest itself in various ways, but one thing that can't
  573. possibly happen is to produce the correct value, since that can't fit
  574. in the space for the value. @xref{Integer Overflow}.
  575. @xref{Functions}, for a full explanation about functions.
  576. @node Stack
  577. @section The Stack, And Stack Overflow
  578. @cindex stack
  579. @cindex stack frame
  580. @cindex stack overflow
  581. @cindex recursion, drawbacks of
  582. @cindex stack frame
  583. Recursion has a drawback: there are limits to how many nested function
  584. calls a program can make. In C, each function call allocates a block
  585. of memory which it uses until the call returns. C allocates these
  586. blocks consecutively within a large area of memory known as the
  587. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  588. The size of the stack is limited; if the program tries to use too
  589. much, that causes the program to fail because the stack is full. This
  590. is called @dfn{stack overflow}.
  591. @cindex crash
  592. @cindex segmentation fault
  593. Stack overflow on GNU/Linux typically manifests itself as the
  594. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  595. fault.'' By default, this signal terminates the program immediately,
  596. rather than letting the program try to recover, or reach an expected
  597. ending point. (We commonly say in this case that the program
  598. ``crashes''). @xref{Signals}.
  599. It is inconvenient to observe a crash by passing too large
  600. an argument to recursive Fibonacci, because the program would run a
  601. long time before it crashes. This algorithm is simple but
  602. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  603. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  604. the final result.
  605. However, you can observe stack overflow very quickly if you use
  606. this function instead:
  607. @example
  608. int
  609. fill_stack (int n)
  610. @{
  611. if (n <= 1) /* @r{This limits the depth of recursion.} */
  612. return 1;
  613. else
  614. return fill_stack (n - 1);
  615. @}
  616. @end example
  617. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  618. and using the default configuration, an experiment showed there is
  619. enough stack space to do 261906 nested calls to that function. One
  620. more, and the stack overflows and the program crashes. On another
  621. platform, with a different configuration, or with a different
  622. function, the limit might be bigger or smaller.
  623. @node Iterative Fibonacci
  624. @section Example: Iterative Fibonacci
  625. @cindex iterative Fibonacci function
  626. @cindex Fibonacci function, iterative
  627. Here's a much faster algorithm for computing the same Fibonacci
  628. series. It is faster for two reasons. First, it uses @dfn{iteration}
  629. (that is, repetition or looping) rather than recursion, so it doesn't
  630. take time for a large number of function calls. But mainly, it is
  631. faster because the number of repetitions is small---only @code{@var{n}}.
  632. @c If you change this, change the duplicate in node Example of for.
  633. @example
  634. int
  635. fib (int n)
  636. @{
  637. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  638. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  639. int i;
  640. for (i = 1; i < n; ++i)
  641. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  642. /* @r{since @code{i < n} is false the first time.} */
  643. @{
  644. /* @r{Now @code{last} is @code{fib (@code{i})}}
  645. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  646. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  647. int next = prev + last;
  648. /* @r{Shift the values down.} */
  649. prev = last;
  650. last = next;
  651. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  652. @r{and @code{prev} is @code{fib (@code{i})}.}
  653. @r{But that won't stay true for long,}
  654. @r{because we are about to increment @code{i}.} */
  655. @}
  656. return last;
  657. @}
  658. @end example
  659. This definition computes @code{fib (@var{n})} in a time proportional
  660. to @code{@var{n}}. The comments in the definition explain how it works: it
  661. advances through the series, always keeps the last two values in
  662. @code{last} and @code{prev}, and adds them to get the next value.
  663. Here are the additional C features that this definition uses:
  664. @table @asis
  665. @item Internal blocks
  666. Within a function, wherever a statement is called for, you can write a
  667. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  668. more statements and declarations. (You can also use additional
  669. blocks as statements in a block.)
  670. The function body also counts as a block, which is why it can contain
  671. statements and declarations.
  672. @xref{Blocks}.
  673. @item Declarations of local variables
  674. This function body contains declarations as well as statements. There
  675. are three declarations directly in the function body, as well as a
  676. fourth declaration in an internal block. Each starts with @code{int}
  677. because it declares a variable whose type is integer. One declaration
  678. can declare several variables, but each of these declarations is
  679. simple and declares just one variable.
  680. Variables declared inside a block (either a function body or an
  681. internal block) are @dfn{local variables}. These variables exist only
  682. within that block; their names are not defined outside the block, and
  683. exiting the block deallocates their storage. This example declares
  684. four local variables: @code{last}, @code{prev}, @code{i}, and
  685. @code{next}.
  686. The most basic local variable declaration looks like this:
  687. @example
  688. @var{type} @var{variablename};
  689. @end example
  690. For instance,
  691. @example
  692. int i;
  693. @end example
  694. @noindent
  695. declares the local variable @code{i} as an integer.
  696. @xref{Variable Declarations}.
  697. @item Initializers
  698. When you declare a variable, you can also specify its initial value,
  699. like this:
  700. @example
  701. @var{type} @var{variablename} = @var{value};
  702. @end example
  703. For instance,
  704. @example
  705. int last = 1;
  706. @end example
  707. @noindent
  708. declares the local variable @code{last} as an integer (type
  709. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  710. @item Assignment
  711. Assignment: a specific kind of expression, written with the @samp{=}
  712. operator, that stores a new value in a variable or other place. Thus,
  713. @example
  714. @var{variable} = @var{value}
  715. @end example
  716. @noindent
  717. is an expression that computes @code{@var{value}} and stores the value in
  718. @code{@var{variable}}. @xref{Assignment Expressions}.
  719. @item Expression statements
  720. An expression statement is an expression followed by a semicolon.
  721. That computes the value of the expression, then ignores the value.
  722. An expression statement is useful when the expression changes some
  723. data or has other side effects---for instance, with function calls, or
  724. with assignments as in this example. @xref{Expression Statement}.
  725. Using an expression with no side effects in an expression statement is
  726. pointless except in very special cases. For instance, the expression
  727. statement @code{x;} would examine the value of @code{x} and ignore it.
  728. That is not useful.
  729. @item Increment operator
  730. The increment operator is @samp{++}. @code{++i} is an
  731. expression that is short for @code{i = i + 1}.
  732. @xref{Increment/Decrement}.
  733. @item @code{for} statements
  734. A @code{for} statement is a clean way of executing a statement
  735. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  736. @example
  737. for (i = 1; i < n; ++i)
  738. @var{body}
  739. @end example
  740. @noindent
  741. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  742. for the loop. The loop itself consists of
  743. @itemize @bullet
  744. @item
  745. Testing @code{i < n} and exiting the loop if that's false.
  746. @item
  747. Executing @var{body}.
  748. @item
  749. Advancing the loop (executing @code{++i}, which increments @code{i}).
  750. @end itemize
  751. The net result is to execute @var{body} with 0 in @code{i},
  752. then with 1 in @code{i}, and so on, stopping just before the repetition
  753. where @code{i} would equal @code{n}.
  754. The body of the @code{for} statement must be one and only one
  755. statement. You can't write two statements in a row there; if you try
  756. to, only the first of them will be treated as part of the loop.
  757. The way to put multiple statements in those places is to group them
  758. with a block, and that's what we do in this example.
  759. @end table
  760. @node Complete Program
  761. @chapter A Complete Program
  762. @cindex complete example program
  763. @cindex example program, complete
  764. It's all very well to write a Fibonacci function, but you cannot run
  765. it by itself. It is a useful program, but it is not a complete
  766. program.
  767. In this chapter we present a complete program that contains the
  768. @code{fib} function. This example shows how to make the program
  769. start, how to make it finish, how to do computation, and how to print
  770. a result.
  771. @menu
  772. * Complete Example:: Turn the simple function into a full program.
  773. * Complete Explanation:: Explanation of each part of the example.
  774. * Complete Line-by-Line:: Explaining each line of the example.
  775. * Compile Example:: Using GCC to compile the example.
  776. @end menu
  777. @node Complete Example
  778. @section Complete Program Example
  779. Here is the complete program that uses the simple, recursive version
  780. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  781. @example
  782. #include <stdio.h>
  783. int
  784. fib (int n)
  785. @{
  786. if (n <= 2) /* @r{This avoids infinite recursion.} */
  787. return 1;
  788. else
  789. return fib (n - 1) + fib (n - 2);
  790. @}
  791. int
  792. main (void)
  793. @{
  794. printf ("Fibonacci series item %d is %d\n",
  795. 20, fib (20));
  796. return 0;
  797. @}
  798. @end example
  799. @noindent
  800. This program prints a message that shows the value of @code{fib (20)}.
  801. Now for an explanation of what that code means.
  802. @node Complete Explanation
  803. @section Complete Program Explanation
  804. @ifnottex
  805. Here's the explanation of the code of the example in the
  806. previous section.
  807. @end ifnottex
  808. This sample program prints a message that shows the value of @code{fib
  809. (20)}, and exits with code 0 (which stands for successful execution).
  810. Every C program is started by running the function named @code{main}.
  811. Therefore, the example program defines a function named @code{main} to
  812. provide a way to start it. Whatever that function does is what the
  813. program does. @xref{The main Function}.
  814. The @code{main} function is the first one called when the program
  815. runs, but it doesn't come first in the example code. The order of the
  816. function definitions in the source code makes no difference to the
  817. program's meaning.
  818. The initial call to @code{main} always passes certain arguments, but
  819. @code{main} does not have to pay attention to them. To ignore those
  820. arguments, define @code{main} with @code{void} as the parameter list.
  821. (@code{void} as a function's parameter list normally means ``call with
  822. no arguments,'' but @code{main} is a special case.)
  823. The function @code{main} returns 0 because that is
  824. the conventional way for @code{main} to indicate successful execution.
  825. It could instead return a positive integer to indicate failure, and
  826. some utility programs have specific conventions for the meaning of
  827. certain numeric @dfn{failure codes}. @xref{Values from main}.
  828. @cindex @code{printf}
  829. The simplest way to print text in C is by calling the @code{printf}
  830. function, so here we explain what that does.
  831. @cindex standard output
  832. The first argument to @code{printf} is a @dfn{string constant}
  833. (@pxref{String Constants}) that is a template for output. The
  834. function @code{printf} copies most of that string directly as output,
  835. including the newline character at the end of the string, which is
  836. written as @samp{\n}. The output goes to the program's @dfn{standard
  837. output} destination, which in the usual case is the terminal.
  838. @samp{%} in the template introduces a code that substitutes other text
  839. into the output. Specifically, @samp{%d} means to take the next
  840. argument to @code{printf} and substitute it into the text as a decimal
  841. number. (The argument for @samp{%d} must be of type @code{int}; if it
  842. isn't, @code{printf} will malfunction.) So the output is a line that
  843. looks like this:
  844. @example
  845. Fibonacci series item 20 is 6765
  846. @end example
  847. This program does not contain a definition for @code{printf} because
  848. it is defined by the C library, which makes it available in all C
  849. programs. However, each program does need to @dfn{declare}
  850. @code{printf} so it will be called correctly. The @code{#include}
  851. line takes care of that; it includes a @dfn{header file} called
  852. @file{stdio.h} into the program's code. That file is provided by the
  853. operating system and it contains declarations for the many standard
  854. input/output functions in the C library, one of which is
  855. @code{printf}.
  856. Don't worry about header files for now; we'll explain them later in
  857. @ref{Header Files}.
  858. The first argument of @code{printf} does not have to be a string
  859. constant; it can be any string (@pxref{Strings}). However, using a
  860. constant is the most common case.
  861. To learn more about @code{printf} and other facilities of the C
  862. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  863. Reference Manual}.
  864. @node Complete Line-by-Line
  865. @section Complete Program, Line by Line
  866. Here's the same example, explained line by line.
  867. @strong{Beginners, do you find this helpful or not?
  868. Would you prefer a different layout for the example?
  869. Please tell rms@@gnu.org.}
  870. @example
  871. #include <stdio.h> /* @r{Include declaration of usual} */
  872. /* @r{I/O functions such as @code{printf}.} */
  873. /* @r{Most programs need these.} */
  874. int /* @r{This function returns an @code{int}.} */
  875. fib (int n) /* @r{Its name is @code{fib};} */
  876. /* @r{its argument is called @code{n}.} */
  877. @{ /* @r{Start of function body.} */
  878. /* @r{This stops the recursion from being infinite.} */
  879. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  880. return 1; /* @r{make @code{fib} return 1.} */
  881. else /* @r{otherwise, add the two previous} */
  882. /* @r{fibonacci numbers.} */
  883. return fib (n - 1) + fib (n - 2);
  884. @}
  885. int /* @r{This function returns an @code{int}.} */
  886. main (void) /* @r{Start here; ignore arguments.} */
  887. @{ /* @r{Print message with numbers in it.} */
  888. printf ("Fibonacci series item %d is %d\n",
  889. 20, fib (20));
  890. return 0; /* @r{Terminate program, report success.} */
  891. @}
  892. @end example
  893. @node Compile Example
  894. @section Compiling the Example Program
  895. @cindex compiling
  896. @cindex executable file
  897. To run a C program requires converting the source code into an
  898. @dfn{executable file}. This is called @dfn{compiling} the program,
  899. and the command to do that using GNU C is @command{gcc}.
  900. This example program consists of a single source file. If we
  901. call that file @file{fib1.c}, the complete command to compile it is
  902. this:
  903. @example
  904. gcc -g -O -o fib1 fib1.c
  905. @end example
  906. @noindent
  907. Here, @option{-g} says to generate debugging information, @option{-O}
  908. says to optimize at the basic level, and @option{-o fib1} says to put
  909. the executable program in the file @file{fib1}.
  910. To run the program, use its file name as a shell command.
  911. For instance,
  912. @example
  913. ./fib1
  914. @end example
  915. @noindent
  916. However, unless you are sure the program is correct, you should
  917. expect to need to debug it. So use this command,
  918. @example
  919. gdb fib1
  920. @end example
  921. @noindent
  922. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  923. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  924. debug the executable program @code{fib1}.
  925. @xref{Compilation}, for an introduction to compiling more complex
  926. programs which consist of more than one source file.
  927. @node Storage
  928. @chapter Storage and Data
  929. @cindex bytes
  930. @cindex storage organization
  931. @cindex memory organization
  932. Storage in C programs is made up of units called @dfn{bytes}. On
  933. nearly all computers, a byte consists of 8 bits, but there are a few
  934. peculiar computers (mostly ``embedded controllers'' for very small
  935. systems) where a byte is longer than that. This manual does not try
  936. to explain the peculiarity of those computers; we assume that a byte
  937. is 8 bits.
  938. Every C data type is made up of a certain number of bytes; that number
  939. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  940. types @code{signed char} and @code{unsigned char} are one byte long;
  941. use those types to operate on data byte by byte. @xref{Signed and
  942. Unsigned Types}. You can refer to a series of consecutive bytes as an
  943. array of @code{char} elements; that's what an ASCII string looks like
  944. in memory. @xref{String Constants}.
  945. @node Beyond Integers
  946. @chapter Beyond Integers
  947. So far we've presented programs that operate on integers. In this
  948. chapter we'll present examples of handling non-integral numbers and
  949. arrays of numbers.
  950. @menu
  951. * Float Example:: A function that uses floating-point numbers.
  952. * Array Example:: A function that works with arrays.
  953. * Array Example Call:: How to call that function.
  954. * Array Example Variations:: Different ways to write the call example.
  955. @end menu
  956. @node Float Example
  957. @section An Example with Non-Integer Numbers
  958. @cindex floating point example
  959. Here's a function that operates on and returns @dfn{floating point}
  960. numbers that don't have to be integers. Floating point represents a
  961. number as a fraction together with a power of 2. (For more detail,
  962. @pxref{Floating-Point Data Types}.) This example calculates the
  963. average of three floating point numbers that are passed to it as
  964. arguments:
  965. @example
  966. double
  967. average_of_three (double a, double b, double c)
  968. @{
  969. return (a + b + c) / 3;
  970. @}
  971. @end example
  972. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  973. integers, and even when they happen to be integers, most likely their
  974. average is not an integer.
  975. @code{double} is the usual data type in C for calculations on
  976. floating-point numbers.
  977. To print a @code{double} with @code{printf}, we must use @samp{%f}
  978. instead of @samp{%d}:
  979. @example
  980. printf ("Average is %f\n",
  981. average_of_three (1.1, 9.8, 3.62));
  982. @end example
  983. The code that calls @code{printf} must pass a @code{double} for
  984. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  985. If the argument has the wrong type, @code{printf} will produce garbage
  986. output.
  987. Here's a complete program that computes the average of three
  988. specific numbers and prints the result:
  989. @example
  990. double
  991. average_of_three (double a, double b, double c)
  992. @{
  993. return (a + b + c) / 3;
  994. @}
  995. int
  996. main (void)
  997. @{
  998. printf ("Average is %f\n",
  999. average_of_three (1.1, 9.8, 3.62));
  1000. return 0;
  1001. @}
  1002. @end example
  1003. From now on we will not present examples of calls to @code{main}.
  1004. Instead we encourage you to write them for yourself when you want
  1005. to test executing some code.
  1006. @node Array Example
  1007. @section An Example with Arrays
  1008. @cindex array example
  1009. A function to take the average of three numbers is very specific and
  1010. limited. A more general function would take the average of any number
  1011. of numbers. That requires passing the numbers in an array. An array
  1012. is an object in memory that contains a series of values of the same
  1013. data type. This chapter presents the basic concepts and use of arrays
  1014. through an example; for the full explanation, see @ref{Arrays}.
  1015. Here's a function definition to take the average of several
  1016. floating-point numbers, passed as type @code{double}. The first
  1017. parameter, @code{length}, specifies how many numbers are passed. The
  1018. second parameter, @code{input_data}, is an array that holds those
  1019. numbers.
  1020. @example
  1021. double
  1022. avg_of_double (int length, double input_data[])
  1023. @{
  1024. double sum = 0;
  1025. int i;
  1026. for (i = 0; i < length; i++)
  1027. sum = sum + input_data[i];
  1028. return sum / length;
  1029. @}
  1030. @end example
  1031. This introduces the expression to refer to an element of an array:
  1032. @code{input_data[i]} means the element at index @code{i} in
  1033. @code{input_data}. The index of the element can be any expression
  1034. with an integer value; in this case, the expression is @code{i}.
  1035. @xref{Accessing Array Elements}.
  1036. @cindex zero-origin indexing
  1037. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1038. valid index is one less than the number of elements. (This is known
  1039. as @dfn{zero-origin indexing}.)
  1040. This example also introduces the way to declare that a function
  1041. parameter is an array. Such declarations are modeled after the syntax
  1042. for an element of the array. Just as @code{double foo} declares that
  1043. @code{foo} is of type @code{double}, @code{double input_data[]}
  1044. declares that each element of @code{input_data} is of type
  1045. @code{double}. Therefore, @code{input_data} itself has type ``array
  1046. of @code{double}.''
  1047. When declaring an array parameter, it's not necessary to say how long
  1048. the array is. In this case, the parameter @code{input_data} has no
  1049. length information. That's why the function needs another parameter,
  1050. @code{length}, for the caller to provide that information to the
  1051. function @code{avg_of_double}.
  1052. @node Array Example Call
  1053. @section Calling the Array Example
  1054. To call the function @code{avg_of_double} requires making an
  1055. array and then passing it as an argument. Here is an example.
  1056. @example
  1057. @{
  1058. /* @r{The array of values to average.} */
  1059. double nums_to_average[5];
  1060. /* @r{The average, once we compute it.} */
  1061. double average;
  1062. /* @r{Fill in elements of @code{nums_to_average}.} */
  1063. nums_to_average[0] = 58.7;
  1064. nums_to_average[1] = 5.1;
  1065. nums_to_average[2] = 7.7;
  1066. nums_to_average[3] = 105.2;
  1067. nums_to_average[4] = -3.14159;
  1068. average = avg_of_double (5, nums_to_average);
  1069. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1070. @}
  1071. @end example
  1072. This shows an array subscripting expression again, this time
  1073. on the left side of an assignment, storing a value into an
  1074. element of an array.
  1075. It also shows how to declare a local variable that is an array:
  1076. @code{double nums_to_average[5];}. Since this declaration allocates the
  1077. space for the array, it needs to know the array's length. You can
  1078. specify the length with any expression whose value is an integer, but
  1079. in this declaration the length is a constant, the integer 5.
  1080. The name of the array, when used by itself as an expression, stands
  1081. for the address of the array's data, and that's what gets passed to
  1082. the function @code{avg_of_double} in @code{avg_of_double (5,
  1083. nums_to_average)}.
  1084. We can make the code easier to maintain by avoiding the need to write
  1085. 5, the array length, when calling @code{avg_of_double}. That way, if
  1086. we change the array to include more elements, we won't have to change
  1087. that call. One way to do this is with the @code{sizeof} operator:
  1088. @example
  1089. average = avg_of_double ((sizeof (nums_to_average)
  1090. / sizeof (nums_to_average[0])),
  1091. nums_to_average);
  1092. @end example
  1093. This computes the number of elements in @code{nums_to_average} by dividing
  1094. its total size by the size of one element. @xref{Type Size}, for more
  1095. details of using @code{sizeof}.
  1096. We don't show in this example what happens after storing the result of
  1097. @code{avg_of_double} in the variable @code{average}. Presumably
  1098. more code would follow that uses that result somehow. (Why compute
  1099. the average and not use it?) But that isn't part of this topic.
  1100. @node Array Example Variations
  1101. @section Variations for Array Example
  1102. The code to call @code{avg_of_double} has two declarations that
  1103. start with the same data type:
  1104. @example
  1105. /* @r{The array of values to average.} */
  1106. double nums_to_average[5];
  1107. /* @r{The average, once we compute it.} */
  1108. double average;
  1109. @end example
  1110. In C, you can combine the two, like this:
  1111. @example
  1112. double nums_to_average[5], average;
  1113. @end example
  1114. This declares @code{nums_to_average} so each of its elements is a
  1115. @code{double}, and @code{average} so that it simply is a
  1116. @code{double}.
  1117. However, while you @emph{can} combine them, that doesn't mean you
  1118. @emph{should}. If it is useful to write comments about the variables,
  1119. and usually it is, then it's clearer to keep the declarations separate
  1120. so you can put a comment on each one.
  1121. We set all of the elements of the array @code{nums_to_average} with
  1122. assignments, but it is more convenient to use an initializer in the
  1123. declaration:
  1124. @example
  1125. @{
  1126. /* @r{The array of values to average.} */
  1127. double nums_to_average[]
  1128. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1129. /* @r{The average, once we compute it.} */
  1130. average = avg_of_double ((sizeof (nums_to_average)
  1131. / sizeof (nums_to_average[0])),
  1132. nums_to_average);
  1133. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1134. @}
  1135. @end example
  1136. The array initializer is a comma-separated list of values, delimited
  1137. by braces. @xref{Initializers}.
  1138. Note that the declaration does not specify a size for
  1139. @code{nums_to_average}, so the size is determined from the
  1140. initializer. There are five values in the initializer, so
  1141. @code{nums_to_average} gets length 5. If we add another element to
  1142. the initializer, @code{nums_to_average} will have six elements.
  1143. Because the code computes the number of elements from the size of
  1144. the array, using @code{sizeof}, the program will operate on all the
  1145. elements in the initializer, regardless of how many those are.
  1146. @node Lexical Syntax
  1147. @chapter Lexical Syntax
  1148. @cindex lexical syntax
  1149. @cindex token
  1150. To start the full description of the C language, we explain the
  1151. lexical syntax and lexical units of C code. The lexical units of a
  1152. programming language are known as @dfn{tokens}. This chapter covers
  1153. all the tokens of C except for constants, which are covered in a later
  1154. chapter (@pxref{Constants}). One vital kind of token is the
  1155. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1156. kind.
  1157. @menu
  1158. * English:: Write programs in English!
  1159. * Characters:: The characters allowed in C programs.
  1160. * Whitespace:: The particulars of whitespace characters.
  1161. * Comments:: How to include comments in C code.
  1162. * Identifiers:: How to form identifiers (names).
  1163. * Operators/Punctuation:: Characters used as operators or punctuation.
  1164. * Line Continuation:: Splitting one line into multiple lines.
  1165. @end menu
  1166. @node English
  1167. @section Write Programs in English!
  1168. In principle, you can write the function and variable names in a
  1169. program, and the comments, in any human language. C allows any kinds
  1170. of characters in comments, and you can put non-ASCII characters into
  1171. identifiers with a special prefix. However, to enable programmers in
  1172. all countries to understand and develop the program, it is best given
  1173. today's circumstances to write identifiers and comments in
  1174. English.
  1175. English is the one language that programmers in all countries
  1176. generally study. If a program's names are in English, most
  1177. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1178. understand them. Most programmers in those countries can speak
  1179. English, or at least read it, but they do not read each other's
  1180. languages at all. In India, with so many languages, two programmers
  1181. may have no common language other than English.
  1182. If you don't feel confident in writing English, do the best you can,
  1183. and follow each English comment with a version in a language you
  1184. write better; add a note asking others to translate that to English.
  1185. Someone will eventually do that.
  1186. The program's user interface is a different matter. We don't need to
  1187. choose one language for that; it is easy to support multiple languages
  1188. and let each user choose the language to use. This requires writing
  1189. the program to support localization of its interface. (The
  1190. @code{gettext} package exists to support this; @pxref{Message
  1191. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1192. Manual}.) Then a community-based translation effort can provide
  1193. support for all the languages users want to use.
  1194. @node Characters
  1195. @section Characters
  1196. @cindex character set
  1197. @cindex Unicode
  1198. @c ??? How to express ¶?
  1199. GNU C source files are usually written in the
  1200. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1201. was defined in the 1960s for English. However, they can also include
  1202. Unicode characters represented in the
  1203. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1204. This makes it possible to represent accented letters such as @samp{á},
  1205. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1206. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1207. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1208. manual.}
  1209. In C source code, non-ASCII characters are valid in comments, in wide
  1210. character constants (@pxref{Wide Character Constants}), and in string
  1211. constants (@pxref{String Constants}).
  1212. @c ??? valid in identifiers?
  1213. Another way to specify non-ASCII characters in constants (character or
  1214. string) and identifiers is with an escape sequence starting with
  1215. backslash, specifying the intended Unicode character. (@xref{Unicode
  1216. Character Codes}.) This specifies non-ASCII characters without
  1217. putting a real non-ASCII character in the source file itself.
  1218. C accepts two-character aliases called @dfn{digraphs} for certain
  1219. characters. @xref{Digraphs}.
  1220. @node Whitespace
  1221. @section Whitespace
  1222. @cindex whitespace characters in source files
  1223. @cindex space character in source
  1224. @cindex tab character in source
  1225. @cindex formfeed in source
  1226. @cindex linefeed in source
  1227. @cindex newline in source
  1228. @cindex carriage return in source
  1229. @cindex vertical tab in source
  1230. Whitespace means characters that exist in a file but appear blank in a
  1231. printed listing of a file (or traditionally did appear blank, several
  1232. decades ago). The C language requires whitespace in order to separate
  1233. two consecutive identifiers, or to separate an identifier from a
  1234. numeric constant. Other than that, and a few special situations
  1235. described later, whitespace is optional; you can put it in when you
  1236. wish, to make the code easier to read.
  1237. Space and tab in C code are treated as whitespace characters. So are
  1238. line breaks. You can represent a line break with the newline
  1239. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1240. the CRLF sequence (two characters: carriage return followed by a
  1241. newline character).
  1242. The @dfn{formfeed} character, Control-L, was traditionally used to
  1243. divide a file into pages. It is still used this way in source code,
  1244. and the tools that generate nice printouts of source code still start
  1245. a new page after each ``formfeed'' character. Dividing code into
  1246. pages separated by formfeed characters is a good way to break it up
  1247. into comprehensible pieces and show other programmers where they start
  1248. and end.
  1249. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1250. make printing advance down to the next section of a page. We know of
  1251. no particular reason to use it in source code, but it is still
  1252. accepted as whitespace in C.
  1253. Comments are also syntactically equivalent to whitespace.
  1254. @ifinfo
  1255. @xref{Comments}.
  1256. @end ifinfo
  1257. @node Comments
  1258. @section Comments
  1259. @cindex comments
  1260. A comment encapsulates text that has no effect on the program's
  1261. execution or meaning.
  1262. The purpose of comments is to explain the code to people that read it.
  1263. Writing good comments for your code is tremendously important---they
  1264. should provide background information that helps programmers
  1265. understand the reasons why the code is written the way it is. You,
  1266. returning to the code six months from now, will need the help of these
  1267. comments to remember why you wrote it this way.
  1268. Outdated comments that become incorrect are counterproductive, so part
  1269. of the software developer's responsibility is to update comments as
  1270. needed to correspond with changes to the program code.
  1271. C allows two kinds of comment syntax, the traditional style and the
  1272. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1273. with @samp{*/}. For instance,
  1274. @example
  1275. /* @r{This is a comment in traditional C syntax.} */
  1276. @end example
  1277. A traditional comment can contain @samp{/*}, but these delimiters do
  1278. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1279. whether it contains @samp{/*} sequences.
  1280. @example
  1281. /* @r{This} /* @r{is a comment} */ But this is not! */
  1282. @end example
  1283. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1284. For instance,
  1285. @example
  1286. // @r{This is a comment in C@t{++} style.}
  1287. @end example
  1288. Line comments do nest, in effect, because @samp{//} inside a line
  1289. comment is part of that comment:
  1290. @example
  1291. // @r{this whole line is} // @r{one comment}
  1292. This is code, not comment.
  1293. @end example
  1294. It is safe to put line comments inside block comments, or vice versa.
  1295. @example
  1296. @group
  1297. /* @r{traditional comment}
  1298. // @r{contains line comment}
  1299. @r{more traditional comment}
  1300. */ text here is not a comment
  1301. // @r{line comment} /* @r{contains traditional comment} */
  1302. @end group
  1303. @end example
  1304. But beware of commenting out one end of a traditional comment with a line
  1305. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1306. inside an already-started comment.
  1307. @example
  1308. @group
  1309. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1310. Oops! The line comment has ended;
  1311. this isn't a comment any more. */
  1312. @end group
  1313. @end example
  1314. Comments are not recognized within string constants. @t{@w{"/* blah
  1315. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1316. string.
  1317. In this manual we show the text in comments in a variable-width font,
  1318. for readability, but this font distinction does not exist in source
  1319. files.
  1320. A comment is syntactically equivalent to whitespace, so it always
  1321. separates tokens. Thus,
  1322. @example
  1323. @group
  1324. int/* @r{comment} */foo;
  1325. @r{is equivalent to}
  1326. int foo;
  1327. @end group
  1328. @end example
  1329. @noindent
  1330. but clean code always uses real whitespace to separate the comment
  1331. visually from surrounding code.
  1332. @node Identifiers
  1333. @section Identifiers
  1334. @cindex identifiers
  1335. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1336. as well as @samp{_}, that does not start with a digit. Most compilers
  1337. also allow @samp{$}. An identifier can be as long as you like; for
  1338. example,
  1339. @example
  1340. int anti_dis_establishment_arian_ism;
  1341. @end example
  1342. @cindex case of letters in identifiers
  1343. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1344. and @code{A} are two different identifiers.
  1345. @cindex keyword
  1346. @cindex reserved words
  1347. Identifiers in C are used as variable names, function names, typedef
  1348. names, enumeration constants, type tags, field names, and labels.
  1349. Certain identifiers in C are @dfn{keywords}, which means they have
  1350. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1351. meaning you cannot use them in any other way. For instance, you can't
  1352. define a variable or function named @code{return} or @code{if}.
  1353. You can also include other characters, even non-ASCII characters, in
  1354. identifiers by writing their Unicode character names, which start with
  1355. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1356. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1357. characters in identifiers, and when they are written in English, they
  1358. never need non-ASCII characters. @xref{English}.
  1359. Whitespace is required to separate two consecutive identifiers, or to
  1360. separate an identifier from a preceding or following numeric
  1361. constant.
  1362. @node Operators/Punctuation
  1363. @section Operators and Punctuation
  1364. @cindex operators
  1365. @cindex punctuation
  1366. Here we describe the lexical syntax of operators and punctuation in C.
  1367. The specific operators of C and their meanings are presented in
  1368. subsequent chapters.
  1369. Most operators in C consist of one or two characters that can't be
  1370. used in identifiers. The characters used for operators in C are
  1371. @samp{!~^&|*/%+-=<>,.?:}.
  1372. Some operators are a single character. For instance, @samp{-} is the
  1373. operator for negation (with one operand) and the operator for
  1374. subtraction (with two operands).
  1375. Some operators are two characters. For example, @samp{++} is the
  1376. increment operator. Recognition of multicharacter operators works by
  1377. grouping together as many consecutive characters as can constitute one
  1378. operator.
  1379. For instance, the character sequence @samp{++} is always interpreted
  1380. as the increment operator; therefore, if we want to write two
  1381. consecutive instances of the operator @samp{+}, we must separate them
  1382. with a space so that they do not combine as one token. Applying the
  1383. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1384. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1385. of a valid C program and the former could not (since @code{a++}
  1386. is not an lvalue and thus can't be the operand of @code{++}).
  1387. A few C operators are keywords rather than special characters. They
  1388. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1389. (@pxref{Type Alignment}).
  1390. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1391. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1392. @samp{@}}) begin and end a block at the statement level
  1393. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1394. for a variable with multiple elements or components (such as arrays or
  1395. structures).
  1396. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1397. @code{array[5]}.
  1398. Parentheses are used in expressions for explicit nesting of
  1399. expressions (@pxref{Basic Arithmetic}), around the parameter
  1400. declarations in a function declaration or definition, and around the
  1401. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1402. (@pxref{Function Calls}). Several kinds of statements also use
  1403. parentheses as part of their syntax---for instance, @code{if}
  1404. statements, @code{for} statements, @code{while} statements, and
  1405. @code{switch} statements. @xref{if Statement}, and following
  1406. sections.
  1407. Parentheses are also required around the operand of the operator
  1408. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1409. type rather than a value. @xref{Type Size}.
  1410. @node Line Continuation
  1411. @section Line Continuation
  1412. @cindex line continuation
  1413. @cindex continuation of lines
  1414. The sequence of a backslash and a newline is ignored absolutely
  1415. anywhere in a C program. This makes it possible to split a single
  1416. source line into multiple lines in the source file. GNU C tolerates
  1417. and ignores other whitespace between the backslash and the newline.
  1418. In particular, it always ignores a CR (carriage return) character
  1419. there, in case some text editor decided to end the line with the CRLF
  1420. sequence.
  1421. The main use of line continuation in C is for macro definitions that
  1422. would be inconveniently long for a single line (@pxref{Macros}).
  1423. It is possible to continue a line comment onto another line with
  1424. backslash-newline. You can put backslash-newline in the middle of an
  1425. identifier, even a keyword, or an operator. You can even split
  1426. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1427. backslash-newline. Here's an ugly example:
  1428. @example
  1429. @group
  1430. /\
  1431. *
  1432. */ fo\
  1433. o +\
  1434. = 1\
  1435. 0;
  1436. @end group
  1437. @end example
  1438. @noindent
  1439. That's equivalent to @samp{/* */ foo += 10;}.
  1440. Don't do those things in real programs, since they make code hard to
  1441. read.
  1442. @strong{Note:} For the sake of using certain tools on the source code, it is
  1443. wise to end every source file with a newline character which is not
  1444. preceded by a backslash, so that it really ends the last line.
  1445. @node Arithmetic
  1446. @chapter Arithmetic
  1447. @cindex arithmetic operators
  1448. @cindex operators, arithmetic
  1449. @c ??? Duplication with other sections -- get rid of that?
  1450. Arithmetic operators in C attempt to be as similar as possible to the
  1451. abstract arithmetic operations, but it is impossible to do this
  1452. perfectly. Numbers in a computer have a finite range of possible
  1453. values, and non-integer values have a limit on their possible
  1454. accuracy. Nonetheless, in most cases you will encounter no surprises
  1455. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1456. for multiplication.
  1457. Each C operator has a @dfn{precedence}, which is its rank in the
  1458. grammatical order of the various operators. The operators with the
  1459. highest precedence grab adjoining operands first; these expressions
  1460. then become operands for operators of lower precedence. We give some
  1461. information about precedence of operators in this chapter where we
  1462. describe the operators; for the full explanation, see @ref{Binary
  1463. Operator Grammar}.
  1464. The arithmetic operators always @dfn{promote} their operands before
  1465. operating on them. This means converting narrow integer data types to
  1466. a wider data type (@pxref{Operand Promotions}). If you are just
  1467. learning C, don't worry about this yet.
  1468. Given two operands that have different types, most arithmetic
  1469. operations convert them both to their @dfn{common type}. For
  1470. instance, if one is @code{int} and the other is @code{double}, the
  1471. common type is @code{double}. (That's because @code{double} can
  1472. represent all the values that an @code{int} can hold, but not vice
  1473. versa.) For the full details, see @ref{Common Type}.
  1474. @menu
  1475. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1476. and division.
  1477. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1478. * Integer Overflow:: When an integer value exceeds the range
  1479. of its type.
  1480. * Mixed Mode:: Calculating with both integer values
  1481. and floating-point values.
  1482. * Division and Remainder:: How integer division works.
  1483. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1484. * Shift Operations:: Shift integer bits left or right.
  1485. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1486. @end menu
  1487. @node Basic Arithmetic
  1488. @section Basic Arithmetic
  1489. @cindex addition operator
  1490. @cindex subtraction operator
  1491. @cindex multiplication operator
  1492. @cindex division operator
  1493. @cindex negation operator
  1494. @cindex operator, addition
  1495. @cindex operator, subtraction
  1496. @cindex operator, multiplication
  1497. @cindex operator, division
  1498. @cindex operator, negation
  1499. Basic arithmetic in C is done with the usual binary operators of
  1500. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1501. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1502. used to change the sign of a number. The unary @code{+} operator also
  1503. exists; it yields its operand unaltered.
  1504. @samp{/} is the division operator, but dividing integers may not give
  1505. the result you expect. Its value is an integer, which is not equal to
  1506. the mathematical quotient when that is a fraction. Use @samp{%} to
  1507. get the corresponding integer remainder when necessary.
  1508. @xref{Division and Remainder}. Floating point division yields value
  1509. as close as possible to the mathematical quotient.
  1510. These operators use algebraic syntax with the usual algebraic
  1511. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1512. and division are done before addition and subtraction, but you can use
  1513. parentheses to explicitly specify how the operators nest. They are
  1514. left-associative (@pxref{Associativity and Ordering}). Thus,
  1515. @example
  1516. -a + b - c + d * e / f
  1517. @end example
  1518. @noindent
  1519. is equivalent to
  1520. @example
  1521. (((-a) + b) - c) + ((d * e) / f)
  1522. @end example
  1523. @node Integer Arithmetic
  1524. @section Integer Arithmetic
  1525. @cindex integer arithmetic
  1526. Each of the basic arithmetic operations in C has two variants for
  1527. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1528. by the data types of their operands.
  1529. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1530. A signed type can hold a range of positive and negative numbers, with
  1531. zero near the middle of the range. An unsigned type can hold only
  1532. nonnegative numbers; its range starts with zero and runs upward.
  1533. The most basic integer types are @code{int}, which normally can hold
  1534. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1535. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1536. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1537. computers but not always on embedded controllers.) @xref{Integer
  1538. Types}, for full information about integer types.
  1539. When a basic arithmetic operation is given two signed operands, it
  1540. does signed arithmetic. Given two unsigned operands, it does
  1541. unsigned arithmetic.
  1542. If one operand is @code{unsigned int} and the other is @code{int}, the
  1543. operator treats them both as unsigned. More generally, the common
  1544. type of the operands determines whether the operation is signed or
  1545. not. @xref{Common Type}.
  1546. Printing the results of unsigned arithmetic with @code{printf} using
  1547. @samp{%d} can produce surprising results for values far away from
  1548. zero. Even though the rules above say that the computation was done
  1549. with unsigned arithmetic, the printed result may appear to be signed!
  1550. The explanation is that the bit pattern resulting from addition,
  1551. subtraction or multiplication is actually the same for signed and
  1552. unsigned operations. The difference is only in the data type of the
  1553. result, which affects the @emph{interpretation} of the result bit pattern,
  1554. and whether the arithmetic operation can overflow (see the next section).
  1555. But @samp{%d} doesn't know its argument's data type. It sees only the
  1556. value's bit pattern, and it is defined to interpret that as
  1557. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1558. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1559. libc, The GNU C Library Reference Manual}.
  1560. Arithmetic in C never operates directly on narrow integer types (those
  1561. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1562. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1563. @node Integer Overflow
  1564. @section Integer Overflow
  1565. @cindex integer overflow
  1566. @cindex overflow, integer
  1567. When the mathematical value of an arithmetic operation doesn't fit in
  1568. the range of the data type in use, that's called @dfn{overflow}.
  1569. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1570. Integer overflow happens only in arithmetic operations. Type conversion
  1571. operations, by definition, do not cause overflow, not even when the
  1572. result can't fit in its new type. @xref{Integer Conversion}.
  1573. Signed numbers use two's-complement representation, in which the most
  1574. negative number lacks a positive counterpart (@pxref{Integers in
  1575. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1576. overflow.
  1577. @menu
  1578. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1579. * Signed Overflow:: Overlow in signed integer arithmetic.
  1580. @end menu
  1581. @node Unsigned Overflow
  1582. @subsection Overflow with Unsigned Integers
  1583. Unsigned arithmetic in C ignores overflow; it produces the true result
  1584. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1585. in the data type. We say it ``truncates'' the true result to the
  1586. lowest @var{n} bits.
  1587. A true result that is negative, when taken modulo the @var{n}th power
  1588. of 2, yields a positive number. For instance,
  1589. @example
  1590. unsigned int x = 1;
  1591. unsigned int y;
  1592. y = -x;
  1593. @end example
  1594. @noindent
  1595. causes overflow because the negative number @minus{}1 can't be stored
  1596. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1597. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1598. is the largest value that the unsigned data type can store. For a
  1599. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1600. and Minimum Values}.
  1601. Adding that number to itself, as here,
  1602. @example
  1603. unsigned int z;
  1604. z = y + y;
  1605. @end example
  1606. @noindent
  1607. ought to yield 8,489,934,590; however, that is again too large to fit,
  1608. so overflow truncates the value to 4,294,967,294. If that were a
  1609. signed integer, it would mean @minus{}2, which (not by coincidence)
  1610. equals @minus{}1 + @minus{}1.
  1611. @node Signed Overflow
  1612. @subsection Overflow with Signed Integers
  1613. @cindex compiler options for integer overflow
  1614. @cindex integer overflow, compiler options
  1615. @cindex overflow, compiler options
  1616. For signed integers, the result of overflow in C is @emph{in
  1617. principle} undefined, meaning that anything whatsoever could happen.
  1618. Therefore, C compilers can do optimizations that treat the overflow
  1619. case with total unconcern. (Since the result of overflow is undefined
  1620. in principle, one cannot claim that these optimizations are
  1621. erroneous.)
  1622. @strong{Watch out:} These optimizations can do surprising things. For
  1623. instance,
  1624. @example
  1625. int i;
  1626. @r{@dots{}}
  1627. if (i < i + 1)
  1628. x = 5;
  1629. @end example
  1630. @noindent
  1631. could be optimized to do the assignment unconditionally, because the
  1632. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1633. GCC offers compiler options to control handling signed integer
  1634. overflow. These options operate per module; that is, each module
  1635. behaves according to the options it was compiled with.
  1636. These two options specify particular ways to handle signed integer
  1637. overflow, other than the default way:
  1638. @table @option
  1639. @item -fwrapv
  1640. Make signed integer operations well-defined, like unsigned integer
  1641. operations: they produce the @var{n} low-order bits of the true
  1642. result. The highest of those @var{n} bits is the sign bit of the
  1643. result. With @option{-fwrapv}, these out-of-range operations are not
  1644. considered overflow, so (strictly speaking) integer overflow never
  1645. happens.
  1646. The option @option{-fwrapv} enables some optimizations based on the
  1647. defined values of out-of-range results. In GCC 8, it disables
  1648. optimizations that are based on assuming signed integer operations
  1649. will not overflow.
  1650. @item -ftrapv
  1651. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1652. This terminates the program unless the program handles the signal.
  1653. @xref{Signals}.
  1654. @end table
  1655. One other option is useful for finding where overflow occurs:
  1656. @ignore
  1657. @item -fno-strict-overflow
  1658. Disable optimizations that are based on assuming signed integer
  1659. operations will not overflow.
  1660. @end ignore
  1661. @table @option
  1662. @item -fsanitize=signed-integer-overflow
  1663. Output a warning message at run time when signed integer overflow
  1664. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1665. This takes priority over @option{-ftrapv}.
  1666. @end table
  1667. @node Mixed Mode
  1668. @section Mixed-Mode Arithmetic
  1669. Mixing integers and floating-point numbers in a basic arithmetic
  1670. operation converts the integers automatically to floating point.
  1671. In most cases, this gives exactly the desired results.
  1672. But sometimes it matters precisely where the conversion occurs.
  1673. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1674. as an integer, then converts the sum to floating point for the
  1675. multiplication. If the addition gets an overflow, that is not
  1676. equivalent to converting both integers to floating point and then
  1677. adding them. You can get the latter result by explicitly converting
  1678. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1679. @xref{Explicit Type Conversion}.
  1680. @c Eggert's report
  1681. Adding or multiplying several values, including some integers and some
  1682. floating point, does the operations left to right. Thus, @code{3.0 +
  1683. i + j} converts @code{i} to floating point, then adds 3.0, then
  1684. converts @code{j} to floating point and adds that. You can specify a
  1685. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1686. and @code{j} first and then adds that result (converting to floating
  1687. point) to 3.0. In this respect, C differs from other languages, such
  1688. as Fortran.
  1689. @node Division and Remainder
  1690. @section Division and Remainder
  1691. @cindex remainder operator
  1692. @cindex modulus
  1693. @cindex operator, remainder
  1694. Division of integers in C rounds the result to an integer. The result
  1695. is always rounded towards zero.
  1696. @example
  1697. 16 / 3 @result{} 5
  1698. -16 / 3 @result{} -5
  1699. 16 / -3 @result{} -5
  1700. -16 / -3 @result{} 5
  1701. @end example
  1702. @noindent
  1703. To get the corresponding remainder, use the @samp{%} operator:
  1704. @example
  1705. 16 % 3 @result{} 1
  1706. -16 % 3 @result{} -1
  1707. 16 % -3 @result{} 1
  1708. -16 % -3 @result{} -1
  1709. @end example
  1710. @noindent
  1711. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1712. From the rounded quotient and the remainder, you can reconstruct
  1713. the dividend, like this:
  1714. @example
  1715. int
  1716. original_dividend (int divisor, int quotient, int remainder)
  1717. @{
  1718. return divisor * quotient + remainder;
  1719. @}
  1720. @end example
  1721. To do unrounded division, use floating point. If only one operand is
  1722. floating point, @samp{/} converts the other operand to floating
  1723. point.
  1724. @example
  1725. 16.0 / 3 @result{} 5.333333333333333
  1726. 16 / 3.0 @result{} 5.333333333333333
  1727. 16.0 / 3.0 @result{} 5.333333333333333
  1728. 16 / 3 @result{} 5
  1729. @end example
  1730. The remainder operator @samp{%} is not allowed for floating-point
  1731. operands, because it is not needed. The concept of remainder makes
  1732. sense for integers because the result of division of integers has to
  1733. be an integer. For floating point, the result of division is a
  1734. floating-point number, in other words a fraction, which will differ
  1735. from the exact result only by a very small amount.
  1736. There are functions in the standard C library to calculate remainders
  1737. from integral-values division of floating-point numbers.
  1738. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1739. Reference Manual}.
  1740. Integer division overflows in one specific case: dividing the smallest
  1741. negative value for the data type (@pxref{Maximum and Minimum Values})
  1742. by @minus{}1. That's because the correct result, which is the
  1743. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1744. in the same number of bits. On some computers now in use, this always
  1745. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1746. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1747. Division by zero leads to unpredictable results---depending on the
  1748. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1749. produce a numeric result.
  1750. @cindex division by zero
  1751. @cindex zero, division by
  1752. @strong{Watch out:} Make sure the program does not divide by zero. If
  1753. you can't prove that the divisor is not zero, test whether it is zero,
  1754. and skip the division if so.
  1755. @node Numeric Comparisons
  1756. @section Numeric Comparisons
  1757. @cindex numeric comparisons
  1758. @cindex comparisons
  1759. @cindex operators, comparison
  1760. @cindex equal operator
  1761. @cindex not-equal operator
  1762. @cindex less-than operator
  1763. @cindex greater-than operator
  1764. @cindex less-or-equal operator
  1765. @cindex greater-or-equal operator
  1766. @cindex operator, equal
  1767. @cindex operator, not-equal
  1768. @cindex operator, less-than
  1769. @cindex operator, greater-than
  1770. @cindex operator, less-or-equal
  1771. @cindex operator, greater-or-equal
  1772. @cindex truth value
  1773. There are two kinds of comparison operators: @dfn{equality} and
  1774. @dfn{ordering}. Equality comparisons test whether two expressions
  1775. have the same value. The result is a @dfn{truth value}: a number that
  1776. is 1 for ``true'' and 0 for ``false.''
  1777. @example
  1778. a == b /* @r{Test for equal.} */
  1779. a != b /* @r{Test for not equal.} */
  1780. @end example
  1781. The equality comparison is written @code{==} because plain @code{=}
  1782. is the assignment operator.
  1783. Ordering comparisons test which operand is greater or less. Their
  1784. results are truth values. These are the ordering comparisons of C:
  1785. @example
  1786. a < b /* @r{Test for less-than.} */
  1787. a > b /* @r{Test for greater-than.} */
  1788. a <= b /* @r{Test for less-than-or-equal.} */
  1789. a >= b /* @r{Test for greater-than-or-equal.} */
  1790. @end example
  1791. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1792. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1793. mathematics. However, if @code{a} and @code{b} are special floating
  1794. point values (not ordinary numbers), all three can be false.
  1795. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1796. @node Shift Operations
  1797. @section Shift Operations
  1798. @cindex shift operators
  1799. @cindex operators, shift
  1800. @cindex operators, shift
  1801. @cindex shift count
  1802. @dfn{Shifting} an integer means moving the bit values to the left or
  1803. right within the bits of the data type. Shifting is defined only for
  1804. integers. Here's the way to write it:
  1805. @example
  1806. /* @r{Left shift.} */
  1807. 5 << 2 @result{} 20
  1808. /* @r{Right shift.} */
  1809. 5 >> 2 @result{} 1
  1810. @end example
  1811. @noindent
  1812. The left operand is the value to be shifted, and the right operand
  1813. says how many bits to shift it (the @dfn{shift count}). The left
  1814. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1815. operates on a narrow integer type; it's always either @code{int} or
  1816. wider. The value of the shift operator has the same type as the
  1817. promoted left operand.
  1818. @menu
  1819. * Bits Shifted In:: How shifting makes new bits to shift in.
  1820. * Shift Caveats:: Caveats of shift operations.
  1821. * Shift Hacks:: Clever tricks with shift operations.
  1822. @end menu
  1823. @node Bits Shifted In
  1824. @subsection Shifting Makes New Bits
  1825. A shift operation shifts towards one end of the number and has to
  1826. generate new bits at the other end.
  1827. Shifting left one bit must generate a new least significant bit. It
  1828. always brings in zero there. It is equivalent to multiplying by the
  1829. appropriate power of 2. For example,
  1830. @example
  1831. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1832. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1833. @end example
  1834. The meaning of shifting right depends on whether the data type is
  1835. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1836. data type, it performs ``arithmetic shift,'' which keeps the number's
  1837. sign unchanged by duplicating the sign bit. For an unsigned data
  1838. type, it performs ``logical shift,'' which always shifts in zeros at
  1839. the most significant bit.
  1840. In both cases, shifting right one bit is division by two, rounding
  1841. towards negative infinity. For example,
  1842. @example
  1843. (unsigned) 19 >> 2 @result{} 4
  1844. (unsigned) 20 >> 2 @result{} 5
  1845. (unsigned) 21 >> 2 @result{} 5
  1846. @end example
  1847. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1848. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1849. zero.
  1850. The shift count must be zero or greater. Shifting by a negative
  1851. number of bits gives machine-dependent results.
  1852. @node Shift Caveats
  1853. @subsection Caveats for Shift Operations
  1854. @strong{Warning:} If the shift count is greater than or equal to the
  1855. width in bits of the first operand, the results are machine-dependent.
  1856. Logically speaking, the ``correct'' value would be either -1 (for
  1857. right shift of a negative number) or 0 (in all other cases), but what
  1858. it really generates is whatever the machine's shift instruction does in
  1859. that case. So unless you can prove that the second operand is not too
  1860. large, write code to check it at run time.
  1861. @strong{Warning:} Never rely on how the shift operators relate in
  1862. precedence to other arithmetic binary operators. Programmers don't
  1863. remember these precedences, and won't understand the code. Always use
  1864. parentheses to explicitly specify the nesting, like this:
  1865. @example
  1866. a + (b << 5) /* @r{Shift first, then add.} */
  1867. (a + b) << 5 /* @r{Add first, then shift.} */
  1868. @end example
  1869. Note: according to the C standard, shifting of signed values isn't
  1870. guaranteed to work properly when the value shifted is negative, or
  1871. becomes negative during the operation of shifting left. However, only
  1872. pedants have a reason to be concerned about this; only computers with
  1873. strange shift instructions could plausibly do this wrong. In GNU C,
  1874. the operation always works as expected,
  1875. @node Shift Hacks
  1876. @subsection Shift Hacks
  1877. You can use the shift operators for various useful hacks. For
  1878. example, given a date specified by day of the month @code{d}, month
  1879. @code{m}, and year @code{y}, you can store the entire date in a single
  1880. integer @code{date}:
  1881. @example
  1882. unsigned int d = 12;
  1883. unsigned int m = 6;
  1884. unsigned int y = 1983;
  1885. unsigned int date = ((y << 4) + m) << 5) + d;
  1886. @end example
  1887. @noindent
  1888. To extract the original day, month, and year out of
  1889. @code{date}, use a combination of shift and remainder.
  1890. @example
  1891. d = date % 32;
  1892. m = (date >> 5) % 16;
  1893. y = date >> 9;
  1894. @end example
  1895. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1896. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1897. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1898. multiplication, since negating a value is equivalent to multiplying it
  1899. by @minus{}1.
  1900. @node Bitwise Operations
  1901. @section Bitwise Operations
  1902. @cindex bitwise operators
  1903. @cindex operators, bitwise
  1904. @cindex negation, bitwise
  1905. @cindex conjunction, bitwise
  1906. @cindex disjunction, bitwise
  1907. Bitwise operators operate on integers, treating each bit independently.
  1908. They are not allowed for floating-point types.
  1909. The examples in this section use binary constants, starting with
  1910. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1911. of type @code{int}.
  1912. @table @code
  1913. @item ~@code{a}
  1914. Unary operator for bitwise negation; this changes each bit of
  1915. @code{a} from 1 to 0 or from 0 to 1.
  1916. @example
  1917. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1918. ~0 @result{} 0b11111111111111111111111111111111
  1919. ~0b11111111111111111111111111111111 @result{} 0
  1920. ~ (-1) @result{} 0
  1921. @end example
  1922. It is useful to remember that @code{~@var{x} + 1} equals
  1923. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1924. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1925. as @var{x}.
  1926. @item @code{a} & @code{b}
  1927. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1928. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1929. @example
  1930. 0b10101010 & 0b11001100 @result{} 0b10001000
  1931. @end example
  1932. @item @code{a} | @code{b}
  1933. Binary operator for bitwise ``or'' (``inclusive or'' or
  1934. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1935. either @code{a} or @code{b}.
  1936. @example
  1937. 0b10101010 | 0b11001100 @result{} 0b11101110
  1938. @end example
  1939. @item @code{a} ^ @code{b}
  1940. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1941. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1942. @example
  1943. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1944. @end example
  1945. @end table
  1946. To understand the effect of these operators on signed integers, keep
  1947. in mind that all modern computers use two's-complement representation
  1948. (@pxref{Integer Representations}) for negative integers. This means
  1949. that the highest bit of the number indicates the sign; it is 1 for a
  1950. negative number and 0 for a positive number. In a negative number,
  1951. the value in the other bits @emph{increases} as the number gets closer
  1952. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1953. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1954. @strong{Warning:} C defines a precedence ordering for the bitwise
  1955. binary operators, but you should never rely on it. You should
  1956. never rely on how bitwise binary operators relate in precedence to the
  1957. arithmetic and shift binary operators. Other programmers don't
  1958. remember this precedence ordering, so always use parentheses to
  1959. explicitly specify the nesting.
  1960. For example, suppose @code{offset} is an integer that specifies
  1961. the offset within shared memory of a table, except that its bottom few
  1962. bits (@code{LOWBITS} says how many) are special flags. Here's
  1963. how to get just that offset and add it to the base address.
  1964. @example
  1965. shared_mem_base + (offset & (-1 << LOWBITS))
  1966. @end example
  1967. Thanks to the outer set of parentheses, we don't need to know whether
  1968. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1969. set, we don't need to know whether @samp{&} has higher precedence than
  1970. @samp{<<}. But we can rely on all unary operators to have higher
  1971. precedence than any binary operator, so we don't need parentheses
  1972. around the left operand of @samp{<<}.
  1973. @node Assignment Expressions
  1974. @chapter Assignment Expressions
  1975. @cindex assignment expressions
  1976. @cindex operators, assignment
  1977. As a general concept in programming, an @dfn{assignment} is a
  1978. construct that stores a new value into a place where values can be
  1979. stored---for instance, in a variable. Such places are called
  1980. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1981. An assignment in C is an expression because it has a value; we call
  1982. it an @dfn{assignment expression}. A simple assignment looks like
  1983. @example
  1984. @var{lvalue} = @var{value-to-store}
  1985. @end example
  1986. @noindent
  1987. We say it assigns the value of the expression @var{value-to-store} to
  1988. the location @var{lvalue}, or that it stores @var{value-to-store}
  1989. there. You can think of the ``l'' in ``lvalue'' as standing for
  1990. ``left,'' since that's what you put on the left side of the assignment
  1991. operator.
  1992. However, that's not the only way to use an lvalue, and not all lvalues
  1993. can be assigned to. To use the lvalue in the left side of an
  1994. assignment, it has to be @dfn{modifiable}. In C, that means it was
  1995. not declared with the type qualifier @code{const} (@pxref{const}).
  1996. The value of the assignment expression is that of @var{lvalue} after
  1997. the new value is stored in it. This means you can use an assignment
  1998. inside other expressions. Assignment operators are right-associative
  1999. so that
  2000. @example
  2001. x = y = z = 0;
  2002. @end example
  2003. @noindent
  2004. is equivalent to
  2005. @example
  2006. x = (y = (z = 0));
  2007. @end example
  2008. This is the only useful way for them to associate;
  2009. the other way,
  2010. @example
  2011. ((x = y) = z) = 0;
  2012. @end example
  2013. @noindent
  2014. would be invalid since an assignment expression such as @code{x = y}
  2015. is not valid as an lvalue.
  2016. @strong{Warning:} Write parentheses around an assignment if you nest
  2017. it inside another expression, unless that is a conditional expression,
  2018. or comma-separated series, or another assignment.
  2019. @menu
  2020. * Simple Assignment:: The basics of storing a value.
  2021. * Lvalues:: Expressions into which a value can be stored.
  2022. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2023. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2024. an lvalue's contents.
  2025. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2026. * Assignment in Subexpressions:: How to avoid ambiguity.
  2027. * Write Assignments Separately:: Write assignments as separate statements.
  2028. @end menu
  2029. @node Simple Assignment
  2030. @section Simple Assignment
  2031. @cindex simple assignment
  2032. @cindex assignment, simple
  2033. A @dfn{simple assignment expression} computes the value of the right
  2034. operand and stores it into the lvalue on the left. Here is a simple
  2035. assignment expression that stores 5 in @code{i}:
  2036. @example
  2037. i = 5
  2038. @end example
  2039. @noindent
  2040. We say that this is an @dfn{assignment to} the variable @code{i} and
  2041. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2042. because it is an expression (so it has a value). Adding a semicolon
  2043. at the end would make it a statement (@pxref{Expression Statement}).
  2044. Here is another example of a simple assignment expression. Its
  2045. operands are not simple, but the kind of assignment done here is
  2046. simple assignment.
  2047. @example
  2048. x[foo ()] = y + 6
  2049. @end example
  2050. A simple assignment with two different numeric data types converts the
  2051. right operand value to the lvalue's type, if possible. It can convert
  2052. any numeric type to any other numeric type.
  2053. Simple assignment is also allowed on some non-numeric types: pointers
  2054. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2055. unions (@pxref{Unions}).
  2056. @strong{Warning:} Assignment is not allowed on arrays because
  2057. there are no array values in C; C variables can be arrays, but these
  2058. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2059. Arrays}.
  2060. @xref{Assignment Type Conversions}, for the complete rules about data
  2061. types used in assignments.
  2062. @node Lvalues
  2063. @section Lvalues
  2064. @cindex lvalues
  2065. An expression that identifies a memory space that holds a value is
  2066. called an @dfn{lvalue}, because it is a location that can hold a value.
  2067. The standard kinds of lvalues are:
  2068. @itemize @bullet
  2069. @item
  2070. A variable.
  2071. @item
  2072. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2073. unary @samp{*}.
  2074. @item
  2075. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2076. the structure value is an lvalue.
  2077. @item
  2078. A structure field reference using @samp{->}. This is always an lvalue
  2079. since @samp{->} implies pointer dereference.
  2080. @item
  2081. A union alternative reference (@pxref{Unions}), on the same conditions
  2082. as for structure fields.
  2083. @item
  2084. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2085. is an lvalue.
  2086. @end itemize
  2087. If an expression's outermost operation is any other operator, that
  2088. expression is not an lvalue. Thus, the variable @code{x} is an
  2089. lvalue, but @code{x + 0} is not, even though these two expressions
  2090. compute the same value (assuming @code{x} is a number).
  2091. An array can be an lvalue (the rules above determine whether it is
  2092. one), but using the array in an expression converts it automatically
  2093. to a pointer to the first element. The result of this conversion is
  2094. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2095. use @code{a} by itself as the left operand of an assignment. But you
  2096. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2097. lvalue since @code{a} is an lvalue.
  2098. @node Modifying Assignment
  2099. @section Modifying Assignment
  2100. @cindex modifying assignment
  2101. @cindex assignment, modifying
  2102. You can abbreviate the common construct
  2103. @example
  2104. @var{lvalue} = @var{lvalue} + @var{expression}
  2105. @end example
  2106. @noindent
  2107. as
  2108. @example
  2109. @var{lvalue} += @var{expression}
  2110. @end example
  2111. This is known as a @dfn{modifying assignment}. For instance,
  2112. @example
  2113. i = i + 5;
  2114. i += 5;
  2115. @end example
  2116. @noindent
  2117. shows two statements that are equivalent. The first uses
  2118. simple assignment; the second uses modifying assignment.
  2119. Modifying assignment works with any binary arithmetic operator. For
  2120. instance, you can subtract something from an lvalue like this,
  2121. @example
  2122. @var{lvalue} -= @var{expression}
  2123. @end example
  2124. @noindent
  2125. or multiply it by a certain amount like this,
  2126. @example
  2127. @var{lvalue} *= @var{expression}
  2128. @end example
  2129. @noindent
  2130. or shift it by a certain amount like this.
  2131. @example
  2132. @var{lvalue} <<= @var{expression}
  2133. @var{lvalue} >>= @var{expression}
  2134. @end example
  2135. In most cases, this feature adds no power to the language, but it
  2136. provides substantial convenience. Also, when @var{lvalue} contains
  2137. code that has side effects, the simple assignment performs those side
  2138. effects twice, while the modifying assignment performs them once. For
  2139. instance,
  2140. @example
  2141. x[foo ()] = x[foo ()] + 5;
  2142. @end example
  2143. @noindent
  2144. calls @code{foo} twice, and it could return different values each
  2145. time. If @code{foo ()} returns 1 the first time and 3 the second
  2146. time, then the effect could be to add @code{x[3]} and 5 and store the
  2147. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2148. result in @code{x[3]}. We don't know which of the two it will do,
  2149. because C does not specify which call to @code{foo} is computed first.
  2150. Such a statement is not well defined, and shouldn't be used.
  2151. By contrast,
  2152. @example
  2153. x[foo ()] += 5;
  2154. @end example
  2155. @noindent
  2156. is well defined: it calls @code{foo} only once to determine which
  2157. element of @code{x} to adjust, and it adjusts that element by adding 5
  2158. to it.
  2159. @node Increment/Decrement
  2160. @section Increment and Decrement Operators
  2161. @cindex increment operator
  2162. @cindex decrement operator
  2163. @cindex operator, increment
  2164. @cindex operator, decrement
  2165. @cindex preincrement expression
  2166. @cindex predecrement expression
  2167. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2168. @dfn{decrement} operators. When used on a numeric value, they add or
  2169. subtract 1. We don't consider them assignments, but they are
  2170. equivalent to assignments.
  2171. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2172. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2173. and the result becomes the expression's value. For instance,
  2174. @example
  2175. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2176. int
  2177. main (void)
  2178. @{
  2179. int i = 5;
  2180. printf ("%d\n", i);
  2181. printf ("%d\n", ++i);
  2182. printf ("%d\n", i);
  2183. return 0;
  2184. @}
  2185. @end example
  2186. @noindent
  2187. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2188. increments @code{i} from 5 to 6, and has the value 6, so the output
  2189. from @code{printf} on that line says @samp{6}.
  2190. Using @samp{--} instead, for predecrement,
  2191. @example
  2192. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2193. int
  2194. main (void)
  2195. @{
  2196. int i = 5;
  2197. printf ("%d\n", i);
  2198. printf ("%d\n", --i);
  2199. printf ("%d\n", i);
  2200. return 0;
  2201. @}
  2202. @end example
  2203. @noindent
  2204. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2205. again @samp{4}.
  2206. @node Postincrement/Postdecrement
  2207. @section Postincrement and Postdecrement
  2208. @cindex postincrement expression
  2209. @cindex postdecrement expression
  2210. @cindex operator, postincrement
  2211. @cindex operator, postdecrement
  2212. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2213. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2214. increments or decrement it. Thus, the value of @code{i++} is the same
  2215. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2216. little later.'' This is called @dfn{postincrement} or
  2217. @dfn{postdecrement}.
  2218. For example,
  2219. @example
  2220. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2221. int
  2222. main (void)
  2223. @{
  2224. int i = 5;
  2225. printf ("%d\n", i);
  2226. printf ("%d\n", i++);
  2227. printf ("%d\n", i);
  2228. return 0;
  2229. @}
  2230. @end example
  2231. @noindent
  2232. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2233. has the value 5, which is the value of @code{i} at the time,
  2234. but it increments @code{i} from 5 to 6 just a little later.
  2235. How much later is ``just a little later''? That is flexible. The
  2236. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2237. that means by the end of the statement. @xref{Sequence Points}.
  2238. If a unary operator precedes a postincrement or postincrement expression,
  2239. the increment nests inside:
  2240. @example
  2241. -a++ @r{is equivalent to} -(a++)
  2242. @end example
  2243. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2244. it can't be incremented.
  2245. @node Assignment in Subexpressions
  2246. @section Pitfall: Assignment in Subexpressions
  2247. @cindex assignment in subexpressions
  2248. @cindex subexpressions, assignment in
  2249. In C, the order of computing parts of an expression is not fixed.
  2250. Aside from a few special cases, the operations can be computed in any
  2251. order. If one part of the expression has an assignment to @code{x}
  2252. and another part of the expression uses @code{x}, the result is
  2253. unpredictable because that use might be computed before or after the
  2254. assignment.
  2255. Here's an example of ambiguous code:
  2256. @example
  2257. x = 20;
  2258. printf ("%d %d\n", x, x = 4);
  2259. @end example
  2260. @noindent
  2261. If the second argument, @code{x}, is computed before the third argument,
  2262. @code{x = 4}, the second argument's value will be 20. If they are
  2263. computed in the other order, the second argument's value will be 4.
  2264. Here's one way to make that code unambiguous:
  2265. @example
  2266. y = 20;
  2267. printf ("%d %d\n", y, x = 4);
  2268. @end example
  2269. Here's another way, with the other meaning:
  2270. @example
  2271. x = 4;
  2272. printf ("%d %d\n", x, x);
  2273. @end example
  2274. This issue applies to all kinds of assignments, and to the increment
  2275. and decrement operators, which are equivalent to assignments.
  2276. @xref{Order of Execution}, for more information about this.
  2277. However, it can be useful to write assignments inside an
  2278. @code{if}-condition or @code{while}-test along with logical operators.
  2279. @xref{Logicals and Assignments}.
  2280. @node Write Assignments Separately
  2281. @section Write Assignments in Separate Statements
  2282. It is often convenient to write an assignment inside an
  2283. @code{if}-condition, but that can reduce the readability of the
  2284. program. Here's an example of what to avoid:
  2285. @example
  2286. if (x = advance (x))
  2287. @r{@dots{}}
  2288. @end example
  2289. The idea here is to advance @code{x} and test if the value is nonzero.
  2290. However, readers might miss the fact that it uses @samp{=} and not
  2291. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2292. inside a condition is a common error, so GNU C can give warnings when
  2293. @samp{=} appears in a way that suggests it's an error.
  2294. It is much clearer to write the assignment as a separate statement, like this:
  2295. @example
  2296. x = advance (x);
  2297. if (x != 0)
  2298. @r{@dots{}}
  2299. @end example
  2300. @noindent
  2301. This makes it unmistakably clear that @code{x} is assigned a new value.
  2302. Another method is to use the comma operator (@pxref{Comma Operator}),
  2303. like this:
  2304. @example
  2305. if (x = advance (x), x != 0)
  2306. @r{@dots{}}
  2307. @end example
  2308. @noindent
  2309. However, putting the assignment in a separate statement is usually clearer
  2310. unless the assignment is very short, because it reduces nesting.
  2311. @node Execution Control Expressions
  2312. @chapter Execution Control Expressions
  2313. @cindex execution control expressions
  2314. @cindex expressions, execution control
  2315. This chapter describes the C operators that combine expressions to
  2316. control which of those expressions execute, or in which order.
  2317. @menu
  2318. * Logical Operators:: Logical conjunction, disjunction, negation.
  2319. * Logicals and Comparison:: Logical operators with comparison operators.
  2320. * Logicals and Assignments:: Assignments with logical operators.
  2321. * Conditional Expression:: An if/else construct inside expressions.
  2322. * Comma Operator:: Build a sequence of subexpressions.
  2323. @end menu
  2324. @node Logical Operators
  2325. @section Logical Operators
  2326. @cindex logical operators
  2327. @cindex operators, logical
  2328. @cindex conjunction operator
  2329. @cindex disjunction operator
  2330. @cindex negation operator, logical
  2331. The @dfn{logical operators} combine truth values, which are normally
  2332. represented in C as numbers. Any expression with a numeric value is a
  2333. valid truth value: zero means false, and any other value means true.
  2334. A pointer type is also meaningful as a truth value; a null pointer
  2335. (which is zero) means false, and a non-null pointer means true
  2336. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2337. or 0 and has type @code{int} (@pxref{Integer Types}).
  2338. The logical operators are used mainly in the condition of an @code{if}
  2339. statement, or in the end test in a @code{for} statement or
  2340. @code{while} statement (@pxref{Statements}). However, they are valid
  2341. in any context where an integer-valued expression is allowed.
  2342. @table @samp
  2343. @item ! @var{exp}
  2344. Unary operator for logical ``not.'' The value is 1 (true) if
  2345. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2346. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2347. function call, you should write parentheses around it.
  2348. @item @var{left} && @var{right}
  2349. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2350. @var{right}. If both of the operands are true, the @samp{&&} expression
  2351. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2352. gives the value 0 (false). If @var{left} yields a false value,
  2353. that determines the overall result, so @var{right} is not computed.
  2354. @item @var{left} || @var{right}
  2355. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2356. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2357. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2358. gives the value 0 (false). If @var{left} yields a true value,
  2359. that determines the overall result, so @var{right} is not computed.
  2360. @end table
  2361. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2362. and @samp{||}. When you use them together, always use parentheses to
  2363. specify explicitly how they nest, as shown here:
  2364. @example
  2365. if ((r != 0 && x % r == 0)
  2366. ||
  2367. (s != 0 && x % s == 0))
  2368. @end example
  2369. @node Logicals and Comparison
  2370. @section Logical Operators and Comparisons
  2371. The most common thing to use inside the logical operators is a
  2372. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2373. precedence than comparison operators and arithmetic operators, so we
  2374. can write expressions like this without parentheses and get the
  2375. nesting that is natural: two comparison operations that must both be
  2376. true.
  2377. @example
  2378. if (r != 0 && x % r == 0)
  2379. @end example
  2380. @noindent
  2381. This example also shows how it is useful that @samp{&&} guarantees to
  2382. skip the right operand if the left one turns out false. Because of
  2383. that, this code never tries to divide by zero.
  2384. This is equivalent:
  2385. @example
  2386. if (r && x % r == 0)
  2387. @end example
  2388. @noindent
  2389. A truth value is simply a number, so @code{r}
  2390. as a truth value tests whether it is nonzero.
  2391. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2392. So it is better style to write the explicit @code{!= 0}.
  2393. Here's another equivalent way to write it:
  2394. @example
  2395. if (!(r == 0) && x % r == 0)
  2396. @end example
  2397. @noindent
  2398. This illustrates the unary @samp{!} operator, and the need to
  2399. write parentheses around its operand.
  2400. @node Logicals and Assignments
  2401. @section Logical Operators and Assignments
  2402. There are cases where assignments nested inside the condition can
  2403. actually make a program @emph{easier} to read. Here is an example
  2404. using a hypothetical type @code{list} which represents a list; it
  2405. tests whether the list has at least two links, using hypothetical
  2406. functions, @code{nonempty} which is true of the argument is a nonempty
  2407. list, and @code{list_next} which advances from one list link to the
  2408. next. We assume that a list is never a null pointer, so that the
  2409. assignment expressions are always ``true.''
  2410. @example
  2411. if (nonempty (list)
  2412. && (temp1 = list_next (list))
  2413. && nonempty (temp1)
  2414. && (temp2 = list_next (temp1)))
  2415. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2416. @end example
  2417. @noindent
  2418. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2419. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2420. only natural place to put the assignments is among those calls.
  2421. It would be possible to rewrite this as several statements, but that
  2422. could make it much more cumbersome. On the other hand, when the test
  2423. is even more complex than this one, splitting it into multiple
  2424. statements might be necessary for clarity.
  2425. If an empty list is a null pointer, we can dispense with calling
  2426. @code{nonempty}:
  2427. @example
  2428. if ((temp1 = list_next (list))
  2429. && (temp2 = list_next (temp1)))
  2430. @r{@dots{}}
  2431. @end example
  2432. @node Conditional Expression
  2433. @section Conditional Expression
  2434. @cindex conditional expression
  2435. @cindex expression, conditional
  2436. C has a conditional expression that selects one of two expressions
  2437. to compute and get the value from. It looks like this:
  2438. @example
  2439. @var{condition} ? @var{iftrue} : @var{iffalse}
  2440. @end example
  2441. @menu
  2442. * Conditional Rules:: Rules for the conditional operator.
  2443. * Conditional Branches:: About the two branches in a conditional.
  2444. @end menu
  2445. @node Conditional Rules
  2446. @subsection Rules for Conditional Operator
  2447. The first operand, @var{condition}, should be a value that can be
  2448. compared with zero---a number or a pointer. If it is true (nonzero),
  2449. then the conditional expression computes @var{iftrue} and its value
  2450. becomes the value of the conditional expression. Otherwise the
  2451. conditional expression computes @var{iffalse} and its value becomes
  2452. the value of the conditional expression. The conditional expression
  2453. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2454. of them.
  2455. Here's an example: the absolute value of a number @code{x}
  2456. can be written as @code{(x >= 0 ? x : -x)}.
  2457. @strong{Warning:} The conditional expression operators have rather low
  2458. syntactic precedence. Except when the conditional expression is used
  2459. as an argument in a function call, write parentheses around it. For
  2460. clarity, always write parentheses around it if it extends across more
  2461. than one line.
  2462. Assignment operators and the comma operator (@pxref{Comma Operator})
  2463. have lower precedence than conditional expression operators, so write
  2464. parentheses around those when they appear inside a conditional
  2465. expression. @xref{Order of Execution}.
  2466. @node Conditional Branches
  2467. @subsection Conditional Operator Branches
  2468. @cindex branches of conditional expression
  2469. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2470. conditional.
  2471. The two branches should normally have the same type, but a few
  2472. exceptions are allowed. If they are both numeric types, the
  2473. conditional converts both to their common type (@pxref{Common Type}).
  2474. With pointers (@pxref{Pointers}), the two values can be pointers to
  2475. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2476. result type is a similar pointer whose target type combines all the
  2477. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2478. If one branch has type @code{void *} and the other is a pointer to an
  2479. object (not to a function), the conditional converts the @code{void *}
  2480. branch to the type of the other.
  2481. If one branch is an integer constant with value zero and the other is
  2482. a pointer, the conditional converts zero to the pointer's type.
  2483. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2484. that case, if @var{condition} is nonzero, its value becomes the value of
  2485. the conditional expression, after conversion to the common type.
  2486. Thus,
  2487. @example
  2488. x ? : y
  2489. @end example
  2490. @noindent
  2491. has the value of @code{x} if that is nonzero; otherwise, the value of
  2492. @code{y}.
  2493. @cindex side effect in ?:
  2494. @cindex ?: side effect
  2495. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2496. In that case, writing that expression twice would carry out the side
  2497. effects twice, but writing it once does them just once. For example,
  2498. if we suppose that the function @code{next_element} advances a pointer
  2499. variable to point to the next element in a list and returns the new
  2500. pointer,
  2501. @example
  2502. next_element () ? : default_pointer
  2503. @end example
  2504. @noindent
  2505. is a way to advance the pointer and use its new value if it isn't
  2506. null, but use @code{default_pointer} if that is null. We must not do
  2507. it this way,
  2508. @example
  2509. next_element () ? next_element () : default_pointer
  2510. @end example
  2511. @noindent
  2512. because it would advance the pointer a second time.
  2513. @node Comma Operator
  2514. @section Comma Operator
  2515. @cindex comma operator
  2516. @cindex operator, comma
  2517. The comma operator stands for sequential execution of expressions.
  2518. The value of the comma expression comes from the last expression in
  2519. the sequence; the previous expressions are computed only for their
  2520. side effects. It looks like this:
  2521. @example
  2522. @var{exp1}, @var{exp2} @r{@dots{}}
  2523. @end example
  2524. @noindent
  2525. You can bundle any number of expressions together this way, by putting
  2526. commas between them.
  2527. @menu
  2528. * Uses of Comma:: When to use the comma operator.
  2529. * Clean Comma:: Clean use of the comma operator.
  2530. * Avoid Comma:: When to not use the comma operator.
  2531. @end menu
  2532. @node Uses of Comma
  2533. @subsection The Uses of the Comma Operator
  2534. With commas, you can put several expressions into a place that
  2535. requires just one expression---for example, in the header of a
  2536. @code{for} statement. This statement
  2537. @example
  2538. for (i = 0, j = 10, k = 20; i < n; i++)
  2539. @end example
  2540. @noindent
  2541. contains three assignment expressions, to initialize @code{i}, @code{j}
  2542. and @code{k}. The syntax of @code{for} requires just one expression
  2543. for initialization; to include three assignments, we use commas to
  2544. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2545. 20}. This technique is also useful in the loop-advance expression,
  2546. the last of the three inside the @code{for} parentheses.
  2547. In the @code{for} statement and the @code{while} statement
  2548. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2549. effect before the loop-exit test. For example,
  2550. @example
  2551. while (printf ("At the test, x = %d\n", x), x != 0)
  2552. @end example
  2553. @node Clean Comma
  2554. @subsection Clean Use of the Comma Operator
  2555. Always write parentheses around a series of comma operators, except
  2556. when it is at top level in an expression statement, or within the
  2557. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2558. statement (@pxref{Statements}). For instance, in
  2559. @example
  2560. for (i = 0, j = 10, k = 20; i < n; i++)
  2561. @end example
  2562. @noindent
  2563. the commas between the assignments are clear because they are between
  2564. a parenthesis and a semicolon.
  2565. The arguments in a function call are also separated by commas, but that is
  2566. not an instance of the comma operator. Note the difference between
  2567. @example
  2568. foo (4, 5, 6)
  2569. @end example
  2570. @noindent
  2571. which passes three arguments to @code{foo} and
  2572. @example
  2573. foo ((4, 5, 6))
  2574. @end example
  2575. @noindent
  2576. which uses the comma operator and passes just one argument
  2577. (with value 6).
  2578. @strong{Warning:} don't use the comma operator around an argument
  2579. of a function unless it helps understand the code. When you do so,
  2580. don't put part of another argument on the same line. Instead, add a
  2581. line break to make the parentheses around the comma operator easier to
  2582. see, like this.
  2583. @example
  2584. foo ((mumble (x, y), frob (z)),
  2585. *p)
  2586. @end example
  2587. @node Avoid Comma
  2588. @subsection When Not to Use the Comma Operator
  2589. You can use a comma in any subexpression, but in most cases it only
  2590. makes the code confusing, and it is clearer to raise all but the last
  2591. of the comma-separated expressions to a higher level. Thus, instead
  2592. of this:
  2593. @example
  2594. x = (y += 4, 8);
  2595. @end example
  2596. @noindent
  2597. it is much clearer to write this:
  2598. @example
  2599. y += 4, x = 8;
  2600. @end example
  2601. @noindent
  2602. or this:
  2603. @example
  2604. y += 4;
  2605. x = 8;
  2606. @end example
  2607. Use commas only in the cases where there is no clearer alternative
  2608. involving multiple statements.
  2609. By contrast, don't hesitate to use commas in the expansion in a macro
  2610. definition. The trade-offs of code clarity are different in that
  2611. case, because the @emph{use} of the macro may improve overall clarity
  2612. so much that the ugliness of the macro's @emph{definition} is a small
  2613. price to pay. @xref{Macros}.
  2614. @node Binary Operator Grammar
  2615. @chapter Binary Operator Grammar
  2616. @cindex binary operator grammar
  2617. @cindex grammar, binary operator
  2618. @cindex operator precedence
  2619. @cindex precedence, operator
  2620. @cindex left-associative
  2621. @dfn{Binary operators} are those that take two operands, one
  2622. on the left and one on the right.
  2623. All the binary operators in C are syntactically left-associative.
  2624. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2625. @var{op} b) @var{op} c}}. However, you should only write repeated
  2626. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2627. @samp{/}, because those cases are clear from algebra. So it is ok to
  2628. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2629. c} or @code{a % b % c}.
  2630. Each C operator has a @dfn{precedence}, which is its rank in the
  2631. grammatical order of the various operators. The operators with the
  2632. highest precedence grab adjoining operands first; these expressions
  2633. then become operands for operators of lower precedence.
  2634. The precedence order of operators in C is fully specified, so any
  2635. combination of operations leads to a well-defined nesting. We state
  2636. only part of the full precedence ordering here because it is bad
  2637. practice for C code to depend on the other cases. For cases not
  2638. specified in this chapter, always use parentheses to make the nesting
  2639. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2640. remembering anything about the C precedence order beyond what's stated
  2641. here. I studied the full precedence table to write the parser, and
  2642. promptly forgot it again. If you need to look up the full precedence order
  2643. to understand some C code, fix the code with parentheses so nobody else
  2644. needs to do that.}
  2645. You can depend on this subsequence of the precedence ordering
  2646. (stated from highest precedence to lowest):
  2647. @enumerate
  2648. @item
  2649. Component access (@samp{.} and @samp{->}).
  2650. @item
  2651. Unary prefix operators.
  2652. @item
  2653. Unary postfix operators.
  2654. @item
  2655. Multiplication, division, and remainder (they have the same precedence).
  2656. @item
  2657. Addition and subtraction (they have the same precedence).
  2658. @item
  2659. Comparisons---but watch out!
  2660. @item
  2661. Logical operators @samp{&&} and @samp{||}---but watch out!
  2662. @item
  2663. Conditional expression with @samp{?} and @samp{:}.
  2664. @item
  2665. Assignments.
  2666. @item
  2667. Sequential execution (the comma operator, @samp{,}).
  2668. @end enumerate
  2669. Two of the lines in the above list say ``but watch out!'' That means
  2670. that the line covers operators with subtly different precedence.
  2671. Never depend on the grammar of C to decide how two comparisons nest;
  2672. instead, always use parentheses to specify their nesting.
  2673. You can let several @samp{&&} operators associate, or several
  2674. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2675. and @samp{||} nest with each other. @xref{Logical Operators}.
  2676. There is one other precedence ordering that code can depend on:
  2677. @enumerate
  2678. @item
  2679. Unary postfix operators.
  2680. @item
  2681. Bitwise and shift operators---but watch out!
  2682. @item
  2683. Conditional expression with @samp{?} and @samp{:}.
  2684. @end enumerate
  2685. The caveat for bitwise and shift operators is like that for logical
  2686. operators: you can let multiple uses of one bitwise operator
  2687. associate, but always use parentheses to control nesting of dissimilar
  2688. operators.
  2689. These lists do not specify any precedence ordering between the bitwise
  2690. and shift operators of the second list and the binary operators above
  2691. conditional expressions in the first list. When they come together,
  2692. parenthesize them. @xref{Bitwise Operations}.
  2693. @node Order of Execution
  2694. @chapter Order of Execution
  2695. @cindex order of execution
  2696. The order of execution of a C program is not always obvious, and not
  2697. necessarily predictable. This chapter describes what you can count on.
  2698. @menu
  2699. * Reordering of Operands:: Operations in C are not necessarily computed
  2700. in the order they are written.
  2701. * Associativity and Ordering:: Some associative operations are performed
  2702. in a particular order; others are not.
  2703. * Sequence Points:: Some guarantees about the order of operations.
  2704. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2705. * Ordering of Operands:: Evaluation order of operands
  2706. and function arguments.
  2707. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2708. only if it has no impact on program results.
  2709. @end menu
  2710. @node Reordering of Operands
  2711. @section Reordering of Operands
  2712. @cindex ordering of operands
  2713. @cindex reordering of operands
  2714. @cindex operand execution ordering
  2715. The C language does not necessarily carry out operations within an
  2716. expression in the order they appear in the code. For instance, in
  2717. this expression,
  2718. @example
  2719. foo () + bar ()
  2720. @end example
  2721. @noindent
  2722. @code{foo} might be called first or @code{bar} might be called first.
  2723. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2724. results can be unpredictable.
  2725. The unpredictable order of computation of subexpressions also makes a
  2726. difference when one of them contains an assignment. We already saw
  2727. this example of bad code,
  2728. @example
  2729. x = 20;
  2730. printf ("%d %d\n", x, x = 4);
  2731. @end example
  2732. @noindent
  2733. in which the second argument, @code{x}, has a different value
  2734. depending on whether it is computed before or after the assignment in
  2735. the third argument.
  2736. @node Associativity and Ordering
  2737. @section Associativity and Ordering
  2738. @cindex associativity and ordering
  2739. An associative binary operator, such as @code{+}, when used repeatedly
  2740. can combine any number of operands. The operands' values may be
  2741. computed in any order.
  2742. If the values are integers and overflow can be ignored, they may be
  2743. combined in any order. Thus, given four functions that return
  2744. @code{unsigned int}, calling them and adding their results as here
  2745. @example
  2746. (foo () + bar ()) + (baz () + quux ())
  2747. @end example
  2748. @noindent
  2749. may add up the results in any order.
  2750. By contrast, arithmetic on signed integers, with overflow significant,
  2751. is not really associative (@pxref{Integer Overflow}). Thus, the
  2752. additions must be done in the order specified, obeying parentheses and
  2753. left-association. That means computing @code{(foo () + bar ())} and
  2754. @code{(baz () + quux ())} first (in either order), then adding the
  2755. two.
  2756. The same applies to arithmetic on floating-point values, since that
  2757. too is not really associative. However, the GCC option
  2758. @option{-funsafe-math-optimizations} allows the compiler to change the
  2759. order of calculation when an associative operation (associative in
  2760. exact mathematics) combines several operands. The option takes effect
  2761. when compiling a module (@pxref{Compilation}). Changing the order
  2762. of association can enable the program to pipeline the floating point
  2763. operations.
  2764. In all these cases, the four function calls can be done in any order.
  2765. There is no right or wrong about that.
  2766. @node Sequence Points
  2767. @section Sequence Points
  2768. @cindex sequence points
  2769. @cindex full expression
  2770. There are some points in the code where C makes limited guarantees
  2771. about the order of operations. These are called @dfn{sequence
  2772. points}. Here is where they occur:
  2773. @itemize @bullet
  2774. @item
  2775. At the end of a @dfn{full expression}; that is to say, an expression
  2776. that is not part of a larger expression. All side effects specified
  2777. by that expression are carried out before execution moves
  2778. on to subsequent code.
  2779. @item
  2780. At the end of the first operand of certain operators: @samp{,},
  2781. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2782. that expression are carried out before any execution of the
  2783. next operand.
  2784. The commas that separate arguments in a function call are @emph{not}
  2785. comma operators, and they do not create sequence points. The rule
  2786. for function arguments and the rule for operands are different
  2787. (@pxref{Ordering of Operands}).
  2788. @item
  2789. Just before calling a function. All side effects specified by the
  2790. argument expressions are carried out before calling the function.
  2791. If the function to be called is not constant---that is, if it is
  2792. computed by an expression---all side effects in that expression are
  2793. carried out before calling the function.
  2794. @end itemize
  2795. The ordering imposed by a sequence point applies locally to a limited
  2796. range of code, as stated above in each case. For instance, the
  2797. ordering imposed by the comma operator does not apply to code outside
  2798. that comma operator. Thus, in this code,
  2799. @example
  2800. (x = 5, foo (x)) + x * x
  2801. @end example
  2802. @noindent
  2803. the sequence point of the comma operator orders @code{x = 5} before
  2804. @code{foo (x)}, but @code{x * x} could be computed before or after
  2805. them.
  2806. @node Postincrement and Ordering
  2807. @section Postincrement and Ordering
  2808. @cindex postincrement and ordering
  2809. @cindex ordering and postincrement
  2810. Ordering requirements are loose with the postincrement and
  2811. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2812. specify side effects to happen ``a little later.'' They must happen
  2813. before the next sequence point, but that still leaves room for various
  2814. meanings. In this expression,
  2815. @example
  2816. z = x++ - foo ()
  2817. @end example
  2818. @noindent
  2819. it's unpredictable whether @code{x} gets incremented before or after
  2820. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2821. it might see the old value or it might see the incremented value.
  2822. In this perverse expression,
  2823. @example
  2824. x = x++
  2825. @end example
  2826. @noindent
  2827. @code{x} will certainly be incremented but the incremented value may
  2828. not stick. If the incrementation of @code{x} happens after the
  2829. assignment to @code{x}, the incremented value will remain in place.
  2830. But if the incrementation happens first, the assignment will overwrite
  2831. that with the not-yet-incremented value, so the expression as a whole
  2832. will leave @code{x} unchanged.
  2833. @node Ordering of Operands
  2834. @section Ordering of Operands
  2835. @cindex ordering of operands
  2836. @cindex operand ordering
  2837. Operands and arguments can be computed in any order, but there are limits to
  2838. this intermixing in GNU C:
  2839. @itemize @bullet
  2840. @item
  2841. The operands of a binary arithmetic operator can be computed in either
  2842. order, but they can't be intermixed: one of them has to come first,
  2843. followed by the other. Any side effects in the operand that's computed
  2844. first are executed before the other operand is computed.
  2845. @item
  2846. That applies to assignment operators too, except that in simple assignment
  2847. the previous value of the left operand is unused.
  2848. @item
  2849. The arguments in a function call can be computed in any order, but
  2850. they can't be intermixed. Thus, one argument is fully computed, then
  2851. another, and so on until they are all done. Any side effects in one argument
  2852. are executed before computation of another argument begins.
  2853. @end itemize
  2854. These rules don't cover side effects caused by postincrement and
  2855. postdecrement operators---those can be deferred up to the next
  2856. sequence point.
  2857. If you want to get pedantic, the fact is that GCC can reorder the
  2858. computations in many other ways provided that doesn't alter the result
  2859. of running the program. However, because they don't alter the result
  2860. of running the program, they are negligible, unless you are concerned
  2861. with the values in certain variables at various times as seen by other
  2862. processes. In those cases, you can use @code{volatile} to prevent
  2863. optimizations that would make them behave strangely. @xref{volatile}.
  2864. @node Optimization and Ordering
  2865. @section Optimization and Ordering
  2866. @cindex optimization and ordering
  2867. @cindex ordering and optimization
  2868. Sequence points limit the compiler's freedom to reorder operations
  2869. arbitrarily, but optimizations can still reorder them if the compiler
  2870. concludes that this won't alter the results. Thus, in this code,
  2871. @example
  2872. x++;
  2873. y = z;
  2874. x++;
  2875. @end example
  2876. @noindent
  2877. there is a sequence point after each statement, so the code is
  2878. supposed to increment @code{x} once before the assignment to @code{y}
  2879. and once after. However, incrementing @code{x} has no effect on
  2880. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2881. the code could be optimized into this:
  2882. @example
  2883. y = z;
  2884. x += 2;
  2885. @end example
  2886. Normally that has no effect except to make the program faster. But
  2887. there are special situations where it can cause trouble due to things
  2888. that the compiler cannot know about, such as shared memory. To limit
  2889. optimization in those places, use the @code{volatile} type qualifier
  2890. (@pxref{volatile}).
  2891. @node Primitive Types
  2892. @chapter Primitive Data Types
  2893. @cindex primitive types
  2894. @cindex types, primitive
  2895. This chapter describes all the primitive data types of C---that is,
  2896. all the data types that aren't built up from other types. They
  2897. include the types @code{int} and @code{double} that we've already covered.
  2898. @menu
  2899. * Integer Types:: Description of integer types.
  2900. * Floating-Point Data Types:: Description of floating-point types.
  2901. * Complex Data Types:: Description of complex number types.
  2902. * The Void Type:: A type indicating no value at all.
  2903. * Other Data Types:: A brief summary of other types.
  2904. * Type Designators:: Referring to a data type abstractly.
  2905. @end menu
  2906. These types are all made up of bytes (@pxref{Storage}).
  2907. @node Integer Types
  2908. @section Integer Data Types
  2909. @cindex integer types
  2910. @cindex types, integer
  2911. Here we describe all the integer types and their basic
  2912. characteristics. @xref{Integers in Depth}, for more information about
  2913. the bit-level integer data representations and arithmetic.
  2914. @menu
  2915. * Basic Integers:: Overview of the various kinds of integers.
  2916. * Signed and Unsigned Types:: Integers can either hold both negative and
  2917. non-negative values, or only non-negative.
  2918. * Narrow Integers:: When to use smaller integer types.
  2919. * Integer Conversion:: Casting a value from one integer type
  2920. to another.
  2921. * Boolean Type:: An integer type for boolean values.
  2922. * Integer Variations:: Sizes of integer types can vary
  2923. across platforms.
  2924. @end menu
  2925. @node Basic Integers
  2926. @subsection Basic Integers
  2927. @findex char
  2928. @findex int
  2929. @findex short int
  2930. @findex long int
  2931. @findex long long int
  2932. Integer data types in C can be signed or unsigned. An unsigned type
  2933. can represent only positive numbers and zero. A signed type can
  2934. represent both positive and negative numbers, in a range spread almost
  2935. equally on both sides of zero.
  2936. Aside from signedness, the integer data types vary in size: how many
  2937. bytes long they are. The size determines how many different integer
  2938. values the type can hold.
  2939. Here's a list of the signed integer data types, with the sizes they
  2940. have on most computers. Each has a corresponding unsigned type; see
  2941. @ref{Signed and Unsigned Types}.
  2942. @table @code
  2943. @item signed char
  2944. One byte (8 bits). This integer type is used mainly for integers that
  2945. represent characters, as part of arrays or other data structures.
  2946. @item short
  2947. @itemx short int
  2948. Two bytes (16 bits).
  2949. @item int
  2950. Four bytes (32 bits).
  2951. @item long
  2952. @itemx long int
  2953. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2954. platform. Typically it is 32 bits on 32-bit computers
  2955. and 64 bits on 64-bit computers, but there are exceptions.
  2956. @item long long
  2957. @itemx long long int
  2958. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2959. incorporated into standard C as of ISO C99.
  2960. @end table
  2961. You can omit @code{int} when you use @code{long} or @code{short}.
  2962. This is harmless and customary.
  2963. @node Signed and Unsigned Types
  2964. @subsection Signed and Unsigned Types
  2965. @cindex signed types
  2966. @cindex unsigned types
  2967. @cindex types, signed
  2968. @cindex types, unsigned
  2969. @findex signed
  2970. @findex unsigned
  2971. An unsigned integer type can represent only positive numbers and zero.
  2972. A signed type can represent both positive and negative number, in a
  2973. range spread almost equally on both sides of zero. For instance,
  2974. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2975. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2976. these types holds 256 different possible values, since they are both 8
  2977. bits wide.
  2978. Write @code{signed} or @code{unsigned} before the type keyword to
  2979. specify a signed or an unsigned type. However, the integer types
  2980. other than @code{char} are signed by default; with them, @code{signed}
  2981. is a no-op.
  2982. Plain @code{char} may be signed or unsigned; this depends on the
  2983. compiler, the machine in use, and its operating system.
  2984. In many programs, it makes no difference whether @code{char} is
  2985. signed. When it does matter, don't leave it to chance; write
  2986. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2987. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2988. Arctic Char. When my meal arrived, I noted that the chef had not
  2989. signed it. So I complained, ``This char is unsigned---I wanted a
  2990. signed char!'' Or rather, I would have said this if I had thought of
  2991. it fast enough.}
  2992. @node Narrow Integers
  2993. @subsection Narrow Integers
  2994. The types that are narrower than @code{int} are rarely used for
  2995. ordinary variables---we declare them @code{int} instead. This is
  2996. because C converts those narrower types to @code{int} for any
  2997. arithmetic. There is literally no reason to declare a local variable
  2998. @code{char}, for instance.
  2999. In particular, if the value is really a character, you should declare
  3000. the variable @code{int}. Not @code{char}! Using that narrow type can
  3001. force the compiler to truncate values for conversion, which is a
  3002. waste. Furthermore, some functions return either a character value,
  3003. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3004. values distinct.
  3005. The narrow integer types are useful as parts of other objects, such as
  3006. arrays and structures. Compare these array declarations, whose sizes
  3007. on 32-bit processors are shown:
  3008. @example
  3009. signed char ac[1000]; /* @r{1000 bytes} */
  3010. short as[1000]; /* @r{2000 bytes} */
  3011. int ai[1000]; /* @r{4000 bytes} */
  3012. long long all[1000]; /* @r{8000 bytes} */
  3013. @end example
  3014. In addition, character strings must be made up of @code{char}s,
  3015. because that's what all the standard library string functions expect.
  3016. Thus, array @code{ac} could be used as a character string, but the
  3017. others could not be.
  3018. @node Integer Conversion
  3019. @subsection Conversion among Integer Types
  3020. C converts between integer types implicitly in many situations. It
  3021. converts the narrow integer types, @code{char} and @code{short}, to
  3022. @code{int} whenever they are used in arithmetic. Assigning a new
  3023. value to an integer variable (or other lvalue) converts the value to
  3024. the variable's type.
  3025. You can also convert one integer type to another explicitly with a
  3026. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3027. The process of conversion to a wider type is straightforward: the
  3028. value is unchanged. The only exception is when converting a negative
  3029. value (in a signed type, obviously) to a wider unsigned type. In that
  3030. case, the result is a positive value with the same bits
  3031. (@pxref{Integers in Depth}).
  3032. @cindex truncation
  3033. Converting to a narrower type, also called @dfn{truncation}, involves
  3034. discarding some of the value's bits. This is not considered overflow
  3035. (@pxref{Integer Overflow}) because loss of significant bits is a
  3036. normal consequence of truncation. Likewise for conversion between
  3037. signed and unsigned types of the same width.
  3038. More information about conversion for assignment is in
  3039. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3040. see @ref{Argument Promotions}.
  3041. @node Boolean Type
  3042. @subsection Boolean Type
  3043. @cindex boolean type
  3044. @cindex type, boolean
  3045. @findex bool
  3046. The unsigned integer type @code{bool} holds truth values: its possible
  3047. values are 0 and 1. Converting any nonzero value to @code{bool}
  3048. results in 1. For example:
  3049. @example
  3050. bool a = 0;
  3051. bool b = 1;
  3052. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3053. @end example
  3054. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3055. the header file @file{stdbool.h}.
  3056. @node Integer Variations
  3057. @subsection Integer Variations
  3058. The integer types of C have standard @emph{names}, but what they
  3059. @emph{mean} varies depending on the kind of platform in use:
  3060. which kind of computer, which operating system, and which compiler.
  3061. It may even depend on the compiler options used.
  3062. Plain @code{char} may be signed or unsigned; this depends on the
  3063. platform, too. Even for GNU C, there is no general rule.
  3064. In theory, all of the integer types' sizes can vary. @code{char} is
  3065. always considered one ``byte'' for C, but it is not necessarily an
  3066. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3067. specifies only that none of these types is narrower than the ones
  3068. above it in the list in @ref{Basic Integers}, and that @code{short}
  3069. has at least 16 bits.
  3070. It is possible that in the future GNU C will support platforms where
  3071. @code{int} is 64 bits long. In practice, however, on today's real
  3072. computers, there is little variation; you can rely on the table
  3073. given previously (@pxref{Basic Integers}).
  3074. To be completely sure of the size of an integer type,
  3075. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3076. Their corresponding unsigned types add @samp{u} at the front.
  3077. To define these, include the header file @file{stdint.h}.
  3078. The GNU C Compiler compiles for some embedded controllers that use two
  3079. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3080. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3081. 32 bits. These processors can't support an ordinary operating system
  3082. (they may have their own specialized operating systems), and most C
  3083. programs do not try to support them.
  3084. @node Floating-Point Data Types
  3085. @section Floating-Point Data Types
  3086. @cindex floating-point types
  3087. @cindex types, floating-point
  3088. @findex double
  3089. @findex float
  3090. @findex long double
  3091. @dfn{Floating point} is the binary analogue of scientific notation:
  3092. internally it represents a number as a fraction and a binary exponent; the
  3093. value is that fraction multiplied by the specified power of 2.
  3094. For instance, to represent 6, the fraction would be 0.75 and the
  3095. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3096. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3097. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3098. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3099. -1 as the exponent.
  3100. These binary exponents are used by machine instructions. You can
  3101. write a floating-point constant this way if you wish, using
  3102. hexadecimal; but normally we write floating-point numbers in decimal.
  3103. @xref{Floating Constants}.
  3104. C has three floating-point data types:
  3105. @table @code
  3106. @item double
  3107. ``Double-precision'' floating point, which uses 64 bits. This is the
  3108. normal floating-point type, and modern computers normally do
  3109. their floating-point computations in this type, or some wider type.
  3110. Except when there is a special reason to do otherwise, this is the
  3111. type to use for floating-point values.
  3112. @item float
  3113. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3114. for floating-point values stored in structures and arrays, to save
  3115. space when the full precision of @code{double} is not needed. In
  3116. addition, single-precision arithmetic is faster on some computers, and
  3117. occasionally that is useful. But not often---most programs don't use
  3118. the type @code{float}.
  3119. C would be cleaner if @code{float} were the name of the type we
  3120. use for most floating-point values; however, for historical reasons,
  3121. that's not so.
  3122. @item long double
  3123. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3124. precision, depending on the machine in use. On some machines, which
  3125. have no floating-point format wider than @code{double}, this is
  3126. equivalent to @code{double}.
  3127. @end table
  3128. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3129. Point in Depth}, for more information.
  3130. @node Complex Data Types
  3131. @section Complex Data Types
  3132. @cindex complex numbers
  3133. @cindex types, complex
  3134. @cindex @code{_Complex} keyword
  3135. @cindex @code{__complex__} keyword
  3136. @findex _Complex
  3137. @findex __complex__
  3138. Complex numbers can include both a real part and an imaginary part.
  3139. The numeric constants covered above have real-numbered values. An
  3140. imaginary-valued constant is an ordinary real-valued constant followed
  3141. by @samp{i}.
  3142. To declare numeric variables as complex, use the @code{_Complex}
  3143. keyword.@footnote{For compatibility with older versions of GNU C, the
  3144. keyword @code{__complex__} is also allowed. Going forward, however,
  3145. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3146. standard C complex data types are floating point,
  3147. @example
  3148. _Complex float foo;
  3149. _Complex double bar;
  3150. _Complex long double quux;
  3151. @end example
  3152. @noindent
  3153. but GNU C supports integer complex types as well.
  3154. Since @code{_Complex} is a keyword just like @code{float} and
  3155. @code{double} and @code{long}, the keywords can appear in any order,
  3156. but the order shown above seems most logical.
  3157. GNU C supports constants for complex values; for instance, @code{4.0 +
  3158. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3159. @xref{Imaginary Constants}.
  3160. To pull the real and imaginary parts of the number back out, GNU C
  3161. provides the keywords @code{__real__} and @code{__imag__}:
  3162. @example
  3163. _Complex double foo = 4.0 + 3.0i;
  3164. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3165. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3166. @end example
  3167. @noindent
  3168. Standard C does not include these keywords, and instead relies on
  3169. functions defined in @code{complex.h} for accessing the real and
  3170. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3171. @code{creall} extract the real part of a float, double, or long double
  3172. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3173. @code{cimagl} extract the imaginary part.
  3174. @cindex complex conjugation
  3175. GNU C also defines @samp{~} as an operator for complex conjugation,
  3176. which means negating the imaginary part of a complex number:
  3177. @example
  3178. _Complex double foo = 4.0 + 3.0i;
  3179. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3180. @end example
  3181. @noindent
  3182. For standard C compatibility, you can use the appropriate library
  3183. function: @code{conjf}, @code{conj}, or @code{confl}.
  3184. @node The Void Type
  3185. @section The Void Type
  3186. @cindex void type
  3187. @cindex type, void
  3188. @findex void
  3189. The data type @code{void} is a dummy---it allows no operations. It
  3190. really means ``no value at all.'' When a function is meant to return
  3191. no value, we write @code{void} for its return type. Then
  3192. @code{return} statements in that function should not specify a value
  3193. (@pxref{return Statement}). Here's an example:
  3194. @example
  3195. void
  3196. print_if_positive (double x, double y)
  3197. @{
  3198. if (x <= 0)
  3199. return;
  3200. if (y <= 0)
  3201. return;
  3202. printf ("Next point is (%f,%f)\n", x, y);
  3203. @}
  3204. @end example
  3205. A @code{void}-returning function is comparable to what some other languages
  3206. call a ``procedure'' instead of a ``function.''
  3207. @c ??? Already presented
  3208. @c @samp{%f} in an output template specifies to format a @code{double} value
  3209. @c as a decimal number, using a decimal point if needed.
  3210. @node Other Data Types
  3211. @section Other Data Types
  3212. Beyond the primitive types, C provides several ways to construct new
  3213. data types. For instance, you can define @dfn{pointers}, values that
  3214. represent the addresses of other data (@pxref{Pointers}). You can
  3215. define @dfn{structures}, as in many other languages
  3216. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3217. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3218. are collections of named integer codes (@pxref{Enumeration Types}).
  3219. @dfn{Array types} in C are used for allocating space for objects,
  3220. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3221. @node Type Designators
  3222. @section Type Designators
  3223. @cindex type designator
  3224. Some C constructs require a way to designate a specific data type
  3225. independent of any particular variable or expression which has that
  3226. type. The way to do this is with a @dfn{type designator}. The
  3227. constucts that need one include casts (@pxref{Explicit Type
  3228. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3229. We also use type designators to talk about the type of a value in C,
  3230. so you will see many type designators in this manual. When we say,
  3231. ``The value has type @code{int},'' @code{int} is a type designator.
  3232. To make the designator for any type, imagine a variable declaration
  3233. for a variable of that type and delete the variable name and the final
  3234. semicolon.
  3235. For example, to designate the type of full-word integers, we start
  3236. with the declaration for a variable @code{foo} with that type,
  3237. which is this:
  3238. @example
  3239. int foo;
  3240. @end example
  3241. @noindent
  3242. Then we delete the variable name @code{foo} and the semicolon, leaving
  3243. @code{int}---exactly the keyword used in such a declaration.
  3244. Therefore, the type designator for this type is @code{int}.
  3245. What about long unsigned integers? From the declaration
  3246. @example
  3247. unsigned long int foo;
  3248. @end example
  3249. @noindent
  3250. we determine that the designator is @code{unsigned long int}.
  3251. Following this procedure, the designator for any primitive type is
  3252. simply the set of keywords which specifies that type in a declaration.
  3253. The same is true for compound types such as structures, unions, and
  3254. enumerations.
  3255. Designators for pointer types do follow the rule of deleting the
  3256. variable name and semicolon, but the result is not so simple.
  3257. @xref{Pointer Type Designators}, as part of the chapter about
  3258. pointers. @xref{Array Type Designators}), for designators for array
  3259. types.
  3260. To understand what type a designator stands for, imagine a variable
  3261. name inserted into the right place in the designator to make a valid
  3262. declaration. What type would that variable be declared as? That is the
  3263. type the designator designates.
  3264. @node Constants
  3265. @chapter Constants
  3266. @cindex constants
  3267. A @dfn{constant} is an expression that stands for a specific value by
  3268. explicitly representing the desired value. C allows constants for
  3269. numbers, characters, and strings. We have already seen numeric and
  3270. string constants in the examples.
  3271. @menu
  3272. * Integer Constants:: Literal integer values.
  3273. * Integer Const Type:: Types of literal integer values.
  3274. * Floating Constants:: Literal floating-point values.
  3275. * Imaginary Constants:: Literal imaginary number values.
  3276. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3277. * Character Constants:: Literal character values.
  3278. * String Constants:: Literal string values.
  3279. * UTF-8 String Constants:: Literal UTF-8 string values.
  3280. * Unicode Character Codes:: Unicode characters represented
  3281. in either UTF-16 or UTF-32.
  3282. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3283. * Wide String Constants:: Literal string values made up of
  3284. 16- or 32-bit characters.
  3285. @end menu
  3286. @node Integer Constants
  3287. @section Integer Constants
  3288. @cindex integer constants
  3289. @cindex constants, integer
  3290. An integer constant consists of a number to specify the value,
  3291. followed optionally by suffix letters to specify the data type.
  3292. The simplest integer constants are numbers written in base 10
  3293. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3294. constant cannot start with the character @samp{0} (zero) because
  3295. that makes the constant octal.
  3296. You can get the effect of a negative integer constant by putting a
  3297. minus sign at the beginning. Grammatically speaking, that is an
  3298. arithmetic expression rather than a constant, but it behaves just like
  3299. a true constant.
  3300. Integer constants can also be written in octal (base 8), hexadecimal
  3301. (base 16), or binary (base 2). An octal constant starts with the
  3302. character @samp{0} (zero), followed by any number of octal digits
  3303. (@samp{0} to @samp{7}):
  3304. @example
  3305. 0 // @r{zero}
  3306. 077 // @r{63}
  3307. 0403 // @r{259}
  3308. @end example
  3309. @noindent
  3310. Pedantically speaking, the constant @code{0} is an octal constant, but
  3311. we can think of it as decimal; it has the same value either way.
  3312. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3313. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3314. through @samp{f} in upper or lower case):
  3315. @example
  3316. 0xff // @r{255}
  3317. 0XA0 // @r{160}
  3318. 0xffFF // @r{65535}
  3319. @end example
  3320. @cindex binary integer constants
  3321. A binary constant starts with @samp{0b} (upper or lower case) followed
  3322. by bits (each represented by the characters @samp{0} or @samp{1}):
  3323. @example
  3324. 0b101 // @r{5}
  3325. @end example
  3326. Binary constants are a GNU C extension, not part of the C standard.
  3327. Sometimes a space is needed after an integer constant to avoid
  3328. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3329. @node Integer Const Type
  3330. @section Integer Constant Data Types
  3331. @cindex integer constant data types
  3332. @cindex constant data types, integer
  3333. @cindex types of integer constants
  3334. The type of an integer constant is normally @code{int}, if the value
  3335. fits in that type, but here are the complete rules. The type
  3336. of an integer constant is the first one in this sequence that can
  3337. properly represent the value,
  3338. @enumerate
  3339. @item
  3340. @code{int}
  3341. @item
  3342. @code{unsigned int}
  3343. @item
  3344. @code{long int}
  3345. @item
  3346. @code{unsigned long int}
  3347. @item
  3348. @code{long long int}
  3349. @item
  3350. @code{unsigned long long int}
  3351. @end enumerate
  3352. @noindent
  3353. and that isn't excluded by the following rules.
  3354. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3355. first two types (non-@code{long}).
  3356. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3357. first four types (non-@code{long long}).
  3358. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3359. the signed types.
  3360. Otherwise, if the constant is decimal, that excludes the unsigned
  3361. types.
  3362. @c ### This said @code{unsigned int} is excluded.
  3363. @c ### See 17 April 2016
  3364. Here are some examples of the suffixes.
  3365. @example
  3366. 3000000000u // @r{three billion as @code{unsigned int}.}
  3367. 0LL // @r{zero as a @code{long long int}.}
  3368. 0403l // @r{259 as a @code{long int}.}
  3369. @end example
  3370. Suffixes in integer constants are rarely used. When the precise type
  3371. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3372. Type Conversion}).
  3373. @xref{Integer Types}.
  3374. @node Floating Constants
  3375. @section Floating-Point Constants
  3376. @cindex floating-point constants
  3377. @cindex constants, floating-point
  3378. A floating-point constant must have either a decimal point, an
  3379. exponent-of-ten, or both; they distinguish it from an integer
  3380. constant.
  3381. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3382. value follows. It is always written as a decimal number; it can
  3383. optionally start with a sign. The exponent @var{n} means to multiply
  3384. the constant's value by ten to the @var{n}th power.
  3385. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3386. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3387. writing a floating-point number whose value is 1500. They are all
  3388. equivalent.
  3389. Here are more examples with decimal points:
  3390. @example
  3391. 1.0
  3392. 1000.
  3393. 3.14159
  3394. .05
  3395. .0005
  3396. @end example
  3397. For each of them, here are some equivalent constants written with
  3398. exponents:
  3399. @example
  3400. 1e0, 1.0000e0
  3401. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3402. 3.14159e0
  3403. 5e-2, .0005e+2, 5E-2, .0005E2
  3404. .05e-2
  3405. @end example
  3406. A floating-point constant normally has type @code{double}. You can
  3407. force it to type @code{float} by adding @samp{f} or @samp{F}
  3408. at the end. For example,
  3409. @example
  3410. 3.14159f
  3411. 3.14159e0f
  3412. 1000.f
  3413. 100E1F
  3414. .0005f
  3415. .05e-2f
  3416. @end example
  3417. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3418. to type @code{long double}.
  3419. You can use exponents in hexadecimal floating constants, but since
  3420. @samp{e} would be interpreted as a hexadecimal digit, the character
  3421. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3422. The exponent in a hexadecimal floating constant is a possibly-signed
  3423. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3424. multiply into the number.
  3425. Here are some examples:
  3426. @example
  3427. @group
  3428. 0xAp2 // @r{40 in decimal}
  3429. 0xAp-1 // @r{5 in decimal}
  3430. 0x2.0Bp4 // @r{16.75 decimal}
  3431. 0xE.2p3 // @r{121 decimal}
  3432. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3433. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3434. 0x100p-8 // @r{1}
  3435. 0x10p-4 // @r{1}
  3436. 0x1p+4 // @r{16}
  3437. 0x1p+8 // @r{256}
  3438. @end group
  3439. @end example
  3440. @xref{Floating-Point Data Types}.
  3441. @node Imaginary Constants
  3442. @section Imaginary Constants
  3443. @cindex imaginary constants
  3444. @cindex complex constants
  3445. @cindex constants, imaginary
  3446. A complex number consists of a real part plus an imaginary part.
  3447. (Either or both parts may be zero.) This section explains how to
  3448. write numeric constants with imaginary values. By adding these to
  3449. ordinary real-valued numeric constants, we can make constants with
  3450. complex values.
  3451. The simple way to write an imaginary-number constant is to attach the
  3452. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3453. floating-point constant. For example, @code{2.5fi} has type
  3454. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3455. The four alternative suffix letters are all equivalent.
  3456. @cindex _Complex_I
  3457. The other way to write an imaginary constant is to multiply a real
  3458. constant by @code{_Complex_I}, which represents the imaginary number
  3459. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3460. this clunky way is needed.
  3461. To write a complex constant with a nonzero real part and a nonzero
  3462. imaginary part, write the two separately and add them, like this:
  3463. @example
  3464. 4.0 + 3.0i
  3465. @end example
  3466. @noindent
  3467. That gives the value 4 + 3i, with type @code{_Complex double}.
  3468. Such a sum can include multiple real constants, or none. Likewise, it
  3469. can include multiple imaginary constants, or none. For example:
  3470. @example
  3471. _Complex double foo, bar, quux;
  3472. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3473. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3474. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3475. @end example
  3476. @xref{Complex Data Types}.
  3477. @node Invalid Numbers
  3478. @section Invalid Numbers
  3479. Some number-like constructs which are not really valid as numeric
  3480. constants are treated as numbers in preprocessing directives. If
  3481. these constructs appear outside of preprocessing, they are erroneous.
  3482. @xref{Preprocessing Tokens}.
  3483. Sometimes we need to insert spaces to separate tokens so that they
  3484. won't be combined into a single number-like construct. For example,
  3485. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3486. constant, so it is a syntax error. If what we want is the three
  3487. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3488. @node Character Constants
  3489. @section Character Constants
  3490. @cindex character constants
  3491. @cindex constants, character
  3492. @cindex escape sequence
  3493. A @dfn{character constant} is written with single quotes, as in
  3494. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3495. character that the constant should represent. The constant has type
  3496. @code{int}, and its value is the character code of that character.
  3497. For instance, @code{'a'} represents the character code for the letter
  3498. @samp{a}: 97, that is.
  3499. To put the @samp{'} character (single quote) in the character
  3500. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3501. constant looks like @code{'\''}. This sort of sequence, starting with
  3502. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3503. here functions as a kind of @dfn{escape character}.
  3504. To put the @samp{\} character (backslash) in the character constant,
  3505. quote it likewise with @samp{\} (another backslash). This character
  3506. constant looks like @code{'\\'}.
  3507. @cindex bell character
  3508. @cindex @samp{\a}
  3509. @cindex backspace
  3510. @cindex @samp{\b}
  3511. @cindex tab (ASCII character)
  3512. @cindex @samp{\t}
  3513. @cindex vertical tab
  3514. @cindex @samp{\v}
  3515. @cindex formfeed
  3516. @cindex @samp{\f}
  3517. @cindex newline
  3518. @cindex @samp{\n}
  3519. @cindex return (ASCII character)
  3520. @cindex @samp{\r}
  3521. @cindex escape (ASCII character)
  3522. @cindex @samp{\e}
  3523. Here are all the escape sequences that represent specific
  3524. characters in a character constant. The numeric values shown are
  3525. the corresponding ASCII character codes, as decimal numbers.
  3526. @example
  3527. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3528. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3529. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3530. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3531. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3532. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3533. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3534. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3535. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3536. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3537. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3538. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3539. @end example
  3540. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3541. You can also write octal and hex character codes as
  3542. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3543. option here, so octal codes do not need to start with @samp{0}.
  3544. The character constant's value has type @code{int}. However, the
  3545. character code is treated initially as a @code{char} value, which is
  3546. then converted to @code{int}. If the character code is greater than
  3547. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3548. on a platform where the type @code{char} is 8 bits long and signed.
  3549. @node String Constants
  3550. @section String Constants
  3551. @cindex string constants
  3552. @cindex constants, string
  3553. A @dfn{string constant} represents a series of characters. It starts
  3554. with @samp{"} and ends with @samp{"}; in between are the contents of
  3555. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3556. newline in the contents works in string constants as in character
  3557. constants. In a string constant, @samp{'} does not need to be quoted.
  3558. A string constant defines an array of characters which contains the
  3559. specified characters followed by the null character (code 0). Using
  3560. the string constant is equivalent to using the name of an array with
  3561. those contents. In simple cases, the length in bytes of the string
  3562. constant is one greater than the number of characters written in it.
  3563. As with any array in C, using the string constant in an expression
  3564. converts the array to a pointer (@pxref{Pointers}) to the array's
  3565. first element (@pxref{Accessing Array Elements}). This pointer will
  3566. have type @code{char *} because it points to an element of type
  3567. @code{char}. @code{char *} is an example of a type designator for a
  3568. pointer type (@pxref{Pointer Type Designators}). That type is used
  3569. for strings generally, not just the strings expressed as constants
  3570. in a program.
  3571. Thus, the string constant @code{"Foo!"} is almost
  3572. equivalent to declaring an array like this
  3573. @example
  3574. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3575. @end example
  3576. @noindent
  3577. and then using @code{string_array_1} in the program. There
  3578. are two differences, however:
  3579. @itemize @bullet
  3580. @item
  3581. The string constant doesn't define a name for the array.
  3582. @item
  3583. The string constant is probably stored in a read-only area of memory.
  3584. @end itemize
  3585. Newlines are not allowed in the text of a string constant. The motive
  3586. for this prohibition is to catch the error of omitting the closing
  3587. @samp{"}. To put a newline in a constant string, write it as
  3588. @samp{\n} in the string constant.
  3589. A real null character in the source code inside a string constant
  3590. causes a warning. To put a null character in the middle of a string
  3591. constant, write @samp{\0} or @samp{\000}.
  3592. Consecutive string constants are effectively concatenated. Thus,
  3593. @example
  3594. "Fo" "o!" @r{is equivalent to} "Foo!"
  3595. @end example
  3596. This is useful for writing a string containing multiple lines,
  3597. like this:
  3598. @example
  3599. "This message is so long that it needs more than\n"
  3600. "a single line of text. C does not allow a newline\n"
  3601. "to represent itself in a string constant, so we have to\n"
  3602. "write \\n to put it in the string. For readability of\n"
  3603. "the source code, it is advisable to put line breaks in\n"
  3604. "the source where they occur in the contents of the\n"
  3605. "constant.\n"
  3606. @end example
  3607. The sequence of a backslash and a newline is ignored anywhere
  3608. in a C program, and that includes inside a string constant.
  3609. Thus, you can write multi-line string constants this way:
  3610. @example
  3611. "This is another way to put newlines in a string constant\n\
  3612. and break the line after them in the source code."
  3613. @end example
  3614. @noindent
  3615. However, concatenation is the recommended way to do this.
  3616. You can also write perverse string constants like this,
  3617. @example
  3618. "Fo\
  3619. o!"
  3620. @end example
  3621. @noindent
  3622. but don't do that---write it like this instead:
  3623. @example
  3624. "Foo!"
  3625. @end example
  3626. Be careful to avoid passing a string constant to a function that
  3627. modifies the string it receives. The memory where the string constant
  3628. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3629. signal that normally terminates the function (@pxref{Signals}. Even
  3630. worse, the memory may not be read-only. Then the function might
  3631. modify the string constant, thus spoiling the contents of other string
  3632. constants that are supposed to contain the same value and are unified
  3633. by the compiler.
  3634. @node UTF-8 String Constants
  3635. @section UTF-8 String Constants
  3636. @cindex UTF-8 String Constants
  3637. Writing @samp{u8} immediately before a string constant, with no
  3638. intervening space, means to represent that string in UTF-8 encoding as
  3639. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3640. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3641. as multibyte sequences. Here is an example of a UTF-8 constant:
  3642. @example
  3643. u8"A cónstàñt"
  3644. @end example
  3645. This constant occupies 13 bytes plus the terminating null,
  3646. because each of the accented letters is a two-byte sequence.
  3647. Concatenating an ordinary string with a UTF-8 string conceptually
  3648. produces another UTF-8 string. However, if the ordinary string
  3649. contains character codes 128 and up, the results cannot be relied on.
  3650. @node Unicode Character Codes
  3651. @section Unicode Character Codes
  3652. @cindex Unicode character codes
  3653. @cindex universal character names
  3654. You can specify Unicode characters, for individual character constants
  3655. or as part of string constants (@pxref{String Constants}), using
  3656. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3657. hexadecimal Unicode character code. If the code value is too big for
  3658. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3659. Unicode character code. (These codes are called @dfn{universal
  3660. character names}.) For example,
  3661. @example
  3662. \u6C34 /* @r{16-bit code (UTF-16)} */
  3663. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3664. @end example
  3665. @noindent
  3666. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3667. Constants}). For instance,
  3668. @example
  3669. u8"fóó \u6C34 \U0010ABCD"
  3670. @end example
  3671. You can also use them in wide character constants (@pxref{Wide
  3672. Character Constants}), like this:
  3673. @example
  3674. u'\u6C34' /* @r{16-bit code} */
  3675. U'\U0010ABCD' /* @r{32-bit code} */
  3676. @end example
  3677. @noindent
  3678. and in wide string constants (@pxref{Wide String Constants}), like
  3679. this:
  3680. @example
  3681. u"\u6C34\u6C33" /* @r{16-bit code} */
  3682. U"\U0010ABCD" /* @r{32-bit code} */
  3683. @end example
  3684. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3685. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3686. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3687. actually ASCII control characters, and you can specify them with other
  3688. escape sequences (@pxref{Character Constants}).
  3689. @node Wide Character Constants
  3690. @section Wide Character Constants
  3691. @cindex wide character constants
  3692. @cindex constants, wide character
  3693. A @dfn{wide character constant} represents characters with more than 8
  3694. bits of character code. This is an obscure feature that we need to
  3695. document but that you probably won't ever use. If you're just
  3696. learning C, you may as well skip this section.
  3697. The original C wide character constant looks like @samp{L} (upper
  3698. case!) followed immediately by an ordinary character constant (with no
  3699. intervening space). Its data type is @code{wchar_t}, which is an
  3700. alias defined in @file{stddef.h} for one of the standard integer
  3701. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3702. it is 16 bits, these character constants use the UTF-16 form of
  3703. Unicode; if 32 bits, UTF-32.
  3704. There are also Unicode wide character constants which explicitly
  3705. specify the width. These constants start with @samp{u} or @samp{U}
  3706. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3707. character constant, and @samp{U} a 32-bit Unicode wide character
  3708. constant. Their types are, respectively, @code{char16_t} and
  3709. @w{@code{char32_t}}; they are declared in the header file
  3710. @file{uchar.h}. These character constants are valid even if
  3711. @file{uchar.h} is not included, but some uses of them may be
  3712. inconvenient without including it to declare those type names.
  3713. The character represented in a wide character constant can be an
  3714. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3715. are all valid, and they are all equal to @code{'a'}.
  3716. In all three kinds of wide character constants, you can write a
  3717. non-ASCII Unicode character in the constant itself; the constant's
  3718. value is the character's Unicode character code. Or you can specify
  3719. the Unicode character with an escape sequence (@pxref{Unicode
  3720. Character Codes}).
  3721. @node Wide String Constants
  3722. @section Wide String Constants
  3723. @cindex wide string constants
  3724. @cindex constants, wide string
  3725. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3726. characters. They are rarely used; if you're just
  3727. learning C, you may as well skip this section.
  3728. There are three kinds of wide string constants, which differ in the
  3729. data type used for each character in the string. Each wide string
  3730. constant is equivalent to an array of integers, but the data type of
  3731. those integers depends on the kind of wide string. Using the constant
  3732. in an expression will convert the array to a pointer to its first
  3733. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3734. For each kind of wide string constant, we state here what type that
  3735. pointer will be.
  3736. @table @code
  3737. @item char16_t
  3738. This is a 16-bit Unicode wide string constant: each element is a
  3739. 16-bit Unicode character code with type @code{char16_t}, so the string
  3740. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3741. @pxref{Pointer Type Designators}.) The constant is written as
  3742. @samp{u} (which must be lower case) followed (with no intervening
  3743. space) by a string constant with the usual syntax.
  3744. @item char32_t
  3745. This is a 32-bit Unicode wide string constant: each element is a
  3746. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3747. It's written as @samp{U} (which must be upper case) followed (with no
  3748. intervening space) by a string constant with the usual syntax.
  3749. @item wchar_t
  3750. This is the original kind of wide string constant. It's written as
  3751. @samp{L} (which must be upper case) followed (with no intervening
  3752. space) by a string constant with the usual syntax, and the string has
  3753. type @code{wchar_t@ *}.
  3754. The width of the data type @code{wchar_t} depends on the target
  3755. platform, which makes this kind of wide string somewhat less useful
  3756. than the newer kinds.
  3757. @end table
  3758. @code{char16_t} and @code{char32_t} are declared in the header file
  3759. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3760. Consecutive wide string constants of the same kind concatenate, just
  3761. like ordinary string constants. A wide string constant concatenated
  3762. with an ordinary string constant results in a wide string constant.
  3763. You can't concatenate two wide string constants of different kinds.
  3764. You also can't concatenate a wide string constant (of any kind) with a
  3765. UTF-8 string constant.
  3766. @node Type Size
  3767. @chapter Type Size
  3768. @cindex type size
  3769. @cindex size of type
  3770. @findex sizeof
  3771. Each data type has a @dfn{size}, which is the number of bytes
  3772. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3773. a C program, use @code{sizeof}. There are two ways to use it:
  3774. @table @code
  3775. @item sizeof @var{expression}
  3776. This gives the size of @var{expression}, based on its data type. It
  3777. does not calculate the value of @var{expression}, only its size, so if
  3778. @var{expression} includes side effects or function calls, they do not
  3779. happen. Therefore, @code{sizeof} is always a compile-time operation
  3780. that has zero run-time cost.
  3781. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3782. operand of @code{sizeof}.
  3783. For example,
  3784. @example
  3785. double a;
  3786. i = sizeof a + 10;
  3787. @end example
  3788. @noindent
  3789. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3790. Here's how to determine the number of elements in an array
  3791. @code{array}:
  3792. @example
  3793. (sizeof array / sizeof array[0])
  3794. @end example
  3795. @noindent
  3796. The expression @code{sizeof array} gives the size of the array, not
  3797. the size of a pointer to an element. However, if @var{expression} is
  3798. a function parameter that was declared as an array, that
  3799. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3800. the result is the size of that pointer.
  3801. @item sizeof (@var{type})
  3802. This gives the size of @var{type}.
  3803. For example,
  3804. @example
  3805. i = sizeof (double) + 10;
  3806. @end example
  3807. @noindent
  3808. is equivalent to the previous example.
  3809. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3810. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3811. C, which makes adding an integer to a function pointer work as desired
  3812. (@pxref{Pointer Arithmetic}).
  3813. @end table
  3814. @strong{Warning}: When you use @code{sizeof} with a type
  3815. instead of an expression, you must write parentheses around the type.
  3816. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3817. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3818. the cast expression to avoid an ambiguity in the grammar of C@.
  3819. Specifically,
  3820. @example
  3821. sizeof (int) -x
  3822. @end example
  3823. @noindent
  3824. parses as
  3825. @example
  3826. (sizeof (int)) - x
  3827. @end example
  3828. @noindent
  3829. If what you want is
  3830. @example
  3831. sizeof ((int) -x)
  3832. @end example
  3833. @noindent
  3834. you must write it that way, with parentheses.
  3835. The data type of the value of the @code{sizeof} operator is always one
  3836. of the unsigned integer types; which one of those types depends on the
  3837. machine. The header file @code{stddef.h} defines the typedef name
  3838. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3839. Names}.
  3840. @node Pointers
  3841. @chapter Pointers
  3842. @cindex pointers
  3843. Among high-level languages, C is rather low level, close to the
  3844. machine. This is mainly because it has explicit @dfn{pointers}. A
  3845. pointer value is the numeric address of data in memory. The type of
  3846. data to be found at that address is specified by the data type of the
  3847. pointer itself. The unary operator @samp{*} gets the data that a
  3848. pointer points to---this is called @dfn{dereferencing the pointer}.
  3849. C also allows pointers to functions, but since there are some
  3850. differences in how they work, we treat them later. @xref{Function
  3851. Pointers}.
  3852. @menu
  3853. * Address of Data:: Using the ``address-of'' operator.
  3854. * Pointer Types:: For each type, there is a pointer type.
  3855. * Pointer Declarations:: Declaring variables with pointer types.
  3856. * Pointer Type Designators:: Designators for pointer types.
  3857. * Pointer Dereference:: Accessing what a pointer points at.
  3858. * Null Pointers:: Pointers which do not point to any object.
  3859. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3860. * Void Pointers:: Totally generic pointers, can cast to any.
  3861. * Pointer Comparison:: Comparing memory address values.
  3862. * Pointer Arithmetic:: Computing memory address values.
  3863. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3864. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3865. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3866. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3867. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3868. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3869. @end menu
  3870. @node Address of Data
  3871. @section Address of Data
  3872. @cindex address-of operator
  3873. The most basic way to make a pointer is with the ``address-of''
  3874. operator, @samp{&}. Let's suppose we have these variables available:
  3875. @example
  3876. int i;
  3877. double a[5];
  3878. @end example
  3879. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3880. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3881. address of the element 3 of @code{a}. (It is actually the fourth
  3882. element in the array, since the first element has index 0.)
  3883. The address-of operator is unusual because it operates on a place to
  3884. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3885. stored there. (The left argument of a simple assignment is unusual in
  3886. the same way.) You can use it on any lvalue except a bit field
  3887. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3888. Constructors}).
  3889. @node Pointer Types
  3890. @section Pointer Types
  3891. For each data type @var{t}, there is a type for pointers to type
  3892. @var{t}. For these variables,
  3893. @example
  3894. int i;
  3895. double a[5];
  3896. @end example
  3897. @itemize @bullet
  3898. @item
  3899. @code{i} has type @code{int}; we say
  3900. @code{&i} is a ``pointer to @code{int}.''
  3901. @item
  3902. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3903. arrays of five @code{double}s.''
  3904. @item
  3905. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3906. to @code{double}.''
  3907. @end itemize
  3908. @node Pointer Declarations
  3909. @section Pointer-Variable Declarations
  3910. The way to declare that a variable @code{foo} points to type @var{t} is
  3911. @example
  3912. @var{t} *foo;
  3913. @end example
  3914. To remember this syntax, think ``if you dereference @code{foo}, using
  3915. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3916. points to type @var{t}.''
  3917. Thus, we can declare variables that hold pointers to these three
  3918. types, like this:
  3919. @example
  3920. int *ptri; /* @r{Pointer to @code{int}.} */
  3921. double *ptrd; /* @r{Pointer to @code{double}.} */
  3922. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3923. @end example
  3924. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3925. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3926. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3927. @code{double}.'' The parentheses express the point that you would
  3928. dereference it first, then subscript it.
  3929. Contrast the last one with this:
  3930. @example
  3931. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3932. @end example
  3933. @noindent
  3934. Because @samp{*} has higher syntactic precedence than subscripting,
  3935. you would subscript @code{aptrd} then dereference it. Therefore, it
  3936. declares an array of pointers, not a pointer.
  3937. @node Pointer Type Designators
  3938. @section Pointer-Type Designators
  3939. Every type in C has a designator; you make it by deleting the variable
  3940. name and the semicolon from a declaration (@pxref{Type
  3941. Designators}). Here are the designators for the pointer
  3942. types of the example declarations in the previous section:
  3943. @example
  3944. int * /* @r{Pointer to @code{int}.} */
  3945. double * /* @r{Pointer to @code{double}.} */
  3946. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3947. @end example
  3948. Remember, to understand what type a designator stands for, imagine the
  3949. variable name that would be in the declaration, and figure out what
  3950. type it would declare that variable with. @code{double (*)[5]} can
  3951. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3952. which, when dereferenced, gives an array of 5 @code{double}s.
  3953. @node Pointer Dereference
  3954. @section Dereferencing Pointers
  3955. @cindex dereferencing pointers
  3956. @cindex pointer dereferencing
  3957. The main use of a pointer value is to @dfn{dereference it} (access the
  3958. data it points at) with the unary @samp{*} operator. For instance,
  3959. @code{*&i} is the value at @code{i}'s address---which is just
  3960. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3961. valid.
  3962. A pointer-dereference expression whose type is data (not a function)
  3963. is an lvalue.
  3964. Pointers become really useful when we store them somewhere and use
  3965. them later. Here's a simple example to illustrate the practice:
  3966. @example
  3967. @{
  3968. int i;
  3969. int *ptr;
  3970. ptr = &i;
  3971. i = 5;
  3972. @r{@dots{}}
  3973. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3974. @}
  3975. @end example
  3976. This shows how to declare the variable @code{ptr} as type
  3977. @code{int *} (pointer to @code{int}), store a pointer value into it
  3978. (pointing at @code{i}), and use it later to get the value of the
  3979. object it points at (the value in @code{i}).
  3980. If anyone can provide a useful example which is this basic,
  3981. I would be grateful.
  3982. @node Null Pointers
  3983. @section Null Pointers
  3984. @cindex null pointers
  3985. @cindex pointers, null
  3986. @c ???stdio loads sttddef
  3987. A pointer value can be @dfn{null}, which means it does not point to
  3988. any object. The cleanest way to get a null pointer is by writing
  3989. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3990. also do it by casting 0 to the desired pointer type, as in
  3991. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  3992. @xref{Explicit Type Conversion}.)
  3993. You can store a null pointer in any lvalue whose data type
  3994. is a pointer type:
  3995. @example
  3996. char *foo;
  3997. foo = NULL;
  3998. @end example
  3999. These two, if consecutive, can be combined into a declaration with
  4000. initializer,
  4001. @example
  4002. char *foo = NULL;
  4003. @end example
  4004. You can also explicitly cast @code{NULL} to the specific pointer type
  4005. you want---it makes no difference.
  4006. @example
  4007. char *foo;
  4008. foo = (char *) NULL;
  4009. @end example
  4010. To test whether a pointer is null, compare it with zero or
  4011. @code{NULL}, as shown here:
  4012. @example
  4013. if (p != NULL)
  4014. /* @r{@code{p} is not null.} */
  4015. operate (p);
  4016. @end example
  4017. Since testing a pointer for not being null is basic and frequent, all
  4018. but beginners in C will understand the conditional without need for
  4019. @code{!= NULL}:
  4020. @example
  4021. if (p)
  4022. /* @r{@code{p} is not null.} */
  4023. operate (p);
  4024. @end example
  4025. @node Invalid Dereference
  4026. @section Dereferencing Null or Invalid Pointers
  4027. Trying to dereference a null pointer is an error. On most platforms,
  4028. it generally causes a signal, usually @code{SIGSEGV}
  4029. (@pxref{Signals}).
  4030. @example
  4031. char *foo = NULL;
  4032. c = *foo; /* @r{This causes a signal and terminates.} */
  4033. @end example
  4034. @noindent
  4035. Likewise a pointer that has the wrong alignment for the target data type
  4036. (on most types of computer), or points to a part of memory that has
  4037. not been allocated in the process's address space.
  4038. The signal terminates the program, unless the program has arranged to
  4039. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4040. The GNU C Library Reference Manual}).
  4041. However, the signal might not happen if the dereference is optimized
  4042. away. In the example above, if you don't subsequently use the value
  4043. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4044. can prevent such optimization using the @code{volatile} qualifier, as
  4045. shown here:
  4046. @example
  4047. volatile char *p;
  4048. volatile char c;
  4049. c = *p;
  4050. @end example
  4051. You can use this to test whether @code{p} points to unallocated
  4052. memory. Set up a signal handler first, so the signal won't terminate
  4053. the program.
  4054. @node Void Pointers
  4055. @section Void Pointers
  4056. @cindex void pointers
  4057. @cindex pointers, void
  4058. The peculiar type @code{void *}, a pointer whose target type is
  4059. @code{void}, is used often in C@. It represents a pointer to
  4060. we-don't-say-what. Thus,
  4061. @example
  4062. void *numbered_slot_pointer (int);
  4063. @end example
  4064. @noindent
  4065. declares a function @code{numbered_slot_pointer} that takes an
  4066. integer parameter and returns a pointer, but we don't say what type of
  4067. data it points to.
  4068. With type @code{void *}, you can pass the pointer around and test
  4069. whether it is null. However, dereferencing it gives a @code{void}
  4070. value that can't be used (@pxref{The Void Type}). To dereference the
  4071. pointer, first convert it to some other pointer type.
  4072. Assignments convert @code{void *} automatically to any other pointer
  4073. type, if the left operand has a pointer type; for instance,
  4074. @example
  4075. @{
  4076. int *p;
  4077. /* @r{Converts return value to @code{int *}.} */
  4078. p = numbered_slot_pointer (5);
  4079. @r{@dots{}}
  4080. @}
  4081. @end example
  4082. Passing an argument of type @code{void *} for a parameter that has a
  4083. pointer type also converts. For example, supposing the function
  4084. @code{hack} is declared to require type @code{float *} for its
  4085. argument, this will convert the null pointer to that type.
  4086. @example
  4087. /* @r{Declare @code{hack} that way.}
  4088. @r{We assume it is defined somewhere else.} */
  4089. void hack (float *);
  4090. @dots{}
  4091. /* @r{Now call @code{hack}.} */
  4092. @{
  4093. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4094. @r{to @code{float *} to pass it to @code{hack}.} */
  4095. hack (numbered_slot_pointer (5));
  4096. @r{@dots{}}
  4097. @}
  4098. @end example
  4099. You can also convert to another pointer type with an explicit cast
  4100. (@pxref{Explicit Type Conversion}), like this:
  4101. @example
  4102. (int *) numbered_slot_pointer (5)
  4103. @end example
  4104. Here is an example which decides at run time which pointer
  4105. type to convert to:
  4106. @example
  4107. void
  4108. extract_int_or_double (void *ptr, bool its_an_int)
  4109. @{
  4110. if (its_an_int)
  4111. handle_an_int (*(int *)ptr);
  4112. else
  4113. handle_a_double (*(double *)ptr);
  4114. @}
  4115. @end example
  4116. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4117. to type @code{int *}, then dereference it.
  4118. @node Pointer Comparison
  4119. @section Pointer Comparison
  4120. @cindex pointer comparison
  4121. @cindex comparison, pointer
  4122. Two pointer values are equal if they point to the same location, or if
  4123. they are both null. You can test for this with @code{==} and
  4124. @code{!=}. Here's a trivial example:
  4125. @example
  4126. @{
  4127. int i;
  4128. int *p, *q;
  4129. p = &i;
  4130. q = &i;
  4131. if (p == q)
  4132. printf ("This will be printed.\n");
  4133. if (p != q)
  4134. printf ("This won't be printed.\n");
  4135. @}
  4136. @end example
  4137. Ordering comparisons such as @code{>} and @code{>=} operate on
  4138. pointers by converting them to unsigned integers. The C standard says
  4139. the two pointers must point within the same object in memory, but on
  4140. GNU/Linux systems these operations simply compare the numeric values
  4141. of the pointers.
  4142. The pointer values to be compared should in principle have the same type, but
  4143. they are allowed to differ in limited cases. First of all, if the two
  4144. pointers' target types are nearly compatible (@pxref{Compatible
  4145. Types}), the comparison is allowed.
  4146. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4147. the other is another pointer type, the comparison operator converts
  4148. the @code{void *} pointer to the other type so as to compare them.
  4149. (In standard C, this is not allowed if the other type is a function
  4150. pointer type, but that works in GNU C@.)
  4151. Comparison operators also allow comparing the integer 0 with a pointer
  4152. value. Thus works by converting 0 to a null pointer of the same type
  4153. as the other operand.
  4154. @node Pointer Arithmetic
  4155. @section Pointer Arithmetic
  4156. @cindex pointer arithmetic
  4157. @cindex arithmetic, pointer
  4158. Adding an integer (positive or negative) to a pointer is valid in C@.
  4159. It assumes that the pointer points to an element in an array, and
  4160. advances or retracts the pointer across as many array elements as the
  4161. integer specifies. Here is an example, in which adding a positive
  4162. integer advances the pointer to a later element in the same array.
  4163. @example
  4164. void
  4165. incrementing_pointers ()
  4166. @{
  4167. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4168. int elt0, elt1, elt4;
  4169. int *p = &array[0];
  4170. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4171. elt0 = *p;
  4172. ++p;
  4173. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4174. elt1 = *p;
  4175. p += 3;
  4176. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4177. elt4 = *p;
  4178. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4179. elt0, elt1, elt4);
  4180. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4181. @}
  4182. @end example
  4183. Here's an example where adding a negative integer retracts the pointer
  4184. to an earlier element in the same array.
  4185. @example
  4186. void
  4187. decrementing_pointers ()
  4188. @{
  4189. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4190. int elt0, elt3, elt4;
  4191. int *p = &array[4];
  4192. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4193. elt4 = *p;
  4194. --p;
  4195. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4196. elt3 = *p;
  4197. p -= 3;
  4198. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4199. elt0 = *p;
  4200. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4201. elt0, elt3, elt4);
  4202. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4203. @}
  4204. @end example
  4205. If one pointer value was made by adding an integer to another
  4206. pointer value, it should be possible to subtract the pointer values
  4207. and recover that integer. That works too in C@.
  4208. @example
  4209. void
  4210. subtract_pointers ()
  4211. @{
  4212. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4213. int *p0, *p3, *p4;
  4214. int *p = &array[4];
  4215. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4216. p4 = p;
  4217. --p;
  4218. /* @r{Now @code{p} points at element 3. Save the value.} */
  4219. p3 = p;
  4220. p -= 3;
  4221. /* @r{Now @code{p} points at element 0. Save the value.} */
  4222. p0 = p;
  4223. printf ("%d, %d, %d, %d\n",
  4224. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4225. /* @r{Prints 4, 0, 3, -3.} */
  4226. @}
  4227. @end example
  4228. The addition operation does not know where arrays are. All it does is
  4229. add the integer (multiplied by object size) to the value of the
  4230. pointer. When the initial pointer and the result point into a single
  4231. array, the result is well-defined.
  4232. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4233. into different memory objects.
  4234. The difference between two pointers has type @code{int}, or
  4235. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4236. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4237. file @file{stddef.h}.
  4238. This definition of pointer subtraction is consistent with
  4239. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4240. @code{p3}, as in ordinary algebra.
  4241. In standard C, addition and subtraction are not allowed on @code{void
  4242. *}, since the target type's size is not defined in that case.
  4243. Likewise, they are not allowed on pointers to function types.
  4244. However, these operations work in GNU C, and the ``size of the target
  4245. type'' is taken as 1.
  4246. @node Pointers and Arrays
  4247. @section Pointers and Arrays
  4248. @cindex pointers and arrays
  4249. @cindex arrays and pointers
  4250. The clean way to refer to an array element is
  4251. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4252. same job is to get the address of that element as a pointer, then
  4253. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4254. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4255. pointer to element zero, then increments it with @code{+} to point to
  4256. the desired element, then gets the value from there.
  4257. That pointer-arithmetic construct is the @emph{definition} of square
  4258. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4259. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4260. symmetrically, so one must be a pointer and the other an integer; it
  4261. does not matter which comes first.
  4262. Since indexing with square brackets is defined in terms of addition
  4263. and dereference, that too is symmetrical. Thus, you can write
  4264. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4265. would be foolish to write @code{3[array]}, since it has no advantage
  4266. and could confuse people who read the code.
  4267. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4268. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4269. instead. Why is this valid? The name of the array, when used by
  4270. itself as an expression (other than in @code{sizeof}), stands for a
  4271. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4272. converts @code{array} implicitly to @code{&array[0]}, and the result
  4273. is a pointer to element 3, equivalent to @code{&array[3]}.
  4274. Since square brackets are defined in terms of such addition,
  4275. @code{array[3]} first converts @code{array} to a pointer. That's why
  4276. it works to use an array directly in that construct.
  4277. @node Pointer Arithmetic Low Level
  4278. @section Pointer Arithmetic at Low Level
  4279. @cindex pointer arithmetic, low level
  4280. @cindex low level pointer arithmetic
  4281. The behavior of pointer arithmetic is theoretically defined only when
  4282. the pointer values all point within one object allocated in memory.
  4283. But the addition and subtraction operators can't tell whether the
  4284. pointer values are all within one object. They don't know where
  4285. objects start and end. So what do they really do?
  4286. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4287. address, which is in fact an integer---call it @var{pint}. It treats
  4288. @var{i} as a number of elements of the type that @var{p} points to.
  4289. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4290. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4291. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4292. If the starting pointer value @var{p} and the result do not point at
  4293. parts of the same object, the operation is not officially legitimate,
  4294. and C code is not ``supposed'' to do it. But you can do it anyway,
  4295. and it gives precisely the results described by the procedure above.
  4296. In some special situations it can do something useful, but non-wizards
  4297. should avoid it.
  4298. Here's a function to offset a pointer value @emph{as if} it pointed to
  4299. an object of any given size, by explicitly performing that calculation:
  4300. @example
  4301. #include <stdint.h>
  4302. void *
  4303. ptr_add (void *p, int i, int objsize)
  4304. @{
  4305. intptr_t p_address = (long) p;
  4306. intptr_t totalsize = i * objsize;
  4307. intptr_t new_address = p_address + totalsize;
  4308. return (void *) new_address;
  4309. @}
  4310. @end example
  4311. @noindent
  4312. @cindex @code{intptr_t}
  4313. This does the same job as @code{@var{p} + @var{i}} with the proper
  4314. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4315. defined in the header file @file{stdint.h}. (In practice, @code{long
  4316. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4317. @node Pointer Increment/Decrement
  4318. @section Pointer Increment and Decrement
  4319. @cindex pointer increment and decrement
  4320. @cindex incrementing pointers
  4321. @cindex decrementing pointers
  4322. The @samp{++} operator adds 1 to a variable. We have seen it for
  4323. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4324. For instance, suppose we have a series of positive integers,
  4325. terminated by a zero, and we want to add them all up.
  4326. @example
  4327. int
  4328. sum_array_till_0 (int *p)
  4329. @{
  4330. int sum = 0;
  4331. for (;;)
  4332. @{
  4333. /* @r{Fetch the next integer.} */
  4334. int next = *p++;
  4335. /* @r{Exit the loop if it's 0.} */
  4336. if (next == 0)
  4337. break;
  4338. /* @r{Add it into running total.} */
  4339. sum += next;
  4340. @}
  4341. return sum;
  4342. @}
  4343. @end example
  4344. @noindent
  4345. The statement @samp{break;} will be explained further on (@pxref{break
  4346. Statement}). Used in this way, it immediately exits the surrounding
  4347. @code{for} statement.
  4348. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4349. takes precedence over a prefix operator. Therefore, it dereferences
  4350. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4351. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4352. pointer, adding 1 to it advances it by the width of the datum it
  4353. points to---in this case, one @code{int}. Therefore, each iteration
  4354. of the loop picks up the next integer from the series and puts it into
  4355. @code{next}.
  4356. This @code{for}-loop has no initialization expression since @code{p}
  4357. and @code{sum} are already initialized, it has no end-test since the
  4358. @samp{break;} statement will exit it, and needs no expression to
  4359. advance it since that's done within the loop by incrementing @code{p}
  4360. and @code{sum}. Thus, those three expressions after @code{for} are
  4361. left empty.
  4362. Another way to write this function is by keeping the parameter value unchanged
  4363. and using indexing to access the integers in the table.
  4364. @example
  4365. int
  4366. sum_array_till_0_indexing (int *p)
  4367. @{
  4368. int i;
  4369. int sum = 0;
  4370. for (i = 0; ; i++)
  4371. @{
  4372. /* @r{Fetch the next integer.} */
  4373. int next = p[i];
  4374. /* @r{Exit the loop if it's 0.} */
  4375. if (next == 0)
  4376. break;
  4377. /* @r{Add it into running total.} */
  4378. sum += next;
  4379. @}
  4380. return sum;
  4381. @}
  4382. @end example
  4383. In this program, instead of advancing @code{p}, we advance @code{i}
  4384. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4385. i)}.) Either way, it uses the same address to get the next integer.
  4386. It makes no difference in this program whether we write @code{i++} or
  4387. @code{++i}, because the value is not used. All that matters is the
  4388. effect, to increment @code{i}.
  4389. The @samp{--} operator also works on pointers; it can be used
  4390. to scan backwards through an array, like this:
  4391. @example
  4392. int
  4393. after_last_nonzero (int *p, int len)
  4394. @{
  4395. /* @r{Set up @code{q} to point just after the last array element.} */
  4396. int *q = p + len;
  4397. while (q != p)
  4398. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4399. if (*--q != 0)
  4400. /* @r{Return the index of the element after that nonzero.} */
  4401. return q - p + 1;
  4402. return 0;
  4403. @}
  4404. @end example
  4405. That function returns the length of the nonzero part of the
  4406. array specified by its arguments; that is, the index of the
  4407. first zero of the run of zeros at the end.
  4408. @node Pointer Arithmetic Drawbacks
  4409. @section Drawbacks of Pointer Arithmetic
  4410. @cindex drawbacks of pointer arithmetic
  4411. @cindex pointer arithmetic, drawbacks
  4412. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4413. major security flaw in the C language. Theoretically, it is only
  4414. valid to adjust a pointer within one object allocated as a unit in
  4415. memory. However, if you unintentionally adjust a pointer across the
  4416. bounds of the object and into some other object, the system has no way
  4417. to detect this error.
  4418. A bug which does that can easily result in clobbering part of another
  4419. object. For example, with @code{array[-1]} you can read or write the
  4420. nonexistent element before the beginning of an array---probably part
  4421. of some other data.
  4422. Combining pointer arithmetic with casts between pointer types, you can
  4423. create a pointer that fails to be properly aligned for its type. For
  4424. example,
  4425. @example
  4426. int a[2];
  4427. char *pa = (char *)a;
  4428. int *p = (int *)(pa + 1);
  4429. @end example
  4430. @noindent
  4431. gives @code{p} a value pointing to an ``integer'' that includes part
  4432. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4433. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4434. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4435. ``works,'' it may be quite slow. It can also cause aliasing
  4436. confusions (@pxref{Aliasing}).
  4437. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4438. unless it is really necessary.
  4439. @node Pointer-Integer Conversion
  4440. @section Pointer-Integer Conversion
  4441. @cindex pointer-integer conversion
  4442. @cindex conversion between pointers and integers
  4443. @cindex @code{uintptr_t}
  4444. On modern computers, an address is simply a number. It occupies the
  4445. same space as some size of integer. In C, you can convert a pointer
  4446. to the appropriate integer types and vice versa, without losing
  4447. information. The appropriate integer types are @code{uintptr_t} (an
  4448. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4449. in @file{stdint.h}.
  4450. For instance,
  4451. @example
  4452. #include <stdint.h>
  4453. #include <stdio.h>
  4454. void
  4455. print_pointer (void *ptr)
  4456. @{
  4457. uintptr_t converted = (uintptr_t) ptr;
  4458. printf ("Pointer value is 0x%x\n",
  4459. (unsigned int) converted);
  4460. @}
  4461. @end example
  4462. @noindent
  4463. The specification @samp{%x} in the template (the first argument) for
  4464. @code{printf} means to represent this argument using hexadecimal
  4465. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4466. printing treats the number as unsigned, but it won't actually matter:
  4467. all @code{printf} gets to see is the series of bits in the number.
  4468. @strong{Warning:} Converting pointers to integers is risky---don't do
  4469. it unless it is really necessary.
  4470. @node Printing Pointers
  4471. @section Printing Pointers
  4472. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4473. For example:
  4474. @example
  4475. void
  4476. print_pointer (void *ptr)
  4477. @{
  4478. printf ("Pointer value is %p\n", ptr);
  4479. @}
  4480. @end example
  4481. The specification @samp{%p} works with any pointer type. It prints
  4482. @samp{0x} followed by the address in hexadecimal, printed as the
  4483. appropriate unsigned integer type.
  4484. @node Structures
  4485. @chapter Structures
  4486. @cindex structures
  4487. @findex struct
  4488. @cindex fields in structures
  4489. A @dfn{structure} is a user-defined data type that holds various
  4490. @dfn{fields} of data. Each field has a name and a data type specified
  4491. in the structure's definition.
  4492. Here we define a structure suitable for storing a linked list of
  4493. integers. Each list item will hold one integer, plus a pointer
  4494. to the next item.
  4495. @example
  4496. struct intlistlink
  4497. @{
  4498. int datum;
  4499. struct intlistlink *next;
  4500. @};
  4501. @end example
  4502. The structure definition has a @dfn{type tag} so that the code can
  4503. refer to this structure. The type tag here is @code{intlistlink}.
  4504. The definition refers recursively to the same structure through that
  4505. tag.
  4506. You can define a structure without a type tag, but then you can't
  4507. refer to it again. That is useful only in some special contexts, such
  4508. as inside a @code{typedef} or a @code{union}.
  4509. The contents of the structure are specified by the @dfn{field
  4510. declarations} inside the braces. Each field in the structure needs a
  4511. declaration there. The fields in one structure definition must have
  4512. distinct names, but these names do not conflict with any other names
  4513. in the program.
  4514. A field declaration looks just like a variable declaration. You can
  4515. combine field declarations with the same beginning, just as you can
  4516. combine variable declarations.
  4517. This structure has two fields. One, named @code{datum}, has type
  4518. @code{int} and will hold one integer in the list. The other, named
  4519. @code{next}, is a pointer to another @code{struct intlistlink}
  4520. which would be the rest of the list. In the last list item, it would
  4521. be @code{NULL}.
  4522. This structure definition is recursive, since the type of the
  4523. @code{next} field refers to the structure type. Such recursion is not
  4524. a problem; in fact, you can use the type @code{struct intlistlink *}
  4525. before the definition of the type @code{struct intlistlink} itself.
  4526. That works because pointers to all kinds of structures really look the
  4527. same at the machine level.
  4528. After defining the structure, you can declare a variable of type
  4529. @code{struct intlistlink} like this:
  4530. @example
  4531. struct intlistlink foo;
  4532. @end example
  4533. The structure definition itself can serve as the beginning of a
  4534. variable declaration, so you can declare variables immediately after,
  4535. like this:
  4536. @example
  4537. struct intlistlink
  4538. @{
  4539. int datum;
  4540. struct intlistlink *next;
  4541. @} foo;
  4542. @end example
  4543. @noindent
  4544. But that is ugly. It is almost always clearer to separate the
  4545. definition of the structure from its uses.
  4546. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4547. the scope of the structure type name to that block. That means the
  4548. structure type is recognized only within that block. Declaring it in
  4549. a function parameter list, as here,
  4550. @example
  4551. int f (struct foo @{int a, b@} parm);
  4552. @end example
  4553. @noindent
  4554. (assuming that @code{struct foo} is not already defined) limits the
  4555. scope of the structure type @code{struct foo} to that parameter list;
  4556. that is basically useless, so it triggers a warning.
  4557. Standard C requires at least one field in a structure.
  4558. GNU C does not require this.
  4559. @menu
  4560. * Referencing Fields:: Accessing field values in a structure object.
  4561. * Dynamic Memory Allocation:: Allocating space for objects
  4562. while the program is running.
  4563. * Field Offset:: Memory layout of fields within a structure.
  4564. * Structure Layout:: Planning the memory layout of fields.
  4565. * Packed Structures:: Packing structure fields as close as possible.
  4566. * Bit Fields:: Dividing integer fields
  4567. into fields with fewer bits.
  4568. * Bit Field Packing:: How bit fields pack together in integers.
  4569. * const Fields:: Making structure fields immutable.
  4570. * Zero Length:: Zero-length array as a variable-length object.
  4571. * Flexible Array Fields:: Another approach to variable-length objects.
  4572. * Overlaying Structures:: Casting one structure type
  4573. over an object of another structure type.
  4574. * Structure Assignment:: Assigning values to structure objects.
  4575. * Unions:: Viewing the same object in different types.
  4576. * Packing With Unions:: Using a union type to pack various types into
  4577. the same memory space.
  4578. * Cast to Union:: Casting a value one of the union's alternative
  4579. types to the type of the union itself.
  4580. * Structure Constructors:: Building new structure objects.
  4581. * Unnamed Types as Fields:: Fields' types do not always need names.
  4582. * Incomplete Types:: Types which have not been fully defined.
  4583. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4584. * Type Tags:: Scope of structure and union type tags.
  4585. @end menu
  4586. @node Referencing Fields
  4587. @section Referencing Structure Fields
  4588. @cindex referencing structure fields
  4589. @cindex structure fields, referencing
  4590. To make a structure useful, there has to be a way to examine and store
  4591. its fields. The @samp{.} (period) operator does that; its use looks
  4592. like @code{@var{object}.@var{field}}.
  4593. Given this structure and variable,
  4594. @example
  4595. struct intlistlink
  4596. @{
  4597. int datum;
  4598. struct intlistlink *next;
  4599. @};
  4600. struct intlistlink foo;
  4601. @end example
  4602. @noindent
  4603. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4604. fields in the value of @code{foo}. These fields are lvalues, so you
  4605. can store values into them, and read the values out again.
  4606. Most often, structures are dynamically allocated (see the next
  4607. section), and we refer to the objects via pointers.
  4608. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4609. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4610. contains this declaration:
  4611. @example
  4612. struct intlistlink *ptr;
  4613. @end example
  4614. @noindent
  4615. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4616. to the two fields in the object that @code{ptr} points to.
  4617. If a unary operator precedes an expression using @samp{->},
  4618. the @samp{->} nests inside:
  4619. @example
  4620. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4621. @end example
  4622. You can intermix @samp{->} and @samp{.} without parentheses,
  4623. as shown here:
  4624. @example
  4625. struct @{ double d; struct intlistlink l; @} foo;
  4626. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4627. @end example
  4628. @node Dynamic Memory Allocation
  4629. @section Dynamic Memory Allocation
  4630. @cindex dynamic memory allocation
  4631. @cindex memory allocation, dynamic
  4632. @cindex allocating memory dynamically
  4633. To allocate an object dynamically, call the library function
  4634. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4635. Reference Manual}). Here is how to allocate an object of type
  4636. @code{struct intlistlink}. To make this code work, include the file
  4637. @file{stdlib.h}, like this:
  4638. @example
  4639. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4640. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4641. @dots{}
  4642. struct intlistlink *
  4643. alloc_intlistlink ()
  4644. @{
  4645. struct intlistlink *p;
  4646. p = malloc (sizeof (struct intlistlink));
  4647. if (p == NULL)
  4648. fatal ("Ran out of storage");
  4649. /* @r{Initialize the contents.} */
  4650. p->datum = 0;
  4651. p->next = NULL;
  4652. return p;
  4653. @}
  4654. @end example
  4655. @noindent
  4656. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4657. will automatically convert it to type @code{struct intlistlink *}.
  4658. The return value of @code{malloc} is always sufficiently aligned
  4659. (@pxref{Type Alignment}) that it is valid for any data type.
  4660. The test for @code{p == NULL} is necessary because @code{malloc}
  4661. returns a null pointer if it cannot get any storage. We assume that
  4662. the program defines the function @code{fatal} to report a fatal error
  4663. to the user.
  4664. Here's how to add one more integer to the front of such a list:
  4665. @example
  4666. struct intlistlink *my_list = NULL;
  4667. void
  4668. add_to_mylist (int my_int)
  4669. @{
  4670. struct intlistlink *p = alloc_intlistlink ();
  4671. p->datum = my_int;
  4672. p->next = mylist;
  4673. mylist = p;
  4674. @}
  4675. @end example
  4676. The way to free the objects is by calling @code{free}. Here's
  4677. a function to free all the links in one of these lists:
  4678. @example
  4679. void
  4680. free_intlist (struct intlistlink *p)
  4681. @{
  4682. while (p)
  4683. @{
  4684. struct intlistlink *q = p;
  4685. p = p->next;
  4686. free (q);
  4687. @}
  4688. @}
  4689. @end example
  4690. We must extract the @code{next} pointer from the object before freeing
  4691. it, because @code{free} can clobber the data that was in the object.
  4692. For the same reason, the program must not use the list any more after
  4693. freeing its elements. To make sure it won't, it is best to clear out
  4694. the variable where the list was stored, like this:
  4695. @example
  4696. free_intlist (mylist);
  4697. mylist = NULL;
  4698. @end example
  4699. @node Field Offset
  4700. @section Field Offset
  4701. @cindex field offset
  4702. @cindex structure field offset
  4703. @cindex offset of structure fields
  4704. To determine the offset of a given field @var{field} in a structure
  4705. type @var{type}, use the macro @code{offsetof}, which is defined in
  4706. the file @file{stddef.h}. It is used like this:
  4707. @example
  4708. offsetof (@var{type}, @var{field})
  4709. @end example
  4710. Here is an example:
  4711. @example
  4712. struct foo
  4713. @{
  4714. int element;
  4715. struct foo *next;
  4716. @};
  4717. offsetof (struct foo, next)
  4718. /* @r{On most machines that is 4. It may be 8.} */
  4719. @end example
  4720. @node Structure Layout
  4721. @section Structure Layout
  4722. @cindex structure layout
  4723. @cindex layout of structures
  4724. The rest of this chapter covers advanced topics about structures. If
  4725. you are just learning C, you can skip it.
  4726. The precise layout of a @code{struct} type is crucial when using it to
  4727. overlay hardware registers, to access data structures in shared
  4728. memory, or to assemble and disassemble packets for network
  4729. communication. It is also important for avoiding memory waste when
  4730. the program makes many objects of that type. However, the layout
  4731. depends on the target platform. Each platform has conventions for
  4732. structure layout, which compilers need to follow.
  4733. Here are the conventions used on most platforms.
  4734. The structure's fields appear in the structure layout in the order
  4735. they are declared. When possible, consecutive fields occupy
  4736. consecutive bytes within the structure. However, if a field's type
  4737. demands more alignment than it would get that way, C gives it the
  4738. alignment it requires by leaving a gap after the previous field.
  4739. Once all the fields have been laid out, it is possible to determine
  4740. the structure's alignment and size. The structure's alignment is the
  4741. maximum alignment of any of the fields in it. Then the structure's
  4742. size is rounded up to a multiple of its alignment. That may require
  4743. leaving a gap at the end of the structure.
  4744. Here are some examples, where we assume that @code{char} has size and
  4745. alignment 1 (always true), and @code{int} has size and alignment 4
  4746. (true on most kinds of computers):
  4747. @example
  4748. struct foo
  4749. @{
  4750. char a, b;
  4751. int c;
  4752. @};
  4753. @end example
  4754. @noindent
  4755. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4756. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4757. There is a gap of 2 bytes before @code{c}.
  4758. Contrast that with this structure:
  4759. @example
  4760. struct foo
  4761. @{
  4762. char a;
  4763. int c;
  4764. char b;
  4765. @};
  4766. @end example
  4767. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4768. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4769. gaps: three bytes before @code{c}, and three bytes at the end.
  4770. These two structures have the same contents at the C level, but one
  4771. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4772. fields. A reliable way to avoid this sort of wastage is to order the
  4773. fields by size, biggest fields first.
  4774. @node Packed Structures
  4775. @section Packed Structures
  4776. @cindex packed structures
  4777. @cindex @code{__attribute__((packed))}
  4778. In GNU C you can force a structure to be laid out with no gaps by
  4779. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4780. end of the structure type declaration). Here's an example:
  4781. @example
  4782. struct __attribute__((packed)) foo
  4783. @{
  4784. char a;
  4785. int c;
  4786. char b;
  4787. @};
  4788. @end example
  4789. Without @code{__attribute__((packed))}, this structure occupies 12
  4790. bytes (as described in the previous section), assuming 4-byte
  4791. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4792. only 6 bytes long---the sum of the lengths of its fields.
  4793. Use of @code{__attribute__((packed))} often results in fields that
  4794. don't have the normal alignment for their types. Taking the address
  4795. of such a field can result in an invalid pointer because of its
  4796. improper alignment. Dereferencing such a pointer can cause a
  4797. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4798. unaligned pointers.
  4799. @xref{Attributes}.
  4800. @node Bit Fields
  4801. @section Bit Fields
  4802. @cindex bit fields
  4803. A structure field declaration with an integer type can specify the
  4804. number of bits the field should occupy. We call that a @dfn{bit
  4805. field}. These are useful because consecutive bit fields are packed
  4806. into a larger storage unit. For instance,
  4807. @example
  4808. unsigned char opcode: 4;
  4809. @end example
  4810. @noindent
  4811. specifies that this field takes just 4 bits.
  4812. Since it is unsigned, its possible values range
  4813. from 0 to 15. A signed field with 4 bits, such as this,
  4814. @example
  4815. signed char small: 4;
  4816. @end example
  4817. @noindent
  4818. can hold values from -8 to 7.
  4819. You can subdivide a single byte into those two parts by writing
  4820. @example
  4821. unsigned char opcode: 4;
  4822. signed char small: 4;
  4823. @end example
  4824. @noindent
  4825. in the structure. With bit fields, these two numbers fit into
  4826. a single @code{char}.
  4827. Here's how to declare a one-bit field that can hold either 0 or 1:
  4828. @example
  4829. unsigned char special_flag: 1;
  4830. @end example
  4831. You can also use the @code{bool} type for bit fields:
  4832. @example
  4833. bool special_flag: 1;
  4834. @end example
  4835. Except when using @code{bool} (which is always unsigned,
  4836. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4837. for a bit field. There is a default, if that's not specified: the bit
  4838. field is signed if plain @code{char} is signed, except that the option
  4839. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4840. is cleaner not to depend on this default.
  4841. Bit fields are special in that you cannot take their address with
  4842. @samp{&}. They are not stored with the size and alignment appropriate
  4843. for the specified type, so they cannot be addressed through pointers
  4844. to that type.
  4845. @node Bit Field Packing
  4846. @section Bit Field Packing
  4847. Programs to communicate with low-level hardware interfaces need to
  4848. define bit fields laid out to match the hardware data. This section
  4849. explains how to do that.
  4850. Consecutive bit fields are packed together, but each bit field must
  4851. fit within a single object of its specified type. In this example,
  4852. @example
  4853. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4854. @end example
  4855. @noindent
  4856. all five fields fit consecutively into one two-byte @code{short}.
  4857. They need 15 bits, and one @code{short} provides 16. By contrast,
  4858. @example
  4859. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4860. @end example
  4861. @noindent
  4862. needs three bytes. It fits @code{a} and @code{b} into one
  4863. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4864. add up to 9 bits). So @code{c} and @code{d} go into a second
  4865. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4866. Then @code{e} needs a third @code{char}. By contrast,
  4867. @example
  4868. unsigned char a : 3, b : 3;
  4869. unsigned int c : 3;
  4870. unsigned char d : 3, e : 3;
  4871. @end example
  4872. @noindent
  4873. needs only two bytes: the type @code{unsigned int}
  4874. allows @code{c} to straddle bytes that are in the same word.
  4875. You can leave a gap of a specified number of bits by defining a
  4876. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4877. It is allocated space in the structure just as a named bit field would
  4878. be allocated.
  4879. You can force the following bit field to advance to the following
  4880. aligned memory object with @code{@var{type} : 0;}.
  4881. Both of these constructs can syntactically share @var{type} with
  4882. ordinary bit fields. This example illustrates both:
  4883. @example
  4884. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4885. @end example
  4886. @noindent
  4887. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4888. between them. Then @code{: 0} advances to the next @code{int},
  4889. so @code{c} and @code{d} fit into that one.
  4890. These rules for packing bit fields apply to most target platforms,
  4891. including all the usual real computers. A few embedded controllers
  4892. have special layout rules.
  4893. @node const Fields
  4894. @section @code{const} Fields
  4895. @cindex const fields
  4896. @cindex structure fields, constant
  4897. @c ??? Is this a C standard feature?
  4898. A structure field declared @code{const} cannot be assigned to
  4899. (@pxref{const}). For instance, let's define this modified version of
  4900. @code{struct intlistlink}:
  4901. @example
  4902. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4903. @{
  4904. const int datum;
  4905. struct intlistlink *next;
  4906. @};
  4907. @end example
  4908. This structure can be used to prevent part of the code from modifying
  4909. the @code{datum} field:
  4910. @example
  4911. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4912. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4913. struct intlistlink_ro *q
  4914. = (struct intlistlink_ro *) p;
  4915. q->datum = 5; /* @r{Error!} */
  4916. p->datum = 5; /* @r{Valid since @code{*p} is}
  4917. @r{not a @code{struct intlistlink_ro}.} */
  4918. @end example
  4919. A @code{const} field can get a value in two ways: by initialization of
  4920. the whole structure, and by making a pointer-to-structure point to an object
  4921. in which that field already has a value.
  4922. Any @code{const} field in a structure type makes assignment impossible
  4923. for structures of that type (@pxref{Structure Assignment}). That is
  4924. because structure assignment works by assigning the structure's
  4925. fields, one by one.
  4926. @node Zero Length
  4927. @section Arrays of Length Zero
  4928. @cindex array of length zero
  4929. @cindex zero-length arrays
  4930. @cindex length-zero arrays
  4931. GNU C allows zero-length arrays. They are useful as the last element
  4932. of a structure that is really a header for a variable-length object.
  4933. Here's an example, where we construct a variable-size structure
  4934. to hold a line which is @code{this_length} characters long:
  4935. @example
  4936. struct line @{
  4937. int length;
  4938. char contents[0];
  4939. @};
  4940. struct line *thisline
  4941. = ((struct line *)
  4942. malloc (sizeof (struct line)
  4943. + this_length));
  4944. thisline->length = this_length;
  4945. @end example
  4946. In ISO C90, we would have to give @code{contents} a length of 1, which
  4947. means either wasting space or complicating the argument to @code{malloc}.
  4948. @node Flexible Array Fields
  4949. @section Flexible Array Fields
  4950. @cindex flexible array fields
  4951. @cindex array fields, flexible
  4952. The C99 standard adopted a more complex equivalent of zero-length
  4953. array fields. It's called a @dfn{flexible array}, and it's indicated
  4954. by omitting the length, like this:
  4955. @example
  4956. struct line
  4957. @{
  4958. int length;
  4959. char contents[];
  4960. @};
  4961. @end example
  4962. The flexible array has to be the last field in the structure, and there
  4963. must be other fields before it.
  4964. Under the C standard, a structure with a flexible array can't be part
  4965. of another structure, and can't be an element of an array.
  4966. GNU C allows static initialization of flexible array fields. The effect
  4967. is to ``make the array long enough'' for the initializer.
  4968. @example
  4969. struct f1 @{ int x; int y[]; @} f1
  4970. = @{ 1, @{ 2, 3, 4 @} @};
  4971. @end example
  4972. @noindent
  4973. This defines a structure variable named @code{f1}
  4974. whose type is @code{struct f1}. In C, a variable name or function name
  4975. never conflicts with a structure type tag.
  4976. Omitting the flexible array field's size lets the initializer
  4977. determine it. This is allowed only when the flexible array is defined
  4978. in the outermost structure and you declare a variable of that
  4979. structure type. For example:
  4980. @example
  4981. struct foo @{ int x; int y[]; @};
  4982. struct bar @{ struct foo z; @};
  4983. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4984. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4985. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4986. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4987. @end example
  4988. @node Overlaying Structures
  4989. @section Overlaying Different Structures
  4990. @cindex overlaying structures
  4991. @cindex structures, overlaying
  4992. Be careful about using different structure types to refer to the same
  4993. memory within one function, because GNU C can optimize code assuming
  4994. it never does that. @xref{Aliasing}. Here's an example of the kind of
  4995. aliasing that can cause the problem:
  4996. @example
  4997. struct a @{ int size; char *data; @};
  4998. struct b @{ int size; char *data; @};
  4999. struct a foo;
  5000. struct b *q = (struct b *) &foo;
  5001. @end example
  5002. Here @code{q} points to the same memory that the variable @code{foo}
  5003. occupies, but they have two different types. The two types
  5004. @code{struct a} and @code{struct b} are defined alike, but they are
  5005. not the same type. Interspersing references using the two types,
  5006. like this,
  5007. @example
  5008. p->size = 0;
  5009. q->size = 1;
  5010. x = p->size;
  5011. @end example
  5012. @noindent
  5013. allows GNU C to assume that @code{p->size} is still zero when it is
  5014. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5015. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5016. Other compilers might also do this optimization. The ISO C standard
  5017. considers such code erroneous, precisely so that this optimization
  5018. will be valid.
  5019. @node Structure Assignment
  5020. @section Structure Assignment
  5021. @cindex structure assignment
  5022. @cindex assigning structures
  5023. Assignment operating on a structure type copies the structure. The
  5024. left and right operands must have the same type. Here is an example:
  5025. @example
  5026. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5027. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5028. @r{@dots{}}
  5029. struct point @{ double x, y; @};
  5030. struct point *
  5031. copy_point (struct point point)
  5032. @{
  5033. struct point *p
  5034. = (struct point *) malloc (sizeof (struct point));
  5035. if (p == NULL)
  5036. fatal ("Out of memory");
  5037. *p = point;
  5038. return p;
  5039. @}
  5040. @end example
  5041. Notionally, assignment on a structure type works by copying each of
  5042. the fields. Thus, if any of the fields has the @code{const}
  5043. qualifier, that structure type does not allow assignment:
  5044. @example
  5045. struct point @{ const double x, y; @};
  5046. struct point a, b;
  5047. a = b; /* @r{Error!} */
  5048. @end example
  5049. @xref{Assignment Expressions}.
  5050. @node Unions
  5051. @section Unions
  5052. @cindex unions
  5053. @findex union
  5054. A @dfn{union type} defines alternative ways of looking at the same
  5055. piece of memory. Each alternative view is defined with a data type,
  5056. and identified by a name. A union definition looks like this:
  5057. @example
  5058. union @var{name}
  5059. @{
  5060. @var{alternative declarations}@r{@dots{}}
  5061. @};
  5062. @end example
  5063. Each alternative declaration looks like a structure field declaration,
  5064. except that it can't be a bit field. For instance,
  5065. @example
  5066. union number
  5067. @{
  5068. long int integer;
  5069. double float;
  5070. @}
  5071. @end example
  5072. @noindent
  5073. lets you store either an integer (type @code{long int}) or a floating
  5074. point number (type @code{double}) in the same place in memory. The
  5075. length and alignment of the union type are the maximum of all the
  5076. alternatives---they do not have to be the same. In this union
  5077. example, @code{double} probably takes more space than @code{long int},
  5078. but that doesn't cause a problem in programs that use the union in the
  5079. normal way.
  5080. The members don't have to be different in data type. Sometimes
  5081. each member pertains to a way the data will be used. For instance,
  5082. @example
  5083. union datum
  5084. @{
  5085. double latitude;
  5086. double longitude;
  5087. double height;
  5088. double weight;
  5089. int continent;
  5090. @}
  5091. @end example
  5092. This union holds one of several kinds of data; most kinds are floating
  5093. points, but the value can also be a code for a continent which is an
  5094. integer. You @emph{could} use one member of type @code{double} to
  5095. access all the values which have that type, but the different member
  5096. names will make the program clearer.
  5097. The alignment of a union type is the maximum of the alignments of the
  5098. alternatives. The size of the union type is the maximum of the sizes
  5099. of the alternatives, rounded up to a multiple of the alignment
  5100. (because every type's size must be a multiple of its alignment).
  5101. All the union alternatives start at the address of the union itself.
  5102. If an alternative is shorter than the union as a whole, it occupies
  5103. the first part of the union's storage, leaving the last part unused
  5104. @emph{for that alternative}.
  5105. @strong{Warning:} if the code stores data using one union alternative
  5106. and accesses it with another, the results depend on the kind of
  5107. computer in use. Only wizards should try to do this. However, when
  5108. you need to do this, a union is a clean way to do it.
  5109. Assignment works on any union type by copying the entire value.
  5110. @node Packing With Unions
  5111. @section Packing With Unions
  5112. Sometimes we design a union with the intention of packing various
  5113. kinds of objects into a certain amount of memory space. For example.
  5114. @example
  5115. union bytes8
  5116. @{
  5117. long long big_int_elt;
  5118. double double_elt;
  5119. struct @{ int first, second; @} two_ints;
  5120. struct @{ void *first, *second; @} two_ptrs;
  5121. @};
  5122. union bytes8 *p;
  5123. @end example
  5124. This union makes it possible to look at 8 bytes of data that @code{p}
  5125. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5126. single floating-point number (@code{p->double_elt}), as a pair of
  5127. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5128. as a pair of pointers (@code{p->two_ptrs.first} and
  5129. @code{p->two_ptrs.second}).
  5130. To pack storage with such a union makes assumptions about the sizes of
  5131. all the types involved. This particular union was written expecting a
  5132. pointer to have the same size as @code{int}. On a machine where one
  5133. pointer takes 8 bytes, the code using this union probably won't work
  5134. as expected. The union, as such, will function correctly---if you
  5135. store two values through @code{two_ints} and extract them through
  5136. @code{two_ints}, you will get the same integers back---but the part of
  5137. the program that expects the union to be 8 bytes long could
  5138. malfunction, or at least use too much space.
  5139. The above example shows one case where a @code{struct} type with no
  5140. tag can be useful. Another way to get effectively the same result
  5141. is with arrays as members of the union:
  5142. @example
  5143. union eight_bytes
  5144. @{
  5145. long long big_int_elt;
  5146. double double_elt;
  5147. int two_ints[2];
  5148. void *two_ptrs[2];
  5149. @};
  5150. @end example
  5151. @node Cast to Union
  5152. @section Cast to a Union Type
  5153. @cindex cast to a union
  5154. @cindex union, casting to a
  5155. In GNU C, you can explicitly cast any of the alternative types to the
  5156. union type; for instance,
  5157. @example
  5158. (union eight_bytes) (long long) 5
  5159. @end example
  5160. @noindent
  5161. makes a value of type @code{union eight_bytes} which gets its contents
  5162. through the alternative named @code{big_int_elt}.
  5163. The value being cast must exactly match the type of the alternative,
  5164. so this is not valid:
  5165. @example
  5166. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5167. @end example
  5168. A cast to union type looks like any other cast, except that the type
  5169. specified is a union type. You can specify the type either with
  5170. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5171. Typedef Names}).
  5172. Using the cast as the right-hand side of an assignment to a variable of
  5173. union type is equivalent to storing in an alternative of the union:
  5174. @example
  5175. union foo u;
  5176. u = (union foo) x @r{means} u.i = x
  5177. u = (union foo) y @r{means} u.d = y
  5178. @end example
  5179. You can also use the union cast as a function argument:
  5180. @example
  5181. void hack (union foo);
  5182. @r{@dots{}}
  5183. hack ((union foo) x);
  5184. @end example
  5185. @node Structure Constructors
  5186. @section Structure Constructors
  5187. @cindex structure constructors
  5188. @cindex constructors, structure
  5189. You can construct a structure value by writing its type in
  5190. parentheses, followed by an initializer that would be valid in a
  5191. declaration for that type. For instance, given this declaration,
  5192. @example
  5193. struct foo @{int a; char b[2];@} structure;
  5194. @end example
  5195. @noindent
  5196. you can create a @code{struct foo} value as follows:
  5197. @example
  5198. ((struct foo) @{x + y, 'a', 0@})
  5199. @end example
  5200. @noindent
  5201. This specifies @code{x + y} for field @code{a},
  5202. the character @samp{a} for field @code{b}'s element 0,
  5203. and the null character for field @code{b}'s element 1.
  5204. The parentheses around that constructor are to necessary, but we
  5205. recommend writing them to make the nesting of the containing
  5206. expression clearer.
  5207. You can also show the nesting of the two by writing it like
  5208. this:
  5209. @example
  5210. ((struct foo) @{x + y, @{'a', 0@} @})
  5211. @end example
  5212. Each of those is equivalent to writing the following statement
  5213. expression (@pxref{Statement Exprs}):
  5214. @example
  5215. (@{
  5216. struct foo temp = @{x + y, 'a', 0@};
  5217. temp;
  5218. @})
  5219. @end example
  5220. You can also create a union value this way, but it is not especially
  5221. useful since that is equivalent to doing a cast:
  5222. @example
  5223. ((union whosis) @{@var{value}@})
  5224. @r{is equivalent to}
  5225. ((union whosis) (@var{value}))
  5226. @end example
  5227. @node Unnamed Types as Fields
  5228. @section Unnamed Types as Fields
  5229. @cindex unnamed structures
  5230. @cindex unnamed unions
  5231. @cindex structures, unnamed
  5232. @cindex unions, unnamed
  5233. A structure or a union can contain, as fields,
  5234. unnamed structures and unions. Here's an example:
  5235. @example
  5236. struct
  5237. @{
  5238. int a;
  5239. union
  5240. @{
  5241. int b;
  5242. float c;
  5243. @};
  5244. int d;
  5245. @} foo;
  5246. @end example
  5247. @noindent
  5248. You can access the fields of the unnamed union within @code{foo} as if they
  5249. were individual fields at the same level as the union definition:
  5250. @example
  5251. foo.a = 42;
  5252. foo.b = 47;
  5253. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5254. foo.d = 314;
  5255. @end example
  5256. Avoid using field names that could cause ambiguity. For example, with
  5257. this definition:
  5258. @example
  5259. struct
  5260. @{
  5261. int a;
  5262. struct
  5263. @{
  5264. int a;
  5265. float b;
  5266. @};
  5267. @} foo;
  5268. @end example
  5269. @noindent
  5270. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5271. an error when a definition is ambiguous in this way.
  5272. @node Incomplete Types
  5273. @section Incomplete Types
  5274. @cindex incomplete types
  5275. @cindex types, incomplete
  5276. A type that has not been fully defined is called an @dfn{incomplete
  5277. type}. Structure and union types are incomplete when the code makes a
  5278. forward reference, such as @code{struct foo}, before defining the
  5279. type. An array type is incomplete when its length is unspecified.
  5280. You can't use an incomplete type to declare a variable or field, or
  5281. use it for a function parameter or return type. The operators
  5282. @code{sizeof} and @code{_Alignof} give errors when used on an
  5283. incomplete type.
  5284. However, you can define a pointer to an incomplete type, and declare a
  5285. variable or field with such a pointer type. In general, you can do
  5286. everything with such pointers except dereference them. For example:
  5287. @example
  5288. extern void bar (struct mysterious_value *);
  5289. void
  5290. foo (struct mysterious_value *arg)
  5291. @{
  5292. bar (arg);
  5293. @}
  5294. @r{@dots{}}
  5295. @{
  5296. struct mysterious_value *p, **q;
  5297. p = *q;
  5298. foo (p);
  5299. @}
  5300. @end example
  5301. @noindent
  5302. These examples are valid because the code doesn't try to understand
  5303. what @code{p} points to; it just passes the pointer around.
  5304. (Presumably @code{bar} is defined in some other file that really does
  5305. have a definition for @code{struct mysterious_value}.) However,
  5306. dereferencing the pointer would get an error; that requires a
  5307. definition for the structure type.
  5308. @node Intertwined Incomplete Types
  5309. @section Intertwined Incomplete Types
  5310. When several structure types contain pointers to each other, you can
  5311. define the types in any order because pointers to types that come
  5312. later are incomplete types. Thus,
  5313. Here is an example.
  5314. @example
  5315. /* @r{An employee record points to a group.} */
  5316. struct employee
  5317. @{
  5318. char *name;
  5319. @r{@dots{}}
  5320. struct group *group; /* @r{incomplete type.} */
  5321. @r{@dots{}}
  5322. @};
  5323. /* @r{An employee list points to employees.} */
  5324. struct employee_list
  5325. @{
  5326. struct employee *this_one;
  5327. struct employee_list *next; /* @r{incomplete type.} */
  5328. @r{@dots{}}
  5329. @};
  5330. /* @r{A group points to one employee_list.} */
  5331. struct group
  5332. @{
  5333. char *name;
  5334. @r{@dots{}}
  5335. struct employee_list *employees;
  5336. @r{@dots{}}
  5337. @};
  5338. @end example
  5339. @node Type Tags
  5340. @section Type Tags
  5341. @cindex type tags
  5342. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5343. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5344. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5345. name or function name; the type tags have a separate @dfn{name space}.
  5346. Thus, there is no name conflict in this code:
  5347. @example
  5348. struct pair @{ int a, b; @};
  5349. int pair = 1;
  5350. @end example
  5351. @noindent
  5352. nor in this one:
  5353. @example
  5354. struct pair @{ int a, b; @} pair;
  5355. @end example
  5356. @noindent
  5357. where @code{pair} is both a structure type tag and a variable name.
  5358. However, @code{struct}, @code{union}, and @code{enum} share the same
  5359. name space of tags, so this is a conflict:
  5360. @example
  5361. struct pair @{ int a, b; @};
  5362. enum pair @{ c, d @};
  5363. @end example
  5364. @noindent
  5365. and so is this:
  5366. @example
  5367. struct pair @{ int a, b; @};
  5368. struct pair @{ int c, d; @};
  5369. @end example
  5370. When the code defines a type tag inside a block, the tag's scope is
  5371. limited to that block (as for local variables). Two definitions for
  5372. one type tag do not conflict if they are in different scopes; rather,
  5373. each is valid in its scope. For example,
  5374. @example
  5375. struct pair @{ int a, b; @};
  5376. void
  5377. pair_up_doubles (int len, double array[])
  5378. @{
  5379. struct pair @{ double a, b; @};
  5380. @r{@dots{}}
  5381. @}
  5382. @end example
  5383. @noindent
  5384. has two definitions for @code{struct pair} which do not conflict. The
  5385. one inside the function applies only within the definition of
  5386. @code{pair_up_doubles}. Within its scope, that definition
  5387. @dfn{shadows} the outer definition.
  5388. If @code{struct pair} appears inside the function body, before the
  5389. inner definition, it refers to the outer definition---the only one
  5390. that has been seen at that point. Thus, in this code,
  5391. @example
  5392. struct pair @{ int a, b; @};
  5393. void
  5394. pair_up_doubles (int len, double array[])
  5395. @{
  5396. struct two_pairs @{ struct pair *p, *q; @};
  5397. struct pair @{ double a, b; @};
  5398. @r{@dots{}}
  5399. @}
  5400. @end example
  5401. @noindent
  5402. the structure @code{two_pairs} has pointers to the outer definition of
  5403. @code{struct pair}, which is probably not desirable.
  5404. To prevent that, you can write @code{struct pair;} inside the function
  5405. body as a variable declaration with no variables. This is a
  5406. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5407. type tag local to the current block, with the details of the type to
  5408. come later. Here's an example:
  5409. @example
  5410. void
  5411. pair_up_doubles (int len, double array[])
  5412. @{
  5413. /* @r{Forward declaration for @code{pair}.} */
  5414. struct pair;
  5415. struct two_pairs @{ struct pair *p, *q; @};
  5416. /* @r{Give the details.} */
  5417. struct pair @{ double a, b; @};
  5418. @r{@dots{}}
  5419. @}
  5420. @end example
  5421. However, the cleanest practice is to avoid shadowing type tags.
  5422. @node Arrays
  5423. @chapter Arrays
  5424. @cindex array
  5425. @cindex elements of arrays
  5426. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5427. all of the same data type. Each element is identified by its numeric
  5428. @var{index} within the array.
  5429. We presented arrays of numbers in the sample programs early in this
  5430. manual (@pxref{Array Example}). However, arrays can have elements of
  5431. any data type, including pointers, structures, unions, and other
  5432. arrays.
  5433. If you know another programming language, you may suppose that you know all
  5434. about arrays, but C arrays have special quirks, so in this chapter we
  5435. collect all the information about arrays in C@.
  5436. The elements of a C array are allocated consecutively in memory,
  5437. with no gaps between them. Each element is aligned as required
  5438. for its data type (@pxref{Type Alignment}).
  5439. @menu
  5440. * Accessing Array Elements:: How to access individual elements of an array.
  5441. * Declaring an Array:: How to name and reserve space for a new array.
  5442. * Strings:: A string in C is a special case of array.
  5443. * Array Type Designators:: Referring to a specific array type.
  5444. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5445. * Limitations of C Arrays:: Arrays are not first-class objects.
  5446. * Multidimensional Arrays:: Arrays of arrays.
  5447. * Constructing Array Values:: Assigning values to an entire array at once.
  5448. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5449. @end menu
  5450. @node Accessing Array Elements
  5451. @section Accessing Array Elements
  5452. @cindex accessing array elements
  5453. @cindex array elements, accessing
  5454. If the variable @code{a} is an array, the @var{n}th element of
  5455. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5456. an element's value or to assign to it:
  5457. @example
  5458. x = a[5];
  5459. a[6] = 1;
  5460. @end example
  5461. @noindent
  5462. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5463. lvalue.
  5464. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5465. valid index is one less than the number of elements.
  5466. The C language does not check whether array indices are in bounds, so
  5467. if the code uses an out-of-range index, it will access memory outside the
  5468. array.
  5469. @strong{Warning:} Using only valid index values in C is the
  5470. programmer's responsibility.
  5471. Array indexing in C is not a primitive operation: it is defined in
  5472. terms of pointer arithmetic and dereferencing. Now that we know
  5473. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5474. its job.
  5475. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5476. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5477. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5478. When an expression with array type (such as @code{a}) appears as part
  5479. of a larger C expression, it is converted automatically to a pointer
  5480. to element zero of that array. For instance, @code{a} in an
  5481. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5482. computed as @code{*(&a[0]+i)}.
  5483. Now we can analyze how that expression gives us the desired element of
  5484. the array. It makes a pointer to element 0 of @code{a}, advances it
  5485. by the value of @code{i}, and dereferences that pointer.
  5486. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5487. @node Declaring an Array
  5488. @section Declaring an Array
  5489. @cindex declaring an array
  5490. @cindex array, declaring
  5491. To make an array declaration, write @code{[@var{length}]} after the
  5492. name being declared. This construct is valid in the declaration of a
  5493. variable, a function parameter, a function value type (the value can't
  5494. be an array, but it can be a pointer to one), a structure field, or a
  5495. union alternative.
  5496. The surrounding declaration specifies the element type of the array;
  5497. that can be any type of data, but not @code{void} or a function type.
  5498. For instance,
  5499. @example
  5500. double a[5];
  5501. @end example
  5502. @noindent
  5503. declares @code{a} as an array of 5 @code{double}s.
  5504. @example
  5505. struct foo bstruct[length];
  5506. @end example
  5507. @noindent
  5508. declares @code{bstruct} as an array of @code{length} objects of type
  5509. @code{struct foo}. A variable array size like this is allowed when
  5510. the array is not file-scope.
  5511. Other declaration constructs can nest within the array declaration
  5512. construct. For instance:
  5513. @example
  5514. struct foo *b[length];
  5515. @end example
  5516. @noindent
  5517. declares @code{b} as an array of @code{length} pointers to
  5518. @code{struct foo}. This shows that the length need not be a constant
  5519. (@pxref{Arrays of Variable Length}).
  5520. @example
  5521. double (*c)[5];
  5522. @end example
  5523. @noindent
  5524. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5525. @example
  5526. char *(*f (int))[5];
  5527. @end example
  5528. @noindent
  5529. declares @code{f} as a function taking an @code{int} argument and
  5530. returning a pointer to an array of 5 strings (pointers to
  5531. @code{char}s).
  5532. @example
  5533. double aa[5][10];
  5534. @end example
  5535. @noindent
  5536. declares @code{aa} as an array of 5 elements, each of which is an
  5537. array of 10 @code{double}s. This shows how to declare a
  5538. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5539. All these declarations specify the array's length, which is needed in
  5540. these cases in order to allocate storage for the array.
  5541. @node Strings
  5542. @section Strings
  5543. @cindex string
  5544. A string in C is a sequence of elements of type @code{char},
  5545. terminated with the null character, the character with code zero.
  5546. Programs often need to use strings with specific, fixed contents. To
  5547. write one in a C program, use a @dfn{string constant} such as
  5548. @code{"Take me to your leader!"}. The data type of a string constant
  5549. is @code{char *}. For the full syntactic details of writing string
  5550. constants, @ref{String Constants}.
  5551. To declare a place to store a non-constant string, declare an array of
  5552. @code{char}. Keep in mind that it must include one extra @code{char}
  5553. for the terminating null. For instance,
  5554. @example
  5555. char text = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5556. @end example
  5557. @noindent
  5558. declares an array named @samp{text} with six elements---five letters
  5559. and the terminating null character. An equivalent way to get the same
  5560. result is this,
  5561. @example
  5562. char text = "Hello";
  5563. @end example
  5564. @noindent
  5565. which copies the elements of the string constant, including @emph{its}
  5566. terminating null character.
  5567. @example
  5568. char message[200];
  5569. @end example
  5570. @noindent
  5571. declares an array long enough to hold a string of 199 ASCII characters
  5572. plus the terminating null character.
  5573. When you store a string into @code{message} be sure to check or prove
  5574. that the length does not exceed its size. For example,
  5575. @example
  5576. void
  5577. set_message (char *text)
  5578. @{
  5579. int i;
  5580. for (i = 0; i < sizeof (message); i++)
  5581. @{
  5582. message[i] = text[i];
  5583. if (text[i] == 0)
  5584. return;
  5585. @}
  5586. fatal_error ("Message is too long for `message');
  5587. @}
  5588. @end example
  5589. It's easy to do this with the standard library function
  5590. @code{strncpy}, which fills out the whole destination array (up to a
  5591. specified length) with null characters. Thus, if the last character
  5592. of the destination is not null, the string did not fit. Many system
  5593. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5594. to run faster than an explicit @code{for}-loop.
  5595. Here's what the code looks like:
  5596. @example
  5597. void
  5598. set_message (char *text)
  5599. @{
  5600. strncpy (message, text, sizeof (message));
  5601. if (message[sizeof (message) - 1] != 0)
  5602. fatal_error ("Message is too long for `message');
  5603. @}
  5604. @end example
  5605. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5606. Library Reference Manual}, for more information about the standard
  5607. library functions for operating on strings.
  5608. You can avoid putting a fixed length limit on strings you construct or
  5609. operate on by allocating the space for them dynamically.
  5610. @xref{Dynamic Memory Allocation}.
  5611. @node Array Type Designators
  5612. @section Array Type Designators
  5613. Every C type has a type designator, which you make by deleting the
  5614. variable name and the semicolon from a declaration (@pxref{Type
  5615. Designators}). The designators for array types follow this rule, but
  5616. they may appear surprising.
  5617. @example
  5618. @r{type} int a[5]; @r{designator} int [5]
  5619. @r{type} double a[5][3]; @r{designator} double [5][3]
  5620. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5621. @end example
  5622. @node Incomplete Array Types
  5623. @section Incomplete Array Types
  5624. @cindex incomplete array types
  5625. @cindex array types, incomplete
  5626. An array is equivalent, for most purposes, to a pointer to its zeroth
  5627. element. When that is true, the length of the array is irrelevant.
  5628. The length needs to be known only for allocating space for the array, or
  5629. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5630. contexts C allows
  5631. @itemize @bullet
  5632. @item
  5633. An @code{extern} declaration says how to refer to a variable allocated
  5634. elsewhere. It does not need to allocate space for the variable,
  5635. so if it is an array, you can omit the length. For example,
  5636. @example
  5637. extern int foo[];
  5638. @end example
  5639. @item
  5640. When declaring a function parameter as an array, the argument value
  5641. passed to the function is really a pointer to the array's zeroth
  5642. element. This value does not say how long the array really is, there
  5643. is no need to declare it. For example,
  5644. @example
  5645. int
  5646. func (int foo[])
  5647. @end example
  5648. @end itemize
  5649. These declarations are examples of @dfn{incomplete} array types, types
  5650. that are not fully specified. The incompleteness makes no difference
  5651. for accessing elements of the array, but it matters for some other
  5652. things. For instance, @code{sizeof} is not allowed on an incomplete
  5653. type.
  5654. With multidimensional arrays, only the first dimension can be omitted:
  5655. @example
  5656. extern struct chesspiece *funnyboard foo[][8];
  5657. @end example
  5658. In other words, the code doesn't have to say how many rows there are,
  5659. but it must state how big each row is.
  5660. @node Limitations of C Arrays
  5661. @section Limitations of C Arrays
  5662. @cindex limitations of C arrays
  5663. @cindex first-class object
  5664. Arrays have quirks in C because they are not ``first-class objects'':
  5665. there is no way in C to operate on an array as a unit.
  5666. The other composite objects in C, structures and unions, are
  5667. first-class objects: a C program can copy a structure or union value
  5668. in an assignment, or pass one as an argument to a function, or make a
  5669. function return one. You can't do those things with an array in C@.
  5670. That is because a value you can operate on never has an array type.
  5671. An expression in C can have an array type, but that doesn't produce
  5672. the array as a value. Instead it is converted automatically to a
  5673. pointer to the array's element at index zero. The code can operate
  5674. on the pointer, and through that on individual elements of the array,
  5675. but it can't get and operate on the array as a unit.
  5676. There are three exceptions to this conversion rule, but none of them
  5677. offers a way to operate on the array as a whole.
  5678. First, @samp{&} applied to an expression with array type gives you the
  5679. address of the array, as an array type. However, you can't operate on the
  5680. whole array that way---if you apply @samp{*} to get the array back,
  5681. that expression converts, as usual, to a pointer to its zeroth
  5682. element.
  5683. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5684. @code{typeof} do not convert the array to a pointer; they leave it as
  5685. an array. But they don't operate on the array's data---they only give
  5686. information about its type.
  5687. Third, a string constant used as an initializer for an array is not
  5688. converted to a pointer---rather, the declaration copies the
  5689. @emph{contents} of that string in that one special case.
  5690. You @emph{can} copy the contents of an array, just not with an
  5691. assignment operator. You can do it by calling the library function
  5692. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5693. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5694. when a structure contains just an array, you can copy that structure.
  5695. An array itself is an lvalue if it is a declared variable, or part of
  5696. a structure or union that is an lvalue. When you construct an array
  5697. from elements (@pxref{Constructing Array Values}), that array is not
  5698. an lvalue.
  5699. @node Multidimensional Arrays
  5700. @section Multidimensional Arrays
  5701. @cindex multidimensional arrays
  5702. @cindex array, multidimensional
  5703. Strictly speaking, all arrays in C are unidimensional. However, you
  5704. can create an array of arrays, which is more or less equivalent to a
  5705. multidimensional array. For example,
  5706. @example
  5707. struct chesspiece *board[8][8];
  5708. @end example
  5709. @noindent
  5710. declares an array of 8 arrays of 8 pointers to @code{struct
  5711. chesspiece}. This data type could represent the state of a chess
  5712. game. To access one square's contents requires two array index
  5713. operations, one for each dimension. For instance, you can write
  5714. @code{board[row][column]}, assuming @code{row} and @code{column}
  5715. are variables with integer values in the proper range.
  5716. How does C understand @code{board[row][column]}? First of all,
  5717. @code{board} is converted automatically to a pointer to the zeroth
  5718. element (at index zero) of @code{board}. Adding @code{row} to that
  5719. makes it point to the desired element. Thus, @code{board[row]}'s
  5720. value is an element of @code{board}---an array of 8 pointers.
  5721. However, as an expression with array type, it is converted
  5722. automatically to a pointer to the array's zeroth element. The second
  5723. array index operation, @code{[column]}, accesses the chosen element
  5724. from that array.
  5725. As this shows, pointer-to-array types are meaningful in C@.
  5726. You can declare a variable that points to a row in a chess board
  5727. like this:
  5728. @example
  5729. struct chesspiece *(*rowptr)[8];
  5730. @end example
  5731. @noindent
  5732. This points to an array of 8 pointers to @code{struct chesspiece}.
  5733. You can assign to it as follows:
  5734. @example
  5735. rowptr = &board[5];
  5736. @end example
  5737. The dimensions don't have to be equal in length. Here we declare
  5738. @code{statepop} as an array to hold the population of each state in
  5739. the United States for each year since 1900:
  5740. @example
  5741. #define NSTATES 50
  5742. @{
  5743. int nyears = current_year - 1900 + 1;
  5744. int statepop[NSTATES][nyears];
  5745. @r{@dots{}}
  5746. @}
  5747. @end example
  5748. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5749. each indexed by the year (counting from 1900). Thus, to get the
  5750. element for a particular state and year, we must subscript it first
  5751. by the number that indicates the state, and second by the index for
  5752. the year:
  5753. @example
  5754. statepop[state][year - 1900]
  5755. @end example
  5756. @cindex array, layout in memory
  5757. The subarrays within the multidimensional array are allocated
  5758. consecutively in memory, and within each subarray, its elements are
  5759. allocated consecutively in memory. The most efficient way to process
  5760. all the elements in the array is to scan the last subscript in the
  5761. innermost loop. This means consecutive accesses go to consecutive
  5762. memory locations, which optimizes use of the processor's memory cache.
  5763. For example:
  5764. @example
  5765. int total = 0;
  5766. float average;
  5767. for (int state = 0; state < NSTATES, ++state)
  5768. @{
  5769. for (int year = 0; year < nyears; ++year)
  5770. @{
  5771. total += statepop[state][year];
  5772. @}
  5773. @}
  5774. average = total / nyears;
  5775. @end example
  5776. C's layout for multidimensional arrays is different from Fortran's
  5777. layout. In Fortran, a multidimensional array is not an array of
  5778. arrays; rather, multidimensional arrays are a primitive feature, and
  5779. it is the first index that varies most rapidly between consecutive
  5780. memory locations. Thus, the memory layout of a 50x114 array in C
  5781. matches that of a 114x50 array in Fortran.
  5782. @node Constructing Array Values
  5783. @section Constructing Array Values
  5784. @cindex constructing array values
  5785. @cindex array values, constructing
  5786. You can construct an array from elements by writing them inside
  5787. braces, and preceding all that with the array type's designator in
  5788. parentheses. There is no need to specify the array length, since the
  5789. number of elements determines that. The constructor looks like this:
  5790. @example
  5791. (@var{elttype}[]) @{ @var{elements} @};
  5792. @end example
  5793. Here is an example, which constructs an array of string pointers:
  5794. @example
  5795. (char *[]) @{ "x", "y", "z" @};
  5796. @end example
  5797. That's equivalent in effect to declaring an array with the same
  5798. initializer, like this:
  5799. @example
  5800. char *array[] = @{ "x", "y", "z" @};
  5801. @end example
  5802. and then using the array.
  5803. If all the elements are simple constant expressions, or made up of
  5804. such, then the compound literal can be coerced to a pointer to its
  5805. zeroth element and used to initialize a file-scope variable
  5806. (@pxref{File-Scope Variables}), as shown here:
  5807. @example
  5808. char **foo = (char *[]) @{ "x", "y", "z" @};
  5809. @end example
  5810. @noindent
  5811. The data type of @code{foo} is @code{char **}, which is a pointer
  5812. type, not an array type. The declaration is equivalent to defining
  5813. and then using an array-type variable:
  5814. @example
  5815. char *nameless_array[] = @{ "x", "y", "z" @};
  5816. char **foo = &nameless_array[0];
  5817. @end example
  5818. @node Arrays of Variable Length
  5819. @section Arrays of Variable Length
  5820. @cindex array of variable length
  5821. @cindex variable-length arrays
  5822. In GNU C, you can declare variable-length arrays like any other
  5823. arrays, but with a length that is not a constant expression. The
  5824. storage is allocated at the point of declaration and deallocated when
  5825. the block scope containing the declaration exits. For example:
  5826. @example
  5827. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5828. #include <string.h> /* @r{Declares @code{str}.} */
  5829. FILE *
  5830. concat_fopen (char *s1, char *s2, char *mode)
  5831. @{
  5832. char str[strlen (s1) + strlen (s2) + 1];
  5833. strcpy (str, s1);
  5834. strcat (str, s2);
  5835. return fopen (str, mode);
  5836. @}
  5837. @end example
  5838. @noindent
  5839. (This uses some standard library functions; see @ref{String and Array
  5840. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5841. The length of an array is computed once when the storage is allocated
  5842. and is remembered for the scope of the array in case it is used in
  5843. @code{sizeof}.
  5844. @strong{Warning:} don't allocate a variable-length array if the size
  5845. might be very large (more than 100,000), or in a recursive function,
  5846. because that is likely to cause stack overflow. Allocate the array
  5847. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5848. Jumping or breaking out of the scope of the array name deallocates the
  5849. storage. Jumping into the scope is not allowed; that gives an error
  5850. message.
  5851. You can also use variable-length arrays as arguments to functions:
  5852. @example
  5853. struct entry
  5854. tester (int len, char data[len][len])
  5855. @{
  5856. @r{@dots{}}
  5857. @}
  5858. @end example
  5859. As usual, a function argument declared with an array type
  5860. is really a pointer to an array that already exists.
  5861. Calling the function does not allocate the array, so there's no
  5862. particular danger of stack overflow in using this construct.
  5863. To pass the array first and the length afterward, use a forward
  5864. declaration in the function's parameter list (another GNU extension).
  5865. For example,
  5866. @example
  5867. struct entry
  5868. tester (int len; char data[len][len], int len)
  5869. @{
  5870. @r{@dots{}}
  5871. @}
  5872. @end example
  5873. The @code{int len} before the semicolon is a @dfn{parameter forward
  5874. declaration}, and it serves the purpose of making the name @code{len}
  5875. known when the declaration of @code{data} is parsed.
  5876. You can write any number of such parameter forward declarations in the
  5877. parameter list. They can be separated by commas or semicolons, but
  5878. the last one must end with a semicolon, which is followed by the
  5879. ``real'' parameter declarations. Each forward declaration must match
  5880. a ``real'' declaration in parameter name and data type. ISO C11 does
  5881. not support parameter forward declarations.
  5882. @node Enumeration Types
  5883. @chapter Enumeration Types
  5884. @cindex enumeration types
  5885. @cindex types, enumeration
  5886. @cindex enumerator
  5887. An @dfn{enumeration type} represents a limited set of integer values,
  5888. each with a name. It is effectively equivalent to a primitive integer
  5889. type.
  5890. Suppose we have a list of possible emotional states to store in an
  5891. integer variable. We can give names to these alternative values with
  5892. an enumeration:
  5893. @example
  5894. enum emotion_state @{ neutral, happy, sad, worried,
  5895. calm, nervous @};
  5896. @end example
  5897. @noindent
  5898. (Never mind that this is a simplistic way to classify emotional states;
  5899. it's just a code example.)
  5900. The names inside the enumeration are called @dfn{enumerators}. The
  5901. enumeration type defines them as constants, and their values are
  5902. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5903. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5904. the enumerators explicitly like this:
  5905. @example
  5906. enum emotion_state @{ neutral = 2, happy = 5,
  5907. sad = 20, worried = 10,
  5908. calm = -5, nervous = -300 @};
  5909. @end example
  5910. Each enumerator which does not specify a value gets value zero
  5911. (if it is at the beginning) or the next consecutive integer.
  5912. @example
  5913. /* @r{@code{neutral} is 0 by default,}
  5914. @r{and @code{worried} is 21 by default.} */
  5915. enum emotion_state @{ neutral,
  5916. happy = 5, sad = 20, worried,
  5917. calm = -5, nervous = -300 @};
  5918. @end example
  5919. If an enumerator is obsolete, you can specify that using it should
  5920. cause a warning, by including an attribute in the enumerator's
  5921. declaration. Here is how @code{happy} would look with this
  5922. attribute:
  5923. @example
  5924. happy __attribute__
  5925. ((deprecated
  5926. ("impossible under plutocratic rule")))
  5927. = 5,
  5928. @end example
  5929. @xref{Attributes}.
  5930. You can declare variables with the enumeration type:
  5931. @example
  5932. enum emotion_state feelings_now;
  5933. @end example
  5934. In the C code itself, this is equivalent to declaring the variable
  5935. @code{int}. (If all the enumeration values are positive, it is
  5936. equivalent to @code{unsigned int}.) However, declaring it with the
  5937. enumeration type has an advantage in debugging, because GDB knows it
  5938. should display the current value of the variable using the
  5939. corresponding name. If the variable's type is @code{int}, GDB can
  5940. only show the value as a number.
  5941. The identifier that follows @code{enum} is called a @dfn{type tag}
  5942. since it distinguishes different enumeration types. Type tags are in
  5943. a separate name space and belong to scopes like most other names in C@.
  5944. @xref{Type Tags}, for explanation.
  5945. You can predeclare an @code{enum} type tag like a structure or union
  5946. type tag, like this:
  5947. @example
  5948. enum foo;
  5949. @end example
  5950. @noindent
  5951. The @code{enum} type is incomplete until you finish defining it.
  5952. You can optionally include a trailing comma at the end of a list of
  5953. enumeration values:
  5954. @example
  5955. enum emotion_state @{ neutral, happy, sad, worried,
  5956. calm, nervous, @};
  5957. @end example
  5958. @noindent
  5959. This is useful in some macro definitions, since it enables you to
  5960. assemble the list of enumerators without knowing which one is last.
  5961. The extra comma does not change the meaning of the enumeration in any
  5962. way.
  5963. @node Defining Typedef Names
  5964. @chapter Defining Typedef Names
  5965. @cindex typedef names
  5966. @findex typedef
  5967. You can define a data type keyword as an alias for any type, and then
  5968. use the alias syntactically like a built-in type keyword such as
  5969. @code{int}. You do this using @code{typedef}, so these aliases are
  5970. also called @dfn{typedef names}.
  5971. @code{typedef} is followed by text that looks just like a variable
  5972. declaration, but instead of declaring variables it defines data type
  5973. keywords.
  5974. Here's how to define @code{fooptr} as a typedef alias for the type
  5975. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5976. with that type:
  5977. @example
  5978. typedef struct foo *fooptr;
  5979. fooptr x, y;
  5980. @end example
  5981. @noindent
  5982. That declaration is equivalent to the following one:
  5983. @example
  5984. struct foo *x, *y;
  5985. @end example
  5986. You can define a typedef alias for any type. For instance, this makes
  5987. @code{frobcount} an alias for type @code{int}:
  5988. @example
  5989. typedef int frobcount;
  5990. @end example
  5991. @noindent
  5992. This doesn't define a new type distinct from @code{int}. Rather,
  5993. @code{frobcount} is another name for the type @code{int}. Once the
  5994. variable is declared, it makes no difference which name the
  5995. declaration used.
  5996. There is a syntactic difference, however, between @code{frobcount} and
  5997. @code{int}: A typedef name cannot be used with
  5998. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  5999. to specify the type all by itself. So you can't write this:
  6000. @example
  6001. unsigned frobcount f1; /* @r{Error!} */
  6002. @end example
  6003. But you can write this:
  6004. @example
  6005. typedef unsigned int unsigned_frobcount;
  6006. unsigned_frobcount f1;
  6007. @end example
  6008. In other words, a typedef name is not an alias for @emph{a keyword}
  6009. such as @code{int}. It stands for a @emph{type}, and that could be
  6010. the type @code{int}.
  6011. Typedef names are in the same namespace as functions and variables, so
  6012. you can't use the same name for a typedef and a function, or a typedef
  6013. and a variable. When a typedef is declared inside a code block, it is
  6014. in scope only in that block.
  6015. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6016. because many of these have standard meanings.
  6017. You can redefine a typedef name to the exact same type as its first
  6018. definition, but you cannot redefine a typedef name to a
  6019. different type, even if the two types are compatible. For example, this
  6020. is valid:
  6021. @example
  6022. typedef int frobcount;
  6023. typedef int frotzcount;
  6024. typedef frotzcount frobcount;
  6025. typedef frobcount frotzcount;
  6026. @end example
  6027. @noindent
  6028. because each typedef name is always defined with the same type
  6029. (@code{int}), but this is not valid:
  6030. @example
  6031. enum foo @{f1, f2, f3@};
  6032. typedef enum foo frobcount;
  6033. typedef int frobcount;
  6034. @end example
  6035. @noindent
  6036. Even though the type @code{enum foo} is compatible with @code{int},
  6037. they are not the @emph{same} type.
  6038. @node Statements
  6039. @chapter Statements
  6040. @cindex statements
  6041. A @dfn{statement} specifies computations to be done for effect; it
  6042. does not produce a value, as an expression would. In general a
  6043. statement ends with a semicolon (@samp{;}), but blocks (which are
  6044. statements, more or less) are an exception to that rule.
  6045. @ifnottex
  6046. @xref{Blocks}.
  6047. @end ifnottex
  6048. The places to use statements are inside a block, and inside a
  6049. complex statement. A @dfn{complex statement} contains one or two
  6050. components that are nested statements. Each such component must
  6051. consist of one and only one statement. The way to put multiple
  6052. statements in such a component is to group them into a @dfn{block}
  6053. (@pxref{Blocks}), which counts as one statement.
  6054. The following sections describe the various kinds of statement.
  6055. @menu
  6056. * Expression Statement:: Evaluate an expression, as a statement,
  6057. usually done for a side effect.
  6058. * if Statement:: Basic conditional execution.
  6059. * if-else Statement:: Multiple branches for conditional execution.
  6060. * Blocks:: Grouping multiple statements together.
  6061. * return Statement:: Return a value from a function.
  6062. * Loop Statements:: Repeatedly executing a statement or block.
  6063. * switch Statement:: Multi-way conditional choices.
  6064. * switch Example:: A plausible example of using @code{switch}.
  6065. * Duffs Device:: A special way to use @code{switch}.
  6066. * Case Ranges:: Ranges of values for @code{switch} cases.
  6067. * Null Statement:: A statement that does nothing.
  6068. * goto Statement:: Jump to another point in the source code,
  6069. identified by a label.
  6070. * Local Labels:: Labels with limited scope.
  6071. * Labels as Values:: Getting the address of a label.
  6072. * Statement Exprs:: A series of statements used as an expression.
  6073. @end menu
  6074. @node Expression Statement
  6075. @section Expression Statement
  6076. @cindex expression statement
  6077. @cindex statement, expression
  6078. The most common kind of statement in C is an @dfn{expression statement}.
  6079. It consists of an expression followed by a
  6080. semicolon. The expression's value is discarded, so the expressions
  6081. that are useful are those that have side effects: assignment
  6082. expressions, increment and decrement expressions, and function calls.
  6083. Here are examples of expression statements:
  6084. @smallexample
  6085. x = 5; /* @r{Assignment expression.} */
  6086. p++; /* @r{Increment expression.} */
  6087. printf ("Done\n"); /* @r{Function call expression.} */
  6088. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6089. x + y; /* @r{Useless statement without effect.} */
  6090. @end smallexample
  6091. In very unusual circumstances we use an expression statement
  6092. whose purpose is to get a fault if an address is invalid:
  6093. @smallexample
  6094. volatile char *p;
  6095. @r{@dots{}}
  6096. *p; /* @r{Cause signal if @code{p} is null.} */
  6097. @end smallexample
  6098. If the target of @code{p} is not declared @code{volatile}, the
  6099. compiler might optimize away the memory access, since it knows that
  6100. the value isn't really used. @xref{volatile}.
  6101. @node if Statement
  6102. @section @code{if} Statement
  6103. @cindex @code{if} statement
  6104. @cindex statement, @code{if}
  6105. @findex if
  6106. An @code{if} statement computes an expression to decide
  6107. whether to execute the following statement or not.
  6108. It looks like this:
  6109. @example
  6110. if (@var{condition})
  6111. @var{execute-if-true}
  6112. @end example
  6113. The first thing this does is compute the value of @var{condition}. If
  6114. that is true (nonzero), then it executes the statement
  6115. @var{execute-if-true}. If the value of @var{condition} is false
  6116. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6117. nothing.
  6118. This is a @dfn{complex statement} because it contains a component
  6119. @var{if-true-substatement} that is a nested statement. It must be one
  6120. and only one statement. The way to put multiple statements there is
  6121. to group them into a @dfn{block} (@pxref{Blocks}).
  6122. @node if-else Statement
  6123. @section @code{if-else} Statement
  6124. @cindex @code{if}@dots{}@code{else} statement
  6125. @cindex statement, @code{if}@dots{}@code{else}
  6126. @findex else
  6127. An @code{if}-@code{else} statement computes an expression to decide
  6128. which of two nested statements to execute.
  6129. It looks like this:
  6130. @example
  6131. if (@var{condition})
  6132. @var{if-true-substatement}
  6133. else
  6134. @var{if-false-substatement}
  6135. @end example
  6136. The first thing this does is compute the value of @var{condition}. If
  6137. that is true (nonzero), then it executes the statement
  6138. @var{if-true-substatement}. If the value of @var{condition} is false
  6139. (zero), then it executes the statement @var{if-false-substatement} instead.
  6140. This is a @dfn{complex statement} because it contains components
  6141. @var{if-true-substatement} and @var{if-else-substatement} that are
  6142. nested statements. Each must be one and only one statement. The way
  6143. to put multiple statements in such a component is to group them into a
  6144. @dfn{block} (@pxref{Blocks}).
  6145. @node Blocks
  6146. @section Blocks
  6147. @cindex block
  6148. @cindex compound statement
  6149. A @dfn{block} is a construct that contains multiple statements of any
  6150. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6151. series of statements and declarations in between. Another name for
  6152. blocks is @dfn{compound statements}.
  6153. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6154. normal statement---it does not end with a semicolon. But you can
  6155. @emph{use} it like a statement; anywhere that a statement is required
  6156. or allowed, you can write a block and consider that block a statement.
  6157. So far it seems that a block is a kind of statement with an unusual
  6158. syntax. But that is not entirely true: a function body is also a
  6159. block, and that block is definitely not a statement. The text after a
  6160. function header is not treated as a statement; only a function body is
  6161. allowed there, and nothing else would be meaningful there.
  6162. In a formal grammar we would have to choose---either a block is a kind
  6163. of statement or it is not. But this manual is meant for humans, not
  6164. for parser generators. The clearest answer for humans is, ``a block
  6165. is a statement, in some ways.''
  6166. @cindex nested block
  6167. @cindex internal block
  6168. A block that isn't a function body is called an @dfn{internal block}
  6169. or a @dfn{nested block}. You can put a nested block directly inside
  6170. another block, but more often the nested block is inside some complex
  6171. statement, such as a @code{for} statement or an @code{if} statement.
  6172. There are two uses for nested blocks in C:
  6173. @itemize @bullet
  6174. @item
  6175. To specify the scope for local declarations. For instance, a local
  6176. variable's scope is the rest of the innermost containing block.
  6177. @item
  6178. To write a series of statements where, syntactically, one statement is
  6179. called for. For instance, the @var{execute-if-true} of an @code{if}
  6180. statement is one statement. To put multiple statements there, they
  6181. have to be wrapped in a block, like this:
  6182. @example
  6183. if (x < 0)
  6184. @{
  6185. printf ("x was negative\n");
  6186. x = -x;
  6187. @}
  6188. @end example
  6189. @end itemize
  6190. This example (repeated from above) shows a nested block which serves
  6191. both purposes: it includes two statements (plus a declaration) in the
  6192. body of a @code{while} statement, and it provides the scope for the
  6193. declaration of @code{q}.
  6194. @example
  6195. void
  6196. free_intlist (struct intlistlink *p)
  6197. @{
  6198. while (p)
  6199. @{
  6200. struct intlistlink *q = p;
  6201. p = p->next;
  6202. free (q);
  6203. @}
  6204. @}
  6205. @end example
  6206. @node return Statement
  6207. @section @code{return} Statement
  6208. @cindex @code{return} statement
  6209. @cindex statement, @code{return}
  6210. @findex return
  6211. The @code{return} statement makes the containing function return
  6212. immediately. It has two forms. This one specifies no value to
  6213. return:
  6214. @example
  6215. return;
  6216. @end example
  6217. @noindent
  6218. That form is meant for functions whose return type is @code{void}
  6219. (@pxref{The Void Type}). You can also use it in a function that
  6220. returns nonvoid data, but that's a bad idea, since it makes the
  6221. function return garbage.
  6222. The form that specifies a value looks like this:
  6223. @example
  6224. return @var{value};
  6225. @end example
  6226. @noindent
  6227. which computes the expression @var{value} and makes the function
  6228. return that. If necessary, the value undergoes type conversion to
  6229. the function's declared return value type, which works like
  6230. assigning the value to a variable of that type.
  6231. @node Loop Statements
  6232. @section Loop Statements
  6233. @cindex loop statements
  6234. @cindex statements, loop
  6235. @cindex iteration
  6236. You can use a loop statement when you need to execute a series of
  6237. statements repeatedly, making an @dfn{iteration}. C provides several
  6238. different kinds of loop statements, described in the following
  6239. subsections.
  6240. Every kind of loop statement is a complex statement because contains a
  6241. component, here called @var{body}, which is a nested statement.
  6242. Most often the body is a block.
  6243. @menu
  6244. * while Statement:: Loop as long as a test expression is true.
  6245. * do-while Statement:: Execute a loop once, with further looping
  6246. as long as a test expression is true.
  6247. * break Statement:: End a loop immediately.
  6248. * for Statement:: Iterative looping.
  6249. * Example of for:: An example of iterative looping.
  6250. * Omitted for-Expressions:: for-loop expression options.
  6251. * for-Index Declarations:: for-loop declaration options.
  6252. * continue Statement:: Begin the next cycle of a loop.
  6253. @end menu
  6254. @node while Statement
  6255. @subsection @code{while} Statement
  6256. @cindex @code{while} statement
  6257. @cindex statement, @code{while}
  6258. @findex while
  6259. The @code{while} statement is the simplest loop construct.
  6260. It looks like this:
  6261. @example
  6262. while (@var{test})
  6263. @var{body}
  6264. @end example
  6265. Here, @var{body} is a statement (often a nested block) to repeat, and
  6266. @var{test} is the test expression that controls whether to repeat it again.
  6267. Each iteration of the loop starts by computing @var{test} and, if it
  6268. is true (nonzero), that means the loop should execute @var{body} again
  6269. and then start over.
  6270. Here's an example of advancing to the last structure in a chain of
  6271. structures chained through the @code{next} field:
  6272. @example
  6273. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6274. @r{@dots{}}
  6275. while (chain->next != NULL)
  6276. chain = chain->next;
  6277. @end example
  6278. @noindent
  6279. This code assumes the chain isn't empty to start with; if the chain is
  6280. empty (that is, if @code{chain} is a null pointer), the code gets a
  6281. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6282. @node do-while Statement
  6283. @subsection @code{do-while} Statement
  6284. @cindex @code{do}--@code{while} statement
  6285. @cindex statement, @code{do}--@code{while}
  6286. @findex do
  6287. The @code{do}--@code{while} statement is a simple loop construct that
  6288. performs the test at the end of the iteration.
  6289. @example
  6290. do
  6291. @var{body}
  6292. while (@var{test});
  6293. @end example
  6294. Here, @var{body} is a statement (possibly a block) to repeat, and
  6295. @var{test} is an expression that controls whether to repeat it again.
  6296. Each iteration of the loop starts by executing @var{body}. Then it
  6297. computes @var{test} and, if it is true (nonzero), that means to go
  6298. back and start over with @var{body}. If @var{test} is false (zero),
  6299. then the loop stops repeating and execution moves on past it.
  6300. @node break Statement
  6301. @subsection @code{break} Statement
  6302. @cindex @code{break} statement
  6303. @cindex statement, @code{break}
  6304. @findex break
  6305. The @code{break} statement looks like @samp{break;}. Its effect is to
  6306. exit immediately from the innermost loop construct or @code{switch}
  6307. statement (@pxref{switch Statement}).
  6308. For example, this loop advances @code{p} until the next null
  6309. character or newline.
  6310. @example
  6311. while (*p)
  6312. @{
  6313. /* @r{End loop if we have reached a newline.} */
  6314. if (*p == '\n')
  6315. break;
  6316. p++
  6317. @}
  6318. @end example
  6319. When there are nested loops, the @code{break} statement exits from the
  6320. innermost loop containing it.
  6321. @example
  6322. struct list_if_tuples
  6323. @{
  6324. struct list_if_tuples next;
  6325. int length;
  6326. data *contents;
  6327. @};
  6328. void
  6329. process_all_elements (struct list_if_tuples *list)
  6330. @{
  6331. while (list)
  6332. @{
  6333. /* @r{Process all the elements in this node's vector,}
  6334. @r{stopping when we reach one that is null.} */
  6335. for (i = 0; i < list->length; i++
  6336. @{
  6337. /* @r{Null element terminates this node's vector.} */
  6338. if (list->contents[i] == NULL)
  6339. /* @r{Exit the @code{for} loop.} */
  6340. break;
  6341. /* @r{Operate on the next element.} */
  6342. process_element (list->contents[i]);
  6343. @}
  6344. list = list->next;
  6345. @}
  6346. @}
  6347. @end example
  6348. The only way in C to exit from an outer loop is with
  6349. @code{goto} (@pxref{goto Statement}).
  6350. @node for Statement
  6351. @subsection @code{for} Statement
  6352. @cindex @code{for} statement
  6353. @cindex statement, @code{for}
  6354. @findex for
  6355. A @code{for} statement uses three expressions written inside a
  6356. parenthetical group to define the repetition of the loop. The first
  6357. expression says how to prepare to start the loop. The second says how
  6358. to test, before each iteration, whether to continue looping. The
  6359. third says how to advance, at the end of an iteration, for the next
  6360. iteration. All together, it looks like this:
  6361. @example
  6362. for (@var{start}; @var{continue-test}; @var{advance})
  6363. @var{body}
  6364. @end example
  6365. The first thing the @code{for} statement does is compute @var{start}.
  6366. The next thing it does is compute the expression @var{continue-test}.
  6367. If that expression is false (zero), the @code{for} statement finishes
  6368. immediately, so @var{body} is executed zero times.
  6369. However, if @var{continue-test} is true (nonzero), the @code{for}
  6370. statement executes @var{body}, then @var{advance}. Then it loops back
  6371. to the not-quite-top to test @var{continue-test} again. But it does
  6372. not compute @var{start} again.
  6373. @node Example of for
  6374. @subsection Example of @code{for}
  6375. Here is the @code{for} statement from the iterative Fibonacci
  6376. function:
  6377. @example
  6378. int i;
  6379. for (i = 1; i < n; ++i)
  6380. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6381. /* @r{since @code{i < n} is false the first time.} */
  6382. @{
  6383. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6384. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6385. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6386. int next = prev + last;
  6387. /* @r{Shift the values down.} */
  6388. prev = last;
  6389. last = next;
  6390. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6391. @r{and @var{prev} is @code{fib (@var{i})}.}
  6392. @r{But that won't stay true for long,}
  6393. @r{because we are about to increment @var{i}.} */
  6394. @}
  6395. @end example
  6396. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6397. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6398. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6399. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6400. that contains a declaration and two statements.
  6401. @node Omitted for-Expressions
  6402. @subsection Omitted @code{for}-Expressions
  6403. A fully-fleshed @code{for} statement contains all these parts,
  6404. @example
  6405. for (@var{start}; @var{continue-test}; @var{advance})
  6406. @var{body}
  6407. @end example
  6408. @noindent
  6409. but you can omit any of the three expressions inside the parentheses.
  6410. The parentheses and the two semicolons are required syntactically, but
  6411. the expressions between them may be missing. A missing expression
  6412. means this loop doesn't use that particular feature of the @code{for}
  6413. statement.
  6414. Instead of using @var{start}, you can do the loop preparation
  6415. before the @code{for} statement: the effect is the same. So we
  6416. could have written the beginning of the previous example this way:
  6417. @example
  6418. int i = 0;
  6419. for (; i < n; ++i)
  6420. @end example
  6421. @noindent
  6422. instead of this way:
  6423. @example
  6424. int i;
  6425. for (i = 0; i < n; ++i)
  6426. @end example
  6427. Omitting @var{continue-test} means the loop runs forever (or until
  6428. something else causes exit from it). Statements inside the loop can
  6429. test conditions for termination and use @samp{break;} to exit. This
  6430. is more flexible since you can put those tests anywhere in the loop,
  6431. not solely at the beginning.
  6432. Putting an expression in @var{advance} is almost equivalent to writing
  6433. it at the end of the loop body; it does almost the same thing. The
  6434. only difference is for the @code{continue} statement (@pxref{continue
  6435. Statement}). So we could have written this:
  6436. @example
  6437. for (i = 0; i < n;)
  6438. @{
  6439. @r{@dots{}}
  6440. ++i;
  6441. @}
  6442. @end example
  6443. @noindent
  6444. instead of this:
  6445. @example
  6446. for (i = 0; i < n; ++i)
  6447. @{
  6448. @r{@dots{}}
  6449. @}
  6450. @end example
  6451. The choice is mainly a matter of what is more readable for
  6452. programmers. However, there is also a syntactic difference:
  6453. @var{advance} is an expression, not a statement. It can't include
  6454. loops, blocks, declarations, etc.
  6455. @node for-Index Declarations
  6456. @subsection @code{for}-Index Declarations
  6457. You can declare loop-index variables directly in the @var{start}
  6458. portion of the @code{for}-loop, like this:
  6459. @example
  6460. for (int i = 0; i < n; ++i)
  6461. @{
  6462. @r{@dots{}}
  6463. @}
  6464. @end example
  6465. This kind of @var{start} is limited to a single declaration; it can
  6466. declare one or more variables, separated by commas, all of which are
  6467. the same @var{basetype} (@code{int}, in this example):
  6468. @example
  6469. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6470. @{
  6471. @r{@dots{}}
  6472. @}
  6473. @end example
  6474. @noindent
  6475. The scope of these variables is the @code{for} statement as a whole.
  6476. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6477. Variables declared in @code{for} statements should have initializers.
  6478. Omitting the initialization gives the variables unpredictable initial
  6479. values, so this code is erroneous.
  6480. @example
  6481. for (int i; i < n; ++i)
  6482. @{
  6483. @r{@dots{}}
  6484. @}
  6485. @end example
  6486. @node continue Statement
  6487. @subsection @code{continue} Statement
  6488. @cindex @code{continue} statement
  6489. @cindex statement, @code{continue}
  6490. @findex continue
  6491. The @code{continue} statement looks like @samp{continue;}, and its
  6492. effect is to jump immediately to the end of the innermost loop
  6493. construct. If it is a @code{for}-loop, the next thing that happens
  6494. is to execute the loop's @var{advance} expression.
  6495. For example, this loop increments @code{p} until the next null character
  6496. or newline, and operates (in some way not shown) on all the characters
  6497. in the line except for spaces. All it does with spaces is skip them.
  6498. @example
  6499. for (;*p; ++p)
  6500. @{
  6501. /* @r{End loop if we have reached a newline.} */
  6502. if (*p == '\n')
  6503. break;
  6504. /* @r{Pay no attention to spaces.} */
  6505. if (*p == ' ')
  6506. continue;
  6507. /* @r{Operate on the next character.} */
  6508. @r{@dots{}}
  6509. @}
  6510. @end example
  6511. @noindent
  6512. Executing @samp{continue;} skips the loop body but it does not
  6513. skip the @var{advance} expression, @code{p++}.
  6514. We could also write it like this:
  6515. @example
  6516. for (;*p; ++p)
  6517. @{
  6518. /* @r{Exit if we have reached a newline.} */
  6519. if (*p == '\n')
  6520. break;
  6521. /* @r{Pay no attention to spaces.} */
  6522. if (*p != ' ')
  6523. @{
  6524. /* @r{Operate on the next character.} */
  6525. @r{@dots{}}
  6526. @}
  6527. @}
  6528. @end example
  6529. The advantage of using @code{continue} is that it reduces the
  6530. depth of nesting.
  6531. Contrast @code{continue} with the @code{break} statement. @xref{break
  6532. Statement}.
  6533. @node switch Statement
  6534. @section @code{switch} Statement
  6535. @cindex @code{switch} statement
  6536. @cindex statement, @code{switch}
  6537. @findex switch
  6538. @findex case
  6539. @findex default
  6540. The @code{switch} statement selects code to run according to the value
  6541. of an expression. The expression, in parentheses, follows the keyword
  6542. @code{switch}. After that come all the cases to select among,
  6543. inside braces. It looks like this:
  6544. @example
  6545. switch (@var{selector})
  6546. @{
  6547. @var{cases}@r{@dots{}}
  6548. @}
  6549. @end example
  6550. A case can look like this:
  6551. @example
  6552. case @var{value}:
  6553. @var{statements}
  6554. break;
  6555. @end example
  6556. @noindent
  6557. which means ``come here if @var{selector} happens to have the value
  6558. @var{value},'' or like this (a GNU C extension):
  6559. @example
  6560. case @var{rangestart} ... @var{rangeend}:
  6561. @var{statements}
  6562. break;
  6563. @end example
  6564. @noindent
  6565. which means ``come here if @var{selector} happens to have a value
  6566. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6567. Ranges}.
  6568. The values in @code{case} labels must reduce to integer constants.
  6569. They can use arithmetic, and @code{enum} constants, but they cannot
  6570. refer to data in memory, because they have to be computed at compile
  6571. time. It is an error if two @code{case} labels specify the same
  6572. value, or ranges that overlap, or if one is a range and the other is a
  6573. value in that range.
  6574. You can also define a default case to handle ``any other value,'' like
  6575. this:
  6576. @example
  6577. default:
  6578. @var{statements}
  6579. break;
  6580. @end example
  6581. If the @code{switch} statement has no @code{default:} label, then it
  6582. does nothing when the value matches none of the cases.
  6583. The brace-group inside the @code{switch} statement is a block, and you
  6584. can declare variables with that scope just as in any other block
  6585. (@pxref{Blocks}). However, initializers in these declarations won't
  6586. necessarily be executed every time the @code{switch} statement runs,
  6587. so it is best to avoid giving them initializers.
  6588. @code{break;} inside a @code{switch} statement exits immediately from
  6589. the @code{switch} statement. @xref{break Statement}.
  6590. If there is no @code{break;} at the end of the code for a case,
  6591. execution continues into the code for the following case. This
  6592. happens more often by mistake than intentionally, but since this
  6593. feature is used in real code, we cannot eliminate it.
  6594. @strong{Warning:} When one case is intended to fall through to the
  6595. next, write a comment like @samp{falls through} to say it's
  6596. intentional. That way, other programmers won't assume it was an error
  6597. and ``fix'' it erroneously.
  6598. Consecutive @code{case} statements could, pedantically, be considered
  6599. an instance of falling through, but we don't consider or treat them that
  6600. way because they won't confuse anyone.
  6601. @node switch Example
  6602. @section Example of @code{switch}
  6603. Here's an example of using the @code{switch} statement
  6604. to distinguish among characters:
  6605. @cindex counting vowels and punctuation
  6606. @example
  6607. struct vp @{ int vowels, punct; @};
  6608. struct vp
  6609. count_vowels_and_punct (char *string)
  6610. @{
  6611. int c;
  6612. int vowels = 0;
  6613. int punct = 0;
  6614. /* @r{Don't change the parameter itself.} */
  6615. /* @r{That helps in debugging.} */
  6616. char *p = string;
  6617. struct vp value;
  6618. while (c = *p++)
  6619. switch (c)
  6620. @{
  6621. case 'y':
  6622. case 'Y':
  6623. /* @r{We assume @code{y_is_consonant} will check surrounding
  6624. letters to determine whether this y is a vowel.} */
  6625. if (y_is_consonant (p - 1))
  6626. break;
  6627. /* @r{Falls through} */
  6628. case 'a':
  6629. case 'e':
  6630. case 'i':
  6631. case 'o':
  6632. case 'u':
  6633. case 'A':
  6634. case 'E':
  6635. case 'I':
  6636. case 'O':
  6637. case 'U':
  6638. vowels++;
  6639. break;
  6640. case '.':
  6641. case ',':
  6642. case ':':
  6643. case ';':
  6644. case '?':
  6645. case '!':
  6646. case '\"':
  6647. case '\'':
  6648. punct++;
  6649. break;
  6650. @}
  6651. value.vowels = vowels;
  6652. value.punct = punct;
  6653. return value;
  6654. @}
  6655. @end example
  6656. @node Duffs Device
  6657. @section Duff's Device
  6658. @cindex Duff's device
  6659. The cases in a @code{switch} statement can be inside other control
  6660. constructs. For instance, we can use a technique known as @dfn{Duff's
  6661. device} to optimize this simple function,
  6662. @example
  6663. void
  6664. copy (char *to, char *from, int count)
  6665. @{
  6666. while (count > 0)
  6667. *to++ = *from++, count--;
  6668. @}
  6669. @end example
  6670. @noindent
  6671. which copies memory starting at @var{from} to memory starting at
  6672. @var{to}.
  6673. Duff's device involves unrolling the loop so that it copies
  6674. several characters each time around, and using a @code{switch} statement
  6675. to enter the loop body at the proper point:
  6676. @example
  6677. void
  6678. copy (char *to, char *from, int count)
  6679. @{
  6680. if (count <= 0)
  6681. return;
  6682. int n = (count + 7) / 8;
  6683. switch (count % 8)
  6684. @{
  6685. do @{
  6686. case 0: *to++ = *from++;
  6687. case 7: *to++ = *from++;
  6688. case 6: *to++ = *from++;
  6689. case 5: *to++ = *from++;
  6690. case 4: *to++ = *from++;
  6691. case 3: *to++ = *from++;
  6692. case 2: *to++ = *from++;
  6693. case 1: *to++ = *from++;
  6694. @} while (--n > 0);
  6695. @}
  6696. @}
  6697. @end example
  6698. @node Case Ranges
  6699. @section Case Ranges
  6700. @cindex case ranges
  6701. @cindex ranges in case statements
  6702. You can specify a range of consecutive values in a single @code{case} label,
  6703. like this:
  6704. @example
  6705. case @var{low} ... @var{high}:
  6706. @end example
  6707. @noindent
  6708. This has the same effect as the proper number of individual @code{case}
  6709. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6710. This feature is especially useful for ranges of ASCII character codes:
  6711. @example
  6712. case 'A' ... 'Z':
  6713. @end example
  6714. @strong{Be careful:} with integers, write spaces around the @code{...}
  6715. to prevent it from being parsed wrong. For example, write this:
  6716. @example
  6717. case 1 ... 5:
  6718. @end example
  6719. @noindent
  6720. rather than this:
  6721. @example
  6722. case 1...5:
  6723. @end example
  6724. @node Null Statement
  6725. @section Null Statement
  6726. @cindex null statement
  6727. @cindex statement, null
  6728. A @dfn{null statement} is just a semicolon. It does nothing.
  6729. A null statement is a placeholder for use where a statement is
  6730. grammatically required, but there is nothing to be done. For
  6731. instance, sometimes all the work of a @code{for}-loop is done in the
  6732. @code{for}-header itself, leaving no work for the body. Here is an
  6733. example that searches for the first newline in @code{array}:
  6734. @example
  6735. for (p = array; *p != '\n'; p++)
  6736. ;
  6737. @end example
  6738. @node goto Statement
  6739. @section @code{goto} Statement and Labels
  6740. @cindex @code{goto} statement
  6741. @cindex statement, @code{goto}
  6742. @cindex label
  6743. @findex goto
  6744. The @code{goto} statement looks like this:
  6745. @example
  6746. goto @var{label};
  6747. @end example
  6748. @noindent
  6749. Its effect is to transfer control immediately to another part of the
  6750. current function---where the label named @var{label} is defined.
  6751. An ordinary label definition looks like this:
  6752. @example
  6753. @var{label}:
  6754. @end example
  6755. @noindent
  6756. and it can appear before any statement. You can't use @code{default}
  6757. as a label, since that has a special meaning for @code{switch}
  6758. statements.
  6759. An ordinary label doesn't need a separate declaration; defining it is
  6760. enough.
  6761. Here's an example of using @code{goto} to implement a loop
  6762. equivalent to @code{do}--@code{while}:
  6763. @example
  6764. @{
  6765. loop_restart:
  6766. @var{body}
  6767. if (@var{condition})
  6768. goto loop_restart;
  6769. @}
  6770. @end example
  6771. The name space of labels is separate from that of variables and functions.
  6772. Thus, there is no error in using a single name in both ways:
  6773. @example
  6774. @{
  6775. int foo; // @r{Variable @code{foo}.}
  6776. foo: // @r{Label @code{foo}.}
  6777. @var{body}
  6778. if (foo > 0) // @r{Variable @code{foo}.}
  6779. goto foo; // @r{Label @code{foo}.}
  6780. @}
  6781. @end example
  6782. Blocks have no effect on ordinary labels; each label name is defined
  6783. throughout the whole of the function it appears in. It looks strange to
  6784. jump into a block with @code{goto}, but it works. For example,
  6785. @example
  6786. if (x < 0)
  6787. goto negative;
  6788. if (y < 0)
  6789. @{
  6790. negative:
  6791. printf ("Negative\n");
  6792. return;
  6793. @}
  6794. @end example
  6795. If the goto jumps into the scope of a variable, it does not
  6796. initialize the variable. For example, if @code{x} is negative,
  6797. @example
  6798. if (x < 0)
  6799. goto negative;
  6800. if (y < 0)
  6801. @{
  6802. int i = 5;
  6803. negative:
  6804. printf ("Negative, and i is %d\n", i);
  6805. return;
  6806. @}
  6807. @end example
  6808. @noindent
  6809. prints junk because @code{i} was not initialized.
  6810. If the block declares a variable-length automatic array, jumping into
  6811. it gives a compilation error. However, jumping out of the scope of a
  6812. variable-length array works fine, and deallocates its storage.
  6813. A label can't come directly before a declaration, so the code can't
  6814. jump directly to one. For example, this is not allowed:
  6815. @example
  6816. @{
  6817. goto foo;
  6818. foo:
  6819. int x = 5;
  6820. bar(&x);
  6821. @}
  6822. @end example
  6823. @noindent
  6824. The workaround is to add a statement, even an empty statement,
  6825. directly after the label. For example:
  6826. @example
  6827. @{
  6828. goto foo;
  6829. foo:
  6830. ;
  6831. int x = 5;
  6832. bar(&x);
  6833. @}
  6834. @end example
  6835. Likewise, a label can't be the last thing in a block. The workaround
  6836. solution is the same: add a semicolon after the label.
  6837. These unnecessary restrictions on labels make no sense, and ought in
  6838. principle to be removed; but they do only a little harm since labels
  6839. and @code{goto} are rarely the best way to write a program.
  6840. These examples are all artificial; it would be more natural to
  6841. write them in other ways, without @code{goto}. For instance,
  6842. the clean way to write the example that prints @samp{Negative} is this:
  6843. @example
  6844. if (x < 0 || y < 0)
  6845. @{
  6846. printf ("Negative\n");
  6847. return;
  6848. @}
  6849. @end example
  6850. @noindent
  6851. It is hard to construct simple examples where @code{goto} is actually
  6852. the best way to write a program. Its rare good uses tend to be in
  6853. complex code, thus not apt for the purpose of explaining the meaning
  6854. of @code{goto}.
  6855. The only good time to use @code{goto} is when it makes the code
  6856. simpler than any alternative. Jumping backward is rarely desirable,
  6857. because usually the other looping and control constructs give simpler
  6858. code. Using @code{goto} to jump forward is more often desirable, for
  6859. instance when a function needs to do some processing in an error case
  6860. and errors can occur at various different places within the function.
  6861. @node Local Labels
  6862. @section Locally Declared Labels
  6863. @cindex local labels
  6864. @cindex macros, local labels
  6865. @findex __label__
  6866. In GNU C you can declare @dfn{local labels} in any nested block
  6867. scope. A local label is used in a @code{goto} statement just like an
  6868. ordinary label, but you can only reference it within the block in
  6869. which it was declared.
  6870. A local label declaration looks like this:
  6871. @example
  6872. __label__ @var{label};
  6873. @end example
  6874. @noindent
  6875. or
  6876. @example
  6877. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6878. @end example
  6879. Local label declarations must come at the beginning of the block,
  6880. before any ordinary declarations or statements.
  6881. The label declaration declares the label @emph{name}, but does not define
  6882. the label itself. That's done in the usual way, with
  6883. @code{@var{label}:}, before one of the statements in the block.
  6884. The local label feature is useful for complex macros. If a macro
  6885. contains nested loops, a @code{goto} can be useful for breaking out of
  6886. them. However, an ordinary label whose scope is the whole function
  6887. cannot be used: if the macro can be expanded several times in one
  6888. function, the label will be multiply defined in that function. A
  6889. local label avoids this problem. For example:
  6890. @example
  6891. #define SEARCH(value, array, target) \
  6892. do @{ \
  6893. __label__ found; \
  6894. __auto_type _SEARCH_target = (target); \
  6895. __auto_type _SEARCH_array = (array); \
  6896. int i, j; \
  6897. int value; \
  6898. for (i = 0; i < max; i++) \
  6899. for (j = 0; j < max; j++) \
  6900. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6901. @{ (value) = i; goto found; @} \
  6902. (value) = -1; \
  6903. found:; \
  6904. @} while (0)
  6905. @end example
  6906. This could also be written using a statement expression
  6907. (@pxref{Statement Exprs}):
  6908. @example
  6909. #define SEARCH(array, target) \
  6910. (@{ \
  6911. __label__ found; \
  6912. __auto_type _SEARCH_target = (target); \
  6913. __auto_type _SEARCH_array = (array); \
  6914. int i, j; \
  6915. int value; \
  6916. for (i = 0; i < max; i++) \
  6917. for (j = 0; j < max; j++) \
  6918. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6919. @{ value = i; goto found; @} \
  6920. value = -1; \
  6921. found: \
  6922. value; \
  6923. @})
  6924. @end example
  6925. Ordinary labels are visible throughout the function where they are
  6926. defined, and only in that function. However, explicitly declared
  6927. local labels of a block are visible in nested functions declared
  6928. within that block. @xref{Nested Functions}, for details.
  6929. @xref{goto Statement}.
  6930. @node Labels as Values
  6931. @section Labels as Values
  6932. @cindex labels as values
  6933. @cindex computed gotos
  6934. @cindex goto with computed label
  6935. @cindex address of a label
  6936. In GNU C, you can get the address of a label defined in the current
  6937. function (or a local label defined in the containing function) with
  6938. the unary operator @samp{&&}. The value has type @code{void *}. This
  6939. value is a constant and can be used wherever a constant of that type
  6940. is valid. For example:
  6941. @example
  6942. void *ptr;
  6943. @r{@dots{}}
  6944. ptr = &&foo;
  6945. @end example
  6946. To use these values requires a way to jump to one. This is done
  6947. with the computed goto statement@footnote{The analogous feature in
  6948. Fortran is called an assigned goto, but that name seems inappropriate in
  6949. C, since you can do more with label addresses than store them in special label
  6950. variables.}, @code{goto *@var{exp};}. For example,
  6951. @example
  6952. goto *ptr;
  6953. @end example
  6954. @noindent
  6955. Any expression of type @code{void *} is allowed.
  6956. @xref{goto Statement}.
  6957. @menu
  6958. * Label Value Uses:: Examples of using label values.
  6959. * Label Value Caveats:: Limitations of label values.
  6960. @end menu
  6961. @node Label Value Uses
  6962. @subsection Label Value Uses
  6963. One use for label-valued constants is to initialize a static array to
  6964. serve as a jump table:
  6965. @example
  6966. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6967. @end example
  6968. Then you can select a label with indexing, like this:
  6969. @example
  6970. goto *array[i];
  6971. @end example
  6972. @noindent
  6973. Note that this does not check whether the subscript is in bounds---array
  6974. indexing in C never checks that.
  6975. You can make the table entries offsets instead of addresses
  6976. by subtracting one label from the others. Here is an example:
  6977. @example
  6978. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6979. &&hack - &&foo @};
  6980. goto *(&&foo + array[i]);
  6981. @end example
  6982. @noindent
  6983. Using offsets is preferable in shared libraries, as it avoids the need
  6984. for dynamic relocation of the array elements; therefore, the array can
  6985. be read-only.
  6986. An array of label values or offsets serves a purpose much like that of
  6987. the @code{switch} statement. The @code{switch} statement is cleaner,
  6988. so use @code{switch} by preference when feasible.
  6989. Another use of label values is in an interpreter for threaded code.
  6990. The labels within the interpreter function can be stored in the
  6991. threaded code for super-fast dispatching.
  6992. @node Label Value Caveats
  6993. @subsection Label Value Caveats
  6994. Jumping to a label defined in another function does not work.
  6995. It can cause unpredictable results.
  6996. The best way to avoid this is to store label values only in
  6997. automatic variables, or static variables whose names are declared
  6998. within the function. Never pass them as arguments.
  6999. @cindex cloning
  7000. An optimization known as @dfn{cloning} generates multiple simplified
  7001. variants of a function's code, for use with specific fixed arguments.
  7002. Using label values in certain ways, such as saving the address in one
  7003. call to the function and using it again in another call, would make cloning
  7004. give incorrect results. These functions must disable cloning.
  7005. Inlining calls to the function would also result in multiple copies of
  7006. the code, each with its own value of the same label. Using the label
  7007. in a computed goto is no problem, because the computed goto inhibits
  7008. inlining. However, using the label value in some other way, such as
  7009. an indication of where an error occurred, would be optimized wrong.
  7010. These functions must disable inlining.
  7011. To prevent inlining or cloning of a function, specify
  7012. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7013. @xref{Attributes}.
  7014. When a function uses a label value in a static variable initializer,
  7015. that automatically prevents inlining or cloning the function.
  7016. @node Statement Exprs
  7017. @section Statements and Declarations in Expressions
  7018. @cindex statements inside expressions
  7019. @cindex declarations inside expressions
  7020. @cindex expressions containing statements
  7021. @c the above section title wrapped and causes an underfull hbox.. i
  7022. @c changed it from "within" to "in". --mew 4feb93
  7023. A block enclosed in parentheses can be used as an expression in GNU
  7024. C@. This provides a way to use local variables, loops and switches within
  7025. an expression. We call it a @dfn{statement expression}.
  7026. Recall that a block is a sequence of statements
  7027. surrounded by braces. In this construct, parentheses go around the
  7028. braces. For example:
  7029. @example
  7030. (@{ int y = foo (); int z;
  7031. if (y > 0) z = y;
  7032. else z = - y;
  7033. z; @})
  7034. @end example
  7035. @noindent
  7036. is a valid (though slightly more complex than necessary) expression
  7037. for the absolute value of @code{foo ()}.
  7038. The last statement in the block should be an expression statement; an
  7039. expression followed by a semicolon, that is. The value of this
  7040. expression serves as the value of statement expression. If the last
  7041. statement is anything else, the statement expression's value is
  7042. @code{void}.
  7043. This feature is mainly useful in making macro definitions compute each
  7044. operand exactly once. @xref{Macros and Auto Type}.
  7045. Statement expressions are not allowed in expressions that must be
  7046. constant, such as the value for an enumerator, the width of a
  7047. bit-field, or the initial value of a static variable.
  7048. Jumping into a statement expression---with @code{goto}, or using a
  7049. @code{switch} statement outside the statement expression---is an
  7050. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7051. compiler can't detect the error, but it still won't work.
  7052. Jumping out of a statement expression is permitted, but since
  7053. subexpressions in C are not computed in a strict order, it is
  7054. unpredictable which other subexpressions will have been computed by
  7055. then. For example,
  7056. @example
  7057. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7058. @end example
  7059. @noindent
  7060. calls @code{foo} and @code{bar1} before it jumps, and never
  7061. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7062. does get called, that occurs after @code{foo} and before @code{bar1}.
  7063. @node Variables
  7064. @chapter Variables
  7065. @cindex variables
  7066. Every variable used in a C program needs to be made known by a
  7067. @dfn{declaration}. It can be used only after it has been declared.
  7068. It is an error to declare a variable name more than once in the same
  7069. scope; an exception is that @code{extern} declarations and tentative
  7070. definitions can coexist with another declaration of the same
  7071. variable.
  7072. Variables can be declared anywhere within a block or file. (Older
  7073. versions of C required that all variable declarations within a block
  7074. occur before any statements.)
  7075. Variables declared within a function or block are @dfn{local} to
  7076. it. This means that the variable name is visible only until the end
  7077. of that function or block, and the memory space is allocated only
  7078. while control is within it.
  7079. Variables declared at the top level in a file are called @dfn{file-scope}.
  7080. They are assigned fixed, distinct memory locations, so they retain
  7081. their values for the whole execution of the program.
  7082. @menu
  7083. * Variable Declarations:: Name a variable and and reserve space for it.
  7084. * Initializers:: Assigning inital values to variables.
  7085. * Designated Inits:: Assigning initial values to array elements
  7086. at particular array indices.
  7087. * Auto Type:: Obtaining the type of a variable.
  7088. * Local Variables:: Variables declared in function definitions.
  7089. * File-Scope Variables:: Variables declared outside of
  7090. function definitions.
  7091. * Static Local Variables:: Variables declared within functions,
  7092. but with permanent storage allocation.
  7093. * Extern Declarations:: Declaring a variable
  7094. which is allocated somewhere else.
  7095. * Allocating File-Scope:: When is space allocated
  7096. for file-scope variables?
  7097. * auto and register:: Historically used storage directions.
  7098. * Omitting Types:: The bad practice of declaring variables
  7099. with implicit type.
  7100. @end menu
  7101. @node Variable Declarations
  7102. @section Variable Declarations
  7103. @cindex variable declarations
  7104. @cindex declaration of variables
  7105. Here's what a variable declaration looks like:
  7106. @example
  7107. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7108. @end example
  7109. The @var{keywords} specify how to handle the scope of the variable
  7110. name and the allocation of its storage. Most declarations have
  7111. no keywords because the defaults are right for them.
  7112. C allows these keywords to come before or after @var{basetype}, or
  7113. even in the middle of it as in @code{unsigned static int}, but don't
  7114. do that---it would surprise other programmers. Always write the
  7115. keywords first.
  7116. The @var{basetype} can be any of the predefined types of C, or a type
  7117. keyword defined with @code{typedef}. It can also be @code{struct
  7118. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7119. addition, it can include type qualifiers such as @code{const} and
  7120. @code{volatile} (@pxref{Type Qualifiers}).
  7121. In the simplest case, @var{decorated-variable} is just the variable
  7122. name. That declares the variable with the type specified by
  7123. @var{basetype}. For instance,
  7124. @example
  7125. int foo;
  7126. @end example
  7127. @noindent
  7128. uses @code{int} as the @var{basetype} and @code{foo} as the
  7129. @var{decorated-variable}. It declares @code{foo} with type
  7130. @code{int}.
  7131. @example
  7132. struct tree_node foo;
  7133. @end example
  7134. @noindent
  7135. declares @code{foo} with type @code{struct tree_node}.
  7136. @menu
  7137. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7138. array and pointer types.
  7139. * Combining Variable Declarations:: More than one variable declaration
  7140. in a single statement.
  7141. @end menu
  7142. @node Declaring Arrays and Pointers
  7143. @subsection Declaring Arrays and Pointers
  7144. @cindex declaring arrays and pointers
  7145. @cindex array, declaring
  7146. @cindex pointers, declaring
  7147. To declare a variable that is an array, write
  7148. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7149. @example
  7150. int foo[5];
  7151. @end example
  7152. To declare a variable that has a pointer type, write
  7153. @code{*@var{variable}} for @var{decorated-variable}:
  7154. @example
  7155. struct list_elt *foo;
  7156. @end example
  7157. These constructs nest. For instance,
  7158. @example
  7159. int foo[3][5];
  7160. @end example
  7161. @noindent
  7162. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7163. @example
  7164. struct list_elt *foo[5];
  7165. @end example
  7166. @noindent
  7167. declares @code{foo} as an array of 5 pointers to structures, and
  7168. @example
  7169. struct list_elt **foo;
  7170. @end example
  7171. @noindent
  7172. declares @code{foo} as a pointer to a pointer to a structure.
  7173. @example
  7174. int **(*foo[30])(int, double);
  7175. @end example
  7176. @noindent
  7177. declares @code{foo} as an array of 30 pointers to functions
  7178. (@pxref{Function Pointers}), each of which must accept two arguments
  7179. (one @code{int} and one @code{double}) and return type @code{int **}.
  7180. @example
  7181. void
  7182. bar (int size)
  7183. @{
  7184. int foo[size];
  7185. @r{@dots{}}
  7186. @}
  7187. @end example
  7188. @noindent
  7189. declares @code{foo} as an array of integers with a size specified at
  7190. run time when the function @code{bar} is called.
  7191. @node Combining Variable Declarations
  7192. @subsection Combining Variable Declarations
  7193. @cindex combining variable declarations
  7194. @cindex variable declarations, combining
  7195. @cindex declarations, combining
  7196. When multiple declarations have the same @var{keywords} and
  7197. @var{basetype}, you can combine them using commas. Thus,
  7198. @example
  7199. @var{keywords} @var{basetype}
  7200. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7201. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7202. @end example
  7203. @noindent
  7204. is equivalent to
  7205. @example
  7206. @var{keywords} @var{basetype}
  7207. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7208. @var{keywords} @var{basetype}
  7209. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7210. @end example
  7211. Here are some simple examples:
  7212. @example
  7213. int a, b;
  7214. int a = 1, b = 2;
  7215. int a, *p, array[5];
  7216. int a = 0, *p = &a, array[5] = @{1, 2@};
  7217. @end example
  7218. @noindent
  7219. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7220. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7221. Since the initializer for @code{array} specifies only two elements,
  7222. the other three elements are initialized to zero.
  7223. @node Initializers
  7224. @section Initializers
  7225. @cindex initializers
  7226. A variable's declaration, unless it is @code{extern}, should also
  7227. specify its initial value. For numeric and pointer-type variables,
  7228. the initializer is an expression for the value. If necessary, it is
  7229. converted to the variable's type, just as in an assignment.
  7230. You can also initialize a local structure-type (@pxref{Structures}) or
  7231. local union-type (@pxref{Unions}) variable this way, from an
  7232. expression whose value has the same type. But you can't initialize an
  7233. array this way (@pxref{Arrays}), since arrays are not first-class
  7234. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7235. assignment.
  7236. You can initialize arrays and structures componentwise,
  7237. with a list of the elements or components. You can initialize
  7238. a union with any one of its alternatives.
  7239. @itemize @bullet
  7240. @item
  7241. A component-wise initializer for an array consists of element values
  7242. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7243. don't cover all the elements in the array, the remaining elements are
  7244. initialized to zero.
  7245. You can omit the size of the array when you declare it, and let
  7246. the initializer specify the size:
  7247. @example
  7248. int array[] = @{ 3, 9, 12 @};
  7249. @end example
  7250. @item
  7251. A component-wise initializer for a structure consists of field values
  7252. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7253. order as the fields are declared in the structure. If the values in
  7254. the initializer don't cover all the fields in the structure, the
  7255. remaining fields are initialized to zero.
  7256. @item
  7257. The initializer for a union-type variable has the form @code{@{
  7258. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7259. in the union definition.
  7260. @end itemize
  7261. For an array of arrays, a structure containing arrays, an array of
  7262. structures, etc., you can nest these constructs. For example,
  7263. @example
  7264. struct point @{ double x, y; @};
  7265. struct point series[]
  7266. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7267. @end example
  7268. You can omit a pair of inner braces if they contain the right
  7269. number of elements for the sub-value they initialize, so that
  7270. no elements or fields need to be filled in with zeros.
  7271. But don't do that very much, as it gets confusing.
  7272. An array of @code{char} can be initialized using a string constant.
  7273. Recall that the string constant includes an implicit null character at
  7274. the end (@pxref{String Constants}). Using a string constant as
  7275. initializer means to use its contents as the initial values of the
  7276. array elements. Here are examples:
  7277. @example
  7278. char text[6] = "text!"; /* @r{Includes the null.} */
  7279. char text[5] = "text!"; /* @r{Excludes the null.} */
  7280. char text[] = "text!"; /* @r{Gets length 6.} */
  7281. char text[]
  7282. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7283. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7284. @end example
  7285. @noindent
  7286. and this kind of initializer can be nested inside braces to initialize
  7287. structures or arrays that contain a @code{char}-array.
  7288. In like manner, you can use a wide string constant to initialize
  7289. an array of @code{wchar_t}.
  7290. @node Designated Inits
  7291. @section Designated Initializers
  7292. @cindex initializers with labeled elements
  7293. @cindex labeled elements in initializers
  7294. @cindex case labels in initializers
  7295. @cindex designated initializers
  7296. In a complex structure or long array, it's useful to indicate
  7297. which field or element we are initializing.
  7298. To designate specific array elements during initialization, include
  7299. the array index in brackets, and an assignment operator, for each
  7300. element:
  7301. @example
  7302. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7303. @end example
  7304. @noindent
  7305. This does the same thing as:
  7306. @example
  7307. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7308. @end example
  7309. The array initialization can include non-designated element values
  7310. alongside designated indices; these follow the expected ordering
  7311. of the array initialization, so that
  7312. @example
  7313. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7314. @end example
  7315. @noindent
  7316. does the same thing as:
  7317. @example
  7318. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7319. @end example
  7320. Note that you can only use constant expressions as array index values,
  7321. not variables.
  7322. If you need to initialize a subsequence of sequential array elements to
  7323. the same value, you can specify a range:
  7324. @example
  7325. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7326. @end example
  7327. @noindent
  7328. Using a range this way is a GNU C extension.
  7329. When subsequence ranges overlap, each element is initialized by the
  7330. last specification that applies to it. Thus, this initialization is
  7331. equivalent to the previous one.
  7332. @example
  7333. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7334. @end example
  7335. @noindent
  7336. as the second overrides the first for elements 0 through 19.
  7337. The value used to initialize a range of elements is evaluated only
  7338. once, for the first element in the range. So for example, this code
  7339. @example
  7340. int random_values[100]
  7341. = @{ [0 ... 99] = get_random_number() @};
  7342. @end example
  7343. @noindent
  7344. would initialize all 100 elements of the array @code{random_values} to
  7345. the same value---probably not what is intended.
  7346. Similarly, you can initialize specific fields of a structure variable
  7347. by specifying the field name prefixed with a dot:
  7348. @example
  7349. struct point @{ int x; int y; @};
  7350. struct point foo = @{ .y = 42; @};
  7351. @end example
  7352. @noindent
  7353. The same syntax works for union variables as well:
  7354. @example
  7355. union int_double @{ int i; double d; @};
  7356. union int_double foo = @{ .d = 34 @};
  7357. @end example
  7358. @noindent
  7359. This casts the integer value 34 to a double and stores it
  7360. in the union variable @code{foo}.
  7361. You can designate both array elements and structure elements in
  7362. the same initialization; for example, here's an array of point
  7363. structures:
  7364. @example
  7365. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7366. @end example
  7367. Along with the capability to specify particular array and structure
  7368. elements to initialize comes the possibility of initializing the same
  7369. element more than once:
  7370. @example
  7371. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7372. @end example
  7373. @noindent
  7374. In such a case, the last initialization value is retained.
  7375. @node Auto Type
  7376. @section Referring to a Type with @code{__auto_type}
  7377. @findex __auto_type
  7378. @findex typeof
  7379. @cindex macros, types of arguments
  7380. You can declare a variable copying the type from
  7381. the initializer by using @code{__auto_type} instead of a particular type.
  7382. Here's an example:
  7383. @example
  7384. #define max(a,b) \
  7385. (@{ __auto_type _a = (a); \
  7386. __auto_type _b = (b); \
  7387. _a > _b ? _a : _b @})
  7388. @end example
  7389. This defines @code{_a} to be of the same type as @code{a}, and
  7390. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7391. to do in a macro that ought to be able to handle any type of data
  7392. (@pxref{Macros and Auto Type}).
  7393. The original GNU C method for obtaining the type of a value is to use
  7394. @code{typeof}, which takes as an argument either a value or the name of
  7395. a type. The previous example could also be written as:
  7396. @example
  7397. #define max(a,b) \
  7398. (@{ typeof(a) _a = (a); \
  7399. typeof(b) _b = (b); \
  7400. _a > _b ? _a : _b @})
  7401. @end example
  7402. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7403. principal use case for @code{typeof} is in variable declarations with
  7404. initialization, which is exactly what @code{__auto_type} handles.
  7405. @node Local Variables
  7406. @section Local Variables
  7407. @cindex local variables
  7408. @cindex variables, local
  7409. Declaring a variable inside a function definition (@pxref{Function
  7410. Definitions}) makes the variable name @dfn{local} to the containing
  7411. block---that is, the containing pair of braces. More precisely, the
  7412. variable's name is visible starting just after where it appears in the
  7413. declaration, and its visibility continues until the end of the block.
  7414. Local variables in C are generally @dfn{automatic} variables: each
  7415. variable's storage exists only from the declaration to the end of the
  7416. block. Execution of the declaration allocates the storage, computes
  7417. the initial value, and stores it in the variable. The end of the
  7418. block deallocates the storage.@footnote{Due to compiler optimizations,
  7419. allocation and deallocation don't necessarily really happen at
  7420. those times.}
  7421. @strong{Warning:} Two declarations for the same local variable
  7422. in the same scope are an error.
  7423. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7424. The total space for the program's stack may be limited; therefore,
  7425. in using very large arrays, it may be necessary to allocate
  7426. them in some other way to stop the program from crashing.
  7427. @strong{Warning:} If the declaration of an automatic variable does not
  7428. specify an initial value, the variable starts out containing garbage.
  7429. In this example, the value printed could be anything at all:
  7430. @example
  7431. @{
  7432. int i;
  7433. printf ("Print junk %d\n", i);
  7434. @}
  7435. @end example
  7436. In a simple test program, that statement is likely to print 0, simply
  7437. because every process starts with memory zeroed. But don't rely on it
  7438. to be zero---that is erroneous.
  7439. @strong{Note:} Make sure to store a value into each local variable (by
  7440. assignment, or by initialization) before referring to its value.
  7441. @node File-Scope Variables
  7442. @section File-Scope Variables
  7443. @cindex file-scope variables
  7444. @cindex global variables
  7445. @cindex variables, file-scope
  7446. @cindex variables, global
  7447. A variable declaration at the top level in a file (not inside a
  7448. function definition) declares a @dfn{file-scope variable}. Loading a
  7449. program allocates the storage for all the file-scope variables in it,
  7450. and initializes them too.
  7451. Each file-scope variable is either @dfn{static} (limited to one
  7452. compilation module) or @dfn{global} (shared with all compilation
  7453. modules in the program). To make the variable static, write the
  7454. keyword @code{static} at the start of the declaration. Omitting
  7455. @code{static} makes the variable global.
  7456. The initial value for a file-scope variable can't depend on the
  7457. contents of storage, and can't call any functions.
  7458. @example
  7459. int foo = 5; /* @r{Valid.} */
  7460. int bar = foo; /* @r{Invalid!} */
  7461. int bar = sin (1.0); /* @r{Invalid!} */
  7462. @end example
  7463. But it can use the address of another file-scope variable:
  7464. @example
  7465. int foo;
  7466. int *bar = &foo; /* @r{Valid.} */
  7467. int arr[5];
  7468. int *bar3 = &arr[3]; /* @r{Valid.} */
  7469. int *bar4 = arr + 4; /* @r{Valid.} */
  7470. @end example
  7471. It is valid for a module to have multiple declarations for a
  7472. file-scope variable, as long as they are all global or all static, but
  7473. at most one declaration can specify an initial value for it.
  7474. @node Static Local Variables
  7475. @section Static Local Variables
  7476. @cindex static local variables
  7477. @cindex variables, static local
  7478. @findex static
  7479. The keyword @code{static} in a local variable declaration says to
  7480. allocate the storage for the variable permanently, just like a
  7481. file-scope variable, even if the declaration is within a function.
  7482. Here's an example:
  7483. @example
  7484. int
  7485. increment_counter ()
  7486. @{
  7487. static int counter = 0;
  7488. return ++counter;
  7489. @}
  7490. @end example
  7491. The scope of the name @code{counter} runs from the declaration to the
  7492. end of the containing block, just like an automatic local variable,
  7493. but its storage is permanent, so the value persists from one call to
  7494. the next. As a result, each call to @code{increment_counter}
  7495. returns a different, unique value.
  7496. The initial value of a static local variable has the same limitations
  7497. as for file-scope variables: it can't depend on the contents of
  7498. storage or call any functions. It can use the address of a file-scope
  7499. variable or a static local variable, because those addresses are
  7500. determined before the program runs.
  7501. @node Extern Declarations
  7502. @section @code{extern} Declarations
  7503. @cindex @code{extern} declarations
  7504. @cindex declarations, @code{extern}
  7505. @findex extern
  7506. An @code{extern} declaration is used to refer to a global variable
  7507. whose principal declaration comes elsewhere---in the same module, or in
  7508. another compilation module. It looks like this:
  7509. @example
  7510. extern @var{basetype} @var{decorated-variable};
  7511. @end example
  7512. Its meaning is that, in the current scope, the variable name refers to
  7513. the file-scope variable of that name---which needs to be declared in a
  7514. non-@code{extern}, non-@code{static} way somewhere else.
  7515. For instance, if one compilation module has this global variable
  7516. declaration
  7517. @example
  7518. int error_count = 0;
  7519. @end example
  7520. @noindent
  7521. then other compilation modules can specify this
  7522. @example
  7523. extern int error_count;
  7524. @end example
  7525. @noindent
  7526. to allow reference to the same variable.
  7527. The usual place to write an @code{extern} declaration is at top level
  7528. in a source file, but you can write an @code{extern} declaration
  7529. inside a block to make a global or static file-scope variable
  7530. accessible in that block.
  7531. Since an @code{extern} declaration does not allocate space for the
  7532. variable, it can omit the size of an array:
  7533. @example
  7534. extern int array[];
  7535. @end example
  7536. You can use @code{array} normally in all contexts where it is
  7537. converted automatically to a pointer. However, to use it as the
  7538. operand of @code{sizeof} is an error, since the size is unknown.
  7539. It is valid to have multiple @code{extern} declarations for the same
  7540. variable, even in the same scope, if they give the same type. They do
  7541. not conflict---they agree. For an array, it is legitimate for some
  7542. @code{extern} declarations can specify the size while others omit it.
  7543. However, if two declarations give different sizes, that is an error.
  7544. Likewise, you can use @code{extern} declarations at file scope
  7545. (@pxref{File-Scope Variables}) followed by an ordinary global
  7546. (non-static) declaration of the same variable. They do not conflict,
  7547. because they say compatible things about the same meaning of the variable.
  7548. @node Allocating File-Scope
  7549. @section Allocating File-Scope Variables
  7550. @cindex allocation file-scope variables
  7551. @cindex file-scope variables, allocating
  7552. Some file-scope declarations allocate space for the variable, and some
  7553. don't.
  7554. A file-scope declaration with an initial value @emph{must} allocate
  7555. space for the variable; if there are two of such declarations for the
  7556. same variable, even in different compilation modules, they conflict.
  7557. An @code{extern} declaration @emph{never} allocates space for the variable.
  7558. If all the top-level declarations of a certain variable are
  7559. @code{extern}, the variable never gets memory space. If that variable
  7560. is used anywhere in the program, the use will be reported as an error,
  7561. saying that the variable is not defined.
  7562. @cindex tentative definition
  7563. A file-scope declaration without an initial value is called a
  7564. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7565. allocate space for the variable, but does not insist. So it causes no
  7566. conflict, no error, if the variable has another declaration that
  7567. allocates space for it, perhaps in another compilation module. But if
  7568. nothing else allocates space for the variable, the tentative
  7569. definition will do it. Any number of compilation modules can declare
  7570. the same variable in this way, and that is sufficient for all of them
  7571. to use the variable.
  7572. @c @opindex -fno-common
  7573. @c @opindex --warn_common
  7574. In programs that are very large or have many contributors, it may be
  7575. wise to adopt the convention of never using tentative definitions.
  7576. You can use the compilation option @option{-fno-common} to make them
  7577. an error, or @option{--warn-common} to warn about them.
  7578. If a file-scope variable gets its space through a tentative
  7579. definition, it starts out containing all zeros.
  7580. @node auto and register
  7581. @section @code{auto} and @code{register}
  7582. @cindex @code{auto} declarations
  7583. @cindex @code{register} declarations
  7584. @findex auto
  7585. @findex register
  7586. For historical reasons, you can write @code{auto} or @code{register}
  7587. before a local variable declaration. @code{auto} merely emphasizes
  7588. that the variable isn't static; it changes nothing.
  7589. @code{register} suggests to the compiler storing this variable in a
  7590. register. However, GNU C ignores this suggestion, since it can
  7591. choose the best variables to store in registers without any hints.
  7592. It is an error to take the address of a variable declared
  7593. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7594. If the variable is an array, you can't use it at all (other than as
  7595. the operand of @code{sizeof}), which makes it rather useless.
  7596. @node Omitting Types
  7597. @section Omitting Types in Declarations
  7598. @cindex omitting types in declarations
  7599. The syntax of C traditionally allows omitting the data type in a
  7600. declaration if it specifies a storage class, a type qualifier (see the
  7601. next chapter), or @code{auto} or @code{register}. Then the type
  7602. defaults to @code{int}. For example:
  7603. @example
  7604. auto foo = 42;
  7605. @end example
  7606. This is bad practice; if you see it, fix it.
  7607. @node Type Qualifiers
  7608. @chapter Type Qualifiers
  7609. A declaration can include type qualifiers to advise the compiler
  7610. about how the variable will be used. There are three different
  7611. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7612. pertain to different issues, so you can use more than one together.
  7613. For instance, @code{const volatile} describes a value that the
  7614. program is not allowed to change, but might have a different value
  7615. each time the program examines it. (This might perhaps be a special
  7616. hardware register, or part of shared memory.)
  7617. If you are just learning C, you can skip this chapter.
  7618. @menu
  7619. * const:: Variables whose values don't change.
  7620. * volatile:: Variables whose values may be accessed
  7621. or changed outside of the control of
  7622. this program.
  7623. * restrict Pointers:: Restricted pointers for code optimization.
  7624. * restrict Pointer Example:: Example of how that works.
  7625. @end menu
  7626. @node const
  7627. @section @code{const} Variables and Fields
  7628. @cindex @code{const} variables and fields
  7629. @cindex variables, @code{const}
  7630. @findex const
  7631. You can mark a variable as ``constant'' by writing @code{const} in
  7632. front of the declaration. This says to treat any assignment to that
  7633. variable as an error. It may also permit some compiler
  7634. optimizations---for instance, to fetch the value only once to satisfy
  7635. multiple references to it. The construct looks like this:
  7636. @example
  7637. const double pi = 3.14159;
  7638. @end example
  7639. After this definition, the code can use the variable @code{pi}
  7640. but cannot assign a different value to it.
  7641. @example
  7642. pi = 3.0; /* @r{Error!} */
  7643. @end example
  7644. Simple variables that are constant can be used for the same purposes
  7645. as enumeration constants, and they are not limited to integers. The
  7646. constantness of the variable propagates into pointers, too.
  7647. A pointer type can specify that the @emph{target} is constant. For
  7648. example, the pointer type @code{const double *} stands for a pointer
  7649. to a constant @code{double}. That's the typethat results from taking
  7650. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7651. left side of an assignment.
  7652. @example
  7653. *(&pi) = 3.0; /* @r{Error!} */
  7654. @end example
  7655. Nonconstant pointers can be converted automatically to constant
  7656. pointers, but not vice versa. For instance,
  7657. @example
  7658. const double *cptr;
  7659. double *ptr;
  7660. cptr = &pi; /* @r{Valid.} */
  7661. cptr = ptr; /* @r{Valid.} */
  7662. ptr = cptr; /* @r{Error!} */
  7663. ptr = &pi; /* @r{Error!} */
  7664. @end example
  7665. This is not an ironclad protection against modifying the value. You
  7666. can always cast the constant pointer to a nonconstant pointer type:
  7667. @example
  7668. ptr = (double *)cptr; /* @r{Valid.} */
  7669. ptr = (double *)&pi; /* @r{Valid.} */
  7670. @end example
  7671. However, @code{const} provides a way to show that a certain function
  7672. won't modify the data structure whose address is passed to it. Here's
  7673. an example:
  7674. @example
  7675. int
  7676. string_length (const char *string)
  7677. @{
  7678. int count = 0;
  7679. while (*string++)
  7680. count++;
  7681. return count;
  7682. @}
  7683. @end example
  7684. @noindent
  7685. Using @code{const char *} for the parameter is a way of saying this
  7686. function never modifies the memory of the string itself.
  7687. In calling @code{string_length}, you can specify an ordinary
  7688. @code{char *} since that can be converted automatically to @code{const
  7689. char *}.
  7690. @node volatile
  7691. @section @code{volatile} Variables and Fields
  7692. @cindex @code{volatile} variables and fields
  7693. @cindex variables, @code{volatile}
  7694. @findex volatile
  7695. The GNU C compiler often performs optimizations that eliminate the
  7696. need to write or read a variable. For instance,
  7697. @example
  7698. int foo;
  7699. foo = 1;
  7700. foo++;
  7701. @end example
  7702. @noindent
  7703. might simply store the value 2 into @code{foo}, without ever storing 1.
  7704. These optimizations can also apply to structure fields in some cases.
  7705. If the memory containing @code{foo} is shared with another program,
  7706. or if it is examined asynchronously by hardware, such optimizations
  7707. could confuse the communication. Using @code{volatile} is one way
  7708. to prevent them.
  7709. Writing @code{volatile} with the type in a variable or field declaration
  7710. says that the value may be examined or changed for reasons outside the
  7711. control of the program at any moment. Therefore, the program must
  7712. execute in a careful way to assure correct interaction with those
  7713. accesses, whenever they may occur.
  7714. The simplest use looks like this:
  7715. @example
  7716. volatile int lock;
  7717. @end example
  7718. This directs the compiler not to do certain common optimizations on
  7719. use of the variable @code{lock}. All the reads and writes for a volatile
  7720. variable or field are really done, and done in the order specified
  7721. by the source code. Thus, this code:
  7722. @example
  7723. lock = 1;
  7724. list = list->next;
  7725. if (lock)
  7726. lock_broken (&lock);
  7727. lock = 0;
  7728. @end example
  7729. @noindent
  7730. really stores the value 1 in @code{lock}, even though there is no
  7731. sign it is really used, and the @code{if} statement reads and
  7732. checks the value of @code{lock}, rather than assuming it is still 1.
  7733. A limited amount of optimization can be done, in principle, on
  7734. @code{volatile} variables and fields: multiple references between two
  7735. sequence points (@pxref{Sequence Points}) can be simplified together.
  7736. Use of @code{volatile} does not eliminate the flexibility in ordering
  7737. the computation of the operands of most operators. For instance, in
  7738. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7739. @code{foo} is not specified, so they may be done in either order; the
  7740. fact that @code{lock} is @code{volatile} has no effect on that.
  7741. @node restrict Pointers
  7742. @section @code{restrict}-Qualified Pointers
  7743. @cindex @code{restrict} pointers
  7744. @cindex pointers, @code{restrict}-qualified
  7745. @findex restrict
  7746. You can declare a pointer as ``restricted'' using the @code{restrict}
  7747. type qualifier, like this:
  7748. @example
  7749. int *restrict p = x;
  7750. @end example
  7751. @noindent
  7752. This enables better optimization of code that uses the pointer.
  7753. If @code{p} is declared with @code{restrict}, and then the code
  7754. references the object that @code{p} points to (using @code{*p} or
  7755. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7756. code will not access that object in any other way---only through
  7757. @code{p}.
  7758. For instance, it means the code must not use another pointer
  7759. to access the same space, as shown here:
  7760. @example
  7761. int *restrict p = @var{whatever};
  7762. int *q = p;
  7763. foo (*p, *q);
  7764. @end example
  7765. @noindent
  7766. That contradicts the @code{restrict} promise by accessing the object
  7767. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7768. Likewise, it must not do this:
  7769. @example
  7770. int *restrict p = @var{whatever};
  7771. struct @{ int *a, *b; @} s;
  7772. s.a = p;
  7773. foo (*p, *s.a);
  7774. @end example
  7775. @noindent
  7776. This example uses a structure field instead of the variable @code{q}
  7777. to hold the other pointer, and that contradicts the promise just the
  7778. same.
  7779. The keyword @code{restrict} also promises that @code{p} won't point to
  7780. the allocated space of any automatic or static variable. So the code
  7781. must not do this:
  7782. @example
  7783. int a;
  7784. int *restrict p = &a;
  7785. foo (*p, a);
  7786. @end example
  7787. @noindent
  7788. because that does direct access to the object (@code{a}) that @code{p}
  7789. points to, which bypasses @code{p}.
  7790. If the code makes such promises with @code{restrict} then breaks them,
  7791. execution is unpredictable.
  7792. @node restrict Pointer Example
  7793. @section @code{restrict} Pointer Example
  7794. Here are examples where @code{restrict} enables real optimization.
  7795. In this example, @code{restrict} assures GCC that the array @code{out}
  7796. points to does not overlap with the array @code{in} points to.
  7797. @example
  7798. void
  7799. process_data (const char *in,
  7800. char * restrict out,
  7801. size_t size)
  7802. @{
  7803. for (i = 0; i < size; i++)
  7804. out[i] = in[i] + in[i + 1];
  7805. @}
  7806. @end example
  7807. Here's a simple tree structure, where each tree node holds data of
  7808. type @code{PAYLOAD} plus two subtrees.
  7809. @example
  7810. struct foo
  7811. @{
  7812. PAYLOAD payload;
  7813. struct foo *left;
  7814. struct foo *right;
  7815. @};
  7816. @end example
  7817. Now here's a function to null out both pointers in the @code{left}
  7818. subtree.
  7819. @example
  7820. void
  7821. null_left (struct foo *a)
  7822. @{
  7823. a->left->left = NULL;
  7824. a->left->right = NULL;
  7825. @}
  7826. @end example
  7827. Since @code{*a} and @code{*a->left} have the same data type,
  7828. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7829. the compiled code for @code{null_left} must read @code{a->left}
  7830. again from memory when executing the second assignment statement.
  7831. We can enable optimization, so that it does not need to read
  7832. @code{a->left} again, by writing @code{null_left} this in a less
  7833. obvious way.
  7834. @example
  7835. void
  7836. null_left (struct foo *a)
  7837. @{
  7838. struct foo *b = a->left;
  7839. b->left = NULL;
  7840. b->right = NULL;
  7841. @}
  7842. @end example
  7843. A more elegant way to fix this is with @code{restrict}.
  7844. @example
  7845. void
  7846. null_left (struct foo *restrict a)
  7847. @{
  7848. a->left->left = NULL;
  7849. a->left->right = NULL;
  7850. @}
  7851. @end example
  7852. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7853. as @code{a->left} will not point to the same memory space as @code{a}.
  7854. Therefore, the memory location @code{a->left->left} cannot be the same
  7855. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7856. reloading @code{a->left} for the second statement.
  7857. @node Functions
  7858. @chapter Functions
  7859. @cindex functions
  7860. We have already presented many examples of functions, so if you've
  7861. read this far, you basically understand the concept of a function. It
  7862. is vital, nonetheless, to have a chapter in the manual that collects
  7863. all the information about functions.
  7864. @menu
  7865. * Function Definitions:: Writing the body of a function.
  7866. * Function Declarations:: Declaring the interface of a function.
  7867. * Function Calls:: Using functions.
  7868. * Function Call Semantics:: Call-by-value argument passing.
  7869. * Function Pointers:: Using references to functions.
  7870. * The main Function:: Where execution of a GNU C program begins.
  7871. * Advanced Definitions:: Advanced features of function definitions.
  7872. * Obsolete Definitions:: Obsolete features still used
  7873. in function definitions in old code.
  7874. @end menu
  7875. @node Function Definitions
  7876. @section Function Definitions
  7877. @cindex function definitions
  7878. @cindex defining functions
  7879. We have already presented many examples of function definitions. To
  7880. summarize the rules, a function definition looks like this:
  7881. @example
  7882. @var{returntype}
  7883. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7884. @{
  7885. @var{body}
  7886. @}
  7887. @end example
  7888. The part before the open-brace is called the @dfn{function header}.
  7889. Write @code{void} as the @var{returntype} if the function does
  7890. not return a value.
  7891. @menu
  7892. * Function Parameter Variables:: Syntax and semantics
  7893. of function parameters.
  7894. * Forward Function Declarations:: Functions can only be called after
  7895. they have been defined or declared.
  7896. * Static Functions:: Limiting visibility of a function.
  7897. * Arrays as Parameters:: Functions that accept array arguments.
  7898. * Structs as Parameters:: Functions that accept structure arguments.
  7899. @end menu
  7900. @node Function Parameter Variables
  7901. @subsection Function Parameter Variables
  7902. @cindex function parameter variables
  7903. @cindex parameter variables in functions
  7904. @cindex parameter list
  7905. A function parameter variable is a local variable (@pxref{Local
  7906. Variables}) used within the function to store the value passed as an
  7907. argument in a call to the function. Usually we say ``function
  7908. parameter'' or ``parameter'' for short, not mentioning the fact that
  7909. it's a variable.
  7910. We declare these variables in the beginning of the function
  7911. definition, in the @dfn{parameter list}. For example,
  7912. @example
  7913. fib (int n)
  7914. @end example
  7915. @noindent
  7916. has a parameter list with one function parameter @code{n}, which has
  7917. type @code{int}.
  7918. Function parameter declarations differ from ordinary variable
  7919. declarations in several ways:
  7920. @itemize @bullet
  7921. @item
  7922. Inside the function definition header, commas separate parameter
  7923. declarations, and each parameter needs a complete declaration
  7924. including the type. For instance, if a function @code{foo} has two
  7925. @code{int} parameters, write this:
  7926. @example
  7927. foo (int a, int b)
  7928. @end example
  7929. You can't share the common @code{int} between the two declarations:
  7930. @example
  7931. foo (int a, b) /* @r{Invalid!} */
  7932. @end example
  7933. @item
  7934. A function parameter variable is initialized to whatever value is
  7935. passed in the function call, so its declaration cannot specify an
  7936. initial value.
  7937. @item
  7938. Writing an array type in a function parameter declaration has the
  7939. effect of declaring it as a pointer. The size specified for the array
  7940. has no effect at all, and we normally omit the size. Thus,
  7941. @example
  7942. foo (int a[5])
  7943. foo (int a[])
  7944. foo (int *a)
  7945. @end example
  7946. @noindent
  7947. are equivalent.
  7948. @item
  7949. The scope of the parameter variables is the entire function body,
  7950. notwithstanding the fact that they are written in the function header,
  7951. which is just outside the function body.
  7952. @end itemize
  7953. If a function has no parameters, it would be most natural for the
  7954. list of parameters in its definition to be empty. But that, in C, has
  7955. a special meaning for historical reasons: ``Do not check that calls to
  7956. this function have the right number of arguments.'' Thus,
  7957. @example
  7958. int
  7959. foo ()
  7960. @{
  7961. return 5;
  7962. @}
  7963. int
  7964. bar (int x)
  7965. @{
  7966. return foo (x);
  7967. @}
  7968. @end example
  7969. @noindent
  7970. would not report a compilation error in passing @code{x} as an
  7971. argument to @code{foo}. By contrast,
  7972. @example
  7973. int
  7974. foo (void)
  7975. @{
  7976. return 5;
  7977. @}
  7978. int
  7979. bar (int x)
  7980. @{
  7981. return foo (x);
  7982. @}
  7983. @end example
  7984. @noindent
  7985. would report an error because @code{foo} is supposed to receive
  7986. no arguments.
  7987. @node Forward Function Declarations
  7988. @subsection Forward Function Declarations
  7989. @cindex forward function declarations
  7990. @cindex function declarations, forward
  7991. The order of the function definitions in the source code makes no
  7992. difference, except that each function needs to be defined or declared
  7993. before code uses it.
  7994. The definition of a function also declares its name for the rest of
  7995. the containing scope. But what if you want to call the function
  7996. before its definition? To permit that, write a compatible declaration
  7997. of the same function, before the first call. A declaration that
  7998. prefigures a subsequent definition in this way is called a
  7999. @dfn{forward declaration}. The function declaration can be at top
  8000. @c ??? file scope
  8001. level or within a block, and it applies until the end of the containing
  8002. scope.
  8003. @xref{Function Declarations}, for more information about these
  8004. declarations.
  8005. @node Static Functions
  8006. @subsection Static Functions
  8007. @cindex static functions
  8008. @cindex functions, static
  8009. @findex static
  8010. The keyword @code{static} in a function definition limits the
  8011. visibility of the name to the current compilation module. (That's the
  8012. same thing @code{static} does in variable declarations;
  8013. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8014. contains this code:
  8015. @example
  8016. static int
  8017. foo (void)
  8018. @{
  8019. @r{@dots{}}
  8020. @}
  8021. @end example
  8022. @noindent
  8023. then the code of that compilation module can call @code{foo} anywhere
  8024. after the definition, but other compilation modules cannot refer to it
  8025. at all.
  8026. @cindex forward declaration
  8027. @cindex static function, declaration
  8028. To call @code{foo} before its definition, it needs a forward
  8029. declaration, which should use @code{static} since the function
  8030. definition does. For this function, it looks like this:
  8031. @example
  8032. static int foo (void);
  8033. @end example
  8034. It is generally wise to use @code{static} on the definitions of
  8035. functions that won't be called from outside the same compilation
  8036. module. This makes sure that calls are not added in other modules.
  8037. If programmers decide to change the function's calling convention, or
  8038. understand all the consequences of its use, they will only have to
  8039. check for calls in the same compilation module.
  8040. @node Arrays as Parameters
  8041. @subsection Arrays as Parameters
  8042. @cindex array as parameters
  8043. @cindex functions with array parameters
  8044. Arrays in C are not first-class objects: it is impossible to copy
  8045. them. So they cannot be passed as arguments like other values.
  8046. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8047. a special way.
  8048. @menu
  8049. * Array Parm Pointer::
  8050. * Passing Array Args::
  8051. * Array Parm Qualifiers::
  8052. @end menu
  8053. @node Array Parm Pointer
  8054. @subsubsection Array parameters are pointers
  8055. Declaring a function parameter variable as an array really gives it a
  8056. pointer type. C does this because an expression with array type, if
  8057. used as an argument in a function call, is converted automatically to
  8058. a pointer (to the zeroth element of the array). If you declare the
  8059. corresponding parameter as an ``array'', it will work correctly with
  8060. the pointer value that really gets passed.
  8061. This relates to the fact that C does not check array bounds in access
  8062. to elements of the array (@pxref{Accessing Array Elements}).
  8063. For example, in this function,
  8064. @example
  8065. void
  8066. clobber4 (int array[20])
  8067. @{
  8068. array[4] = 0;
  8069. @}
  8070. @end example
  8071. @noindent
  8072. the parameter @code{array}'s real type is @code{int *}; the specified
  8073. length, 20, has no effect on the program. You can leave out the length
  8074. and write this:
  8075. @example
  8076. void
  8077. clobber4 (int array[])
  8078. @{
  8079. array[4] = 0;
  8080. @}
  8081. @end example
  8082. @noindent
  8083. or write the parameter declaration explicitly as a pointer:
  8084. @example
  8085. void
  8086. clobber4 (int *array)
  8087. @{
  8088. array[4] = 0;
  8089. @}
  8090. @end example
  8091. They are all equivalent.
  8092. @node Passing Array Args
  8093. @subsubsection Passing array arguments
  8094. The function call passes this pointer by
  8095. value, like all argument values in C@. However, the result is
  8096. paradoxical in that the array itself is passed by reference: its
  8097. contents are treated as shared memory---shared between the caller and
  8098. the called function, that is. When @code{clobber4} assigns to element
  8099. 4 of @code{array}, the effect is to alter element 4 of the array
  8100. specified in the call.
  8101. @example
  8102. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8103. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8104. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8105. int
  8106. main (void)
  8107. @{
  8108. int data[] = @{1, 2, 3, 4, 5, 6@};
  8109. int i;
  8110. /* @r{Show the initial value of element 4.} */
  8111. for (i = 0; i < 6; i++)
  8112. printf ("data[%d] = %d\n", i, data[i]);
  8113. printf ("\n");
  8114. clobber4 (data);
  8115. /* @r{Show that element 4 has been changed.} */
  8116. for (i = 0; i < 6; i++)
  8117. printf ("data[%d] = %d\n", i, data[i]);
  8118. printf ("\n");
  8119. return EXIT_SUCCESS;
  8120. @}
  8121. @end example
  8122. @noindent
  8123. shows that @code{data[4]} has become zero after the call to
  8124. @code{clobber4}.
  8125. The array @code{data} has 6 elements, but passing it to a function
  8126. whose argument type is written as @code{int [20]} is not an error,
  8127. because that really stands for @code{int *}. The pointer that is the
  8128. real argument carries no indication of the length of the array it
  8129. points into. It is not required to point to the beginning of the
  8130. array, either. For instance,
  8131. @example
  8132. clobber4 (data+1);
  8133. @end example
  8134. @noindent
  8135. passes an ``array'' that starts at element 1 of @code{data}, and the
  8136. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8137. If all calls to the function will provide an array of a particular
  8138. size, you can specify the size of the array to be @code{static}:
  8139. @example
  8140. void
  8141. clobber4 (int array[static 20])
  8142. @r{@dots{}}
  8143. @end example
  8144. @noindent
  8145. This is a promise to the compiler that the function will always be
  8146. called with an array of 20 elements, so that the compiler can optimize
  8147. code accordingly. If the code breaks this promise and calls the
  8148. function with, for example, a shorter array, unpredictable things may
  8149. happen.
  8150. @node Array Parm Qualifiers
  8151. @subsubsection Type qualifiers on array parameters
  8152. You can use the type qualifiers @code{const}, @code{restrict}, and
  8153. @code{volatile} with array parameters; for example:
  8154. @example
  8155. void
  8156. clobber4 (volatile int array[20])
  8157. @r{@dots{}}
  8158. @end example
  8159. @noindent
  8160. denotes that @code{array} is equivalent to a pointer to a volatile
  8161. @code{int}. Alternatively:
  8162. @example
  8163. void
  8164. clobber4 (int array[const 20])
  8165. @r{@dots{}}
  8166. @end example
  8167. @noindent
  8168. makes the array parameter equivalent to a constant pointer to an
  8169. @code{int}. If we want the @code{clobber4} function to succeed, it
  8170. would not make sense to write
  8171. @example
  8172. void
  8173. clobber4 (const int array[20])
  8174. @r{@dots{}}
  8175. @end example
  8176. @noindent
  8177. as this would tell the compiler that the parameter should point to an
  8178. array of constant @code{int} values, and then we would not be able to
  8179. store zeros in them.
  8180. In a function with multiple array parameters, you can use @code{restrict}
  8181. to tell the compiler that each array parameter passed in will be distinct:
  8182. @example
  8183. void
  8184. foo (int array1[restrict 10], int array2[restrict 10])
  8185. @r{@dots{}}
  8186. @end example
  8187. @noindent
  8188. Using @code{restrict} promises the compiler that callers will
  8189. not pass in the same array for more than one @code{restrict} array
  8190. parameter. Knowing this enables the compiler to perform better code
  8191. optimization. This is the same effect as using @code{restrict}
  8192. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8193. the code that an array of a specific size is expected.
  8194. @node Structs as Parameters
  8195. @subsection Functions That Accept Structure Arguments
  8196. Structures in GNU C are first-class objects, so using them as function
  8197. parameters and arguments works in the natural way. This function
  8198. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8199. and returns a structure of the same type but with the fields
  8200. exchanged.
  8201. @example
  8202. struct foo @{ int a, b; @};
  8203. struct foo x;
  8204. struct foo
  8205. swapfoo (struct foo inval)
  8206. @{
  8207. struct foo outval;
  8208. outval.a = inval.b;
  8209. outval.b = inval.a;
  8210. return outval;
  8211. @}
  8212. @end example
  8213. This simpler definition of @code{swapfoo} avoids using a local
  8214. variable to hold the result about to be return, by using a structure
  8215. constructor (@pxref{Structure Constructors}), like this:
  8216. @example
  8217. struct foo
  8218. swapfoo (struct foo inval)
  8219. @{
  8220. return (struct foo) @{ inval.b, inval.a @};
  8221. @}
  8222. @end example
  8223. It is valid to define a structure type in a function's parameter list,
  8224. as in
  8225. @example
  8226. int
  8227. frob_bar (struct bar @{ int a, b; @} inval)
  8228. @{
  8229. @var{body}
  8230. @}
  8231. @end example
  8232. @noindent
  8233. and @var{body} can access the fields of @var{inval} since the
  8234. structure type @code{struct bar} is defined for the whole function
  8235. body. However, there is no way to create a @code{struct bar} argument
  8236. to pass to @code{frob_bar}, except with kludges. As a result,
  8237. defining a structure type in a parameter list is useless in practice.
  8238. @node Function Declarations
  8239. @section Function Declarations
  8240. @cindex function declarations
  8241. @cindex declararing functions
  8242. To call a function, or use its name as a pointer, a @dfn{function
  8243. declaration} for the function name must be in effect at that point in
  8244. the code. The function's definition serves as a declaration of that
  8245. function for the rest of the containing scope, but to use the function
  8246. in code before the definition, or from another compilation module, a
  8247. separate function declaration must precede the use.
  8248. A function declaration looks like the start of a function definition.
  8249. It begins with the return value type (@code{void} if none) and the
  8250. function name, followed by argument declarations in parentheses
  8251. (though these can sometimes be omitted). But that's as far as the
  8252. similarity goes: instead of the function body, the declaration uses a
  8253. semicolon.
  8254. @cindex function prototype
  8255. @cindex prototype of a function
  8256. A declaration that specifies argument types is called a @dfn{function
  8257. prototype}. You can include the argument names or omit them. The
  8258. names, if included in the declaration, have no effect, but they may
  8259. serve as documentation.
  8260. This form of prototype specifies fixed argument types:
  8261. @example
  8262. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8263. @end example
  8264. @noindent
  8265. This form says the function takes no arguments:
  8266. @example
  8267. @var{rettype} @var{function} (void);
  8268. @end example
  8269. @noindent
  8270. This form declares types for some arguments, and allows additional
  8271. arguments whose types are not specified:
  8272. @example
  8273. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8274. @end example
  8275. For a parameter that's an array of variable length, you can write
  8276. its declaration with @samp{*} where the ``length'' of the array would
  8277. normally go; for example, these are all equivalent.
  8278. @example
  8279. double maximum (int n, int m, double a[n][m]);
  8280. double maximum (int n, int m, double a[*][*]);
  8281. double maximum (int n, int m, double a[ ][*]);
  8282. double maximum (int n, int m, double a[ ][m]);
  8283. @end example
  8284. @noindent
  8285. The old-fashioned form of declaration, which is not a prototype, says
  8286. nothing about the types of arguments or how many they should be:
  8287. @example
  8288. @var{rettype} @var{function} ();
  8289. @end example
  8290. @strong{Warning:} Arguments passed to a function declared without a
  8291. prototype are converted with the default argument promotions
  8292. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8293. types are unspecified.
  8294. Function declarations are usually written at the top level in a source file,
  8295. but you can also put them inside code blocks. Then the function name
  8296. is visible for the rest of the containing scope. For example:
  8297. @example
  8298. void
  8299. foo (char *file_name)
  8300. @{
  8301. void save_file (char *);
  8302. save_file (file_name);
  8303. @}
  8304. @end example
  8305. If another part of the code tries to call the function
  8306. @code{save_file}, this declaration won't be in effect there. So the
  8307. function will get an implicit declaration of the form @code{extern int
  8308. save_file ();}. That conflicts with the explicit declaration
  8309. here, and the discrepancy generates a warning.
  8310. The syntax of C traditionally allows omitting the data type in a
  8311. function declaration if it specifies a storage class or a qualifier.
  8312. Then the type defaults to @code{int}. For example:
  8313. @example
  8314. static foo (double x);
  8315. @end example
  8316. @noindent
  8317. defaults the return type to @code{int}.
  8318. This is bad practice; if you see it, fix it.
  8319. Calling a function that is undeclared has the effect of an creating
  8320. @dfn{implicit} declaration in the innermost containing scope,
  8321. equivalent to this:
  8322. @example
  8323. extern int @dfn{function} ();
  8324. @end example
  8325. @noindent
  8326. This declaration says that the function returns @code{int} but leaves
  8327. its argument types unspecified. If that does not accurately fit the
  8328. function, then the program @strong{needs} an explicit declaration of
  8329. the function with argument types in order to call it correctly.
  8330. Implicit declarations are deprecated, and a function call that creates one
  8331. causes a warning.
  8332. @node Function Calls
  8333. @section Function Calls
  8334. @cindex function calls
  8335. @cindex calling functions
  8336. Starting a program automatically calls the function named @code{main}
  8337. (@pxref{The main Function}). Aside from that, a function does nothing
  8338. except when it is @dfn{called}. That occurs during the execution of a
  8339. function-call expression specifying that function.
  8340. A function-call expression looks like this:
  8341. @example
  8342. @var{function} (@var{arguments}@r{@dots{}})
  8343. @end example
  8344. Most of the time, @var{function} is a function name. However, it can
  8345. also be an expression with a function pointer value; that way, the
  8346. program can determine at run time which function to call.
  8347. The @var{arguments} are a series of expressions separated by commas.
  8348. Each expression specifies one argument to pass to the function.
  8349. The list of arguments in a function call looks just like use of the
  8350. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8351. the parentheses of a function call gives it a different meaning.
  8352. Here's an example of a function call, taken from an example near the
  8353. beginning (@pxref{Complete Program}).
  8354. @example
  8355. printf ("Fibonacci series item %d is %d\n",
  8356. 19, fib (19));
  8357. @end example
  8358. The three arguments given to @code{printf} are a constant string, the
  8359. integer 19, and the integer returned by @code{fib (19)}.
  8360. @node Function Call Semantics
  8361. @section Function Call Semantics
  8362. @cindex function call semantics
  8363. @cindex semantics of function calls
  8364. @cindex call-by-value
  8365. The meaning of a function call is to compute the specified argument
  8366. expressions, convert their values according to the function's
  8367. declaration, then run the function giving it copies of the converted
  8368. values. (This method of argument passing is known as
  8369. @dfn{call-by-value}.) When the function finishes, the value it
  8370. returns becomes the value of the function-call expression.
  8371. Call-by-value implies that an assignment to the function argument
  8372. variable has no direct effect on the caller. For instance,
  8373. @example
  8374. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8375. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8376. void
  8377. subroutine (int x)
  8378. @{
  8379. x = 5;
  8380. @}
  8381. void
  8382. main (void)
  8383. @{
  8384. int y = 20;
  8385. subroutine (y);
  8386. printf ("y is %d\n", y);
  8387. return EXIT_SUCCESS;
  8388. @}
  8389. @end example
  8390. @noindent
  8391. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8392. from the value of @code{y}, but this does not establish any other
  8393. relationship between the two variables. Thus, the assignment to
  8394. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8395. If an argument's type is specified by the function's declaration, the
  8396. function call converts the argument expression to that type if
  8397. possible. If the conversion is impossible, that is an error.
  8398. If the function's declaration doesn't specify the type of that
  8399. argument, then the @emph{default argument promotions} apply.
  8400. @xref{Argument Promotions}.
  8401. @node Function Pointers
  8402. @section Function Pointers
  8403. @cindex function pointers
  8404. @cindex pointers to functions
  8405. A function name refers to a fixed function. Sometimes it is useful to
  8406. call a function to be determined at run time; to do this, you can use
  8407. a @dfn{function pointer value} that points to the chosen function
  8408. (@pxref{Pointers}).
  8409. Pointer-to-function types can be used to declare variables and other
  8410. data, including array elements, structure fields, and union
  8411. alternatives. They can also be used for function arguments and return
  8412. values. These types have the peculiarity that they are never
  8413. converted automatically to @code{void *} or vice versa. However, you
  8414. can do that conversion with a cast.
  8415. @menu
  8416. * Declaring Function Pointers:: How to declare a pointer to a function.
  8417. * Assigning Function Pointers:: How to assign values to function pointers.
  8418. * Calling Function Pointers:: How to call functions through pointers.
  8419. @end menu
  8420. @node Declaring Function Pointers
  8421. @subsection Declaring Function Pointers
  8422. @cindex declaring function pointers
  8423. @cindex function pointers, declaring
  8424. The declaration of a function pointer variable (or structure field)
  8425. looks almost like a function declaration, except it has an additional
  8426. @samp{*} just before the variable name. Proper nesting requires a
  8427. pair of parentheses around the two of them. For instance, @code{int
  8428. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8429. an @code{int}-returning function.''
  8430. Contrast these three declarations:
  8431. @example
  8432. /* @r{Declare a function returning @code{char *}.} */
  8433. char *a (char *);
  8434. /* @r{Declare a pointer to a function returning @code{char}.} */
  8435. char (*a) (char *);
  8436. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8437. char *(*a) (char *);
  8438. @end example
  8439. The possible argument types of the function pointed to are the same
  8440. as in a function declaration. You can write a prototype
  8441. that specifies all the argument types:
  8442. @example
  8443. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8444. @end example
  8445. @noindent
  8446. or one that specifies some and leaves the rest unspecified:
  8447. @example
  8448. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8449. @end example
  8450. @noindent
  8451. or one that says there are no arguments:
  8452. @example
  8453. @var{rettype} (*@var{function}) (void);
  8454. @end example
  8455. You can also write a non-prototype declaration that says
  8456. nothing about the argument types:
  8457. @example
  8458. @var{rettype} (*@var{function}) ();
  8459. @end example
  8460. For example, here's a declaration for a variable that should
  8461. point to some arithmetic function that operates on two @code{double}s:
  8462. @example
  8463. double (*binary_op) (double, double);
  8464. @end example
  8465. Structure fields, union alternatives, and array elements can be
  8466. function pointers; so can parameter variables. The function pointer
  8467. declaration construct can also be combined with other operators
  8468. allowed in declarations. For instance,
  8469. @example
  8470. int **(*foo)();
  8471. @end example
  8472. @noindent
  8473. declares @code{foo} as a pointer to a function that returns
  8474. type @code{int **}, and
  8475. @example
  8476. int **(*foo[30])();
  8477. @end example
  8478. @noindent
  8479. declares @code{foo} as an array of 30 pointers to functions that
  8480. return type @code{int **}.
  8481. @example
  8482. int **(**foo)();
  8483. @end example
  8484. @noindent
  8485. declares @code{foo} as a pointer to a pointer to a function that
  8486. returns type @code{int **}.
  8487. @node Assigning Function Pointers
  8488. @subsection Assigning Function Pointers
  8489. @cindex assigning function pointers
  8490. @cindex function pointers, assigning
  8491. Assuming we have declared the variable @code{binary_op} as in the
  8492. previous section, giving it a value requires a suitable function to
  8493. use. So let's define a function suitable for the variable to point
  8494. to. Here's one:
  8495. @example
  8496. double
  8497. double_add (double a, double b)
  8498. @{
  8499. return a+b;
  8500. @}
  8501. @end example
  8502. Now we can give it a value:
  8503. @example
  8504. binary_op = double_add;
  8505. @end example
  8506. The target type of the function pointer must be upward compatible with
  8507. the type of the function (@pxref{Compatible Types}).
  8508. There is no need for @samp{&} in front of @code{double_add}.
  8509. Using a function name such as @code{double_add} as an expression
  8510. automatically converts it to the function's address, with the
  8511. appropriate function pointer type. However, it is ok to use
  8512. @samp{&} if you feel that is clearer:
  8513. @example
  8514. binary_op = &double_add;
  8515. @end example
  8516. @node Calling Function Pointers
  8517. @subsection Calling Function Pointers
  8518. @cindex calling function pointers
  8519. @cindex function pointers, calling
  8520. To call the function specified by a function pointer, just write the
  8521. function pointer value in a function call. For instance, here's a
  8522. call to the function @code{binary_op} points to:
  8523. @example
  8524. binary_op (x, 5)
  8525. @end example
  8526. Since the data type of @code{binary_op} explicitly specifies type
  8527. @code{double} for the arguments, the call converts @code{x} and 5 to
  8528. @code{double}.
  8529. The call conceptually dereferences the pointer @code{binary_op} to
  8530. ``get'' the function it points to, and calls that function. If you
  8531. wish, you can explicitly represent the derefence by writing the
  8532. @code{*} operator:
  8533. @example
  8534. (*binary_op) (x, 5)
  8535. @end example
  8536. The @samp{*} reminds people reading the code that @code{binary_op} is
  8537. a function pointer rather than the name of a specific function.
  8538. @node The main Function
  8539. @section The @code{main} Function
  8540. @cindex @code{main} function
  8541. @findex main
  8542. Every complete executable program requires at least one function,
  8543. called @code{main}, which is where execution begins. You do not have
  8544. to explicitly declare @code{main}, though GNU C permits you to do so.
  8545. Conventionally, @code{main} should be defined to follow one of these
  8546. calling conventions:
  8547. @example
  8548. int main (void) @{@r{@dots{}}@}
  8549. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8550. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8551. @end example
  8552. @noindent
  8553. Using @code{void} as the parameter list means that @code{main} does
  8554. not use the arguments. You can write @code{char **argv} instead of
  8555. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8556. constructs are equivalent.
  8557. @ignore @c Not so at present
  8558. Defining @code{main} in any other way generates a warning. Your
  8559. program will still compile, but you may get unexpected results when
  8560. executing it.
  8561. @end ignore
  8562. You can call @code{main} from C code, as you can call any other
  8563. function, though that is an unusual thing to do. When you do that,
  8564. you must write the call to pass arguments that match the parameters in
  8565. the definition of @code{main}.
  8566. The @code{main} function is not actually the first code that runs when
  8567. a program starts. In fact, the first code that runs is system code
  8568. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8569. code, but in GNU we replaced it with C code. Its job is to find
  8570. the arguments for @code{main} and call that.
  8571. @menu
  8572. * Values from main:: Returning values from the main function.
  8573. * Command-line Parameters:: Accessing command-line parameters
  8574. provided to the program.
  8575. * Environment Variables:: Accessing system environment variables.
  8576. @end menu
  8577. @node Values from main
  8578. @subsection Returning Values from @code{main}
  8579. @cindex returning values from @code{main}
  8580. @cindex success
  8581. @cindex failure
  8582. @cindex exit status
  8583. When @code{main} returns, the process terminates. Whatever value
  8584. @code{main} returns becomes the exit status which is reported to the
  8585. parent process. While nominally the return value is of type
  8586. @code{int}, in fact the exit status gets truncated to eight bits; if
  8587. @code{main} returns the value 256, the exit status is 0.
  8588. Normally, programs return only one of two values: 0 for success,
  8589. and 1 for failure. For maximum portability, use the macro
  8590. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8591. @code{stdlib.h}. Here's an example:
  8592. @cindex @code{EXIT_FAILURE}
  8593. @cindex @code{EXIT_SUCCESS}
  8594. @example
  8595. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8596. /* @r{and @code{EXIT_FAILURE}.} */
  8597. int
  8598. main (void)
  8599. @{
  8600. @r{@dots{}}
  8601. if (foo)
  8602. return EXIT_SUCCESS;
  8603. else
  8604. return EXIT_FAILURE;
  8605. @}
  8606. @end example
  8607. Some types of programs maintain special conventions for various return
  8608. values; for example, comparison programs including @code{cmp} and
  8609. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8610. the comparison couldn't be performed.
  8611. @node Command-line Parameters
  8612. @subsection Accessing Command-line Parameters
  8613. @cindex command-line parameters
  8614. @cindex parameters, command-line
  8615. If the program was invoked with any command-line arguments, it can
  8616. access them through the arguments of @code{main}, @code{argc} and
  8617. @code{argv}. (You can give these arguments any names, but the names
  8618. @code{argc} and @code{argv} are customary.)
  8619. The value of @code{argv} is an array containing all of the
  8620. command-line arguments as strings, with the name of the command
  8621. invoked as the first string. @code{argc} is an integer that says how
  8622. many strings @code{argv} contains. Here is an example of accessing
  8623. the command-line parameters, retrieving the program's name and
  8624. checking for the standard @option{--version} and @option{--help} options:
  8625. @example
  8626. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8627. int
  8628. main (int argc, char *argv[])
  8629. @{
  8630. char *program_name = argv[0];
  8631. for (int i = 1; i < argc; i++)
  8632. @{
  8633. if (!strcmp (argv[i], "--version"))
  8634. @{
  8635. /* @r{Print version information and exit.} */
  8636. @r{@dots{}}
  8637. @}
  8638. else if (!strcmp (argv[i], "--help"))
  8639. @{
  8640. /* @r{Print help information and exit.} */
  8641. @r{@dots{}}
  8642. @}
  8643. @}
  8644. @r{@dots{}}
  8645. @}
  8646. @end example
  8647. @node Environment Variables
  8648. @subsection Accessing Environment Variables
  8649. @cindex environment variables
  8650. You can optionally include a third parameter to @code{main}, another
  8651. array of strings, to capture the environment variables available to
  8652. the program. Unlike what happens with @code{argv}, there is no
  8653. additional parameter for the count of environment variables; rather,
  8654. the array of environment variables concludes with a null pointer.
  8655. @example
  8656. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8657. int
  8658. main (int argc, char *argv[], char *envp[])
  8659. @{
  8660. /* @r{Print out all environment variables.} */
  8661. int i = 0;
  8662. while (envp[i])
  8663. @{
  8664. printf ("%s\n", envp[i]);
  8665. i++;
  8666. @}
  8667. @}
  8668. @end example
  8669. Another method of retrieving environment variables is to use the
  8670. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8671. Using @code{getenv} does not require defining @code{main} to accept the
  8672. @code{envp} pointer. For example, here is a program that fetches and prints
  8673. the user's home directory (if defined):
  8674. @example
  8675. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8676. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8677. int
  8678. main (void)
  8679. @{
  8680. char *home_directory = getenv ("HOME");
  8681. if (home_directory)
  8682. printf ("My home directory is: %s\n", home_directory);
  8683. else
  8684. printf ("My home directory is not defined!\n");
  8685. @}
  8686. @end example
  8687. @node Advanced Definitions
  8688. @section Advanced Function Features
  8689. This section describes some advanced or obscure features for GNU C
  8690. function definitions. If you are just learning C, you can skip the
  8691. rest of this chapter.
  8692. @menu
  8693. * Variable-Length Array Parameters:: Functions that accept arrays
  8694. of variable length.
  8695. * Variable Number of Arguments:: Variadic functions.
  8696. * Nested Functions:: Defining functions within functions.
  8697. * Inline Function Definitions:: A function call optimization technique.
  8698. @end menu
  8699. @node Variable-Length Array Parameters
  8700. @subsection Variable-Length Array Parameters
  8701. @cindex variable-length array parameters
  8702. @cindex array parameters, variable-length
  8703. @cindex functions that accept variable-length arrays
  8704. An array parameter can have variable length: simply declare the array
  8705. type with a size that isn't constant. In a nested function, the
  8706. length can refer to a variable defined in a containing scope. In any
  8707. function, it can refer to a previous parameter, like this:
  8708. @example
  8709. struct entry
  8710. tester (int len, char data[len][len])
  8711. @{
  8712. @r{@dots{}}
  8713. @}
  8714. @end example
  8715. Alternatively, in function declarations (but not in function
  8716. definitions), you can use @code{[*]} to denote that the array
  8717. parameter is of a variable length, such that these two declarations
  8718. mean the same thing:
  8719. @example
  8720. struct entry
  8721. tester (int len, char data[len][len]);
  8722. @end example
  8723. @example
  8724. struct entry
  8725. tester (int len, char data[*][*]);
  8726. @end example
  8727. @noindent
  8728. The two forms of input are equivalent in GNU C, but emphasizing that
  8729. the array parameter is variable-length may be helpful to those
  8730. studying the code.
  8731. You can also omit the length parameter, and instead use some other
  8732. in-scope variable for the length in the function definition:
  8733. @example
  8734. struct entry
  8735. tester (char data[*][*]);
  8736. @r{@dots{}}
  8737. int dataLength = 20;
  8738. @r{@dots{}}
  8739. struct entry
  8740. tester (char data[dataLength][dataLength])
  8741. @{
  8742. @r{@dots{}}
  8743. @}
  8744. @end example
  8745. @c ??? check text above
  8746. @cindex parameter forward declaration
  8747. In GNU C, to pass the array first and the length afterward, you can
  8748. use a @dfn{parameter forward declaration}, like this:
  8749. @example
  8750. struct entry
  8751. tester (int len; char data[len][len], int len)
  8752. @{
  8753. @r{@dots{}}
  8754. @}
  8755. @end example
  8756. The @samp{int len} before the semicolon is the parameter forward
  8757. declaration; it serves the purpose of making the name @code{len} known
  8758. when the declaration of @code{data} is parsed.
  8759. You can write any number of such parameter forward declarations in the
  8760. parameter list. They can be separated by commas or semicolons, but
  8761. the last one must end with a semicolon, which is followed by the
  8762. ``real'' parameter declarations. Each forward declaration must match
  8763. a subsequent ``real'' declaration in parameter name and data type.
  8764. Standard C does not support parameter forward declarations.
  8765. @node Variable Number of Arguments
  8766. @subsection Variable-Length Parameter Lists
  8767. @cindex variable-length parameter lists
  8768. @cindex parameters lists, variable length
  8769. @cindex function parameter lists, variable length
  8770. @cindex variadic function
  8771. A function that takes a variable number of arguments is called a
  8772. @dfn{variadic function}. In C, a variadic function must specify at
  8773. least one fixed argument with an explicitly declared data type.
  8774. Additional arguments can follow, and can vary in both quantity and
  8775. data type.
  8776. In the function header, declare the fixed parameters in the normal
  8777. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8778. example of a variadic function header:
  8779. @example
  8780. int add_multiple_values (int number, ...)
  8781. @end example
  8782. @cindex @code{va_list}
  8783. @cindex @code{va_start}
  8784. @cindex @code{va_end}
  8785. The function body can refer to fixed arguments by their parameter
  8786. names, but the additional arguments have no names. Accessing them in
  8787. the function body uses certain standard macros. They are defined in
  8788. the library header file @file{stdarg.h}, so the code must
  8789. @code{#include} that file.
  8790. In the body, write
  8791. @example
  8792. va_list ap;
  8793. va_start (ap, @var{last_fixed_parameter});
  8794. @end example
  8795. @noindent
  8796. This declares the variable @code{ap} (you can use any name for it)
  8797. and then sets it up to point before the first additional argument.
  8798. Then, to fetch the next consecutive additional argument, write this:
  8799. @example
  8800. va_arg (ap, @var{type})
  8801. @end example
  8802. After fetching all the additional arguments (or as many as need to be
  8803. used), write this:
  8804. @example
  8805. va_end (ap);
  8806. @end example
  8807. Here's an example of a variadic function definition that adds any
  8808. number of @code{int} arguments. The first (fixed) argument says how
  8809. many more arguments follow.
  8810. @example
  8811. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8812. @r{@dots{}}
  8813. int
  8814. add_multiple_values (int argcount, ...)
  8815. @{
  8816. int counter, total = 0;
  8817. /* @r{Declare a variable of type @code{va_list}.} */
  8818. va_list argptr;
  8819. /* @r{Initialize that variable..} */
  8820. va_start (argptr, argcount);
  8821. for (counter = 0; counter < argcount; counter++)
  8822. @{
  8823. /* @r{Get the next additional argument.} */
  8824. total += va_arg (argptr, int);
  8825. @}
  8826. /* @r{End use of the @code{argptr} variable.} */
  8827. va_end (argptr);
  8828. return total;
  8829. @}
  8830. @end example
  8831. With GNU C, @code{va_end} is superfluous, but some other compilers
  8832. might make @code{va_start} allocate memory so that calling
  8833. @code{va_end} is necessary to avoid a memory leak. Before doing
  8834. @code{va_start} again with the same variable, do @code{va_end}
  8835. first.
  8836. @cindex @code{va_copy}
  8837. Because of this possible memory allocation, it is risky (in principle)
  8838. to copy one @code{va_list} variable to another with assignment.
  8839. Instead, use @code{va_copy}, which copies the substance but allocates
  8840. separate memory in the variable you copy to. The call looks like
  8841. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8842. @var{from} should be variables of type @code{va_list}. In principle,
  8843. do @code{va_end} on each of these variables before its scope ends.
  8844. Since the additional arguments' types are not specified in the
  8845. function's definition, the default argument promotions
  8846. (@pxref{Argument Promotions}) apply to them in function calls. The
  8847. function definition must take account of this; thus, if an argument
  8848. was passed as @code{short}, the function should get it as @code{int}.
  8849. If an argument was passed as @code{float}, the function should get it
  8850. as @code{double}.
  8851. C has no mechanism to tell the variadic function how many arguments
  8852. were passed to it, so its calling convention must give it a way to
  8853. determine this. That's why @code{add_multiple_values} takes a fixed
  8854. argument that says how many more arguments follow. Thus, you can
  8855. call the function like this:
  8856. @example
  8857. sum = add_multiple_values (3, 12, 34, 190);
  8858. /* @r{Value is 12+34+190.} */
  8859. @end example
  8860. In GNU C, there is no actual need to use the @code{va_end} function.
  8861. In fact, it does nothing. It's used for compatibility with other
  8862. compilers, when that matters.
  8863. It is a mistake to access variables declared as @code{va_list} except
  8864. in the specific ways described here. Just what that type consists of
  8865. is an implementation detail, which could vary from one platform to
  8866. another.
  8867. @node Nested Functions
  8868. @subsection Nested Functions
  8869. @cindex nested functions
  8870. @cindex functions, nested
  8871. @cindex downward funargs
  8872. @cindex thunks
  8873. A @dfn{nested function} is a function defined inside another function.
  8874. The nested function's name is local to the block where it is defined.
  8875. For example, here we define a nested function named @code{square}, and
  8876. call it twice:
  8877. @example
  8878. @group
  8879. foo (double a, double b)
  8880. @{
  8881. double square (double z) @{ return z * z; @}
  8882. return square (a) + square (b);
  8883. @}
  8884. @end group
  8885. @end example
  8886. The nested function can access all the variables of the containing
  8887. function that are visible at the point of its definition. This is
  8888. called @dfn{lexical scoping}. For example, here we show a nested
  8889. function that uses an inherited variable named @code{offset}:
  8890. @example
  8891. @group
  8892. bar (int *array, int offset, int size)
  8893. @{
  8894. int access (int *array, int index)
  8895. @{ return array[index + offset]; @}
  8896. int i;
  8897. @r{@dots{}}
  8898. for (i = 0; i < size; i++)
  8899. @r{@dots{}} access (array, i) @r{@dots{}}
  8900. @}
  8901. @end group
  8902. @end example
  8903. Nested function definitions can appear wherever automatic variable
  8904. declarations are allowed; that is, in any block, interspersed with the
  8905. other declarations and statements in the block.
  8906. The nested function's name is visible only within the parent block;
  8907. the name's scope starts from its definition and continues to the end
  8908. of the containing block. If the nested function's name
  8909. is the same as the parent function's name, there wil be
  8910. no way to refer to the parent function inside the scope of the
  8911. name of the nested function.
  8912. Using @code{extern} or @code{static} on a nested function definition
  8913. is an error.
  8914. It is possible to call the nested function from outside the scope of its
  8915. name by storing its address or passing the address to another function.
  8916. You can do this safely, but you must be careful:
  8917. @example
  8918. @group
  8919. hack (int *array, int size, int addition)
  8920. @{
  8921. void store (int index, int value)
  8922. @{ array[index] = value + addition; @}
  8923. intermediate (store, size);
  8924. @}
  8925. @end group
  8926. @end example
  8927. Here, the function @code{intermediate} receives the address of
  8928. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8929. the arguments given to @code{store} are used to store into @code{array}.
  8930. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8931. It is safe for @code{intermediate} to call @code{store} because
  8932. @code{hack}'s stack frame, with its arguments and local variables,
  8933. continues to exist during the call to @code{intermediate}.
  8934. Calling the nested function through its address after the containing
  8935. function has exited is asking for trouble. If it is called after a
  8936. containing scope level has exited, and if it refers to some of the
  8937. variables that are no longer in scope, it will refer to memory
  8938. containing junk or other data. It's not wise to take the risk.
  8939. The GNU C Compiler implements taking the address of a nested function
  8940. using a technique called @dfn{trampolines}. This technique was
  8941. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8942. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8943. A nested function can jump to a label inherited from a containing
  8944. function, provided the label was explicitly declared in the containing
  8945. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8946. containing function, exiting the nested function that did the
  8947. @code{goto} and any intermediate function invocations as well. Here
  8948. is an example:
  8949. @example
  8950. @group
  8951. bar (int *array, int offset, int size)
  8952. @{
  8953. /* @r{Explicitly declare the label @code{failure}.} */
  8954. __label__ failure;
  8955. int access (int *array, int index)
  8956. @{
  8957. if (index > size)
  8958. /* @r{Exit this function,}
  8959. @r{and return to @code{bar}.} */
  8960. goto failure;
  8961. return array[index + offset];
  8962. @}
  8963. @end group
  8964. @group
  8965. int i;
  8966. @r{@dots{}}
  8967. for (i = 0; i < size; i++)
  8968. @r{@dots{}} access (array, i) @r{@dots{}}
  8969. @r{@dots{}}
  8970. return 0;
  8971. /* @r{Control comes here from @code{access}
  8972. if it does the @code{goto}.} */
  8973. failure:
  8974. return -1;
  8975. @}
  8976. @end group
  8977. @end example
  8978. To declare the nested function before its definition, use
  8979. @code{auto} (which is otherwise meaningless for function declarations;
  8980. @pxref{auto and register}). For example,
  8981. @example
  8982. bar (int *array, int offset, int size)
  8983. @{
  8984. auto int access (int *, int);
  8985. @r{@dots{}}
  8986. @r{@dots{}} access (array, i) @r{@dots{}}
  8987. @r{@dots{}}
  8988. int access (int *array, int index)
  8989. @{
  8990. @r{@dots{}}
  8991. @}
  8992. @r{@dots{}}
  8993. @}
  8994. @end example
  8995. @node Inline Function Definitions
  8996. @subsection Inline Function Definitions
  8997. @cindex inline function definitions
  8998. @cindex function definitions, inline
  8999. @findex inline
  9000. To declare a function inline, use the @code{inline} keyword in its
  9001. definition. Here's a simple function that takes a pointer-to-@code{int}
  9002. and increments the integer stored there---declared inline.
  9003. @example
  9004. struct list
  9005. @{
  9006. struct list *first, *second;
  9007. @};
  9008. inline struct list *
  9009. list_first (struct list *p)
  9010. @{
  9011. return p->first;
  9012. @}
  9013. inline struct list *
  9014. list_second (struct list *p)
  9015. @{
  9016. return p->second;
  9017. @}
  9018. @end example
  9019. optimized compilation can substitute the inline function's body for
  9020. any call to it. This is called @emph{inlining} the function. It
  9021. makes the code that contains the call run faster, significantly so if
  9022. the inline function is small.
  9023. Here's a function that uses @code{pair_second}:
  9024. @example
  9025. int
  9026. pairlist_length (struct list *l)
  9027. @{
  9028. int length = 0;
  9029. while (l)
  9030. @{
  9031. length++;
  9032. l = pair_second (l);
  9033. @}
  9034. return length;
  9035. @}
  9036. @end example
  9037. Substituting the code of @code{pair_second} into the definition of
  9038. @code{pairlist_length} results in this code, in effect:
  9039. @example
  9040. int
  9041. pairlist_length (struct list *l)
  9042. @{
  9043. int length = 0;
  9044. while (l)
  9045. @{
  9046. length++;
  9047. l = l->second;
  9048. @}
  9049. return length;
  9050. @}
  9051. @end example
  9052. Since the definition of @code{pair_second} does not say @code{extern}
  9053. or @code{static}, that definition is used only for inlining. It
  9054. doesn't generate code that can be called at run time. If not all the
  9055. calls to the function are inlined, there must be a definition of the
  9056. same function name in another module for them to call.
  9057. @cindex inline functions, omission of
  9058. @c @opindex fkeep-inline-functions
  9059. Adding @code{static} to an inline function definition means the
  9060. function definition is limited to this compilation module. Also, it
  9061. generates run-time code if necessary for the sake of any calls that
  9062. were not inlined. If all calls are inlined then the function
  9063. definition does not generate run-time code, but you can force
  9064. generation of run-time code with the option
  9065. @option{-fkeep-inline-functions}.
  9066. @cindex extern inline function
  9067. Specifying @code{extern} along with @code{inline} means the function is
  9068. external and generates run-time code to be called from other
  9069. separately compiled modules, as well as inlined. You can define the
  9070. function as @code{inline} without @code{extern} in other modules so as
  9071. to inline calls to the same function in those modules.
  9072. Why are some calls not inlined? First of all, inlining is an
  9073. optimization, so non-optimized compilation does not inline.
  9074. Some calls cannot be inlined for technical reasons. Also, certain
  9075. usages in a function definition can make it unsuitable for inline
  9076. substitution. Among these usages are: variadic functions, use of
  9077. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9078. use of nonlocal goto. The option @option{-Winline} requests a warning
  9079. when a function marked @code{inline} is unsuitable to be inlined. The
  9080. warning explains what obstacle makes it unsuitable.
  9081. Just because a call @emph{can} be inlined does not mean it
  9082. @emph{should} be inlined. The GNU C compiler weighs costs and
  9083. benefits to decide whether inlining a particular call is advantageous.
  9084. You can force inlining of all calls to a given function that can be
  9085. inlined, even in a non-optimized compilation. by specifying the
  9086. @samp{always_inline} attribute for the function, like this:
  9087. @example
  9088. /* @r{Prototype.} */
  9089. inline void foo (const char) __attribute__((always_inline));
  9090. @end example
  9091. @noindent
  9092. This is a GNU C extension. @xref{Attributes}.
  9093. A function call may be inlined even if not declared @code{inline} in
  9094. special cases where the compiler can determine this is correct and
  9095. desirable. For instance, when a static function is called only once,
  9096. it will very likely be inlined. With @option{-flto}, link-time
  9097. optimization, any function might be inlined. To absolutely prevent
  9098. inlining of a specific function, specify
  9099. @code{__attribute__((__noinline__))} in the function's definition.
  9100. @node Obsolete Definitions
  9101. @section Obsolete Function Features
  9102. These features of function definitions are still used in old
  9103. programs, but you shouldn't write code this way today.
  9104. If you are just learning C, you can skip this section.
  9105. @menu
  9106. * Old GNU Inlining:: An older inlining technique.
  9107. * Old-Style Function Definitions:: Original K&R style functions.
  9108. @end menu
  9109. @node Old GNU Inlining
  9110. @subsection Older GNU C Inlining
  9111. The GNU C spec for inline functions, before GCC version 5, defined
  9112. @code{extern inline} on a function definition to mean to inline calls
  9113. to it but @emph{not} generate code for the function that could be
  9114. called at run time. By contrast, @code{inline} without @code{extern}
  9115. specified to generate run-time code for the function. In effect, ISO
  9116. incompatibly flipped the meanings of these two cases. We changed GCC
  9117. in version 5 to adopt the ISO specification.
  9118. Many programs still use these cases with the previous GNU C meanings.
  9119. You can specify use of those meanings with the option
  9120. @option{-fgnu89-inline}. You can also specify this for a single
  9121. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9122. @example
  9123. inline __attribute__ ((gnu_inline))
  9124. int
  9125. inc (int *a)
  9126. @{
  9127. (*a)++;
  9128. @}
  9129. @end example
  9130. @node Old-Style Function Definitions
  9131. @subsection Old-Style Function Definitions
  9132. @cindex old-style function definitions
  9133. @cindex function definitions, old-style
  9134. @cindex K&R-style function definitions
  9135. The syntax of C traditionally allows omitting the data type in a
  9136. function declaration if it specifies a storage class or a qualifier.
  9137. Then the type defaults to @code{int}. For example:
  9138. @example
  9139. static foo (double x);
  9140. @end example
  9141. @noindent
  9142. defaults the return type to @code{int}. This is bad practice; if you
  9143. see it, fix it.
  9144. An @dfn{old-style} (or ``K&R'') function definition is the way
  9145. function definitions were written in the 1980s. It looks like this:
  9146. @example
  9147. @var{rettype}
  9148. @var{function} (@var{parmnames})
  9149. @var{parm_declarations}
  9150. @{
  9151. @var{body}
  9152. @}
  9153. @end example
  9154. In @var{parmnames}, only the parameter names are listed, separated by
  9155. commas. Then @var{parm_declarations} declares their data types; these
  9156. declarations look just like variable declarations. If a parameter is
  9157. listed in @var{parmnames} but has no declaration, it is implicitly
  9158. declared @code{int}.
  9159. There is no reason to write a definition this way nowadays, but they
  9160. can still be seen in older GNU programs.
  9161. An old-style variadic function definition looks like this:
  9162. @example
  9163. #include <varargs.h>
  9164. int
  9165. add_multiple_values (va_alist)
  9166. va_dcl
  9167. @{
  9168. int argcount;
  9169. int counter, total = 0;
  9170. /* @r{Declare a variable of type @code{va_list}.} */
  9171. va_list argptr;
  9172. /* @r{Initialize that variable.} */
  9173. va_start (argptr);
  9174. /* @r{Get the first argument (fixed).} */
  9175. argcount = va_arg (int);
  9176. for (counter = 0; counter < argcount; counter++)
  9177. @{
  9178. /* @r{Get the next additional argument.} */
  9179. total += va_arg (argptr, int);
  9180. @}
  9181. /* @r{End use of the @code{argptr} variable.} */
  9182. va_end (argptr);
  9183. return total;
  9184. @}
  9185. @end example
  9186. Note that the old-style variadic function definition has no fixed
  9187. parameter variables; all arguments must be obtained with
  9188. @code{va_arg}.
  9189. @node Compatible Types
  9190. @chapter Compatible Types
  9191. @cindex compatible types
  9192. @cindex types, compatible
  9193. Declaring a function or variable twice is valid in C only if the two
  9194. declarations specify @dfn{compatible} types. In addition, some
  9195. operations on pointers require operands to have compatible target
  9196. types.
  9197. In C, two different primitive types are never compatible. Likewise for
  9198. the defined types @code{struct}, @code{union} and @code{enum}: two
  9199. separately defined types are incompatible unless they are defined
  9200. exactly the same way.
  9201. However, there are a few cases where different types can be
  9202. compatible:
  9203. @itemize @bullet
  9204. @item
  9205. Every enumeration type is compatible with some integer type. In GNU
  9206. C, the choice of integer type depends on the largest enumeration
  9207. value.
  9208. @c ??? Which one, in GCC?
  9209. @c ??? ... it varies, depending on the enum values. Testing on
  9210. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9211. @c ??? then moves on to an 8-byte signed integer. These details
  9212. @c ??? might be platform-dependent, as the C standard says that even
  9213. @c ??? char could be used as an enum type, but it's at least true
  9214. @c ??? that GCC chooses a type that is at least large enough to
  9215. @c ??? hold the largest enum value.
  9216. @item
  9217. Array types are compatible if the element types are compatible
  9218. and the sizes (when specified) match.
  9219. @item
  9220. Pointer types are compatible if the pointer target types are
  9221. compatible.
  9222. @item
  9223. Function types that specify argument types are compatible if the
  9224. return types are compatible and the argument types are compatible,
  9225. argument by argument. In addition, they must all agree in whether
  9226. they use @code{...} to allow additional arguments.
  9227. @item
  9228. Function types that don't specify argument types are compatible if the
  9229. return types are.
  9230. @item
  9231. Function types that specify the argument types are compatible with
  9232. function types that omit them, if the return types are compatible and
  9233. the specified argument types are unaltered by the argument promotions
  9234. (@pxref{Argument Promotions}).
  9235. @end itemize
  9236. In order for types to be compatible, they must agree in their type
  9237. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9238. It follows that @code{const int *} and @code{int *} are incompatible
  9239. too (they are pointers to types that are not compatible).
  9240. If two types are compatible ignoring the qualifiers, we call them
  9241. @dfn{nearly compatible}. (If they are array types, we ignore
  9242. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9243. Comparison of pointers is valid if the pointers' target types are
  9244. nearly compatible. Likewise, the two branches of a conditional
  9245. expression may be pointers to nearly compatible target types.
  9246. If two types are compatible ignoring the qualifiers, and the first
  9247. type has all the qualifiers of the second type, we say the first is
  9248. @dfn{upward compatible} with the second. Assignment of pointers
  9249. requires the assigned pointer's target type to be upward compatible
  9250. with the right operand (the new value)'s target type.
  9251. @node Type Conversions
  9252. @chapter Type Conversions
  9253. @cindex type conversions
  9254. @cindex conversions, type
  9255. C converts between data types automatically when that seems clearly
  9256. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9257. @menu
  9258. * Explicit Type Conversion:: Casting a value from one type to another.
  9259. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9260. * Argument Promotions:: Automatic conversion of function parameters.
  9261. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9262. * Common Type:: When operand types differ, which one is used?
  9263. @end menu
  9264. @node Explicit Type Conversion
  9265. @section Explicit Type Conversion
  9266. @cindex cast
  9267. @cindex explicit type conversion
  9268. You can do explicit conversions using the unary @dfn{cast} operator,
  9269. which is written as a type designator (@pxref{Type Designators}) in
  9270. parentheses. For example, @code{(int)} is the operator to cast to
  9271. type @code{int}. Here's an example of using it:
  9272. @example
  9273. @{
  9274. double d = 5.5;
  9275. printf ("Floating point value: %f\n", d);
  9276. printf ("Rounded to integer: %d\n", (int) d);
  9277. @}
  9278. @end example
  9279. Using @code{(int) d} passes an @code{int} value as argument to
  9280. @code{printf}, so you can print it with @samp{%d}. Using just
  9281. @code{d} without the cast would pass the value as @code{double}.
  9282. That won't work at all with @samp{%d}; the results would be gibberish.
  9283. To divide one integer by another without rounding,
  9284. cast either of the integers to @code{double} first:
  9285. @example
  9286. (double) @var{dividend} / @var{divisor}
  9287. @var{dividend} / (double) @var{divisor}
  9288. @end example
  9289. It is enough to cast one of them, because that forces the common type
  9290. to @code{double} so the other will be converted automatically.
  9291. The valid cast conversions are:
  9292. @itemize @bullet
  9293. @item
  9294. One numerical type to another.
  9295. @item
  9296. One pointer type to another.
  9297. (Converting between pointers that point to functions
  9298. and pointers that point to data is not standard C.)
  9299. @item
  9300. A pointer type to an integer type.
  9301. @item
  9302. An integer type to a pointer type.
  9303. @item
  9304. To a union type, from the type of any alternative in the union
  9305. (@pxref{Unions}). (This is a GNU extension.)
  9306. @item
  9307. Anything, to @code{void}.
  9308. @end itemize
  9309. @node Assignment Type Conversions
  9310. @section Assignment Type Conversions
  9311. @cindex assignment type conversions
  9312. Certain type conversions occur automatically in assignments
  9313. and certain other contexts. These are the conversions
  9314. assignments can do:
  9315. @itemize @bullet
  9316. @item
  9317. Converting any numeric type to any other numeric type.
  9318. @item
  9319. Converting @code{void *} to any other pointer type
  9320. (except pointer-to-function types).
  9321. @item
  9322. Converting any other pointer type to @code{void *}.
  9323. (except pointer-to-function types).
  9324. @item
  9325. Converting 0 (a null pointer constant) to any pointer type.
  9326. @item
  9327. Converting any pointer type to @code{bool}. (The result is
  9328. 1 if the pointer is not null.)
  9329. @item
  9330. Converting between pointer types when the left-hand target type is
  9331. upward compatible with the right-hand target type. @xref{Compatible
  9332. Types}.
  9333. @end itemize
  9334. These type conversions occur automatically in certain contexts,
  9335. which are:
  9336. @itemize @bullet
  9337. @item
  9338. An assignment converts the type of the right-hand expression
  9339. to the type wanted by the left-hand expression. For example,
  9340. @example
  9341. double i;
  9342. i = 5;
  9343. @end example
  9344. @noindent
  9345. converts 5 to @code{double}.
  9346. @item
  9347. A function call, when the function specifies the type for that
  9348. argument, converts the argument value to that type. For example,
  9349. @example
  9350. void foo (double);
  9351. foo (5);
  9352. @end example
  9353. @noindent
  9354. converts 5 to @code{double}.
  9355. @item
  9356. A @code{return} statement converts the specified value to the type
  9357. that the function is declared to return. For example,
  9358. @example
  9359. double
  9360. foo ()
  9361. @{
  9362. return 5;
  9363. @}
  9364. @end example
  9365. @noindent
  9366. also converts 5 to @code{double}.
  9367. @end itemize
  9368. In all three contexts, if the conversion is impossible, that
  9369. constitutes an error.
  9370. @node Argument Promotions
  9371. @section Argument Promotions
  9372. @cindex argument promotions
  9373. @cindex promotion of arguments
  9374. When a function's definition or declaration does not specify the type
  9375. of an argument, that argument is passed without conversion in whatever
  9376. type it has, with these exceptions:
  9377. @itemize @bullet
  9378. @item
  9379. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9380. expression is a narrow integer, such as @code{char} or @code{short},
  9381. the call converts it automatically to @code{int} (@pxref{Integer
  9382. Types}).@footnote{On an embedded controller where @code{char}
  9383. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9384. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9385. never occurs in GNU C on real computers.}
  9386. In this example, the expression @code{c} is passed as an @code{int}:
  9387. @example
  9388. char c = '$';
  9389. printf ("Character c is '%c'\n", c);
  9390. @end example
  9391. @item
  9392. If the expression
  9393. has type @code{float}, the call converts it automatically to
  9394. @code{double}.
  9395. @item
  9396. An array as argument is converted to a pointer to its zeroth element.
  9397. @item
  9398. A function name as argument is converted to a pointer to that function.
  9399. @end itemize
  9400. @node Operand Promotions
  9401. @section Operand Promotions
  9402. @cindex operand promotions
  9403. The operands in arithmetic operations undergo type conversion automatically.
  9404. These @dfn{operand promotions} are the same as the argument promotions
  9405. except without converting @code{float} to @code{double}. In other words,
  9406. the operand promotions convert
  9407. @itemize @bullet
  9408. @item
  9409. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9410. @item
  9411. an array to a pointer to its zeroth element, and
  9412. @item
  9413. a function name to a pointer to that function.
  9414. @end itemize
  9415. @node Common Type
  9416. @section Common Type
  9417. @cindex common type
  9418. Arithmetic binary operators (except the shift operators) convert their
  9419. operands to the @dfn{common type} before operating on them.
  9420. Conditional expressions also convert the two possible results to their
  9421. common type. Here are the rules for determining the common type.
  9422. If one of the numbers has a floating-point type and the other is an
  9423. integer, the common type is that floating-point type. For instance,
  9424. @example
  9425. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9426. @end example
  9427. If both are floating point, the type with the larger range is the
  9428. common type.
  9429. If both are integers but of different widths, the common type
  9430. is the wider of the two.
  9431. If they are integer types of the same width, the common type is
  9432. unsigned if either operand is unsigned, and it's @code{long} if either
  9433. operand is @code{long}. It's @code{long long} if either operand is
  9434. @code{long long}.
  9435. These rules apply to addition, subtraction, multiplication, division,
  9436. remainder, comparisons, and bitwise operations. They also apply to
  9437. the two branches of a conditional expression, and to the arithmetic
  9438. done in a modifying assignment operation.
  9439. @node Scope
  9440. @chapter Scope
  9441. @cindex scope
  9442. @cindex block scope
  9443. @cindex function scope
  9444. @cindex function prototype scope
  9445. Each definition or declaration of an identifier is visible
  9446. in certain parts of the program, which is typically less than the whole
  9447. of the program. The parts where it is visible are called its @dfn{scope}.
  9448. Normally, declarations made at the top-level in the source -- that is,
  9449. not within any blocks and function definitions -- are visible for the
  9450. entire contents of the source file after that point. This is called
  9451. @dfn{file scope} (@pxref{File-Scope Variables}).
  9452. Declarations made within blocks of code, including within function
  9453. definitions, are visible only within those blocks. This is called
  9454. @dfn{block scope}. Here is an example:
  9455. @example
  9456. @group
  9457. void
  9458. foo (void)
  9459. @{
  9460. int x = 42;
  9461. @}
  9462. @end group
  9463. @end example
  9464. @noindent
  9465. In this example, the variable @code{x} has block scope; it is visible
  9466. only within the @code{foo} function definition block. Thus, other
  9467. blocks could have their own variables, also named @code{x}, without
  9468. any conflict between those variables.
  9469. A variable declared inside a subblock has a scope limited to
  9470. that subblock,
  9471. @example
  9472. @group
  9473. void
  9474. foo (void)
  9475. @{
  9476. @{
  9477. int x = 42;
  9478. @}
  9479. // @r{@code{x} is out of scope here.}
  9480. @}
  9481. @end group
  9482. @end example
  9483. If a variable declared within a block has the same name as a variable
  9484. declared outside of that block, the definition within the block
  9485. takes precedence during its scope:
  9486. @example
  9487. @group
  9488. int x = 42;
  9489. void
  9490. foo (void)
  9491. @{
  9492. int x = 17;
  9493. printf ("%d\n", x);
  9494. @}
  9495. @end group
  9496. @end example
  9497. @noindent
  9498. This prints 17, the value of the variable @code{x} declared in the
  9499. function body block, rather than the value of the variable @code{x} at
  9500. file scope. We say that the inner declaration of @code{x}
  9501. @dfn{shadows} the outer declaration, for the extent of the inner
  9502. declaration's scope.
  9503. A declaration with block scope can be shadowed by another declaration
  9504. with the same name in a subblock.
  9505. @example
  9506. @group
  9507. void
  9508. foo (void)
  9509. @{
  9510. char *x = "foo";
  9511. @{
  9512. int x = 42;
  9513. @r{@dots{}}
  9514. exit (x / 6);
  9515. @}
  9516. @}
  9517. @end group
  9518. @end example
  9519. A function parameter's scope is the entire function body, but it can
  9520. be shadowed. For example:
  9521. @example
  9522. @group
  9523. int x = 42;
  9524. void
  9525. foo (int x)
  9526. @{
  9527. printf ("%d\n", x);
  9528. @}
  9529. @end group
  9530. @end example
  9531. @noindent
  9532. This prints the value of @code{x} the function parameter, rather than
  9533. the value of the file-scope variable @code{x}. However,
  9534. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9535. is visible for the whole of the containing function body, both before
  9536. and after the label declaration:
  9537. @example
  9538. @group
  9539. void
  9540. foo (void)
  9541. @{
  9542. @r{@dots{}}
  9543. goto bar;
  9544. @r{@dots{}}
  9545. @{ // @r{Subblock does not affect labels.}
  9546. bar:
  9547. @r{@dots{}}
  9548. @}
  9549. goto bar;
  9550. @}
  9551. @end group
  9552. @end example
  9553. Except for labels, a declared identifier is not
  9554. visible to code before its declaration. For example:
  9555. @example
  9556. @group
  9557. int x = 5;
  9558. int y = x + 10;
  9559. @end group
  9560. @end example
  9561. @noindent
  9562. will work, but:
  9563. @example
  9564. @group
  9565. int x = y + 10;
  9566. int y = 5;
  9567. @end group
  9568. @end example
  9569. @noindent
  9570. cannot refer to the variable @code{y} before its declaration.
  9571. @include cpp.texi
  9572. @node Integers in Depth
  9573. @chapter Integers in Depth
  9574. This chapter explains the machine-level details of integer types: how
  9575. they are represented as bits in memory, and the range of possible
  9576. values for each integer type.
  9577. @menu
  9578. * Integer Representations:: How integer values appear in memory.
  9579. * Maximum and Minimum Values:: Value ranges of integer types.
  9580. @end menu
  9581. @node Integer Representations
  9582. @section Integer Representations
  9583. @cindex integer representations
  9584. @cindex representation of integers
  9585. Modern computers store integer values as binary (base-2) numbers that
  9586. occupy a single unit of storage, typically either as an 8-bit
  9587. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9588. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9589. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9590. any of these types could have some other size, bit it's not worth even
  9591. a minute to cater to that possibility. It never happens on
  9592. GNU/Linux.}
  9593. @cindex @code{CHAR_BIT}
  9594. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9595. of bits in type @code{char}. On any real operating system, the value
  9596. is 8.
  9597. The fixed sizes of numeric types necessarily limits their @dfn{range
  9598. of values}, and the particular encoding of integers decides what that
  9599. range is.
  9600. @cindex two's-complement representation
  9601. For unsigned integers, the entire space is used to represent a
  9602. nonnegative value. Signed integers are stored using
  9603. @dfn{two's-complement representation}: a signed integer with @var{n}
  9604. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9605. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9606. high-order, bit is called the @dfn{sign bit}.
  9607. @c ??? Needs correcting
  9608. There is only one value that means zero, and the most negative number
  9609. lacks a positive counterpart. As a result, negating that number
  9610. causes overflow; in practice, its result is that number back again.
  9611. For example, a two's-complement signed 8-bit integer can represent all
  9612. decimal numbers from @minus{}128 to +127. We will revisit that
  9613. peculiarity shortly.
  9614. Decades ago, there were computers that didn't use two's-complement
  9615. representation for integers (@pxref{Integers in Depth}), but they are
  9616. long gone and not worth any effort to support.
  9617. @c ??? Is this duplicate?
  9618. When an arithmetic operation produces a value that is too big to
  9619. represent, the operation is said to @dfn{overflow}. In C, integer
  9620. overflow does not interrupt the control flow or signal an error.
  9621. What it does depends on signedness.
  9622. For unsigned arithmetic, the result of an operation that overflows is
  9623. the @var{n} low-order bits of the correct value. If the correct value
  9624. is representable in @var{n} bits, that is always the result;
  9625. thus we often say that ``integer arithmetic is exact,'' omitting the
  9626. crucial qualifying phrase ``as long as the exact result is
  9627. representable.''
  9628. In principle, a C program should be written so that overflow never
  9629. occurs for signed integers, but in GNU C you can specify various ways
  9630. of handling such overflow (@pxref{Integer Overflow}).
  9631. Integer representations are best understood by looking at a table for
  9632. a tiny integer size; here are the possible values for an integer with
  9633. three bits:
  9634. @multitable @columnfractions .25 .25 .25 .25
  9635. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9636. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9637. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9638. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9639. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9640. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9641. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9642. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9643. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9644. @end multitable
  9645. The parenthesized decimal numbers in the last column represent the
  9646. signed meanings of the two's-complement of the line's value. Recall
  9647. that, in two's-complement encoding, the high-order bit is 0 when
  9648. the number is nonnegative.
  9649. We can now understand the peculiar behavior of negation of the
  9650. most negative two's-complement integer: start with 0b100,
  9651. invert the bits to get 0b011, and add 1: we get
  9652. 0b100, the value we started with.
  9653. We can also see overflow behavior in two's-complement:
  9654. @example
  9655. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9656. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9657. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9658. @end example
  9659. @noindent
  9660. A sum of two nonnegative signed values that overflows has a 1 in the
  9661. sign bit, so the exact positive result is truncated to a negative
  9662. value.
  9663. @c =====================================================================
  9664. @node Maximum and Minimum Values
  9665. @section Maximum and Minimum Values
  9666. @cindex maximum integer values
  9667. @cindex minimum integer values
  9668. @cindex integer ranges
  9669. @cindex ranges of integer types
  9670. @findex INT_MAX
  9671. @findex UINT_MAX
  9672. @findex SHRT_MAX
  9673. @findex LONG_MAX
  9674. @findex LLONG_MAX
  9675. @findex USHRT_MAX
  9676. @findex ULONG_MAX
  9677. @findex ULLONG_MAX
  9678. @findex CHAR_MAX
  9679. @findex SCHAR_MAX
  9680. @findex UCHAR_MAX
  9681. For each primitive integer type, there is a standard macro defined in
  9682. @file{limits.h} that gives the largest value that type can hold. For
  9683. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9684. On a 32-bit computer, that is equal to 2,147,483,647. The
  9685. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9686. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9687. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9688. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9689. @code{ULLONG_MAX}.
  9690. Since there are three ways to specify a @code{char} type, there are
  9691. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9692. @code{UCHAR_MAX}.
  9693. For each type that is or might be signed, there is another symbol that
  9694. gives the minimum value it can hold. (Just replace @code{MAX} with
  9695. @code{MIN} in the names listed above.) There is no minimum limit
  9696. symbol for types specified with @code{unsigned} because the
  9697. minimum for them is universally zero.
  9698. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9699. two's-complement representation, the most negative number is 1 less
  9700. than the negative of the most positive number. Thus, @code{INT_MIN}
  9701. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9702. actually write the value that way in C, since it would overflow.
  9703. That's a good reason to use @code{INT_MIN} to specify
  9704. that value. Its definition is written to avoid overflow.
  9705. @include fp.texi
  9706. @node Compilation
  9707. @chapter Compilation
  9708. @cindex object file
  9709. @cindex compilation module
  9710. @cindex make rules
  9711. Early in the manual we explained how to compile a simple C program
  9712. that consists of a single source file (@pxref{Compile Example}).
  9713. However, we handle only short programs that way. A typical C program
  9714. consists of many source files, each of which is a separate
  9715. @dfn{compilation module}---meaning that it has to be compiled
  9716. separately.
  9717. The full details of how to compile with GCC are documented in xxxx.
  9718. @c ??? ref
  9719. Here we give only a simple introduction.
  9720. These are the commands to compile two compilation modules,
  9721. @file{foo.c} and @file{bar.c}, with a command for each module:
  9722. @example
  9723. gcc -c -O -g foo.c
  9724. gcc -c -O -g bar.c
  9725. @end example
  9726. @noindent
  9727. In these commands, @option{-g} says to generate debugging information,
  9728. @option{-O} says to do some optimization, and @option{-c} says to put
  9729. the compiled code for that module into a corresponding @dfn{object
  9730. file} and go no further. The object file for @file{foo.c} is called
  9731. @file{foo.o}, and so on.
  9732. If you wish, you can specify the additional options @option{-Wformat
  9733. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9734. One reason to divide a large program into multiple compilation modules
  9735. is to control how each module can access the internals of the others.
  9736. When a module declares a function or variable @code{extern}, other
  9737. modules can access it. The other functions and variables in
  9738. a module can't be accessed from outside that module.
  9739. The other reason for using multiple modules is so that changing
  9740. one source file does not require recompiling all of them in order
  9741. to try the modified program. Dividing a large program into many
  9742. substantial modules in this way typically makes recompilation much faster.
  9743. @cindex linking object files
  9744. After you compile all the program's modules, in order to run the
  9745. program you must @dfn{link} the object files into a combined
  9746. executable, like this:
  9747. @example
  9748. gcc -o foo foo.o bar.o
  9749. @end example
  9750. @noindent
  9751. In this command, @option{-o foo} species the file name for the
  9752. executable file, and the other arguments are the object files to link.
  9753. Always specify the executable file name in a command that generates
  9754. one.
  9755. Normally we don't run any of these commands directly. Instead we
  9756. write a set of @dfn{make rules} for the program, then use the
  9757. @command{make} program to recompile only the source files that need to
  9758. be recompiled.
  9759. @c ??? ref to make manual
  9760. @node Directing Compilation
  9761. @chapter Directing Compilation
  9762. This chapter describes C constructs that don't alter the program's
  9763. meaning @emph{as such}, but rather direct the compiler how to treat
  9764. some aspects of the program.
  9765. @menu
  9766. * Pragmas:: Controling compilation of some constructs.
  9767. * Static Assertions:: Compile-time tests for conditions.
  9768. @end menu
  9769. @node Pragmas
  9770. @section Pragmas
  9771. A @dfn{pragma} is an annotation in a program that gives direction to
  9772. the compiler.
  9773. @menu
  9774. * Pragma Basics:: Pragma syntax and usage.
  9775. * Severity Pragmas:: Settings for compile-time pragma output.
  9776. * Optimization Pragmas:: Controlling optimizations.
  9777. @end menu
  9778. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9779. @node Pragma Basics
  9780. @subsection Pragma Basics
  9781. C defines two syntactical forms for pragmas, the line form and the
  9782. token form. You can write any pragma in either form, with the same
  9783. meaning.
  9784. The line form is a line in the source code, like this:
  9785. @example
  9786. #pragma @var{line}
  9787. @end example
  9788. @noindent
  9789. The line pragma has no effect on the parsing of the lines around it.
  9790. This form has the drawback that it can't be generated by a macro expansion.
  9791. The token form is a series of tokens; it can appear anywhere in the
  9792. program between the other tokens.
  9793. @example
  9794. _Pragma (@var{stringconstant})
  9795. @end example
  9796. @noindent
  9797. The pragma has no effect on the syntax of the tokens that surround it;
  9798. thus, here's a pragma in the middle of an @code{if} statement:
  9799. @example
  9800. if _Pragma ("hello") (x > 1)
  9801. @end example
  9802. @noindent
  9803. However, that's an unclear thing to do; for the sake of
  9804. understandability, it is better to put a pragma on a line by itself
  9805. and not embedded in the middle of another construct.
  9806. Both forms of pragma have a textual argument. In a line pragma, the
  9807. text is the rest of the line. The textual argument to @code{_Pragma}
  9808. uses the same syntax as a C string constant: surround the text with
  9809. two @samp{"} characters, and add a backslash before each @samp{"} or
  9810. @samp{\} character in it.
  9811. With either syntax, the textual argument specifies what to do.
  9812. It begins with one or several words that specify the operation.
  9813. If the compiler does not recognize them, it ignores the pragma.
  9814. Here are the pragma operations supported in GNU C@.
  9815. @c ??? Verify font for []
  9816. @table @code
  9817. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9818. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9819. Declares that the current source file depends on @var{file}, so GNU C
  9820. compares the file times and gives a warning if @var{file} is newer
  9821. than the current source file.
  9822. This directive searches for @var{file} the way @code{#include}
  9823. searches for a non-system header file.
  9824. If @var{message} is given, the warning message includes that text.
  9825. Examples:
  9826. @example
  9827. #pragma GCC dependency "parse.y"
  9828. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9829. rerun fixincludes")
  9830. @end example
  9831. @item #pragma GCC poison @var{identifiers}
  9832. @itemx _Pragma ("GCC poison @var{identifiers}")
  9833. Poisons the identifiers listed in @var{identifiers}.
  9834. This is useful to make sure all mention of @var{identifiers} has been
  9835. deleted from the program and that no reference to them creeps back in.
  9836. If any of those identifiers appears anywhere in the source after the
  9837. directive, it causes a compilation error. For example,
  9838. @example
  9839. #pragma GCC poison printf sprintf fprintf
  9840. sprintf(some_string, "hello");
  9841. @end example
  9842. @noindent
  9843. generates an error.
  9844. If a poisoned identifier appears as part of the expansion of a macro
  9845. that was defined before the identifier was poisoned, it will @emph{not}
  9846. cause an error. Thus, system headers that define macros that use
  9847. the identifier will not cause errors.
  9848. For example,
  9849. @example
  9850. #define strrchr rindex
  9851. _Pragma ("GCC poison rindex")
  9852. strrchr(some_string, 'h');
  9853. @end example
  9854. @noindent
  9855. does not cause a compilation error.
  9856. @item #pragma GCC system_header
  9857. @itemx _Pragma ("GCC system_header")
  9858. Specify treating the rest of the current source file as if it came
  9859. from a system header file. @xref{System Headers, System Headers,
  9860. System Headers, gcc, Using the GNU Compiler Collection}.
  9861. @item #pragma GCC warning @var{message}
  9862. @itemx _Pragma ("GCC warning @var{message}")
  9863. Equivalent to @code{#warning}. Its advantage is that the
  9864. @code{_Pragma} form can be included in a macro definition.
  9865. @item #pragma GCC error @var{message}
  9866. @itemx _Pragma ("GCC error @var{message}")
  9867. Equivalent to @code{#error}. Its advantage is that the
  9868. @code{_Pragma} form can be included in a macro definition.
  9869. @item #pragma GCC message @var{message}
  9870. @itemx _Pragma ("GCC message @var{message}")
  9871. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9872. informational message, and could be used to include additional warning
  9873. or error text without triggering more warnings or errors. (Note that
  9874. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9875. @samp{GCC} as part of the pragma.)
  9876. @end table
  9877. @node Severity Pragmas
  9878. @subsection Severity Pragmas
  9879. These pragmas control the severity of classes of diagnostics.
  9880. You can specify the class of diagnostic with the GCC option that causes
  9881. those diagnostics to be generated.
  9882. @table @code
  9883. @item #pragma GCC diagnostic error @var{option}
  9884. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9885. For code following this pragma, treat diagnostics of the variety
  9886. specified by @var{option} as errors. For example:
  9887. @example
  9888. _Pragma ("GCC diagnostic error -Wformat")
  9889. @end example
  9890. @noindent
  9891. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9892. as errors rather than warnings.
  9893. @item #pragma GCC diagnostic warning @var{option}
  9894. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9895. For code following this pragma, treat diagnostics of the variety
  9896. specified by @var{option} as warnings. This overrides the
  9897. @var{-Werror} option which says to treat warnings as errors.
  9898. @item #pragma GCC diagnostic ignore @var{option}
  9899. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9900. For code following this pragma, refrain from reporting any diagnostics
  9901. of the variety specified by @var{option}.
  9902. @item #pragma GCC diagnostic push
  9903. @itemx _Pragma ("GCC diagnostic push")
  9904. @itemx #pragma GCC diagnostic pop
  9905. @itemx _Pragma ("GCC diagnostic pop")
  9906. These pragmas maintain a stack of states for severity settings.
  9907. @samp{GCC diagnostic push} saves the current settings on the stack,
  9908. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9909. the current settings from that.
  9910. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9911. restores the settings to what they were at the start of compilation.
  9912. Here is an example:
  9913. @example
  9914. _Pragma ("GCC diagnostic error -Wformat")
  9915. /* @r{@option{-Wformat} messages treated as errors. } */
  9916. _Pragma ("GCC diagnostic push")
  9917. _Pragma ("GCC diagnostic warning -Wformat")
  9918. /* @r{@option{-Wformat} messages treated as warnings. } */
  9919. _Pragma ("GCC diagnostic push")
  9920. _Pragma ("GCC diagnostic ignored -Wformat")
  9921. /* @r{@option{-Wformat} messages suppressed. } */
  9922. _Pragma ("GCC diagnostic pop")
  9923. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9924. _Pragma ("GCC diagnostic pop")
  9925. /* @r{@option{-Wformat} messages treated as errors again. } */
  9926. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9927. _Pragma ("GCC diagnostic pop")
  9928. /* @r{@option{-Wformat} messages treated once again}
  9929. @r{as specified by the GCC command-line options.} */
  9930. @end example
  9931. @end table
  9932. @node Optimization Pragmas
  9933. @subsection Optimization Pragmas
  9934. These pragmas enable a particular optimization for specific function
  9935. definitions. The settings take effect at the end of a function
  9936. definition, so the clean place to use these pragmas is between
  9937. function definitions.
  9938. @table @code
  9939. @item #pragma GCC optimize @var{optimization}
  9940. @itemx _Pragma ("GCC optimize @var{optimization}")
  9941. These pragmas enable the optimization @var{optimization} for the
  9942. following functions. For example,
  9943. @example
  9944. _Pragma ("GCC optimize -fforward-propagate")
  9945. @end example
  9946. @noindent
  9947. says to apply the @samp{forward-propagate} optimization to all
  9948. following function definitions. Specifying optimizations for
  9949. individual functions, rather than for the entire program, is rare but
  9950. can be useful for getting around a bug in the compiler.
  9951. If @var{optimization} does not correspond to a defined optimization
  9952. option, the pragma is erroneous. To turn off an optimization, use the
  9953. corresponding @samp{-fno-} option, such as
  9954. @samp{-fno-forward-propagate}.
  9955. @item #pragma GCC target @var{optimizations}
  9956. @itemx _Pragma ("GCC target @var{optimizations}")
  9957. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9958. used for platform-specific optimizations. Thus,
  9959. @example
  9960. _Pragma ("GCC target popcnt")
  9961. @end example
  9962. @noindent
  9963. activates the optimization @samp{popcnt} for all
  9964. following function definitions. This optimization is supported
  9965. on a few common targets but not on others.
  9966. @item #pragma GCC push_options
  9967. @itemx _Pragma ("GCC push_options")
  9968. The @samp{push_options} pragma saves on a stack the current settings
  9969. specified with the @samp{target} and @samp{optimize} pragmas.
  9970. @item #pragma GCC pop_options
  9971. @itemx _Pragma ("GCC pop_options")
  9972. The @samp{pop_options} pragma pops saved settings from that stack.
  9973. Here's an example of using this stack.
  9974. @example
  9975. _Pragma ("GCC push_options")
  9976. _Pragma ("GCC optimize forward-propagate")
  9977. /* @r{Functions to compile}
  9978. @r{with the @code{forward-propagate} optimization.} */
  9979. _Pragma ("GCC pop_options")
  9980. /* @r{Ends enablement of @code{forward-propagate}.} */
  9981. @end example
  9982. @item #pragma GCC reset_options
  9983. @itemx _Pragma ("GCC reset_options")
  9984. Clears all pragma-defined @samp{target} and @samp{optimize}
  9985. optimization settings.
  9986. @end table
  9987. @node Static Assertions
  9988. @section Static Assertions
  9989. @cindex static assertions
  9990. @findex _Static_assert
  9991. You can add compiler-time tests for necessary conditions into your
  9992. code using @code{_Static_assert}. This can be useful, for example, to
  9993. check that the compilation target platform supports the type sizes
  9994. that the code expects. For example,
  9995. @example
  9996. _Static_assert ((sizeof (long int) >= 8),
  9997. "long int needs to be at least 8 bytes");
  9998. @end example
  9999. @noindent
  10000. reports a compile-time error if compiled on a system with long
  10001. integers smaller than 8 bytes, with @samp{long int needs to be at
  10002. least 8 bytes} as the error message.
  10003. Since calls @code{_Static_assert} are processed at compile time, the
  10004. expression must be computable at compile time and the error message
  10005. must be a literal string. The expression can refer to the sizes of
  10006. variables, but can't refer to their values. For example, the
  10007. following static assertion is invalid for two reasons:
  10008. @example
  10009. char *error_message
  10010. = "long int needs to be at least 8 bytes";
  10011. int size_of_long_int = sizeof (long int);
  10012. _Static_assert (size_of_long_int == 8, error_message);
  10013. @end example
  10014. @noindent
  10015. The expression @code{size_of_long_int == 8} isn't computable at
  10016. compile time, and the error message isn't a literal string.
  10017. You can, though, use preprocessor definition values with
  10018. @code{_Static_assert}:
  10019. @example
  10020. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10021. at least 8 bytes"
  10022. _Static_assert ((sizeof (long int) == 8),
  10023. LONG_INT_ERROR_MESSAGE);
  10024. @end example
  10025. Static assertions are permitted wherever a statement or declaration is
  10026. permitted, including at top level in the file, and also inside the
  10027. definition of a type.
  10028. @example
  10029. union y
  10030. @{
  10031. int i;
  10032. int *ptr;
  10033. _Static_assert (sizeof (int *) == sizeof (int),
  10034. "Pointer and int not same size");
  10035. @};
  10036. @end example
  10037. @node Type Alignment
  10038. @appendix Type Alignment
  10039. @cindex type alignment
  10040. @cindex alignment of type
  10041. @findex _Alignof
  10042. @findex __alignof__
  10043. Code for device drivers and other communication with low-level
  10044. hardware sometimes needs to be concerned with the alignment of
  10045. data objects in memory.
  10046. Each data type has a required @dfn{alignment}, always a power of 2,
  10047. that says at which memory addresses an object of that type can validly
  10048. start. A valid address for the type must be a multiple of its
  10049. alignment. If a type's alignment is 1, that means it can validly
  10050. start at any address. If a type's alignment is 2, that means it can
  10051. only start at an even address. If a type's alignment is 4, that means
  10052. it can only start at an address that is a multiple of 4.
  10053. The alignment of a type (except @code{char}) can vary depending on the
  10054. kind of computer in use. To refer to the alignment of a type in a C
  10055. program, use @code{_Alignof}, whose syntax parallels that of
  10056. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10057. operation, and it doesn't compute the value of the expression used
  10058. as its argument.
  10059. Nominally, each integer and floating-point type has an alignment equal to
  10060. the largest power of 2 that divides its size. Thus, @code{int} with
  10061. size 4 has a nominal alignment of 4, and @code{long long int} with
  10062. size 8 has a nominal alignment of 8.
  10063. However, each kind of computer generally has a maximum alignment, and
  10064. no type needs more alignment than that. If the computer's maximum
  10065. alignment is 4 (which is common), then no type's alignment is more
  10066. than 4.
  10067. The size of any type is always a multiple of its alignment; that way,
  10068. in an array whose elements have that type, all the elements are
  10069. properly aligned if the first one is.
  10070. These rules apply to all real computers today, but some embedded
  10071. controllers have odd exceptions. We don't have references to cite for
  10072. them.
  10073. @c We can't cite a nonfree manual as documentation.
  10074. Ordinary C code guarantees that every object of a given type is in
  10075. fact aligned as that type requires.
  10076. If the operand of @code{_Alignof} is a structure field, the value
  10077. is the alignment it requires. It may have a greater alignment by
  10078. coincidence, due to the other fields, but @code{_Alignof} is not
  10079. concerned about that. @xref{Structures}.
  10080. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10081. but now that the feature has been standardized, it is better
  10082. to use the standard keyword @code{_Alignof}.
  10083. @findex _Alignas
  10084. @findex __aligned__
  10085. You can explicitly specify an alignment requirement for a particular
  10086. variable or structure field by adding @code{_Alignas
  10087. (@var{alignment})} to the declaration, where @var{alignment} is a
  10088. power of 2 or a type name. For instance:
  10089. @example
  10090. char _Alignas (8) x;
  10091. @end example
  10092. @noindent
  10093. or
  10094. @example
  10095. char _Alignas (double) x;
  10096. @end example
  10097. @noindent
  10098. specifies that @code{x} must start on an address that is a multiple of
  10099. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10100. machine, that maximum is how much alignment @code{x} will get.
  10101. The older GNU C syntax for this feature looked like
  10102. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10103. declaration, and was added after the variable. For instance:
  10104. @example
  10105. char x __attribute__ ((__aligned__ 8));
  10106. @end example
  10107. @xref{Attributes}.
  10108. @node Aliasing
  10109. @appendix Aliasing
  10110. @cindex aliasing (of storage)
  10111. @cindex pointer type conversion
  10112. @cindex type conversion, pointer
  10113. We have already presented examples of casting a @code{void *} pointer
  10114. to another pointer type, and casting another pointer type to
  10115. @code{void *}.
  10116. One common kind of pointer cast is guaranteed safe: casting the value
  10117. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10118. Allocation}). It is safe because these functions do not save the
  10119. pointer anywhere else; the only way the program will access the newly
  10120. allocated memory is via the pointer just returned.
  10121. In fact, C allows casting any pointer type to any other pointer type.
  10122. Using this to access the same place in memory using two
  10123. different data types is called @dfn{aliasing}.
  10124. Aliasing is necessary in some programs that do sophisticated memory
  10125. management, such as GNU Emacs, but most C programs don't need to do
  10126. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10127. aliasing correctly requires following the rules stated below.
  10128. Otherwise, the aliasing may result in malfunctions when the program
  10129. runs.
  10130. The rest of this appendix explains the pitfalls and rules of aliasing.
  10131. @menu
  10132. * Aliasing Alignment:: Memory alignment considerations for
  10133. casting between pointer types.
  10134. * Aliasing Length:: Type size considerations for
  10135. casting between pointer types.
  10136. * Aliasing Type Rules:: Even when type alignment and size matches,
  10137. aliasing can still have surprising results.
  10138. @end menu
  10139. @node Aliasing Alignment
  10140. @appendixsection Aliasing and Alignment
  10141. In order for a type-converted pointer to be valid, it must have the
  10142. alignment that the new pointer type requires. For instance, on most
  10143. computers, @code{int} has alignment 4; the address of an @code{int}
  10144. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10145. address of a @code{char} is usually not a multiple of 4. Taking the
  10146. address of such a @code{char} and casting it to @code{int *} probably
  10147. results in an invalid pointer. Trying to dereference it may cause a
  10148. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10149. @example
  10150. foo ()
  10151. @{
  10152. char i[4];
  10153. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10154. return *p; /* @r{Crash!} */
  10155. @}
  10156. @end example
  10157. This requirement is never a problem when casting the return value
  10158. of @code{malloc} because that function always returns a pointer
  10159. with as much alignment as any type can require.
  10160. @node Aliasing Length
  10161. @appendixsection Aliasing and Length
  10162. When converting a pointer to a different pointer type, make sure the
  10163. object it really points to is at least as long as the target of the
  10164. converted pointer. For instance, suppose @code{p} has type @code{int
  10165. *} and it's cast as follows:
  10166. @example
  10167. int *p;
  10168. struct
  10169. @{
  10170. double d, e, f;
  10171. @} foo;
  10172. struct foo *q = (struct foo *)p;
  10173. q->f = 5.14159;
  10174. @end example
  10175. @noindent
  10176. the value @code{q->f} will run past the end of the @code{int} that
  10177. @code{p} points to. If @code{p} was initialized to the start of an
  10178. array of type @code{int[6]}, the object is long enough for three
  10179. @code{double}s. But if @code{p} points to something shorter,
  10180. @code{q->f} will run on beyond the end of that, overlaying some other
  10181. data. Storing that will garble that other data. Or it could extend
  10182. past the end of memory space and cause a @code{SIGSEGV} signal
  10183. (@pxref{Signals}).
  10184. @node Aliasing Type Rules
  10185. @appendixsection Type Rules for Aliasing
  10186. C code that converts a pointer to a different pointer type can use the
  10187. pointers to access the same memory locations with two different data
  10188. types. If the same address is accessed with different types in a
  10189. single control thread, optimization can make the code do surprising
  10190. things (in effect, make it malfunction).
  10191. Here's a concrete example where aliasing that can change the code's
  10192. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10193. long, like @code{int}, and so is every pointer. Thus, the structures
  10194. @code{struct a} and @code{struct b} are both 8 bytes.
  10195. @example
  10196. #include <stdio.h>
  10197. struct a @{ int size; char *data; @};
  10198. struct b @{ float size; char *data; @};
  10199. void sub (struct a *p, struct b *q)
  10200. @{
  10201.   int x;
  10202.   p->size = 0;
  10203.   q->size = 1;
  10204.   x = p->size;
  10205.   printf("x       =%d\n", x);
  10206.   printf("p->size =%d\n", (int)p->size);
  10207.   printf("q->size =%d\n", (int)q->size);
  10208. @}
  10209. int main(void)
  10210. @{
  10211.   struct a foo;
  10212.   struct a *p = &foo;
  10213.   struct b *q = (struct b *) &foo;
  10214.   sub (p, q);
  10215. @}
  10216. @end example
  10217. This code works as intended when compiled without optimization. All
  10218. the operations are carried out sequentially as written. The code
  10219. sets @code{x} to @code{p->size}, but what it actually gets is the
  10220. bits of the floating point number 1, as type @code{int}.
  10221. However, when optimizing, the compiler is allowed to assume
  10222. (mistakenly, here) that @code{q} does not point to the same storage as
  10223. @code{p}, because their data types are not allowed to alias.
  10224. From this assumption, the compiler can deduce (falsely, here) that the
  10225. assignment into @code{q->size} has no effect on the value of
  10226. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10227. be set to 0.
  10228. GNU C, following the C standard, @emph{defines} this optimization as
  10229. legitimate. Code that misbehaves when optimized following these rules
  10230. is, by definition, incorrect C code.
  10231. The rules for storage aliasing in C are based on the two data types:
  10232. the type of the object, and the type it is accessed through. The
  10233. rules permit accessing part of a storage object of type @var{t} using
  10234. only these types:
  10235. @itemize @bullet
  10236. @item
  10237. @var{t}.
  10238. @item
  10239. A type compatible with @var{t}. @xref{Compatible Types}.
  10240. @item
  10241. A signed or unsigned version of one of the above.
  10242. @item
  10243. A qualifed version of one of the above.
  10244. @xref{Type Qualifiers}.
  10245. @item
  10246. An array, structure (@pxref{Structures}), or union type
  10247. (@code{Unions}) that contains one of the above, either directly as a
  10248. field or through multiple levels of fields. If @var{t} is
  10249. @code{double}, this would include @code{struct s @{ union @{ double
  10250. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10251. inside it somewhere.
  10252. @item
  10253. A character type.
  10254. @end itemize
  10255. What do these rules say about the example in this subsection?
  10256. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10257. @code{int}. The type @code{float} is not allowed as an aliasing type
  10258. by those rules, so @code{b->size} is not supposed to alias with
  10259. elements of @code{j}. Based on that assumption, GNU C makes a
  10260. permitted optimization that was not, in this case, consistent with
  10261. what the programmer intended the program to do.
  10262. Whether GCC actually performs type-based aliasing analysis depends on
  10263. the details of the code. GCC has other ways to determine (in some cases)
  10264. whether objects alias, and if it gets a reliable answer that way, it won't
  10265. fall back on type-based heuristics.
  10266. @c @opindex -fno-strict-aliasing
  10267. The importance of knowing the type-based aliasing rules is not so as
  10268. to ensure that the optimization is done where it would be safe, but so
  10269. as to ensure it is @emph{not} done in a way that would break the
  10270. program. You can turn off type-based aliasing analysis by giving GCC
  10271. the option @option{-fno-strict-aliasing}.
  10272. @node Digraphs
  10273. @appendix Digraphs
  10274. @cindex digraphs
  10275. C accepts aliases for certain characters. Apparently in the 1990s
  10276. some computer systems had trouble inputting these characters, or
  10277. trouble displaying them. These digraphs almost never appear in C
  10278. programs nowadays, but we mention them for completeness.
  10279. @table @samp
  10280. @item <:
  10281. An alias for @samp{[}.
  10282. @item :>
  10283. An alias for @samp{]}.
  10284. @item <%
  10285. An alias for @samp{@{}.
  10286. @item %>
  10287. An alias for @samp{@}}.
  10288. @item %:
  10289. An alias for @samp{#},
  10290. used for preprocessing directives (@pxref{Directives}) and
  10291. macros (@pxref{Macros}).
  10292. @end table
  10293. @node Attributes
  10294. @appendix Attributes in Declarations
  10295. @cindex attributes
  10296. @findex __attribute__
  10297. You can specify certain additional requirements in a declaration, to
  10298. get fine-grained control over code generation, and helpful
  10299. informational messages during compilation. We use a few attributes in
  10300. code examples throughout this manual, including
  10301. @table @code
  10302. @item aligned
  10303. The @code{aligned} attribute specifies a minimum alignment for a
  10304. variable or structure field, measured in bytes:
  10305. @example
  10306. int foo __attribute__ ((aligned (8))) = 0;
  10307. @end example
  10308. @noindent
  10309. This directs GNU C to allocate @code{foo} at an address that is a
  10310. multiple of 8 bytes. However, you can't force an alignment bigger
  10311. than the computer's maximum meaningful alignment.
  10312. @item packed
  10313. The @code{packed} attribute specifies to compact the fields of a
  10314. structure by not leaving gaps between fields. For example,
  10315. @example
  10316. struct __attribute__ ((packed)) bar
  10317. @{
  10318. char a;
  10319. int b;
  10320. @};
  10321. @end example
  10322. @noindent
  10323. allocates the integer field @code{b} at byte 1 in the structure,
  10324. immediately after the character field @code{a}. The packed structure
  10325. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10326. alignment is 1, that of @code{char}.
  10327. @item deprecated
  10328. Applicable to both variables and functions, the @code{deprecated}
  10329. attribute tells the compiler to issue a warning if the variable or
  10330. function is ever used in the source file.
  10331. @example
  10332. int old_foo __attribute__ ((deprecated));
  10333. int old_quux () __attribute__ ((deprecated));
  10334. @end example
  10335. @item __noinline__
  10336. The @code{__noinline__} attribute, in a function's declaration or
  10337. definition, specifies never to inline calls to that function. All
  10338. calls to that function, in a compilation unit where it has this
  10339. attribute, will be compiled to invoke the separately compiled
  10340. function. @xref{Inline Function Definitions}.
  10341. @item __noclone__
  10342. The @code{__noclone__} attribute, in a function's declaration or
  10343. definition, specifies never to clone that function. Thus, there will
  10344. be only one compiled version of the function. @xref{Label Value
  10345. Caveats}, for more information about cloning.
  10346. @item always_inline
  10347. The @code{always_inline} attribute, in a function's declaration or
  10348. definition, specifies to inline all calls to that function (unless
  10349. something about the function makes inlining impossible). This applies
  10350. to all calls to that function in a compilation unit where it has this
  10351. attribute. @xref{Inline Function Definitions}.
  10352. @item gnu_inline
  10353. The @code{gnu_inline} attribute, in a function's declaration or
  10354. definition, specifies to handle the @code{inline} keywprd the way GNU
  10355. C originally implemented it, many years before ISO C said anything
  10356. about inlining. @xref{Inline Function Definitions}.
  10357. @end table
  10358. For full documentation of attributes, see the GCC manual.
  10359. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10360. the GNU Compiler Collection}.
  10361. @node Signals
  10362. @appendix Signals
  10363. @cindex signal
  10364. @cindex handler (for signal)
  10365. @cindex @code{SIGSEGV}
  10366. @cindex @code{SIGFPE}
  10367. @cindex @code{SIGBUS}
  10368. Some program operations bring about an error condition called a
  10369. @dfn{signal}. These signals terminate the program, by default.
  10370. There are various different kinds of signals, each with a name. We
  10371. have seen several such error conditions through this manual:
  10372. @table @code
  10373. @item SIGSEGV
  10374. This signal is generated when a program tries to read or write outside
  10375. the memory that is allocated for it, or to write memory that can only
  10376. be read. The name is an abbreviation for ``segmentation violation''.
  10377. @item SIGFPE
  10378. This signal indicates a fatal arithmetic error. The name is an
  10379. abbreviation for ``floating-point exception'', but covers all types of
  10380. arithmetic errors, including division by zero and overflow.
  10381. @item SIGBUS
  10382. This signal is generated when an invalid pointer is dereferenced,
  10383. typically the result of dereferencing an uninintalized pointer. It is
  10384. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10385. invalid access to valid memory, while @code{SIGBUS} indicates an
  10386. attempt to access an invalid address.
  10387. @end table
  10388. These kinds of signal allow the program to specify a function as a
  10389. @dfn{signal handler}. When a signal has a handler, it doesn't
  10390. terminate the program; instead it calls the handler.
  10391. There are many other kinds of signal; here we list only those that
  10392. come from run-time errors in C operations. The rest have to do with
  10393. the functioning of the operating system. The GNU C Library Reference
  10394. Manual gives more explanation about signals (@pxref{Program Signal
  10395. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10396. Manual}).
  10397. @node GNU Free Documentation License
  10398. @appendix GNU Free Documentation License
  10399. @include fdl.texi
  10400. @node Symbol Index
  10401. @unnumbered Index of Symbols and Keywords
  10402. @printindex fn
  10403. @node Concept Index
  10404. @unnumbered Concept Index
  10405. @printindex cp
  10406. @bye