c.texi 423 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076
  1. \input texinfo
  2. @c Copyright (C) 2022 Richard Stallman and Free Software Foundation, Inc.
  3. @c (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. @c licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Introduction}
  34. @center @titlefont{and Reference Manual}
  35. @sp 4
  36. @c @center @value{EDITION} Edition
  37. @sp 5
  38. @center Richard Stallman
  39. @center and
  40. @center Trevis Rothwell
  41. @center plus Nelson Beebe
  42. @center on floating point
  43. @page
  44. @vskip 0pt plus 1filll
  45. @insertcopying
  46. @sp 2
  47. @ignore
  48. WILL BE Published by the Free Software Foundation @*
  49. 51 Franklin Street, Fifth Floor @*
  50. Boston, MA 02110-1301 USA @*
  51. ISBN ?-??????-??-?
  52. @end ignore
  53. @ignore
  54. @sp 1
  55. Cover art by J. Random Artist
  56. @end ignore
  57. @end titlepage
  58. @summarycontents
  59. @contents
  60. @node Top
  61. @ifnottex
  62. @top GNU C Manual
  63. @end ifnottex
  64. @iftex
  65. @top Preface
  66. @end iftex
  67. This manual explains the C language for use with the GNU Compiler
  68. Collection (GCC) on the GNU/Linux system and other systems. We refer
  69. to this dialect as GNU C. If you already know C, you can use this as
  70. a reference manual.
  71. If you understand basic concepts of programming but know nothing about
  72. C, you can read this manual sequentially from the beginning to learn
  73. the C language.
  74. If you are a beginner in programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are provided by
  112. functions defined in the standard library, which is automatically
  113. available in every C program. @xref{Top, The GNU C Library, , libc,
  114. The GNU C Library Reference Manual}.
  115. GNU/Linux systems use the GNU C Library to do this job. It is itself
  116. a C program, so once you know C you can read its source code and see
  117. how its library functions do their jobs. Some fraction of the
  118. functions are implemented as @dfn{system calls}, which means they
  119. contain a special instruction that asks the system kernel (Linux) to
  120. do a specific task. To understand how those are implemented, you'd
  121. need to read Linux source code instead. Whether a library function is
  122. a system call is an internal implementation detail that makes no
  123. difference for how to call the function.
  124. This manual incorporates the former GNU C Preprocessor Manual, which
  125. was among the earliest GNU manuals. It also uses some text from the
  126. earlier GNU C Manual that was written by Trevis Rothwell and James
  127. Youngman.
  128. GNU C has many obscure features, each one either for historical
  129. compatibility or meant for very special situations. We have left them
  130. to a companion manual, the GNU C Obscurities Manual, which will be
  131. published digitally later.
  132. Please report errors and suggestions to c-manual@@gnu.org.
  133. @menu
  134. * The First Example:: Getting started with basic C code.
  135. * Complete Program:: A whole example program
  136. that can be compiled and run.
  137. * Storage:: Basic layout of storage; bytes.
  138. * Beyond Integers:: Exploring different numeric types.
  139. * Lexical Syntax:: The various lexical components of C programs.
  140. * Arithmetic:: Numeric computations.
  141. * Assignment Expressions:: Storing values in variables.
  142. * Execution Control Expressions:: Expressions combining values in various ways.
  143. * Binary Operator Grammar:: An overview of operator precedence.
  144. * Order of Execution:: The order of program execution.
  145. * Primitive Types:: More details about primitive data types.
  146. * Constants:: Explicit constant values:
  147. details and examples.
  148. * Type Size:: The memory space occupied by a type.
  149. * Pointers:: Creating and manipulating memory pointers.
  150. * Structures:: Compound data types built
  151. by grouping other types.
  152. * Arrays:: Creating and manipulating arrays.
  153. * Enumeration Types:: Sets of integers with named values.
  154. * Defining Typedef Names:: Using @code{typedef} to define type names.
  155. * Statements:: Controling program flow.
  156. * Variables:: Details about declaring, initializing,
  157. and using variables.
  158. * Type Qualifiers:: Mark variables for certain intended uses.
  159. * Functions:: Declaring, defining, and calling functions.
  160. * Compatible Types:: How to tell if two types are compatible
  161. with each other.
  162. * Type Conversions:: Converting between types.
  163. * Scope:: Different categories of identifier scope.
  164. * Preprocessing:: Using the GNU C preprocessor.
  165. * Integers in Depth:: How integer numbers are represented.
  166. * Floating Point in Depth:: How floating-point numbers are represented.
  167. * Compilation:: How to compile multi-file programs.
  168. * Directing Compilation:: Operations that affect compilation
  169. but don't change the program.
  170. Appendices
  171. * Type Alignment:: Where in memory a type can validly start.
  172. * Aliasing:: Accessing the same data in two types.
  173. * Digraphs:: Two-character aliases for some characters.
  174. * Attributes:: Specifying additional information
  175. in a declaration.
  176. * Signals:: Fatal errors triggered in various scenarios.
  177. * GNU Free Documentation License:: The license for this manual.
  178. * Symbol Index:: Keyword and symbol index.
  179. * Concept Index:: Detailed topical index.
  180. @detailmenu
  181. --- The Detailed Node Listing ---
  182. * Recursive Fibonacci:: Writing a simple function recursively.
  183. * Stack:: Each function call uses space in the stack.
  184. * Iterative Fibonacci:: Writing the same function iteratively.
  185. * Complete Example:: Turn the simple function into a full program.
  186. * Complete Explanation:: Explanation of each part of the example.
  187. * Complete Line-by-Line:: Explaining each line of the example.
  188. * Compile Example:: Using GCC to compile the example.
  189. * Float Example:: A function that uses floating-point numbers.
  190. * Array Example:: A function that works with arrays.
  191. * Array Example Call:: How to call that function.
  192. * Array Example Variations:: Different ways to write the call example.
  193. Lexical Syntax
  194. * English:: Write programs in English!
  195. * Characters:: The characters allowed in C programs.
  196. * Whitespace:: The particulars of whitespace characters.
  197. * Comments:: How to include comments in C code.
  198. * Identifiers:: How to form identifiers (names).
  199. * Operators/Punctuation:: Characters used as operators or punctuation.
  200. * Line Continuation:: Splitting one line into multiple lines.
  201. * Digraphs:: Two-character substitutes for some characters.
  202. Arithmetic
  203. * Basic Arithmetic:: Addition, subtraction, multiplication,
  204. and division.
  205. * Integer Arithmetic:: How C performs arithmetic with integer values.
  206. * Integer Overflow:: When an integer value exceeds the range
  207. of its type.
  208. * Mixed Mode:: Calculating with both integer values
  209. and floating-point values.
  210. * Division and Remainder:: How integer division works.
  211. * Numeric Comparisons:: Comparing numeric values for
  212. equality or order.
  213. * Shift Operations:: Shift integer bits left or right.
  214. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  215. Assignment Expressions
  216. * Simple Assignment:: The basics of storing a value.
  217. * Lvalues:: Expressions into which a value can be stored.
  218. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  219. * Increment/Decrement:: Shorthand for incrementing and decrementing
  220. an lvalue's contents.
  221. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  222. * Assignment in Subexpressions:: How to avoid ambiguity.
  223. * Write Assignments Separately:: Write assignments as separate statements.
  224. Execution Control Expressions
  225. * Logical Operators:: Logical conjunction, disjunction, negation.
  226. * Logicals and Comparison:: Logical operators with comparison operators.
  227. * Logicals and Assignments:: Assignments with logical operators.
  228. * Conditional Expression:: An if/else construct inside expressions.
  229. * Comma Operator:: Build a sequence of subexpressions.
  230. Order of Execution
  231. * Reordering of Operands:: Operations in C are not necessarily computed
  232. in the order they are written.
  233. * Associativity and Ordering:: Some associative operations are performed
  234. in a particular order; others are not.
  235. * Sequence Points:: Some guarantees about the order of operations.
  236. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  237. * Ordering of Operands:: Evaluation order of operands
  238. and function arguments.
  239. * Optimization and Ordering:: Compiler optimizations can reorder operations
  240. only if it has no impact on program results.
  241. Primitive Data Types
  242. * Integer Types:: Description of integer types.
  243. * Floating-Point Data Types:: Description of floating-point types.
  244. * Complex Data Types:: Description of complex number types.
  245. * The Void Type:: A type indicating no value at all.
  246. * Other Data Types:: A brief summary of other types.
  247. Constants
  248. * Integer Constants:: Literal integer values.
  249. * Integer Const Type:: Types of literal integer values.
  250. * Floating Constants:: Literal floating-point values.
  251. * Imaginary Constants:: Literal imaginary number values.
  252. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  253. * Character Constants:: Literal character values.
  254. * Unicode Character Codes:: Unicode characters represented
  255. in either UTF-16 or UTF-32.
  256. * Wide Character Constants:: Literal characters values larger than 8 bits.
  257. * String Constants:: Literal string values.
  258. * UTF-8 String Constants:: Literal UTF-8 string values.
  259. * Wide String Constants:: Literal string values made up of
  260. 16- or 32-bit characters.
  261. Pointers
  262. * Address of Data:: Using the ``address-of'' operator.
  263. * Pointer Types:: For each type, there is a pointer type.
  264. * Pointer Declarations:: Declaring variables with pointer types.
  265. * Pointer Type Designators:: Designators for pointer types.
  266. * Pointer Dereference:: Accessing what a pointer points at.
  267. * Null Pointers:: Pointers which do not point to any object.
  268. * Invalid Dereference:: Dereferencing null or invalid pointers.
  269. * Void Pointers:: Totally generic pointers, can cast to any.
  270. * Pointer Comparison:: Comparing memory address values.
  271. * Pointer Arithmetic:: Computing memory address values.
  272. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  273. * Pointer Arithmetic Low Level:: More about computing memory address values.
  274. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  275. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  276. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  277. * Printing Pointers:: Using @code{printf} for a pointer's value.
  278. Structures
  279. * Referencing Fields:: Accessing field values in a structure object.
  280. * Dynamic Memory Allocation:: Allocating space for objects
  281. while the program is running.
  282. * Field Offset:: Memory layout of fields within a structure.
  283. * Structure Layout:: Planning the memory layout of fields.
  284. * Packed Structures:: Packing structure fields as close as possible.
  285. * Bit Fields:: Dividing integer fields
  286. into fields with fewer bits.
  287. * Bit Field Packing:: How bit fields pack together in integers.
  288. * const Fields:: Making structure fields immutable.
  289. * Zero Length:: Zero-length array as a variable-length object.
  290. * Flexible Array Fields:: Another approach to variable-length objects.
  291. * Overlaying Structures:: Casting one structure type
  292. over an object of another structure type.
  293. * Structure Assignment:: Assigning values to structure objects.
  294. * Unions:: Viewing the same object in different types.
  295. * Packing With Unions:: Using a union type to pack various types into
  296. the same memory space.
  297. * Cast to Union:: Casting a value one of the union's alternative
  298. types to the type of the union itself.
  299. * Structure Constructors:: Building new structure objects.
  300. * Unnamed Types as Fields:: Fields' types do not always need names.
  301. * Incomplete Types:: Types which have not been fully defined.
  302. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  303. * Type Tags:: Scope of structure and union type tags.
  304. Arrays
  305. * Accessing Array Elements:: How to access individual elements of an array.
  306. * Declaring an Array:: How to name and reserve space for a new array.
  307. * Strings:: A string in C is a special case of array.
  308. * Incomplete Array Types:: Naming, but not allocating, a new array.
  309. * Limitations of C Arrays:: Arrays are not first-class objects.
  310. * Multidimensional Arrays:: Arrays of arrays.
  311. * Constructing Array Values:: Assigning values to an entire array at once.
  312. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  313. Statements
  314. * Expression Statement:: Evaluate an expression, as a statement,
  315. usually done for a side effect.
  316. * if Statement:: Basic conditional execution.
  317. * if-else Statement:: Multiple branches for conditional execution.
  318. * Blocks:: Grouping multiple statements together.
  319. * return Statement:: Return a value from a function.
  320. * Loop Statements:: Repeatedly executing a statement or block.
  321. * switch Statement:: Multi-way conditional choices.
  322. * switch Example:: A plausible example of using @code{switch}.
  323. * Duffs Device:: A special way to use @code{switch}.
  324. * Case Ranges:: Ranges of values for @code{switch} cases.
  325. * Null Statement:: A statement that does nothing.
  326. * goto Statement:: Jump to another point in the source code,
  327. identified by a label.
  328. * Local Labels:: Labels with limited scope.
  329. * Labels as Values:: Getting the address of a label.
  330. * Statement Exprs:: A series of statements used as an expression.
  331. Variables
  332. * Variable Declarations:: Name a variable and and reserve space for it.
  333. * Initializers:: Assigning inital values to variables.
  334. * Designated Inits:: Assigning initial values to array elements
  335. at particular array indices.
  336. * Auto Type:: Obtaining the type of a variable.
  337. * Local Variables:: Variables declared in function definitions.
  338. * File-Scope Variables:: Variables declared outside of
  339. function definitions.
  340. * Static Local Variables:: Variables declared within functions,
  341. but with permanent storage allocation.
  342. * Extern Declarations:: Declaring a variable
  343. which is allocated somewhere else.
  344. * Allocating File-Scope:: When is space allocated
  345. for file-scope variables?
  346. * auto and register:: Historically used storage directions.
  347. * Omitting Types:: The bad practice of declaring variables
  348. with implicit type.
  349. Type Qualifiers
  350. * const:: Variables whose values don't change.
  351. * volatile:: Variables whose values may be accessed
  352. or changed outside of the control of
  353. this program.
  354. * restrict Pointers:: Restricted pointers for code optimization.
  355. * restrict Pointer Example:: Example of how that works.
  356. Functions
  357. * Function Definitions:: Writing the body of a function.
  358. * Function Declarations:: Declaring the interface of a function.
  359. * Function Calls:: Using functions.
  360. * Function Call Semantics:: Call-by-value argument passing.
  361. * Function Pointers:: Using references to functions.
  362. * The main Function:: Where execution of a GNU C program begins.
  363. Type Conversions
  364. * Explicit Type Conversion:: Casting a value from one type to another.
  365. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  366. * Argument Promotions:: Automatic conversion of function parameters.
  367. * Operand Promotions:: Automatic conversion of arithmetic operands.
  368. * Common Type:: When operand types differ, which one is used?
  369. Scope
  370. * Scope:: Different categories of identifier scope.
  371. Preprocessing
  372. * Preproc Overview:: Introduction to the C preprocessor.
  373. * Directives:: The form of preprocessor directives.
  374. * Preprocessing Tokens:: The lexical elements of preprocessing.
  375. * Header Files:: Including one source file in another.
  376. * Macros:: Macro expansion by the preprocessor.
  377. * Conditionals:: Controling whether to compile some lines
  378. or ignore them.
  379. * Diagnostics:: Reporting warnings and errors.
  380. * Line Control:: Reporting source line numbers.
  381. * Null Directive:: A preprocessing no-op.
  382. Integers in Depth
  383. * Integer Representations:: How integer values appear in memory.
  384. * Maximum and Minimum Values:: Value ranges of integer types.
  385. Floating Point in Depth
  386. * Floating Representations:: How floating-point values appear in memory.
  387. * Floating Type Specs:: Precise details of memory representations.
  388. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  389. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  390. * Exception Flags:: Handling certain conditions in floating point.
  391. * Exact Floating-Point:: Not all floating calculations lose precision.
  392. * Rounding:: When a floating result can't be represented
  393. exactly in the floating-point type in use.
  394. * Rounding Issues:: Avoid magnifying rounding errors.
  395. * Significance Loss:: Subtracting numbers that are almost equal.
  396. * Fused Multiply-Add:: Taking advantage of a special floating-point
  397. instruction for faster execution.
  398. * Error Recovery:: Determining rounding errors.
  399. * Exact Floating Constants:: Precisely specified floating-point numbers.
  400. * Handling Infinity:: When floating calculation is out of range.
  401. * Handling NaN:: What floating calculation is undefined.
  402. * Signed Zeros:: Positive zero vs. negative zero.
  403. * Scaling by the Base:: A useful exact floating-point operation.
  404. * Rounding Control:: Specifying some rounding behaviors.
  405. * Machine Epsilon:: The smallest number you can add to 1.0
  406. and get a sum which is larger than 1.0.
  407. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  408. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  409. * Further Reading:: References for floating-point numbers.
  410. Directing Compilation
  411. * Pragmas:: Controling compilation of some constructs.
  412. * Static Assertions:: Compile-time tests for conditions.
  413. @end detailmenu
  414. @end menu
  415. @node The First Example
  416. @chapter The First Example
  417. This chapter presents the source code for a very simple C program and
  418. uses it to explain a few features of the language. If you already
  419. know the basic points of C presented in this chapter, you can skim it
  420. or skip it.
  421. We present examples of C source code (other than comments) using a
  422. fixed-width typeface, since that's the way they look when you edit
  423. them in an editor such as GNU Emacs.
  424. @menu
  425. * Recursive Fibonacci:: Writing a simple function recursively.
  426. * Stack:: Each function call uses space in the stack.
  427. * Iterative Fibonacci:: Writing the same function iteratively.
  428. @end menu
  429. @node Recursive Fibonacci
  430. @section Example: Recursive Fibonacci
  431. @cindex recursive Fibonacci function
  432. @cindex Fibonacci function, recursive
  433. To introduce the most basic features of C, let's look at code for a
  434. simple mathematical function that does calculations on integers. This
  435. function calculates the @var{n}th number in the Fibonacci series, in
  436. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  437. 13, 21, 34, 55, @dots{}.
  438. @example
  439. int
  440. fib (int n)
  441. @{
  442. if (n <= 2) /* @r{This avoids infinite recursion.} */
  443. return 1;
  444. else
  445. return fib (n - 1) + fib (n - 2);
  446. @}
  447. @end example
  448. This very simple program illustrates several features of C:
  449. @itemize @bullet
  450. @item
  451. A function definition, whose first two lines constitute the function
  452. header. @xref{Function Definitions}.
  453. @item
  454. A function parameter @code{n}, referred to as the variable @code{n}
  455. inside the function body. @xref{Function Parameter Variables}.
  456. A function definition uses parameters to refer to the argument
  457. values provided in a call to that function.
  458. @item
  459. Arithmetic. C programs add with @samp{+} and subtract with
  460. @samp{-}. @xref{Arithmetic}.
  461. @item
  462. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  463. equal.'' @xref{Numeric Comparisons}.
  464. @item
  465. Integer constants written in base 10.
  466. @xref{Integer Constants}.
  467. @item
  468. A function call. The function call @code{fib (n - 1)} calls the
  469. function @code{fib}, passing as its argument the value @code{n - 1}.
  470. @xref{Function Calls}.
  471. @item
  472. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  473. comment has no effect on the execution of the program. Its purpose is
  474. to provide explanations to people reading the source code. Including
  475. comments in the code is tremendously important---they provide
  476. background information so others can understand the code more quickly.
  477. @xref{Comments}.
  478. In this manual, we present comment text in the variable-width typeface
  479. used for the text of the chapters, not in the fixed-width typeface
  480. used for the rest of the code. That is to make comments easier to
  481. read. This distinction of typeface does not exist in a real file of C
  482. source code.
  483. @item
  484. Two kinds of statements, the @code{return} statement and the
  485. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  486. @item
  487. Recursion. The function @code{fib} calls itself; that is called a
  488. @dfn{recursive call}. These are valid in C, and quite common.
  489. The @code{fib} function would not be useful if it didn't return.
  490. Thus, recursive definitions, to be of any use, must avoid
  491. @dfn{infinite recursion}.
  492. This function definition prevents infinite recursion by specially
  493. handling the case where @code{n} is two or less. Thus the maximum
  494. depth of recursive calls is less than @code{n}.
  495. @end itemize
  496. @menu
  497. * Function Header:: The function's name and how it is called.
  498. * Function Body:: Declarations and statements that implement the function.
  499. @end menu
  500. @node Function Header
  501. @subsection Function Header
  502. @cindex function header
  503. In our example, the first two lines of the function definition are the
  504. @dfn{header}. Its purpose is to state the function's name and say how
  505. it is called:
  506. @example
  507. int
  508. fib (int n)
  509. @end example
  510. @noindent
  511. says that the function returns an integer (type @code{int}), its name is
  512. @code{fib}, and it takes one argument named @code{n} which is also an
  513. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  514. @node Function Body
  515. @subsection Function Body
  516. @cindex function body
  517. @cindex recursion
  518. The rest of the function definition is called the @dfn{function body}.
  519. Like every function body, this one starts with @samp{@{}, ends with
  520. @samp{@}}, and contains zero or more @dfn{statements} and
  521. @dfn{declarations}. Statements specify actions to take, whereas
  522. declarations define names of variables, functions, and so on. Each
  523. statement and each declaration ends with a semicolon (@samp{;}).
  524. Statements and declarations often contain @dfn{expressions}; an
  525. expression is a construct whose execution produces a @dfn{value} of
  526. some data type, but may also take actions through ``side effects''
  527. that alter subsequent execution. A statement, by contrast, does not
  528. have a value; it affects further execution of the program only through
  529. the actions it takes.
  530. This function body contains no declarations, and just one statement,
  531. but that one is a complex statement in that it contains nested
  532. statements. This function uses two kinds of statements:
  533. @table @code
  534. @item return
  535. The @code{return} statement makes the function return immediately.
  536. It looks like this:
  537. @example
  538. return @var{value};
  539. @end example
  540. Its meaning is to compute the expression @var{value} and exit the
  541. function, making it return whatever value that expression produced.
  542. For instance,
  543. @example
  544. return 1;
  545. @end example
  546. @noindent
  547. returns the integer 1 from the function, and
  548. @example
  549. return fib (n - 1) + fib (n - 2);
  550. @end example
  551. @noindent
  552. returns a value computed by performing two function calls
  553. as specified and adding their results.
  554. @item @code{if}@dots{}@code{else}
  555. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  556. Each time it executes, it chooses one of its two substatements to execute
  557. and ignores the other. It looks like this:
  558. @example
  559. if (@var{condition})
  560. @var{if-true-statement}
  561. else
  562. @var{if-false-statement}
  563. @end example
  564. Its meaning is to compute the expression @var{condition} and, if it's
  565. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  566. @var{if-false-statement}. @xref{if-else Statement}.
  567. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  568. simply an expression. It's considered ``true'' if its value is
  569. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  570. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  571. Comparisons}.) Thus,
  572. @example
  573. if (n <= 2)
  574. return 1;
  575. else
  576. return fib (n - 1) + fib (n - 2);
  577. @end example
  578. @noindent
  579. first tests whether the value of @code{n} is less than or equal to 2.
  580. If so, the expression @code{n <= 2} has the value 1. So execution
  581. continues with the statement
  582. @example
  583. return 1;
  584. @end example
  585. @noindent
  586. Otherwise, execution continues with this statement:
  587. @example
  588. return fib (n - 1) + fib (n - 2);
  589. @end example
  590. Each of these statements ends the execution of the function and
  591. provides a value for it to return. @xref{return Statement}.
  592. @end table
  593. Calculating @code{fib} using ordinary integers in C works only for
  594. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  595. in type @code{int}. The addition operation that tries to add
  596. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  597. This occurrence is called @dfn{integer overflow}.
  598. Overflow can manifest itself in various ways, but one thing that can't
  599. possibly happen is to produce the correct value, since that can't fit
  600. in the space for the value. @xref{Integer Overflow}.
  601. @xref{Functions}, for a full explanation about functions.
  602. @node Stack
  603. @section The Stack, And Stack Overflow
  604. @cindex stack
  605. @cindex stack frame
  606. @cindex stack overflow
  607. @cindex recursion, drawbacks of
  608. @cindex stack frame
  609. Recursion has a drawback: there are limits to how many nested levels of
  610. function calls a program can make. In C, each function call allocates a block
  611. of memory which it uses until the call returns. C allocates these
  612. blocks consecutively within a large area of memory known as the
  613. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  614. The size of the stack is limited; if the program tries to use too
  615. much, that causes the program to fail because the stack is full. This
  616. is called @dfn{stack overflow}.
  617. @cindex crash
  618. @cindex segmentation fault
  619. Stack overflow on GNU/Linux typically manifests itself as the
  620. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  621. fault.'' By default, this signal terminates the program immediately,
  622. rather than letting the program try to recover, or reach an expected
  623. ending point. (We commonly say in this case that the program
  624. ``crashes''). @xref{Signals}.
  625. It is inconvenient to observe a crash by passing too large
  626. an argument to recursive Fibonacci, because the program would run a
  627. long time before it crashes. This algorithm is simple but
  628. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  629. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  630. the final result.
  631. However, you can observe stack overflow very quickly if you use
  632. this function instead:
  633. @example
  634. int
  635. fill_stack (int n)
  636. @{
  637. if (n <= 1) /* @r{This limits the depth of recursion.} */
  638. return 1;
  639. else
  640. return fill_stack (n - 1);
  641. @}
  642. @end example
  643. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  644. and using the default configuration, an experiment showed there is
  645. enough stack space to do 261906 nested calls to that function. One
  646. more, and the stack overflows and the program crashes. On another
  647. platform, with a different configuration, or with a different
  648. function, the limit might be bigger or smaller.
  649. @node Iterative Fibonacci
  650. @section Example: Iterative Fibonacci
  651. @cindex iterative Fibonacci function
  652. @cindex Fibonacci function, iterative
  653. Here's a much faster algorithm for computing the same Fibonacci
  654. series. It is faster for two reasons. First, it uses @dfn{iteration}
  655. (that is, repetition or looping) rather than recursion, so it doesn't
  656. take time for a large number of function calls. But mainly, it is
  657. faster because the number of repetitions is small---only @code{@var{n}}.
  658. @c If you change this, change the duplicate in node Example of for.
  659. @example
  660. int
  661. fib (int n)
  662. @{
  663. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  664. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  665. int i;
  666. for (i = 1; i < n; ++i)
  667. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  668. /* @r{since @code{i < n} is false the first time.} */
  669. @{
  670. /* @r{Now @code{last} is @code{fib (@code{i})}}
  671. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  672. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  673. int next = prev + last;
  674. /* @r{Shift the values down.} */
  675. prev = last;
  676. last = next;
  677. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  678. @r{and @code{prev} is @code{fib (@code{i})}.}
  679. @r{But that won't stay true for long,}
  680. @r{because we are about to increment @code{i}.} */
  681. @}
  682. return last;
  683. @}
  684. @end example
  685. This definition computes @code{fib (@var{n})} in a time proportional
  686. to @code{@var{n}}. The comments in the definition explain how it works: it
  687. advances through the series, always keeps the last two values in
  688. @code{last} and @code{prev}, and adds them to get the next value.
  689. Here are the additional C features that this definition uses:
  690. @table @asis
  691. @item Internal blocks
  692. Within a function, wherever a statement is called for, you can write a
  693. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  694. more statements and declarations. (You can also use additional
  695. blocks as statements in a block.)
  696. The function body also counts as a block, which is why it can contain
  697. statements and declarations.
  698. @xref{Blocks}.
  699. @item Declarations of local variables
  700. This function body contains declarations as well as statements. There
  701. are three declarations directly in the function body, as well as a
  702. fourth declaration in an internal block. Each starts with @code{int}
  703. because it declares a variable whose type is integer. One declaration
  704. can declare several variables, but each of these declarations is
  705. simple and declares just one variable.
  706. Variables declared inside a block (either a function body or an
  707. internal block) are @dfn{local variables}. These variables exist only
  708. within that block; their names are not defined outside the block, and
  709. exiting the block deallocates their storage. This example declares
  710. four local variables: @code{last}, @code{prev}, @code{i}, and
  711. @code{next}.
  712. The most basic local variable declaration looks like this:
  713. @example
  714. @var{type} @var{variablename};
  715. @end example
  716. For instance,
  717. @example
  718. int i;
  719. @end example
  720. @noindent
  721. declares the local variable @code{i} as an integer.
  722. @xref{Variable Declarations}.
  723. @item Initializers
  724. When you declare a variable, you can also specify its initial value,
  725. like this:
  726. @example
  727. @var{type} @var{variablename} = @var{value};
  728. @end example
  729. For instance,
  730. @example
  731. int last = 1;
  732. @end example
  733. @noindent
  734. declares the local variable @code{last} as an integer (type
  735. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  736. @item Assignment
  737. Assignment: a specific kind of expression, written with the @samp{=}
  738. operator, that stores a new value in a variable or other place. Thus,
  739. @example
  740. @var{variable} = @var{value}
  741. @end example
  742. @noindent
  743. is an expression that computes @code{@var{value}} and stores the value in
  744. @code{@var{variable}}. @xref{Assignment Expressions}.
  745. @item Expression statements
  746. An expression statement is an expression followed by a semicolon.
  747. That computes the value of the expression, then ignores the value.
  748. An expression statement is useful when the expression changes some
  749. data or has other side effects---for instance, with function calls, or
  750. with assignments as in this example. @xref{Expression Statement}.
  751. Using an expression with no side effects in an expression statement is
  752. pointless except in very special cases. For instance, the expression
  753. statement @code{x;} would examine the value of @code{x} and ignore it.
  754. That is not useful.
  755. @item Increment operator
  756. The increment operator is @samp{++}. @code{++i} is an
  757. expression that is short for @code{i = i + 1}.
  758. @xref{Increment/Decrement}.
  759. @item @code{for} statements
  760. A @code{for} statement is a clean way of executing a statement
  761. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  762. @example
  763. for (i = 1; i < n; ++i)
  764. @var{body}
  765. @end example
  766. @noindent
  767. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  768. for the loop. The loop itself consists of
  769. @itemize @bullet
  770. @item
  771. Testing @code{i < n} and exiting the loop if that's false.
  772. @item
  773. Executing @var{body}.
  774. @item
  775. Advancing the loop (executing @code{++i}, which increments @code{i}).
  776. @end itemize
  777. The net result is to execute @var{body} with 1 in @code{i},
  778. then with 2 in @code{i}, and so on, stopping just before the repetition
  779. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  780. the loop will execute the body zero times.
  781. The body of the @code{for} statement must be one and only one
  782. statement. You can't write two statements in a row there; if you try
  783. to, only the first of them will be treated as part of the loop.
  784. The way to put multiple statements in such a place is to group them
  785. with a block, and that's what we do in this example.
  786. @end table
  787. @node Complete Program
  788. @chapter A Complete Program
  789. @cindex complete example program
  790. @cindex example program, complete
  791. It's all very well to write a Fibonacci function, but you cannot run
  792. it by itself. It is a useful program, but it is not a complete
  793. program.
  794. In this chapter we present a complete program that contains the
  795. @code{fib} function. This example shows how to make the program
  796. start, how to make it finish, how to do computation, and how to print
  797. a result.
  798. @menu
  799. * Complete Example:: Turn the simple function into a full program.
  800. * Complete Explanation:: Explanation of each part of the example.
  801. * Complete Line-by-Line:: Explaining each line of the example.
  802. * Compile Example:: Using GCC to compile the example.
  803. @end menu
  804. @node Complete Example
  805. @section Complete Program Example
  806. Here is the complete program that uses the simple, recursive version
  807. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  808. @example
  809. #include <stdio.h>
  810. int
  811. fib (int n)
  812. @{
  813. if (n <= 2) /* @r{This avoids infinite recursion.} */
  814. return 1;
  815. else
  816. return fib (n - 1) + fib (n - 2);
  817. @}
  818. int
  819. main (void)
  820. @{
  821. printf ("Fibonacci series item %d is %d\n",
  822. 20, fib (20));
  823. return 0;
  824. @}
  825. @end example
  826. @noindent
  827. This program prints a message that shows the value of @code{fib (20)}.
  828. Now for an explanation of what that code means.
  829. @node Complete Explanation
  830. @section Complete Program Explanation
  831. @ifnottex
  832. Here's the explanation of the code of the example in the
  833. previous section.
  834. @end ifnottex
  835. This sample program prints a message that shows the value of @code{fib
  836. (20)}, and exits with code 0 (which stands for successful execution).
  837. Every C program is started by running the function named @code{main}.
  838. Therefore, the example program defines a function named @code{main} to
  839. provide a way to start it. Whatever that function does is what the
  840. program does. @xref{The main Function}.
  841. The @code{main} function is the first one called when the program
  842. runs, but it doesn't come first in the example code. The order of the
  843. function definitions in the source code makes no difference to the
  844. program's meaning.
  845. The initial call to @code{main} always passes certain arguments, but
  846. @code{main} does not have to pay attention to them. To ignore those
  847. arguments, define @code{main} with @code{void} as the parameter list.
  848. (@code{void} as a function's parameter list normally means ``call with
  849. no arguments,'' but @code{main} is a special case.)
  850. The function @code{main} returns 0 because that is
  851. the conventional way for @code{main} to indicate successful execution.
  852. It could instead return a positive integer to indicate failure, and
  853. some utility programs have specific conventions for the meaning of
  854. certain numeric @dfn{failure codes}. @xref{Values from main}.
  855. @cindex @code{printf}
  856. The simplest way to print text in C is by calling the @code{printf}
  857. function, so here we explain very briefly what that function does.
  858. For a full explanation of @code{printf} and the other standard I/O
  859. functions, see @ref{I/O on Streams, The GNU C Library, , libc, The GNU
  860. C Library Reference Manual}.
  861. @cindex standard output
  862. The first argument to @code{printf} is a @dfn{string constant}
  863. (@pxref{String Constants}) that is a template for output. The
  864. function @code{printf} copies most of that string directly as output,
  865. including the newline character at the end of the string, which is
  866. written as @samp{\n}. The output goes to the program's @dfn{standard
  867. output} destination, which in the usual case is the terminal.
  868. @samp{%} in the template introduces a code that substitutes other text
  869. into the output. Specifically, @samp{%d} means to take the next
  870. argument to @code{printf} and substitute it into the text as a decimal
  871. number. (The argument for @samp{%d} must be of type @code{int}; if it
  872. isn't, @code{printf} will malfunction.) So the output is a line that
  873. looks like this:
  874. @example
  875. Fibonacci series item 20 is 6765
  876. @end example
  877. This program does not contain a definition for @code{printf} because
  878. it is defined by the C library, which makes it available in all C
  879. programs. However, each program does need to @dfn{declare}
  880. @code{printf} so it will be called correctly. The @code{#include}
  881. line takes care of that; it includes a @dfn{header file} called
  882. @file{stdio.h} into the program's code. That file is provided by the
  883. operating system and it contains declarations for the many standard
  884. input/output functions in the C library, one of which is
  885. @code{printf}.
  886. Don't worry about header files for now; we'll explain them later in
  887. @ref{Header Files}.
  888. The first argument of @code{printf} does not have to be a string
  889. constant; it can be any string (@pxref{Strings}). However, using a
  890. constant is the most common case.
  891. @node Complete Line-by-Line
  892. @section Complete Program, Line by Line
  893. Here's the same example, explained line by line.
  894. @strong{Beginners, do you find this helpful or not?
  895. Would you prefer a different layout for the example?
  896. Please tell rms@@gnu.org.}
  897. @example
  898. #include <stdio.h> /* @r{Include declaration of usual} */
  899. /* @r{I/O functions such as @code{printf}.} */
  900. /* @r{Most programs need these.} */
  901. int /* @r{This function returns an @code{int}.} */
  902. fib (int n) /* @r{Its name is @code{fib};} */
  903. /* @r{its argument is called @code{n}.} */
  904. @{ /* @r{Start of function body.} */
  905. /* @r{This stops the recursion from being infinite.} */
  906. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  907. return 1; /* @r{make @code{fib} return 1.} */
  908. else /* @r{otherwise, add the two previous} */
  909. /* @r{fibonacci numbers.} */
  910. return fib (n - 1) + fib (n - 2);
  911. @}
  912. int /* @r{This function returns an @code{int}.} */
  913. main (void) /* @r{Start here; ignore arguments.} */
  914. @{ /* @r{Print message with numbers in it.} */
  915. printf ("Fibonacci series item %d is %d\n",
  916. 20, fib (20));
  917. return 0; /* @r{Terminate program, report success.} */
  918. @}
  919. @end example
  920. @node Compile Example
  921. @section Compiling the Example Program
  922. @cindex compiling
  923. @cindex executable file
  924. To run a C program requires converting the source code into an
  925. @dfn{executable file}. This is called @dfn{compiling} the program,
  926. and the command to do that using GNU C is @command{gcc}.
  927. This example program consists of a single source file. If we
  928. call that file @file{fib1.c}, the complete command to compile it is
  929. this:
  930. @example
  931. gcc -g -O -o fib1 fib1.c
  932. @end example
  933. @noindent
  934. Here, @option{-g} says to generate debugging information, @option{-O}
  935. says to optimize at the basic level, and @option{-o fib1} says to put
  936. the executable program in the file @file{fib1}.
  937. To run the program, use its file name as a shell command.
  938. For instance,
  939. @example
  940. ./fib1
  941. @end example
  942. @noindent
  943. However, unless you are sure the program is correct, you should
  944. expect to need to debug it. So use this command,
  945. @example
  946. gdb fib1
  947. @end example
  948. @noindent
  949. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  950. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  951. debug the executable program @code{fib1}.
  952. Richard Stallman's advice, from personal experience, is to turn to the
  953. debugger as soon as you can reproduce the problem. Don't try to avoid
  954. it by using other methods instead---occasionally they are shortcuts,
  955. but usually they waste an unbounded amount of time. With the
  956. debugger, you will surely find the bug in a reasonable time; overall,
  957. you will get your work done faster. The sooner you get serious and
  958. start the debugger, the sooner you are likely to find the bug.
  959. @xref{Compilation}, for an introduction to compiling more complex
  960. programs which consist of more than one source file.
  961. @node Storage
  962. @chapter Storage and Data
  963. @cindex bytes
  964. @cindex storage organization
  965. @cindex memory organization
  966. Storage in C programs is made up of units called @dfn{bytes}. On
  967. nearly all computers, a byte consists of 8 bits, but there are a few
  968. peculiar computers (mostly ``embedded controllers'' for very small
  969. systems) where a byte is longer than that. This manual does not try
  970. to explain the peculiarity of those computers; we assume that a byte
  971. is 8 bits.
  972. Every C data type is made up of a certain number of bytes; that number
  973. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  974. types @code{signed char} and @code{unsigned char} are one byte long;
  975. use those types to operate on data byte by byte. @xref{Signed and
  976. Unsigned Types}. You can refer to a series of consecutive bytes as an
  977. array of @code{char} elements; that's what an ASCII string looks like
  978. in memory. @xref{String Constants}.
  979. @node Beyond Integers
  980. @chapter Beyond Integers
  981. So far we've presented programs that operate on integers. In this
  982. chapter we'll present examples of handling non-integral numbers and
  983. arrays of numbers.
  984. @menu
  985. * Float Example:: A function that uses floating-point numbers.
  986. * Array Example:: A function that works with arrays.
  987. * Array Example Call:: How to call that function.
  988. * Array Example Variations:: Different ways to write the call example.
  989. @end menu
  990. @node Float Example
  991. @section An Example with Non-Integer Numbers
  992. @cindex floating point example
  993. Here's a function that operates on and returns @dfn{floating point}
  994. numbers that don't have to be integers. Floating point represents a
  995. number as a fraction together with a power of 2. (For more detail,
  996. @pxref{Floating-Point Data Types}.) This example calculates the
  997. average of three floating point numbers that are passed to it as
  998. arguments:
  999. @example
  1000. double
  1001. average_of_three (double a, double b, double c)
  1002. @{
  1003. return (a + b + c) / 3;
  1004. @}
  1005. @end example
  1006. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  1007. integers, and even when they happen to be integers, most likely their
  1008. average is not an integer.
  1009. @code{double} is the usual data type in C for calculations on
  1010. floating-point numbers.
  1011. To print a @code{double} with @code{printf}, we must use @samp{%f}
  1012. instead of @samp{%d}:
  1013. @example
  1014. printf ("Average is %f\n",
  1015. average_of_three (1.1, 9.8, 3.62));
  1016. @end example
  1017. The code that calls @code{printf} must pass a @code{double} for
  1018. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  1019. If the argument has the wrong type, @code{printf} will produce garbage
  1020. output.
  1021. Here's a complete program that computes the average of three
  1022. specific numbers and prints the result:
  1023. @example
  1024. double
  1025. average_of_three (double a, double b, double c)
  1026. @{
  1027. return (a + b + c) / 3;
  1028. @}
  1029. int
  1030. main (void)
  1031. @{
  1032. printf ("Average is %f\n",
  1033. average_of_three (1.1, 9.8, 3.62));
  1034. return 0;
  1035. @}
  1036. @end example
  1037. From now on we will not present examples of calls to @code{main}.
  1038. Instead we encourage you to write them for yourself when you want
  1039. to test executing some code.
  1040. @node Array Example
  1041. @section An Example with Arrays
  1042. @cindex array example
  1043. A function to take the average of three numbers is very specific and
  1044. limited. A more general function would take the average of any number
  1045. of numbers. That requires passing the numbers in an array. An array
  1046. is an object in memory that contains a series of values of the same
  1047. data type. This chapter presents the basic concepts and use of arrays
  1048. through an example; for the full explanation, see @ref{Arrays}.
  1049. Here's a function definition to take the average of several
  1050. floating-point numbers, passed as type @code{double}. The first
  1051. parameter, @code{length}, specifies how many numbers are passed. The
  1052. second parameter, @code{input_data}, is an array that holds those
  1053. numbers.
  1054. @example
  1055. double
  1056. avg_of_double (int length, double input_data[])
  1057. @{
  1058. double sum = 0;
  1059. int i;
  1060. for (i = 0; i < length; i++)
  1061. sum = sum + input_data[i];
  1062. return sum / length;
  1063. @}
  1064. @end example
  1065. This introduces the expression to refer to an element of an array:
  1066. @code{input_data[i]} means the element at index @code{i} in
  1067. @code{input_data}. The index of the element can be any expression
  1068. with an integer value; in this case, the expression is @code{i}.
  1069. @xref{Accessing Array Elements}.
  1070. @cindex zero-origin indexing
  1071. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1072. valid index is one less than the number of elements. (This is known
  1073. as @dfn{zero-origin indexing}.)
  1074. This example also introduces the way to declare that a function
  1075. parameter is an array. Such declarations are modeled after the syntax
  1076. for an element of the array. Just as @code{double foo} declares that
  1077. @code{foo} is of type @code{double}, @code{double input_data[]}
  1078. declares that each element of @code{input_data} is of type
  1079. @code{double}. Therefore, @code{input_data} itself has type ``array
  1080. of @code{double}.''
  1081. When declaring an array parameter, it's not necessary to say how long
  1082. the array is. In this case, the parameter @code{input_data} has no
  1083. length information. That's why the function needs another parameter,
  1084. @code{length}, for the caller to provide that information to the
  1085. function @code{avg_of_double}.
  1086. @node Array Example Call
  1087. @section Calling the Array Example
  1088. To call the function @code{avg_of_double} requires making an
  1089. array and then passing it as an argument. Here is an example.
  1090. @example
  1091. @{
  1092. /* @r{The array of values to average.} */
  1093. double nums_to_average[5];
  1094. /* @r{The average, once we compute it.} */
  1095. double average;
  1096. /* @r{Fill in elements of @code{nums_to_average}.} */
  1097. nums_to_average[0] = 58.7;
  1098. nums_to_average[1] = 5.1;
  1099. nums_to_average[2] = 7.7;
  1100. nums_to_average[3] = 105.2;
  1101. nums_to_average[4] = -3.14159;
  1102. average = avg_of_double (5, nums_to_average);
  1103. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1104. @}
  1105. @end example
  1106. This shows an array subscripting expression again, this time
  1107. on the left side of an assignment, storing a value into an
  1108. element of an array.
  1109. It also shows how to declare a local variable that is an array:
  1110. @code{double nums_to_average[5];}. Since this declaration allocates the
  1111. space for the array, it needs to know the array's length. You can
  1112. specify the length with any expression whose value is an integer, but
  1113. in this declaration the length is a constant, the integer 5.
  1114. The name of the array, when used by itself as an expression, stands
  1115. for the address of the array's data, and that's what gets passed to
  1116. the function @code{avg_of_double} in @code{avg_of_double (5,
  1117. nums_to_average)}.
  1118. We can make the code easier to maintain by avoiding the need to write
  1119. 5, the array length, when calling @code{avg_of_double}. That way, if
  1120. we change the array to include more elements, we won't have to change
  1121. that call. One way to do this is with the @code{sizeof} operator:
  1122. @example
  1123. average = avg_of_double ((sizeof (nums_to_average)
  1124. / sizeof (nums_to_average[0])),
  1125. nums_to_average);
  1126. @end example
  1127. This computes the number of elements in @code{nums_to_average} by dividing
  1128. its total size by the size of one element. @xref{Type Size}, for more
  1129. details of using @code{sizeof}.
  1130. We don't show in this example what happens after storing the result of
  1131. @code{avg_of_double} in the variable @code{average}. Presumably
  1132. more code would follow that uses that result somehow. (Why compute
  1133. the average and not use it?) But that isn't part of this topic.
  1134. @node Array Example Variations
  1135. @section Variations for Array Example
  1136. The code to call @code{avg_of_double} has two declarations that
  1137. start with the same data type:
  1138. @example
  1139. /* @r{The array of values to average.} */
  1140. double nums_to_average[5];
  1141. /* @r{The average, once we compute it.} */
  1142. double average;
  1143. @end example
  1144. In C, you can combine the two, like this:
  1145. @example
  1146. double nums_to_average[5], average;
  1147. @end example
  1148. This declares @code{nums_to_average} so each of its elements is a
  1149. @code{double}, and @code{average} so that it simply is a
  1150. @code{double}.
  1151. However, while you @emph{can} combine them, that doesn't mean you
  1152. @emph{should}. If it is useful to write comments about the variables,
  1153. and usually it is, then it's clearer to keep the declarations separate
  1154. so you can put a comment on each one.
  1155. We set all of the elements of the array @code{nums_to_average} with
  1156. assignments, but it is more convenient to use an initializer in the
  1157. declaration:
  1158. @example
  1159. @{
  1160. /* @r{The array of values to average.} */
  1161. double nums_to_average[]
  1162. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1163. /* @r{The average, once we compute it.} */
  1164. average = avg_of_double ((sizeof (nums_to_average)
  1165. / sizeof (nums_to_average[0])),
  1166. nums_to_average);
  1167. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1168. @}
  1169. @end example
  1170. The array initializer is a comma-separated list of values, delimited
  1171. by braces. @xref{Initializers}.
  1172. Note that the declaration does not specify a size for
  1173. @code{nums_to_average}, so the size is determined from the
  1174. initializer. There are five values in the initializer, so
  1175. @code{nums_to_average} gets length 5. If we add another element to
  1176. the initializer, @code{nums_to_average} will have six elements.
  1177. Because the code computes the number of elements from the size of
  1178. the array, using @code{sizeof}, the program will operate on all the
  1179. elements in the initializer, regardless of how many those are.
  1180. @node Lexical Syntax
  1181. @chapter Lexical Syntax
  1182. @cindex lexical syntax
  1183. @cindex token
  1184. To start the full description of the C language, we explain the
  1185. lexical syntax and lexical units of C code. The lexical units of a
  1186. programming language are known as @dfn{tokens}. This chapter covers
  1187. all the tokens of C except for constants, which are covered in a later
  1188. chapter (@pxref{Constants}). One vital kind of token is the
  1189. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1190. kind.
  1191. @menu
  1192. * English:: Write programs in English!
  1193. * Characters:: The characters allowed in C programs.
  1194. * Whitespace:: The particulars of whitespace characters.
  1195. * Comments:: How to include comments in C code.
  1196. * Identifiers:: How to form identifiers (names).
  1197. * Operators/Punctuation:: Characters used as operators or punctuation.
  1198. * Line Continuation:: Splitting one line into multiple lines.
  1199. @end menu
  1200. @node English
  1201. @section Write Programs in English!
  1202. In principle, you can write the function and variable names in a
  1203. program, and the comments, in any human language. C allows any kinds
  1204. of characters in comments, and you can put non-ASCII characters into
  1205. identifiers with a special prefix. However, to enable programmers in
  1206. all countries to understand and develop the program, it is best given
  1207. today's circumstances to write identifiers and comments in
  1208. English.
  1209. English is the one language that programmers in all countries
  1210. generally study. If a program's names are in English, most
  1211. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1212. understand them. Most programmers in those countries can speak
  1213. English, or at least read it, but they do not read each other's
  1214. languages at all. In India, with so many languages, two programmers
  1215. may have no common language other than English.
  1216. If you don't feel confident in writing English, do the best you can,
  1217. and follow each English comment with a version in a language you
  1218. write better; add a note asking others to translate that to English.
  1219. Someone will eventually do that.
  1220. The program's user interface is a different matter. We don't need to
  1221. choose one language for that; it is easy to support multiple languages
  1222. and let each user choose the language to use. This requires writing
  1223. the program to support localization of its interface. (The
  1224. @code{gettext} package exists to support this; @pxref{Message
  1225. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1226. Manual}.) Then a community-based translation effort can provide
  1227. support for all the languages users want to use.
  1228. @node Characters
  1229. @section Characters
  1230. @cindex character set
  1231. @cindex Unicode
  1232. @c ??? How to express ¶?
  1233. GNU C source files are usually written in the
  1234. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1235. was defined in the 1960s for English. However, they can also include
  1236. Unicode characters represented in the
  1237. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1238. This makes it possible to represent accented letters such as @samp{á},
  1239. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1240. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1241. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1242. manual.}
  1243. In C source code, non-ASCII characters are valid in comments, in wide
  1244. character constants (@pxref{Wide Character Constants}), and in string
  1245. constants (@pxref{String Constants}).
  1246. @c ??? valid in identifiers?
  1247. Another way to specify non-ASCII characters in constants (character or
  1248. string) and identifiers is with an escape sequence starting with
  1249. backslash, specifying the intended Unicode character. (@xref{Unicode
  1250. Character Codes}.) This specifies non-ASCII characters without
  1251. putting a real non-ASCII character in the source file itself.
  1252. C accepts two-character aliases called @dfn{digraphs} for certain
  1253. characters. @xref{Digraphs}.
  1254. @node Whitespace
  1255. @section Whitespace
  1256. @cindex whitespace characters in source files
  1257. @cindex space character in source
  1258. @cindex tab character in source
  1259. @cindex formfeed in source
  1260. @cindex linefeed in source
  1261. @cindex newline in source
  1262. @cindex carriage return in source
  1263. @cindex vertical tab in source
  1264. Whitespace means characters that exist in a file but appear blank in a
  1265. printed listing of a file (or traditionally did appear blank, several
  1266. decades ago). The C language requires whitespace in order to separate
  1267. two consecutive identifiers, or to separate an identifier from a
  1268. numeric constant. Other than that, and a few special situations
  1269. described later, whitespace is optional; you can put it in when you
  1270. wish, to make the code easier to read.
  1271. Space and tab in C code are treated as whitespace characters. So are
  1272. line breaks. You can represent a line break with the newline
  1273. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1274. the CRLF sequence (two characters: carriage return followed by a
  1275. newline character).
  1276. The @dfn{formfeed} character, Control-L, was traditionally used to
  1277. divide a file into pages. It is still used this way in source code,
  1278. and the tools that generate nice printouts of source code still start
  1279. a new page after each ``formfeed'' character. Dividing code into
  1280. pages separated by formfeed characters is a good way to break it up
  1281. into comprehensible pieces and show other programmers where they start
  1282. and end.
  1283. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1284. make printing advance down to the next section of a page. We know of
  1285. no particular reason to use it in source code, but it is still
  1286. accepted as whitespace in C.
  1287. Comments are also syntactically equivalent to whitespace.
  1288. @ifinfo
  1289. @xref{Comments}.
  1290. @end ifinfo
  1291. @node Comments
  1292. @section Comments
  1293. @cindex comments
  1294. A comment encapsulates text that has no effect on the program's
  1295. execution or meaning.
  1296. The purpose of comments is to explain the code to people that read it.
  1297. Writing good comments for your code is tremendously important---they
  1298. should provide background information that helps programmers
  1299. understand the reasons why the code is written the way it is. You,
  1300. returning to the code six months from now, will need the help of these
  1301. comments to remember why you wrote it this way.
  1302. Outdated comments that become incorrect are counterproductive, so part
  1303. of the software developer's responsibility is to update comments as
  1304. needed to correspond with changes to the program code.
  1305. C allows two kinds of comment syntax, the traditional style and the
  1306. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1307. with @samp{*/}. For instance,
  1308. @example
  1309. /* @r{This is a comment in traditional C syntax.} */
  1310. @end example
  1311. A traditional comment can contain @samp{/*}, but these delimiters do
  1312. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1313. whether it contains @samp{/*} sequences.
  1314. @example
  1315. /* @r{This} /* @r{is a comment} */ But this is not! */
  1316. @end example
  1317. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1318. For instance,
  1319. @example
  1320. // @r{This is a comment in C@t{++} style.}
  1321. @end example
  1322. Line comments do nest, in effect, because @samp{//} inside a line
  1323. comment is part of that comment:
  1324. @example
  1325. // @r{this whole line is} // @r{one comment}
  1326. This is code, not comment.
  1327. @end example
  1328. It is safe to put line comments inside block comments, or vice versa.
  1329. @example
  1330. @group
  1331. /* @r{traditional comment}
  1332. // @r{contains line comment}
  1333. @r{more traditional comment}
  1334. */ text here is not a comment
  1335. // @r{line comment} /* @r{contains traditional comment} */
  1336. @end group
  1337. @end example
  1338. But beware of commenting out one end of a traditional comment with a line
  1339. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1340. inside an already-started comment.
  1341. @example
  1342. @group
  1343. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1344. Oops! The line comment has ended;
  1345. this isn't a comment any more. */
  1346. @end group
  1347. @end example
  1348. Comments are not recognized within string constants. @t{@w{"/* blah
  1349. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1350. string.
  1351. In this manual we show the text in comments in a variable-width font,
  1352. for readability, but this font distinction does not exist in source
  1353. files.
  1354. A comment is syntactically equivalent to whitespace, so it always
  1355. separates tokens. Thus,
  1356. @example
  1357. @group
  1358. int/* @r{comment} */foo;
  1359. @r{is equivalent to}
  1360. int foo;
  1361. @end group
  1362. @end example
  1363. @noindent
  1364. but clean code always uses real whitespace to separate the comment
  1365. visually from surrounding code.
  1366. @node Identifiers
  1367. @section Identifiers
  1368. @cindex identifiers
  1369. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1370. as well as @samp{_}, that does not start with a digit. Most compilers
  1371. also allow @samp{$}. An identifier can be as long as you like; for
  1372. example,
  1373. @example
  1374. int anti_dis_establishment_arian_ism;
  1375. @end example
  1376. @cindex case of letters in identifiers
  1377. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1378. and @code{A} are two different identifiers.
  1379. @cindex keyword
  1380. @cindex reserved words
  1381. Identifiers in C are used as variable names, function names, typedef
  1382. names, enumeration constants, type tags, field names, and labels.
  1383. Certain identifiers in C are @dfn{keywords}, which means they have
  1384. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1385. meaning you cannot use them in any other way. For instance, you can't
  1386. define a variable or function named @code{return} or @code{if}.
  1387. You can also include other characters, even non-ASCII characters, in
  1388. identifiers by writing their Unicode character names, which start with
  1389. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1390. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1391. characters in identifiers, and when they are written in English, they
  1392. never need non-ASCII characters. @xref{English}.
  1393. Whitespace is required to separate two consecutive identifiers, or to
  1394. separate an identifier from a preceding or following numeric
  1395. constant.
  1396. @node Operators/Punctuation
  1397. @section Operators and Punctuation
  1398. @cindex operators
  1399. @cindex punctuation
  1400. Here we describe the lexical syntax of operators and punctuation in C.
  1401. The specific operators of C and their meanings are presented in
  1402. subsequent chapters.
  1403. Most operators in C consist of one or two characters that can't be
  1404. used in identifiers. The characters used for operators in C are
  1405. @samp{!~^&|*/%+-=<>,.?:}.
  1406. Some operators are a single character. For instance, @samp{-} is the
  1407. operator for negation (with one operand) and the operator for
  1408. subtraction (with two operands).
  1409. Some operators are two characters. For example, @samp{++} is the
  1410. increment operator. Recognition of multicharacter operators works by
  1411. grouping together as many consecutive characters as can constitute one
  1412. operator.
  1413. For instance, the character sequence @samp{++} is always interpreted
  1414. as the increment operator; therefore, if we want to write two
  1415. consecutive instances of the operator @samp{+}, we must separate them
  1416. with a space so that they do not combine as one token. Applying the
  1417. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1418. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1419. of a valid C program and the former could not (since @code{a++}
  1420. is not an lvalue and thus can't be the operand of @code{++}).
  1421. A few C operators are keywords rather than special characters. They
  1422. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1423. (@pxref{Type Alignment}).
  1424. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1425. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1426. @samp{@}}) begin and end a block at the statement level
  1427. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1428. for a variable with multiple elements or components (such as arrays or
  1429. structures).
  1430. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1431. @code{array[5]}.
  1432. Parentheses are used in expressions for explicit nesting of
  1433. expressions (@pxref{Basic Arithmetic}), around the parameter
  1434. declarations in a function declaration or definition, and around the
  1435. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1436. (@pxref{Function Calls}). Several kinds of statements also use
  1437. parentheses as part of their syntax---for instance, @code{if}
  1438. statements, @code{for} statements, @code{while} statements, and
  1439. @code{switch} statements. @xref{if Statement}, and following
  1440. sections.
  1441. Parentheses are also required around the operand of the operator
  1442. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1443. type rather than a value. @xref{Type Size}.
  1444. @node Line Continuation
  1445. @section Line Continuation
  1446. @cindex line continuation
  1447. @cindex continuation of lines
  1448. The sequence of a backslash and a newline is ignored absolutely
  1449. anywhere in a C program. This makes it possible to split a single
  1450. source line into multiple lines in the source file. GNU C tolerates
  1451. and ignores other whitespace between the backslash and the newline.
  1452. In particular, it always ignores a CR (carriage return) character
  1453. there, in case some text editor decided to end the line with the CRLF
  1454. sequence.
  1455. The main use of line continuation in C is for macro definitions that
  1456. would be inconveniently long for a single line (@pxref{Macros}).
  1457. It is possible to continue a line comment onto another line with
  1458. backslash-newline. You can put backslash-newline in the middle of an
  1459. identifier, even a keyword, or an operator. You can even split
  1460. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1461. backslash-newline. Here's an ugly example:
  1462. @example
  1463. @group
  1464. /\
  1465. *
  1466. */ fo\
  1467. o +\
  1468. = 1\
  1469. 0;
  1470. @end group
  1471. @end example
  1472. @noindent
  1473. That's equivalent to @samp{/* */ foo += 10;}.
  1474. Don't do those things in real programs, since they make code hard to
  1475. read.
  1476. @strong{Note:} For the sake of using certain tools on the source code, it is
  1477. wise to end every source file with a newline character which is not
  1478. preceded by a backslash, so that it really ends the last line.
  1479. @node Arithmetic
  1480. @chapter Arithmetic
  1481. @cindex arithmetic operators
  1482. @cindex operators, arithmetic
  1483. @c ??? Duplication with other sections -- get rid of that?
  1484. Arithmetic operators in C attempt to be as similar as possible to the
  1485. abstract arithmetic operations, but it is impossible to do this
  1486. perfectly. Numbers in a computer have a finite range of possible
  1487. values, and non-integer values have a limit on their possible
  1488. accuracy. Nonetheless, except when results are out of range, you will
  1489. encounter no surprises in using @samp{+} for addition, @samp{-} for
  1490. subtraction, and @samp{*} for multiplication.
  1491. Each C operator has a @dfn{precedence}, which is its rank in the
  1492. grammatical order of the various operators. The operators with the
  1493. highest precedence grab adjoining operands first; these expressions
  1494. then become operands for operators of lower precedence. We give some
  1495. information about precedence of operators in this chapter where we
  1496. describe the operators; for the full explanation, see @ref{Binary
  1497. Operator Grammar}.
  1498. The arithmetic operators always @dfn{promote} their operands before
  1499. operating on them. This means converting narrow integer data types to
  1500. a wider data type (@pxref{Operand Promotions}). If you are just
  1501. learning C, don't worry about this yet.
  1502. Given two operands that have different types, most arithmetic
  1503. operations convert them both to their @dfn{common type}. For
  1504. instance, if one is @code{int} and the other is @code{double}, the
  1505. common type is @code{double}. (That's because @code{double} can
  1506. represent all the values that an @code{int} can hold, but not vice
  1507. versa.) For the full details, see @ref{Common Type}.
  1508. @menu
  1509. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1510. and division.
  1511. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1512. * Integer Overflow:: When an integer value exceeds the range
  1513. of its type.
  1514. * Mixed Mode:: Calculating with both integer values
  1515. and floating-point values.
  1516. * Division and Remainder:: How integer division works.
  1517. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1518. * Shift Operations:: Shift integer bits left or right.
  1519. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1520. @end menu
  1521. @node Basic Arithmetic
  1522. @section Basic Arithmetic
  1523. @cindex addition operator
  1524. @cindex subtraction operator
  1525. @cindex multiplication operator
  1526. @cindex division operator
  1527. @cindex negation operator
  1528. @cindex operator, addition
  1529. @cindex operator, subtraction
  1530. @cindex operator, multiplication
  1531. @cindex operator, division
  1532. @cindex operator, negation
  1533. Basic arithmetic in C is done with the usual binary operators of
  1534. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1535. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1536. used to change the sign of a number. The unary @code{+} operator also
  1537. exists; it yields its operand unaltered.
  1538. @samp{/} is the division operator, but dividing integers may not give
  1539. the result you expect. Its value is an integer, which is not equal to
  1540. the mathematical quotient when that is a fraction. Use @samp{%} to
  1541. get the corresponding integer remainder when necessary.
  1542. @xref{Division and Remainder}. Floating point division yields value
  1543. as close as possible to the mathematical quotient.
  1544. These operators use algebraic syntax with the usual algebraic
  1545. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1546. and division are done before addition and subtraction, but you can use
  1547. parentheses to explicitly specify how the operators nest. They are
  1548. left-associative (@pxref{Associativity and Ordering}). Thus,
  1549. @example
  1550. -a + b - c + d * e / f
  1551. @end example
  1552. @noindent
  1553. is equivalent to
  1554. @example
  1555. (((-a) + b) - c) + ((d * e) / f)
  1556. @end example
  1557. @node Integer Arithmetic
  1558. @section Integer Arithmetic
  1559. @cindex integer arithmetic
  1560. Each of the basic arithmetic operations in C has two variants for
  1561. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1562. by the data types of their operands.
  1563. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1564. A signed type can hold a range of positive and negative numbers, with
  1565. zero near the middle of the range. An unsigned type can hold only
  1566. nonnegative numbers; its range starts with zero and runs upward.
  1567. The most basic integer types are @code{int}, which normally can hold
  1568. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1569. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1570. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1571. computers but not always on embedded controllers.) @xref{Integer
  1572. Types}, for full information about integer types.
  1573. When a basic arithmetic operation is given two signed operands, it
  1574. does signed arithmetic. Given two unsigned operands, it does
  1575. unsigned arithmetic.
  1576. If one operand is @code{unsigned int} and the other is @code{int}, the
  1577. operator treats them both as unsigned. More generally, the common
  1578. type of the operands determines whether the operation is signed or
  1579. not. @xref{Common Type}.
  1580. Printing the results of unsigned arithmetic with @code{printf} using
  1581. @samp{%d} can produce surprising results for values far away from
  1582. zero. Even though the rules above say that the computation was done
  1583. with unsigned arithmetic, the printed result may appear to be signed!
  1584. The explanation is that the bit pattern resulting from addition,
  1585. subtraction or multiplication is actually the same for signed and
  1586. unsigned operations. The difference is only in the data type of the
  1587. result, which affects the @emph{interpretation} of the result bit pattern,
  1588. and whether the arithmetic operation can overflow (see the next section).
  1589. But @samp{%d} doesn't know its argument's data type. It sees only the
  1590. value's bit pattern, and it is defined to interpret that as
  1591. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1592. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1593. libc, The GNU C Library Reference Manual}.
  1594. Arithmetic in C never operates directly on narrow integer types (those
  1595. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1596. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1597. @node Integer Overflow
  1598. @section Integer Overflow
  1599. @cindex integer overflow
  1600. @cindex overflow, integer
  1601. When the mathematical value of an arithmetic operation doesn't fit in
  1602. the range of the data type in use, that's called @dfn{overflow}.
  1603. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1604. Integer overflow happens only in arithmetic operations. Type conversion
  1605. operations, by definition, do not cause overflow, not even when the
  1606. result can't fit in its new type. @xref{Integer Conversion}.
  1607. Signed numbers use two's-complement representation, in which the most
  1608. negative number lacks a positive counterpart (@pxref{Integers in
  1609. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1610. overflow.
  1611. @menu
  1612. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1613. * Signed Overflow:: Overlow in signed integer arithmetic.
  1614. @end menu
  1615. @node Unsigned Overflow
  1616. @subsection Overflow with Unsigned Integers
  1617. Unsigned arithmetic in C ignores overflow; it produces the true result
  1618. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1619. in the data type. We say it ``truncates'' the true result to the
  1620. lowest @var{n} bits.
  1621. A true result that is negative, when taken modulo the @var{n}th power
  1622. of 2, yields a positive number. For instance,
  1623. @example
  1624. unsigned int x = 1;
  1625. unsigned int y;
  1626. y = -x;
  1627. @end example
  1628. @noindent
  1629. causes overflow because the negative number @minus{}1 can't be stored
  1630. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1631. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1632. is the largest value that the unsigned data type can store. For a
  1633. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1634. and Minimum Values}.
  1635. Adding that number to itself, as here,
  1636. @example
  1637. unsigned int z;
  1638. z = y + y;
  1639. @end example
  1640. @noindent
  1641. ought to yield 8,489,934,590; however, that is again too large to fit,
  1642. so overflow truncates the value to 4,294,967,294. If that were a
  1643. signed integer, it would mean @minus{}2, which (not by coincidence)
  1644. equals @minus{}1 + @minus{}1.
  1645. @node Signed Overflow
  1646. @subsection Overflow with Signed Integers
  1647. @cindex compiler options for integer overflow
  1648. @cindex integer overflow, compiler options
  1649. @cindex overflow, compiler options
  1650. For signed integers, the result of overflow in C is @emph{in
  1651. principle} undefined, meaning that anything whatsoever could happen.
  1652. Therefore, C compilers can do optimizations that treat the overflow
  1653. case with total unconcern. (Since the result of overflow is undefined
  1654. in principle, one cannot claim that these optimizations are
  1655. erroneous.)
  1656. @strong{Watch out:} These optimizations can do surprising things. For
  1657. instance,
  1658. @example
  1659. int i;
  1660. @r{@dots{}}
  1661. if (i < i + 1)
  1662. x = 5;
  1663. @end example
  1664. @noindent
  1665. could be optimized to do the assignment unconditionally, because the
  1666. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1667. GCC offers compiler options to control handling signed integer
  1668. overflow. These options operate per module; that is, each module
  1669. behaves according to the options it was compiled with.
  1670. These two options specify particular ways to handle signed integer
  1671. overflow, other than the default way:
  1672. @table @option
  1673. @item -fwrapv
  1674. Make signed integer operations well-defined, like unsigned integer
  1675. operations: they produce the @var{n} low-order bits of the true
  1676. result. The highest of those @var{n} bits is the sign bit of the
  1677. result. With @option{-fwrapv}, these out-of-range operations are not
  1678. considered overflow, so (strictly speaking) integer overflow never
  1679. happens.
  1680. The option @option{-fwrapv} enables some optimizations based on the
  1681. defined values of out-of-range results. In GCC 8, it disables
  1682. optimizations that are based on assuming signed integer operations
  1683. will not overflow.
  1684. @item -ftrapv
  1685. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1686. This terminates the program unless the program handles the signal.
  1687. @xref{Signals}.
  1688. @end table
  1689. One other option is useful for finding where overflow occurs:
  1690. @ignore
  1691. @item -fno-strict-overflow
  1692. Disable optimizations that are based on assuming signed integer
  1693. operations will not overflow.
  1694. @end ignore
  1695. @table @option
  1696. @item -fsanitize=signed-integer-overflow
  1697. Output a warning message at run time when signed integer overflow
  1698. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1699. This takes priority over @option{-ftrapv}.
  1700. @end table
  1701. @node Mixed Mode
  1702. @section Mixed-Mode Arithmetic
  1703. Mixing integers and floating-point numbers in a basic arithmetic
  1704. operation converts the integers automatically to floating point.
  1705. In most cases, this gives exactly the desired results.
  1706. But sometimes it matters precisely where the conversion occurs.
  1707. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1708. as an integer, then converts the sum to floating point for the
  1709. multiplication. If the addition causes an overflow, that is not
  1710. equivalent to converting each integer to floating point and then
  1711. adding the two floating point numbers. You can get the latter result
  1712. by explicitly converting the integers, as in @code{((double) i +
  1713. (double) j) * 2.0}. @xref{Explicit Type Conversion}.
  1714. @c Eggert's report
  1715. Adding or multiplying several values, including some integers and some
  1716. floating point, performs the operations left to right. Thus, @code{3.0 +
  1717. i + j} converts @code{i} to floating point, then adds 3.0, then
  1718. converts @code{j} to floating point and adds that. You can specify a
  1719. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1720. and @code{j} first and then adds that sum (converted to floating
  1721. point) to 3.0. In this respect, C differs from other languages, such
  1722. as Fortran.
  1723. @node Division and Remainder
  1724. @section Division and Remainder
  1725. @cindex remainder operator
  1726. @cindex modulus
  1727. @cindex operator, remainder
  1728. Division of integers in C rounds the result to an integer. The result
  1729. is always rounded towards zero.
  1730. @example
  1731. 16 / 3 @result{} 5
  1732. -16 / 3 @result{} -5
  1733. 16 / -3 @result{} -5
  1734. -16 / -3 @result{} 5
  1735. @end example
  1736. @noindent
  1737. To get the corresponding remainder, use the @samp{%} operator:
  1738. @example
  1739. 16 % 3 @result{} 1
  1740. -16 % 3 @result{} -1
  1741. 16 % -3 @result{} 1
  1742. -16 % -3 @result{} -1
  1743. @end example
  1744. @noindent
  1745. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1746. From the rounded quotient and the remainder, you can reconstruct
  1747. the dividend, like this:
  1748. @example
  1749. int
  1750. original_dividend (int divisor, int quotient, int remainder)
  1751. @{
  1752. return divisor * quotient + remainder;
  1753. @}
  1754. @end example
  1755. To do unrounded division, use floating point. If only one operand is
  1756. floating point, @samp{/} converts the other operand to floating
  1757. point.
  1758. @example
  1759. 16.0 / 3 @result{} 5.333333333333333
  1760. 16 / 3.0 @result{} 5.333333333333333
  1761. 16.0 / 3.0 @result{} 5.333333333333333
  1762. 16 / 3 @result{} 5
  1763. @end example
  1764. The remainder operator @samp{%} is not allowed for floating-point
  1765. operands, because it is not needed. The concept of remainder makes
  1766. sense for integers because the result of division of integers has to
  1767. be an integer. For floating point, the result of division is a
  1768. floating-point number, in other words a fraction, which will differ
  1769. from the exact result only by a very small amount.
  1770. There are functions in the standard C library to calculate remainders
  1771. from integral-values division of floating-point numbers.
  1772. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1773. Reference Manual}.
  1774. Integer division overflows in one specific case: dividing the smallest
  1775. negative value for the data type (@pxref{Maximum and Minimum Values})
  1776. by @minus{}1. That's because the correct result, which is the
  1777. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1778. in the same number of bits. On some computers now in use, this always
  1779. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1780. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1781. Division by zero leads to unpredictable results---depending on the
  1782. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1783. produce a numeric result.
  1784. @cindex division by zero
  1785. @cindex zero, division by
  1786. @strong{Watch out:} Make sure the program does not divide by zero. If
  1787. you can't prove that the divisor is not zero, test whether it is zero,
  1788. and skip the division if so.
  1789. @node Numeric Comparisons
  1790. @section Numeric Comparisons
  1791. @cindex numeric comparisons
  1792. @cindex comparisons
  1793. @cindex operators, comparison
  1794. @cindex equal operator
  1795. @cindex not-equal operator
  1796. @cindex less-than operator
  1797. @cindex greater-than operator
  1798. @cindex less-or-equal operator
  1799. @cindex greater-or-equal operator
  1800. @cindex operator, equal
  1801. @cindex operator, not-equal
  1802. @cindex operator, less-than
  1803. @cindex operator, greater-than
  1804. @cindex operator, less-or-equal
  1805. @cindex operator, greater-or-equal
  1806. @cindex truth value
  1807. There are two kinds of comparison operators: @dfn{equality} and
  1808. @dfn{ordering}. Equality comparisons test whether two expressions
  1809. have the same value. The result is a @dfn{truth value}: a number that
  1810. is 1 for ``true'' and 0 for ``false.''
  1811. @example
  1812. a == b /* @r{Test for equal.} */
  1813. a != b /* @r{Test for not equal.} */
  1814. @end example
  1815. The equality comparison is written @code{==} because plain @code{=}
  1816. is the assignment operator.
  1817. Ordering comparisons test which operand is greater or less. Their
  1818. results are truth values. These are the ordering comparisons of C:
  1819. @example
  1820. a < b /* @r{Test for less-than.} */
  1821. a > b /* @r{Test for greater-than.} */
  1822. a <= b /* @r{Test for less-than-or-equal.} */
  1823. a >= b /* @r{Test for greater-than-or-equal.} */
  1824. @end example
  1825. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1826. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1827. mathematics. However, if @code{a} and @code{b} are special floating
  1828. point values (not ordinary numbers), all three can be false.
  1829. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1830. @node Shift Operations
  1831. @section Shift Operations
  1832. @cindex shift operators
  1833. @cindex operators, shift
  1834. @cindex operators, shift
  1835. @cindex shift count
  1836. @dfn{Shifting} an integer means moving the bit values to the left or
  1837. right within the bits of the data type. Shifting is defined only for
  1838. integers. Here's the way to write it:
  1839. @example
  1840. /* @r{Left shift.} */
  1841. 5 << 2 @result{} 20
  1842. /* @r{Right shift.} */
  1843. 5 >> 2 @result{} 1
  1844. @end example
  1845. @noindent
  1846. The left operand is the value to be shifted, and the right operand
  1847. says how many bits to shift it (the @dfn{shift count}). The left
  1848. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1849. operates on a narrow integer type; it's always either @code{int} or
  1850. wider. The result of the shift operation has the same type as the
  1851. promoted left operand.
  1852. @menu
  1853. * Bits Shifted In:: How shifting makes new bits to shift in.
  1854. * Shift Caveats:: Caveats of shift operations.
  1855. * Shift Hacks:: Clever tricks with shift operations.
  1856. @end menu
  1857. @node Bits Shifted In
  1858. @subsection Shifting Makes New Bits
  1859. A shift operation shifts towards one end of the number and has to
  1860. generate new bits at the other end.
  1861. Shifting left one bit must generate a new least significant bit. It
  1862. always brings in zero there. It is equivalent to multiplying by the
  1863. appropriate power of 2. For example,
  1864. @example
  1865. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1866. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1867. @end example
  1868. The meaning of shifting right depends on whether the data type is
  1869. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1870. data type, it performs ``arithmetic shift,'' which keeps the number's
  1871. sign unchanged by duplicating the sign bit. For an unsigned data
  1872. type, it performs ``logical shift,'' which always shifts in zeros at
  1873. the most significant bit.
  1874. In both cases, shifting right one bit is division by two, rounding
  1875. towards negative infinity. For example,
  1876. @example
  1877. (unsigned) 19 >> 2 @result{} 4
  1878. (unsigned) 20 >> 2 @result{} 5
  1879. (unsigned) 21 >> 2 @result{} 5
  1880. @end example
  1881. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1882. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1883. zero.
  1884. The shift count must be zero or greater. Shifting by a negative
  1885. number of bits gives machine-dependent results.
  1886. @node Shift Caveats
  1887. @subsection Caveats for Shift Operations
  1888. @strong{Warning:} If the shift count is greater than or equal to the
  1889. width in bits of the promoted first operand, the results are
  1890. machine-dependent. Logically speaking, the ``correct'' value would be
  1891. either @minus{}1 (for right shift of a negative number) or 0 (in all other
  1892. cases), but the actual result is whatever the machine's shift
  1893. instruction does in that case. So unless you can prove that the
  1894. second operand is not too large, write code to check it at run time.
  1895. @strong{Warning:} Never rely on how the shift operators relate in
  1896. precedence to other arithmetic binary operators. Programmers don't
  1897. remember these precedences, and won't understand the code. Always use
  1898. parentheses to explicitly specify the nesting, like this:
  1899. @example
  1900. a + (b << 5) /* @r{Shift first, then add.} */
  1901. (a + b) << 5 /* @r{Add first, then shift.} */
  1902. @end example
  1903. Note: according to the C standard, shifting of signed values isn't
  1904. guaranteed to work properly when the value shifted is negative, or
  1905. becomes negative during the operation of shifting left. However, only
  1906. pedants have a reason to be concerned about this; only computers with
  1907. strange shift instructions could plausibly do this wrong. In GNU C,
  1908. the operation always works as expected,
  1909. @node Shift Hacks
  1910. @subsection Shift Hacks
  1911. You can use the shift operators for various useful hacks. For
  1912. example, given a date specified by day of the month @code{d}, month
  1913. @code{m}, and year @code{y}, you can store the entire date in a single
  1914. integer @code{date}:
  1915. @example
  1916. unsigned int d = 12;
  1917. unsigned int m = 6;
  1918. unsigned int y = 1983;
  1919. unsigned int date = ((y << 4) + m) << 5) + d;
  1920. @end example
  1921. @noindent
  1922. To extract the original day, month, and year out of
  1923. @code{date}, use a combination of shift and remainder.
  1924. @example
  1925. d = date % 32;
  1926. m = (date >> 5) % 16;
  1927. y = date >> 9;
  1928. @end example
  1929. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1930. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1931. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1932. multiplication, since negating a value is equivalent to multiplying it
  1933. by @minus{}1.
  1934. @node Bitwise Operations
  1935. @section Bitwise Operations
  1936. @cindex bitwise operators
  1937. @cindex operators, bitwise
  1938. @cindex negation, bitwise
  1939. @cindex conjunction, bitwise
  1940. @cindex disjunction, bitwise
  1941. Bitwise operators operate on integers, treating each bit independently.
  1942. They are not allowed for floating-point types.
  1943. The examples in this section use binary constants, starting with
  1944. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1945. of type @code{int}.
  1946. @table @code
  1947. @item ~@code{a}
  1948. Unary operator for bitwise negation; this changes each bit of
  1949. @code{a} from 1 to 0 or from 0 to 1.
  1950. @example
  1951. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1952. ~0 @result{} 0b11111111111111111111111111111111
  1953. ~0b11111111111111111111111111111111 @result{} 0
  1954. ~ (-1) @result{} 0
  1955. @end example
  1956. It is useful to remember that @code{~@var{x} + 1} equals
  1957. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1958. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1959. as @var{x}.
  1960. @item @code{a} & @code{b}
  1961. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1962. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1963. @example
  1964. 0b10101010 & 0b11001100 @result{} 0b10001000
  1965. @end example
  1966. @item @code{a} | @code{b}
  1967. Binary operator for bitwise ``or'' (``inclusive or'' or
  1968. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1969. either @code{a} or @code{b}.
  1970. @example
  1971. 0b10101010 | 0b11001100 @result{} 0b11101110
  1972. @end example
  1973. @item @code{a} ^ @code{b}
  1974. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1975. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1976. @example
  1977. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1978. @end example
  1979. @end table
  1980. To understand the effect of these operators on signed integers, keep
  1981. in mind that all modern computers use two's-complement representation
  1982. (@pxref{Integer Representations}) for negative integers. This means
  1983. that the highest bit of the number indicates the sign; it is 1 for a
  1984. negative number and 0 for a positive number. In a negative number,
  1985. the value in the other bits @emph{increases} as the number gets closer
  1986. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1987. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1988. @strong{Warning:} C defines a precedence ordering for the bitwise
  1989. binary operators, but you should never rely on it. You should
  1990. never rely on how bitwise binary operators relate in precedence to the
  1991. arithmetic and shift binary operators. Other programmers don't
  1992. remember this precedence ordering, so always use parentheses to
  1993. explicitly specify the nesting.
  1994. For example, suppose @code{offset} is an integer that specifies
  1995. the offset within shared memory of a table, except that its bottom few
  1996. bits (@code{LOWBITS} says how many) are special flags. Here's
  1997. how to get just that offset and add it to the base address.
  1998. @example
  1999. shared_mem_base + (offset & (-1 << LOWBITS))
  2000. @end example
  2001. Thanks to the outer set of parentheses, we don't need to know whether
  2002. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  2003. set, we don't need to know whether @samp{&} has higher precedence than
  2004. @samp{<<}. But we can rely on all unary operators to have higher
  2005. precedence than any binary operator, so we don't need parentheses
  2006. around the left operand of @samp{<<}.
  2007. @node Assignment Expressions
  2008. @chapter Assignment Expressions
  2009. @cindex assignment expressions
  2010. @cindex operators, assignment
  2011. As a general concept in programming, an @dfn{assignment} is a
  2012. construct that stores a new value into a place where values can be
  2013. stored---for instance, in a variable. Such places are called
  2014. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  2015. An assignment in C is an expression because it has a value; we call
  2016. it an @dfn{assignment expression}. A simple assignment looks like
  2017. @example
  2018. @var{lvalue} = @var{value-to-store}
  2019. @end example
  2020. @noindent
  2021. We say it assigns the value of the expression @var{value-to-store} to
  2022. the location @var{lvalue}, or that it stores @var{value-to-store}
  2023. there. You can think of the ``l'' in ``lvalue'' as standing for
  2024. ``left,'' since that's what you put on the left side of the assignment
  2025. operator.
  2026. However, that's not the only way to use an lvalue, and not all lvalues
  2027. can be assigned to. To use the lvalue in the left side of an
  2028. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2029. not declared with the type qualifier @code{const} (@pxref{const}).
  2030. The value of the assignment expression is that of @var{lvalue} after
  2031. the new value is stored in it. This means you can use an assignment
  2032. inside other expressions. Assignment operators are right-associative
  2033. so that
  2034. @example
  2035. x = y = z = 0;
  2036. @end example
  2037. @noindent
  2038. is equivalent to
  2039. @example
  2040. x = (y = (z = 0));
  2041. @end example
  2042. This is the only useful way for them to associate;
  2043. the other way,
  2044. @example
  2045. ((x = y) = z) = 0;
  2046. @end example
  2047. @noindent
  2048. would be invalid since an assignment expression such as @code{x = y}
  2049. is not valid as an lvalue.
  2050. @strong{Warning:} Write parentheses around an assignment if you nest
  2051. it inside another expression, unless that is a conditional expression,
  2052. or comma-separated series, or another assignment.
  2053. @menu
  2054. * Simple Assignment:: The basics of storing a value.
  2055. * Lvalues:: Expressions into which a value can be stored.
  2056. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2057. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2058. an lvalue's contents.
  2059. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2060. * Assignment in Subexpressions:: How to avoid ambiguity.
  2061. * Write Assignments Separately:: Write assignments as separate statements.
  2062. @end menu
  2063. @node Simple Assignment
  2064. @section Simple Assignment
  2065. @cindex simple assignment
  2066. @cindex assignment, simple
  2067. A @dfn{simple assignment expression} computes the value of the right
  2068. operand and stores it into the lvalue on the left. Here is a simple
  2069. assignment expression that stores 5 in @code{i}:
  2070. @example
  2071. i = 5
  2072. @end example
  2073. @noindent
  2074. We say that this is an @dfn{assignment to} the variable @code{i} and
  2075. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2076. because it is an expression (so it has a value). Adding a semicolon
  2077. at the end would make it a statement (@pxref{Expression Statement}).
  2078. Here is another example of a simple assignment expression. Its
  2079. operands are not simple, but the kind of assignment done here is
  2080. simple assignment.
  2081. @example
  2082. x[foo ()] = y + 6
  2083. @end example
  2084. A simple assignment with two different numeric data types converts the
  2085. right operand value to the lvalue's type, if possible. It can convert
  2086. any numeric type to any other numeric type.
  2087. Simple assignment is also allowed on some non-numeric types: pointers
  2088. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2089. unions (@pxref{Unions}).
  2090. @strong{Warning:} Assignment is not allowed on arrays because
  2091. there are no array values in C; C variables can be arrays, but these
  2092. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2093. Arrays}.
  2094. @xref{Assignment Type Conversions}, for the complete rules about data
  2095. types used in assignments.
  2096. @node Lvalues
  2097. @section Lvalues
  2098. @cindex lvalues
  2099. An expression that identifies a memory space that holds a value is
  2100. called an @dfn{lvalue}, because it is a location that can hold a value.
  2101. The standard kinds of lvalues are:
  2102. @itemize @bullet
  2103. @item
  2104. A variable.
  2105. @item
  2106. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2107. unary @samp{*}.
  2108. @item
  2109. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2110. the structure value is an lvalue.
  2111. @item
  2112. A structure field reference using @samp{->}. This is always an lvalue
  2113. since @samp{->} implies pointer dereference.
  2114. @item
  2115. A union alternative reference (@pxref{Unions}), on the same conditions
  2116. as for structure fields.
  2117. @item
  2118. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2119. is an lvalue.
  2120. @end itemize
  2121. If an expression's outermost operation is any other operator, that
  2122. expression is not an lvalue. Thus, the variable @code{x} is an
  2123. lvalue, but @code{x + 0} is not, even though these two expressions
  2124. compute the same value (assuming @code{x} is a number).
  2125. An array can be an lvalue (the rules above determine whether it is
  2126. one), but using the array in an expression converts it automatically
  2127. to a pointer to the first element. The result of this conversion is
  2128. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2129. use @code{a} by itself as the left operand of an assignment. But you
  2130. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2131. lvalue since @code{a} is an lvalue.
  2132. @node Modifying Assignment
  2133. @section Modifying Assignment
  2134. @cindex modifying assignment
  2135. @cindex assignment, modifying
  2136. You can abbreviate the common construct
  2137. @example
  2138. @var{lvalue} = @var{lvalue} + @var{expression}
  2139. @end example
  2140. @noindent
  2141. as
  2142. @example
  2143. @var{lvalue} += @var{expression}
  2144. @end example
  2145. This is known as a @dfn{modifying assignment}. For instance,
  2146. @example
  2147. i = i + 5;
  2148. i += 5;
  2149. @end example
  2150. @noindent
  2151. shows two statements that are equivalent. The first uses
  2152. simple assignment; the second uses modifying assignment.
  2153. Modifying assignment works with any binary arithmetic operator. For
  2154. instance, you can subtract something from an lvalue like this,
  2155. @example
  2156. @var{lvalue} -= @var{expression}
  2157. @end example
  2158. @noindent
  2159. or multiply it by a certain amount like this,
  2160. @example
  2161. @var{lvalue} *= @var{expression}
  2162. @end example
  2163. @noindent
  2164. or shift it by a certain amount like this.
  2165. @example
  2166. @var{lvalue} <<= @var{expression}
  2167. @var{lvalue} >>= @var{expression}
  2168. @end example
  2169. In most cases, this feature adds no power to the language, but it
  2170. provides substantial convenience. Also, when @var{lvalue} contains
  2171. code that has side effects, the simple assignment performs those side
  2172. effects twice, while the modifying assignment performs them once. For
  2173. instance,
  2174. @example
  2175. x[foo ()] = x[foo ()] + 5;
  2176. @end example
  2177. @noindent
  2178. calls @code{foo} twice, and it could return different values each
  2179. time. If @code{foo ()} returns 1 the first time and 3 the second
  2180. time, then the effect could be to add @code{x[3]} and 5 and store the
  2181. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2182. result in @code{x[3]}. We don't know which of the two it will do,
  2183. because C does not specify which call to @code{foo} is computed first.
  2184. Such a statement is not well defined, and shouldn't be used.
  2185. By contrast,
  2186. @example
  2187. x[foo ()] += 5;
  2188. @end example
  2189. @noindent
  2190. is well defined: it calls @code{foo} only once to determine which
  2191. element of @code{x} to adjust, and it adjusts that element by adding 5
  2192. to it.
  2193. @node Increment/Decrement
  2194. @section Increment and Decrement Operators
  2195. @cindex increment operator
  2196. @cindex decrement operator
  2197. @cindex operator, increment
  2198. @cindex operator, decrement
  2199. @cindex preincrement expression
  2200. @cindex predecrement expression
  2201. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2202. @dfn{decrement} operators. When used on a numeric value, they add or
  2203. subtract 1. We don't consider them assignments, but they are
  2204. equivalent to assignments.
  2205. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2206. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2207. and the result becomes the expression's value. For instance,
  2208. @example
  2209. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2210. int
  2211. main (void)
  2212. @{
  2213. int i = 5;
  2214. printf ("%d\n", i);
  2215. printf ("%d\n", ++i);
  2216. printf ("%d\n", i);
  2217. return 0;
  2218. @}
  2219. @end example
  2220. @noindent
  2221. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2222. increments @code{i} from 5 to 6, and has the value 6, so the output
  2223. from @code{printf} on that line says @samp{6}.
  2224. Using @samp{--} instead, for predecrement,
  2225. @example
  2226. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2227. int
  2228. main (void)
  2229. @{
  2230. int i = 5;
  2231. printf ("%d\n", i);
  2232. printf ("%d\n", --i);
  2233. printf ("%d\n", i);
  2234. return 0;
  2235. @}
  2236. @end example
  2237. @noindent
  2238. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2239. again @samp{4}.
  2240. @node Postincrement/Postdecrement
  2241. @section Postincrement and Postdecrement
  2242. @cindex postincrement expression
  2243. @cindex postdecrement expression
  2244. @cindex operator, postincrement
  2245. @cindex operator, postdecrement
  2246. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2247. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2248. increments or decrements it. Thus, the value of @code{i++} is the same
  2249. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2250. little later.'' This is called @dfn{postincrement} or
  2251. @dfn{postdecrement}.
  2252. For example,
  2253. @example
  2254. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2255. int
  2256. main (void)
  2257. @{
  2258. int i = 5;
  2259. printf ("%d\n", i);
  2260. printf ("%d\n", i++);
  2261. printf ("%d\n", i);
  2262. return 0;
  2263. @}
  2264. @end example
  2265. @noindent
  2266. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2267. has the value 5, which is the value of @code{i} at the time,
  2268. but it increments @code{i} from 5 to 6 just a little later.
  2269. How much later is ``just a little later''? That is flexible. The
  2270. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2271. that means by the end of the statement. @xref{Sequence Points}.
  2272. If a unary operator precedes a postincrement or postincrement expression,
  2273. the increment nests inside:
  2274. @example
  2275. -a++ @r{is equivalent to} -(a++)
  2276. @end example
  2277. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2278. it can't be incremented.
  2279. @node Assignment in Subexpressions
  2280. @section Pitfall: Assignment in Subexpressions
  2281. @cindex assignment in subexpressions
  2282. @cindex subexpressions, assignment in
  2283. In C, the order of computing parts of an expression is not fixed.
  2284. Aside from a few special cases, the operations can be computed in any
  2285. order. If one part of the expression has an assignment to @code{x}
  2286. and another part of the expression uses @code{x}, the result is
  2287. unpredictable because that use might be computed before or after the
  2288. assignment.
  2289. Here's an example of ambiguous code:
  2290. @example
  2291. x = 20;
  2292. printf ("%d %d\n", x, x = 4);
  2293. @end example
  2294. @noindent
  2295. If the second argument, @code{x}, is computed before the third argument,
  2296. @code{x = 4}, the second argument's value will be 20. If they are
  2297. computed in the other order, the second argument's value will be 4.
  2298. Here's one way to make that code unambiguous:
  2299. @example
  2300. y = 20;
  2301. printf ("%d %d\n", y, x = 4);
  2302. @end example
  2303. Here's another way, with the other meaning:
  2304. @example
  2305. x = 4;
  2306. printf ("%d %d\n", x, x);
  2307. @end example
  2308. This issue applies to all kinds of assignments, and to the increment
  2309. and decrement operators, which are equivalent to assignments.
  2310. @xref{Order of Execution}, for more information about this.
  2311. However, it can be useful to write assignments inside an
  2312. @code{if}-condition or @code{while}-test along with logical operators.
  2313. @xref{Logicals and Assignments}.
  2314. @node Write Assignments Separately
  2315. @section Write Assignments in Separate Statements
  2316. It is often convenient to write an assignment inside an
  2317. @code{if}-condition, but that can reduce the readability of the
  2318. program. Here's an example of what to avoid:
  2319. @example
  2320. if (x = advance (x))
  2321. @r{@dots{}}
  2322. @end example
  2323. The idea here is to advance @code{x} and test if the value is nonzero.
  2324. However, readers might miss the fact that it uses @samp{=} and not
  2325. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2326. inside a condition is a common error, so GNU C can give warnings when
  2327. @samp{=} appears in a way that suggests it's an error.
  2328. It is much clearer to write the assignment as a separate statement, like this:
  2329. @example
  2330. x = advance (x);
  2331. if (x != 0)
  2332. @r{@dots{}}
  2333. @end example
  2334. @noindent
  2335. This makes it unmistakably clear that @code{x} is assigned a new value.
  2336. Another method is to use the comma operator (@pxref{Comma Operator}),
  2337. like this:
  2338. @example
  2339. if (x = advance (x), x != 0)
  2340. @r{@dots{}}
  2341. @end example
  2342. @noindent
  2343. However, putting the assignment in a separate statement is usually clearer
  2344. unless the assignment is very short, because it reduces nesting.
  2345. @node Execution Control Expressions
  2346. @chapter Execution Control Expressions
  2347. @cindex execution control expressions
  2348. @cindex expressions, execution control
  2349. This chapter describes the C operators that combine expressions to
  2350. control which of those expressions execute, or in which order.
  2351. @menu
  2352. * Logical Operators:: Logical conjunction, disjunction, negation.
  2353. * Logicals and Comparison:: Logical operators with comparison operators.
  2354. * Logicals and Assignments:: Assignments with logical operators.
  2355. * Conditional Expression:: An if/else construct inside expressions.
  2356. * Comma Operator:: Build a sequence of subexpressions.
  2357. @end menu
  2358. @node Logical Operators
  2359. @section Logical Operators
  2360. @cindex logical operators
  2361. @cindex operators, logical
  2362. @cindex conjunction operator
  2363. @cindex disjunction operator
  2364. @cindex negation operator, logical
  2365. The @dfn{logical operators} combine truth values, which are normally
  2366. represented in C as numbers. Any expression with a numeric value is a
  2367. valid truth value: zero means false, and any other value means true.
  2368. A pointer type is also meaningful as a truth value; a null pointer
  2369. (which is zero) means false, and a non-null pointer means true
  2370. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2371. or 0 and has type @code{int} (@pxref{Integer Types}).
  2372. The logical operators are used mainly in the condition of an @code{if}
  2373. statement, or in the end test in a @code{for} statement or
  2374. @code{while} statement (@pxref{Statements}). However, they are valid
  2375. in any context where an integer-valued expression is allowed.
  2376. @table @samp
  2377. @item ! @var{exp}
  2378. Unary operator for logical ``not.'' The value is 1 (true) if
  2379. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2380. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2381. function call, you should write parentheses around it.
  2382. @item @var{left} && @var{right}
  2383. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2384. @var{right}. If both of the operands are true, the @samp{&&} expression
  2385. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2386. gives the value 0 (false). If @var{left} yields a false value,
  2387. that determines the overall result, so @var{right} is not computed.
  2388. @item @var{left} || @var{right}
  2389. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2390. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2391. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2392. gives the value 0 (false). If @var{left} yields a true value,
  2393. that determines the overall result, so @var{right} is not computed.
  2394. @end table
  2395. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2396. and @samp{||}. When you use them together, always use parentheses to
  2397. specify explicitly how they nest, as shown here:
  2398. @example
  2399. if ((r != 0 && x % r == 0)
  2400. ||
  2401. (s != 0 && x % s == 0))
  2402. @end example
  2403. @node Logicals and Comparison
  2404. @section Logical Operators and Comparisons
  2405. The most common thing to use inside the logical operators is a
  2406. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2407. precedence than comparison operators and arithmetic operators, so we
  2408. can write expressions like this without parentheses and get the
  2409. nesting that is natural: two comparison operations that must both be
  2410. true.
  2411. @example
  2412. if (r != 0 && x % r == 0)
  2413. @end example
  2414. @noindent
  2415. This example also shows how it is useful that @samp{&&} guarantees to
  2416. skip the right operand if the left one turns out false. Because of
  2417. that, this code never tries to divide by zero.
  2418. This is equivalent:
  2419. @example
  2420. if (r && x % r == 0)
  2421. @end example
  2422. @noindent
  2423. A truth value is simply a number, so using @code{r} as a truth value
  2424. tests whether it is nonzero. But @code{r}'s meaning as en expression
  2425. is not a truth value---it is a number to divide by. So it is better
  2426. style to write the explicit @code{!= 0}.
  2427. Here's another equivalent way to write it:
  2428. @example
  2429. if (!(r == 0) && x % r == 0)
  2430. @end example
  2431. @noindent
  2432. This illustrates the unary @samp{!} operator, and the need to
  2433. write parentheses around its operand.
  2434. @node Logicals and Assignments
  2435. @section Logical Operators and Assignments
  2436. There are cases where assignments nested inside the condition can
  2437. actually make a program @emph{easier} to read. Here is an example
  2438. using a hypothetical type @code{list} which represents a list; it
  2439. tests whether the list has at least two links, using hypothetical
  2440. functions, @code{nonempty} which is true if the argument is a nonempty
  2441. list, and @code{list_next} which advances from one list link to the
  2442. next. We assume that a list is never a null pointer, so that the
  2443. assignment expressions are always ``true.''
  2444. @example
  2445. if (nonempty (list)
  2446. && (temp1 = list_next (list))
  2447. && nonempty (temp1)
  2448. && (temp2 = list_next (temp1)))
  2449. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2450. @end example
  2451. @noindent
  2452. Here we take advantage of the @samp{&&} operator to avoid executing
  2453. the rest of the code if a call to @code{nonempty} returns ``false.'' The
  2454. only natural place to put the assignments is among those calls.
  2455. It would be possible to rewrite this as several statements, but that
  2456. could make it much more cumbersome. On the other hand, when the test
  2457. is even more complex than this one, splitting it into multiple
  2458. statements might be necessary for clarity.
  2459. If an empty list is a null pointer, we can dispense with calling
  2460. @code{nonempty}:
  2461. @example
  2462. if ((temp1 = list_next (list))
  2463. && (temp2 = list_next (temp1)))
  2464. @r{@dots{}}
  2465. @end example
  2466. @node Conditional Expression
  2467. @section Conditional Expression
  2468. @cindex conditional expression
  2469. @cindex expression, conditional
  2470. C has a conditional expression that selects one of two expressions
  2471. to compute and get the value from. It looks like this:
  2472. @example
  2473. @var{condition} ? @var{iftrue} : @var{iffalse}
  2474. @end example
  2475. @menu
  2476. * Conditional Rules:: Rules for the conditional operator.
  2477. * Conditional Branches:: About the two branches in a conditional.
  2478. @end menu
  2479. @node Conditional Rules
  2480. @subsection Rules for the Conditional Operator
  2481. The first operand, @var{condition}, should be a value that can be
  2482. compared with zero---a number or a pointer. If it is true (nonzero),
  2483. then the conditional expression computes @var{iftrue} and its value
  2484. becomes the value of the conditional expression. Otherwise the
  2485. conditional expression computes @var{iffalse} and its value becomes
  2486. the value of the conditional expression. The conditional expression
  2487. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2488. of them.
  2489. Here's an example: the absolute value of a number @code{x}
  2490. can be written as @code{(x >= 0 ? x : -x)}.
  2491. @strong{Warning:} The conditional expression operators have rather low
  2492. syntactic precedence. Except when the conditional expression is used
  2493. as an argument in a function call, write parentheses around it. For
  2494. clarity, always write parentheses around it if it extends across more
  2495. than one line.
  2496. Assignment operators and the comma operator (@pxref{Comma Operator})
  2497. have lower precedence than conditional expression operators, so write
  2498. parentheses around those when they appear inside a conditional
  2499. expression. @xref{Order of Execution}.
  2500. @node Conditional Branches
  2501. @subsection Conditional Operator Branches
  2502. @cindex branches of conditional expression
  2503. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2504. conditional.
  2505. The two branches should normally have the same type, but a few
  2506. exceptions are allowed. If they are both numeric types, the
  2507. conditional converts both to their common type (@pxref{Common Type}).
  2508. With pointers (@pxref{Pointers}), the two values can be pointers to
  2509. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2510. result type is a similar pointer whose target type combines all the
  2511. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2512. If one branch has type @code{void *} and the other is a pointer to an
  2513. object (not to a function), the conditional converts the @code{void *}
  2514. branch to the type of the other.
  2515. If one branch is an integer constant with value zero and the other is
  2516. a pointer, the conditional converts zero to the pointer's type.
  2517. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2518. that case, if @var{condition} is nonzero, its value becomes the value of
  2519. the conditional expression, after conversion to the common type.
  2520. Thus,
  2521. @example
  2522. x ? : y
  2523. @end example
  2524. @noindent
  2525. has the value of @code{x} if that is nonzero; otherwise, the value of
  2526. @code{y}.
  2527. @cindex side effect in ?:
  2528. @cindex ?: side effect
  2529. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2530. In that case, writing that expression twice would carry out the side
  2531. effects twice, but writing it once does them just once. For example,
  2532. if we suppose that the function @code{next_element} advances a pointer
  2533. variable to point to the next element in a list and returns the new
  2534. pointer,
  2535. @example
  2536. next_element () ? : default_pointer
  2537. @end example
  2538. @noindent
  2539. is a way to advance the pointer and use its new value if it isn't
  2540. null, but use @code{default_pointer} if that is null. We cannot do
  2541. it this way,
  2542. @example
  2543. next_element () ? next_element () : default_pointer
  2544. @end example
  2545. @noindent
  2546. because that would advance the pointer a second time.
  2547. @node Comma Operator
  2548. @section Comma Operator
  2549. @cindex comma operator
  2550. @cindex operator, comma
  2551. The comma operator stands for sequential execution of expressions.
  2552. The value of the comma expression comes from the last expression in
  2553. the sequence; the previous expressions are computed only for their
  2554. side effects. It looks like this:
  2555. @example
  2556. @var{exp1}, @var{exp2} @r{@dots{}}
  2557. @end example
  2558. @noindent
  2559. You can bundle any number of expressions together this way, by putting
  2560. commas between them.
  2561. @menu
  2562. * Uses of Comma:: When to use the comma operator.
  2563. * Clean Comma:: Clean use of the comma operator.
  2564. * Avoid Comma:: When to not use the comma operator.
  2565. @end menu
  2566. @node Uses of Comma
  2567. @subsection The Uses of the Comma Operator
  2568. With commas, you can put several expressions into a place that
  2569. requires just one expression---for example, in the header of a
  2570. @code{for} statement. This statement
  2571. @example
  2572. for (i = 0, j = 10, k = 20; i < n; i++)
  2573. @end example
  2574. @noindent
  2575. contains three assignment expressions, to initialize @code{i}, @code{j}
  2576. and @code{k}. The syntax of @code{for} requires just one expression
  2577. for initialization; to include three assignments, we use commas to
  2578. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2579. 20}. This technique is also useful in the loop-advance expression,
  2580. the last of the three inside the @code{for} parentheses.
  2581. In the @code{for} statement and the @code{while} statement
  2582. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2583. effect before the loop-exit test. For example,
  2584. @example
  2585. while (printf ("At the test, x = %d\n", x), x != 0)
  2586. @end example
  2587. @node Clean Comma
  2588. @subsection Clean Use of the Comma Operator
  2589. Always write parentheses around a series of comma operators, except
  2590. when it is at top level in an expression statement, or within the
  2591. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2592. statement (@pxref{Statements}). For instance, in
  2593. @example
  2594. for (i = 0, j = 10, k = 20; i < n; i++)
  2595. @end example
  2596. @noindent
  2597. the commas between the assignments are clear because they are between
  2598. a parenthesis and a semicolon.
  2599. The arguments in a function call are also separated by commas, but that is
  2600. not an instance of the comma operator. Note the difference between
  2601. @example
  2602. foo (4, 5, 6)
  2603. @end example
  2604. @noindent
  2605. which passes three arguments to @code{foo} and
  2606. @example
  2607. foo ((4, 5, 6))
  2608. @end example
  2609. @noindent
  2610. which uses the comma operator and passes just one argument
  2611. (with value 6).
  2612. @strong{Warning:} don't use the comma operator around an argument
  2613. of a function unless it makes the code more readable. When you do so,
  2614. don't put part of another argument on the same line. Instead, add a
  2615. line break to make the parentheses around the comma operator easier to
  2616. see, like this.
  2617. @example
  2618. foo ((mumble (x, y), frob (z)),
  2619. *p)
  2620. @end example
  2621. @node Avoid Comma
  2622. @subsection When Not to Use the Comma Operator
  2623. You can use a comma in any subexpression, but in most cases it only
  2624. makes the code confusing, and it is clearer to raise all but the last
  2625. of the comma-separated expressions to a higher level. Thus, instead
  2626. of this:
  2627. @example
  2628. x = (y += 4, 8);
  2629. @end example
  2630. @noindent
  2631. it is much clearer to write this:
  2632. @example
  2633. y += 4, x = 8;
  2634. @end example
  2635. @noindent
  2636. or this:
  2637. @example
  2638. y += 4;
  2639. x = 8;
  2640. @end example
  2641. Use commas only in the cases where there is no clearer alternative
  2642. involving multiple statements.
  2643. By contrast, don't hesitate to use commas in the expansion in a macro
  2644. definition. The trade-offs of code clarity are different in that
  2645. case, because the @emph{use} of the macro may improve overall clarity
  2646. so much that the ugliness of the macro's @emph{definition} is a small
  2647. price to pay. @xref{Macros}.
  2648. @node Binary Operator Grammar
  2649. @chapter Binary Operator Grammar
  2650. @cindex binary operator grammar
  2651. @cindex grammar, binary operator
  2652. @cindex operator precedence
  2653. @cindex precedence, operator
  2654. @cindex left-associative
  2655. @dfn{Binary operators} are those that take two operands, one
  2656. on the left and one on the right.
  2657. All the binary operators in C are syntactically left-associative.
  2658. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2659. @var{op} b) @var{op} c}}. However, the only operators you should
  2660. repeat in this way without parentheses are @samp{+}, @samp{-},
  2661. @samp{*} and @samp{/}, because those cases are clear from algebra. So
  2662. it is ok to write @code{a + b + c} or @code{a - b - c}, but never
  2663. @code{a == b == c} or @code{a % b % c}. For those operators, use
  2664. explicit parentheses to show how the operations nest.
  2665. Each C operator has a @dfn{precedence}, which is its rank in the
  2666. grammatical order of the various operators. The operators with the
  2667. highest precedence grab adjoining operands first; these expressions
  2668. then become operands for operators of lower precedence.
  2669. The precedence order of operators in C is fully specified, so any
  2670. combination of operations leads to a well-defined nesting. We state
  2671. only part of the full precedence ordering here because it is bad
  2672. practice for C code to depend on the other cases. For cases not
  2673. specified in this chapter, always use parentheses to make the nesting
  2674. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2675. remembering anything about the C precedence order beyond what's stated
  2676. here. I studied the full precedence table to write the parser, and
  2677. promptly forgot it again. If you need to look up the full precedence order
  2678. to understand some C code, fix the code with parentheses so nobody else
  2679. needs to do that.}
  2680. You can depend on this subsequence of the precedence ordering
  2681. (stated from highest precedence to lowest):
  2682. @enumerate
  2683. @item
  2684. Component access (@samp{.} and @samp{->}).
  2685. @item
  2686. Unary prefix operators.
  2687. @item
  2688. Unary postfix operators.
  2689. @item
  2690. Multiplication, division, and remainder (they have the same precedence).
  2691. @item
  2692. Addition and subtraction (they have the same precedence).
  2693. @item
  2694. Comparisons---but watch out!
  2695. @item
  2696. Logical operators @samp{&&} and @samp{||}---but watch out!
  2697. @item
  2698. Conditional expression with @samp{?} and @samp{:}.
  2699. @item
  2700. Assignments.
  2701. @item
  2702. Sequential execution (the comma operator, @samp{,}).
  2703. @end enumerate
  2704. Two of the lines in the above list say ``but watch out!'' That means
  2705. that the line covers operators with subtly different precedence.
  2706. Never depend on the grammar of C to decide how two comparisons nest;
  2707. instead, always use parentheses to specify their nesting.
  2708. You can let several @samp{&&} operators associate, or several
  2709. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2710. and @samp{||} nest with each other. @xref{Logical Operators}.
  2711. There is one other precedence ordering that code can depend on:
  2712. @enumerate
  2713. @item
  2714. Unary postfix operators.
  2715. @item
  2716. Bitwise and shift operators---but watch out!
  2717. @item
  2718. Conditional expression with @samp{?} and @samp{:}.
  2719. @end enumerate
  2720. The caveat for bitwise and shift operators is like that for logical
  2721. operators: you can let multiple uses of one bitwise operator
  2722. associate, but always use parentheses to control nesting of dissimilar
  2723. operators.
  2724. These lists do not specify any precedence ordering between the bitwise
  2725. and shift operators of the second list and the binary operators above
  2726. conditional expressions in the first list. When they come together,
  2727. parenthesize them. @xref{Bitwise Operations}.
  2728. @node Order of Execution
  2729. @chapter Order of Execution
  2730. @cindex order of execution
  2731. The order of execution of a C program is not always obvious, and not
  2732. necessarily predictable. This chapter describes what you can count on.
  2733. @menu
  2734. * Reordering of Operands:: Operations in C are not necessarily computed
  2735. in the order they are written.
  2736. * Associativity and Ordering:: Some associative operations are performed
  2737. in a particular order; others are not.
  2738. * Sequence Points:: Some guarantees about the order of operations.
  2739. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2740. * Ordering of Operands:: Evaluation order of operands
  2741. and function arguments.
  2742. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2743. only if it has no impact on program results.
  2744. @end menu
  2745. @node Reordering of Operands
  2746. @section Reordering of Operands
  2747. @cindex ordering of operands
  2748. @cindex reordering of operands
  2749. @cindex operand execution ordering
  2750. The C language does not necessarily carry out operations within an
  2751. expression in the order they appear in the code. For instance, in
  2752. this expression,
  2753. @example
  2754. foo () + bar ()
  2755. @end example
  2756. @noindent
  2757. @code{foo} might be called first or @code{bar} might be called first.
  2758. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2759. results can be unpredictable.
  2760. The unpredictable order of computation of subexpressions also makes a
  2761. difference when one of them contains an assignment. We already saw
  2762. this example of bad code,
  2763. @example
  2764. x = 20;
  2765. printf ("%d %d\n", x, x = 4);
  2766. @end example
  2767. @noindent
  2768. in which the second argument, @code{x}, has a different value
  2769. depending on whether it is computed before or after the assignment in
  2770. the third argument.
  2771. @node Associativity and Ordering
  2772. @section Associativity and Ordering
  2773. @cindex associativity and ordering
  2774. An associative binary operator, such as @code{+}, when used repeatedly
  2775. can combine any number of operands. The operands' values may be
  2776. computed in any order.
  2777. If the values are integers and overflow can be ignored, they may be
  2778. combined in any order. Thus, given four functions that return
  2779. @code{unsigned int}, calling them and adding their results as here
  2780. @example
  2781. (foo () + bar ()) + (baz () + quux ())
  2782. @end example
  2783. @noindent
  2784. may add up the results in any order.
  2785. By contrast, arithmetic on signed integers, in which overflow is significant,
  2786. is not always associative (@pxref{Integer Overflow}). Thus, the
  2787. additions must be done in the order specified, obeying parentheses and
  2788. left-association. That means computing @code{(foo () + bar ())} and
  2789. @code{(baz () + quux ())} first (in either order), then adding the
  2790. two.
  2791. The same applies to arithmetic on floating-point values, since that
  2792. too is not really associative. However, the GCC option
  2793. @option{-funsafe-math-optimizations} allows the compiler to change the
  2794. order of calculation when an associative operation (associative in
  2795. exact mathematics) combines several operands. The option takes effect
  2796. when compiling a module (@pxref{Compilation}). Changing the order
  2797. of association can enable the program to pipeline the floating point
  2798. operations.
  2799. In all these cases, the four function calls can be done in any order.
  2800. There is no right or wrong about that.
  2801. @node Sequence Points
  2802. @section Sequence Points
  2803. @cindex sequence points
  2804. @cindex full expression
  2805. There are some points in the code where C makes limited guarantees
  2806. about the order of operations. These are called @dfn{sequence
  2807. points}. Here is where they occur:
  2808. @itemize @bullet
  2809. @item
  2810. At the end of a @dfn{full expression}; that is to say, an expression
  2811. that is not part of a larger expression. All side effects specified
  2812. by that expression are carried out before execution moves
  2813. on to subsequent code.
  2814. @item
  2815. At the end of the first operand of certain operators: @samp{,},
  2816. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2817. that expression are carried out before any execution of the
  2818. next operand.
  2819. The commas that separate arguments in a function call are @emph{not}
  2820. comma operators, and they do not create sequence points. The rule
  2821. for function arguments and the rule for operands are different
  2822. (@pxref{Ordering of Operands}).
  2823. @item
  2824. Just before calling a function. All side effects specified by the
  2825. argument expressions are carried out before calling the function.
  2826. If the function to be called is not constant---that is, if it is
  2827. computed by an expression---all side effects in that expression are
  2828. carried out before calling the function.
  2829. @end itemize
  2830. The ordering imposed by a sequence point applies locally to a limited
  2831. range of code, as stated above in each case. For instance, the
  2832. ordering imposed by the comma operator does not apply to code outside
  2833. the operands of that comma operator. Thus, in this code,
  2834. @example
  2835. (x = 5, foo (x)) + x * x
  2836. @end example
  2837. @noindent
  2838. the sequence point of the comma operator orders @code{x = 5} before
  2839. @code{foo (x)}, but @code{x * x} could be computed before or after
  2840. them.
  2841. @node Postincrement and Ordering
  2842. @section Postincrement and Ordering
  2843. @cindex postincrement and ordering
  2844. @cindex ordering and postincrement
  2845. The ordering requirements for the postincrement and postdecrement
  2846. operations (@pxref{Postincrement/Postdecrement}) are loose: those side
  2847. effects must happen ``a little later,'' before the next sequence
  2848. point. That still leaves room for various orders that give different
  2849. results. In this expression,
  2850. @example
  2851. z = x++ - foo ()
  2852. @end example
  2853. @noindent
  2854. it's unpredictable whether @code{x} gets incremented before or after
  2855. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2856. it might see the old value or it might see the incremented value.
  2857. In this perverse expression,
  2858. @example
  2859. x = x++
  2860. @end example
  2861. @noindent
  2862. @code{x} will certainly be incremented but the incremented value may
  2863. be replaced with the old value. That's because the incrementation and
  2864. the assignment may occur in either oder. If the incrementation of
  2865. @code{x} occurs after the assignment to @code{x}, the incremented
  2866. value will remain in place. But if the incrementation happens first,
  2867. the assignment will put the not-yet-incremented value back into
  2868. @code{x}, so the expression as a whole will leave @code{x} unchanged.
  2869. The conclusion: @strong{avoid such expressions}. Take care, when you
  2870. use postincrement and postdecrement, that the specific expression you
  2871. use is not ambiguous as to order of execution.
  2872. @node Ordering of Operands
  2873. @section Ordering of Operands
  2874. @cindex ordering of operands
  2875. @cindex operand ordering
  2876. Operands and arguments can be computed in any order, but there are limits to
  2877. this intermixing in GNU C:
  2878. @itemize @bullet
  2879. @item
  2880. The operands of a binary arithmetic operator can be computed in either
  2881. order, but they can't be intermixed: one of them has to come first,
  2882. followed by the other. Any side effects in the operand that's computed
  2883. first are executed before the other operand is computed.
  2884. @item
  2885. That applies to assignment operators too, except that, in simple assignment,
  2886. the previous value of the left operand is unused.
  2887. @item
  2888. The arguments in a function call can be computed in any order, but
  2889. they can't be intermixed. Thus, one argument is fully computed, then
  2890. another, and so on until they have all been done. Any side effects in
  2891. one argument are executed before computation of another argument
  2892. begins.
  2893. @end itemize
  2894. These rules don't cover side effects caused by postincrement and
  2895. postdecrement operators---those can be deferred up to the next
  2896. sequence point.
  2897. If you want to get pedantic, the fact is that GCC can reorder the
  2898. computations in many other ways provided that it doesn't alter the result
  2899. of running the program. However, because it doesn't alter the result
  2900. of running the program, it is negligible, unless you are concerned
  2901. with the values in certain variables at various times as seen by other
  2902. processes. In those cases, you should use @code{volatile} to prevent
  2903. optimizations that would make them behave strangely. @xref{volatile}.
  2904. @node Optimization and Ordering
  2905. @section Optimization and Ordering
  2906. @cindex optimization and ordering
  2907. @cindex ordering and optimization
  2908. Sequence points limit the compiler's freedom to reorder operations
  2909. arbitrarily, but optimizations can still reorder them if the compiler
  2910. concludes that this won't alter the results. Thus, in this code,
  2911. @example
  2912. x++;
  2913. y = z;
  2914. x++;
  2915. @end example
  2916. @noindent
  2917. there is a sequence point after each statement, so the code is
  2918. supposed to increment @code{x} once before the assignment to @code{y}
  2919. and once after. However, incrementing @code{x} has no effect on
  2920. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2921. the code could be optimized into this:
  2922. @example
  2923. y = z;
  2924. x += 2;
  2925. @end example
  2926. Normally that has no effect except to make the program faster. But
  2927. there are special situations where it can cause trouble due to things
  2928. that the compiler cannot know about, such as shared memory. To limit
  2929. optimization in those places, use the @code{volatile} type qualifier
  2930. (@pxref{volatile}).
  2931. @node Primitive Types
  2932. @chapter Primitive Data Types
  2933. @cindex primitive types
  2934. @cindex types, primitive
  2935. This chapter describes all the primitive data types of C---that is,
  2936. all the data types that aren't built up from other types. They
  2937. include the types @code{int} and @code{double} that we've already covered.
  2938. @menu
  2939. * Integer Types:: Description of integer types.
  2940. * Floating-Point Data Types:: Description of floating-point types.
  2941. * Complex Data Types:: Description of complex number types.
  2942. * The Void Type:: A type indicating no value at all.
  2943. * Other Data Types:: A brief summary of other types.
  2944. * Type Designators:: Referring to a data type abstractly.
  2945. @end menu
  2946. These types are all made up of bytes (@pxref{Storage}).
  2947. @node Integer Types
  2948. @section Integer Data Types
  2949. @cindex integer types
  2950. @cindex types, integer
  2951. Here we describe all the integer types and their basic
  2952. characteristics. @xref{Integers in Depth}, for more information about
  2953. the bit-level integer data representations and arithmetic.
  2954. @menu
  2955. * Basic Integers:: Overview of the various kinds of integers.
  2956. * Signed and Unsigned Types:: Integers can either hold both negative and
  2957. non-negative values, or only non-negative.
  2958. * Narrow Integers:: When to use smaller integer types.
  2959. * Integer Conversion:: Casting a value from one integer type
  2960. to another.
  2961. * Boolean Type:: An integer type for boolean values.
  2962. * Integer Variations:: Sizes of integer types can vary
  2963. across platforms.
  2964. @end menu
  2965. @node Basic Integers
  2966. @subsection Basic Integers
  2967. @findex char
  2968. @findex int
  2969. @findex short int
  2970. @findex long int
  2971. @findex long long int
  2972. Integer data types in C can be signed or unsigned. An unsigned type
  2973. can represent only positive numbers and zero. A signed type can
  2974. represent both positive and negative numbers, in a range spread almost
  2975. equally on both sides of zero.
  2976. Aside from signedness, the integer data types vary in size: how many
  2977. bytes long they are. The size determines the range of integer values
  2978. the type can hold.
  2979. Here's a list of the signed integer data types, with the sizes they
  2980. have on most computers. Each has a corresponding unsigned type; see
  2981. @ref{Signed and Unsigned Types}.
  2982. @table @code
  2983. @item signed char
  2984. One byte (8 bits). This integer type is used mainly for integers that
  2985. represent characters, usually as elements of arrays or fields of other
  2986. data structures.
  2987. @item short
  2988. @itemx short int
  2989. Two bytes (16 bits).
  2990. @item int
  2991. Four bytes (32 bits).
  2992. @item long
  2993. @itemx long int
  2994. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2995. platform. Typically it is 32 bits on 32-bit computers
  2996. and 64 bits on 64-bit computers, but there are exceptions.
  2997. @item long long
  2998. @itemx long long int
  2999. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  3000. incorporated into standard C as of ISO C99.
  3001. @end table
  3002. You can omit @code{int} when you use @code{long} or @code{short}.
  3003. This is harmless and customary.
  3004. @node Signed and Unsigned Types
  3005. @subsection Signed and Unsigned Types
  3006. @cindex signed types
  3007. @cindex unsigned types
  3008. @cindex types, signed
  3009. @cindex types, unsigned
  3010. @findex signed
  3011. @findex unsigned
  3012. An unsigned integer type can represent only positive numbers and zero.
  3013. A signed type can represent both positive and negative number, in a
  3014. range spread almost equally on both sides of zero. For instance,
  3015. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  3016. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  3017. these types holds 256 different possible values, since they are both 8
  3018. bits wide.
  3019. Write @code{signed} or @code{unsigned} before the type keyword to
  3020. specify a signed or an unsigned type. However, the integer types
  3021. other than @code{char} are signed by default; with them, @code{signed}
  3022. is a no-op.
  3023. Plain @code{char} may be signed or unsigned; this depends on the
  3024. compiler, the machine in use, and its operating system.
  3025. In many programs, it makes no difference whether @code{char} is
  3026. signed. When it does matter, don't leave it to chance; write
  3027. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  3028. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  3029. Arctic Char. When my meal arrived, I noted that the chef had not
  3030. signed it. So I complained, ``This char is unsigned---I wanted a
  3031. signed char!'' Or rather, I would have said this if I had thought of
  3032. it fast enough.}
  3033. @node Narrow Integers
  3034. @subsection Narrow Integers
  3035. The types that are narrower than @code{int} are rarely used for
  3036. ordinary variables---we declare them @code{int} instead. This is
  3037. because C converts those narrower types to @code{int} for any
  3038. arithmetic. There is literally no reason to declare a local variable
  3039. @code{char}, for instance.
  3040. In particular, if the value is really a character, you should declare
  3041. the variable @code{int}. Not @code{char}! Using that narrow type can
  3042. force the compiler to truncate values for conversion, which is a
  3043. waste. Furthermore, some functions return either a character value,
  3044. or @minus{}1 for ``no character.'' Using @code{int} makes it possible
  3045. to distinguish @minus{}1 from a character by sign.
  3046. The narrow integer types are useful as parts of other objects, such as
  3047. arrays and structures. Compare these array declarations, whose sizes
  3048. on 32-bit processors are shown:
  3049. @example
  3050. signed char ac[1000]; /* @r{1000 bytes} */
  3051. short as[1000]; /* @r{2000 bytes} */
  3052. int ai[1000]; /* @r{4000 bytes} */
  3053. long long all[1000]; /* @r{8000 bytes} */
  3054. @end example
  3055. In addition, character strings must be made up of @code{char}s,
  3056. because that's what all the standard library string functions expect.
  3057. Thus, array @code{ac} could be used as a character string, but the
  3058. others could not be.
  3059. @node Integer Conversion
  3060. @subsection Conversion among Integer Types
  3061. C converts between integer types implicitly in many situations. It
  3062. converts the narrow integer types, @code{char} and @code{short}, to
  3063. @code{int} whenever they are used in arithmetic. Assigning a new
  3064. value to an integer variable (or other lvalue) converts the value to
  3065. the variable's type.
  3066. You can also convert one integer type to another explicitly with a
  3067. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3068. The process of conversion to a wider type is straightforward: the
  3069. value is unchanged. The only exception is when converting a negative
  3070. value (in a signed type, obviously) to a wider unsigned type. In that
  3071. case, the result is a positive value with the same bits
  3072. (@pxref{Integers in Depth}).
  3073. @cindex truncation
  3074. Converting to a narrower type, also called @dfn{truncation}, involves
  3075. discarding some of the value's bits. This is not considered overflow
  3076. (@pxref{Integer Overflow}) because loss of significant bits is a
  3077. normal consequence of truncation. Likewise for conversion between
  3078. signed and unsigned types of the same width.
  3079. More information about conversion for assignment is in
  3080. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3081. see @ref{Argument Promotions}.
  3082. @node Boolean Type
  3083. @subsection Boolean Type
  3084. @cindex boolean type
  3085. @cindex type, boolean
  3086. @findex bool
  3087. The unsigned integer type @code{bool} holds truth values: its possible
  3088. values are 0 and 1. Converting any nonzero value to @code{bool}
  3089. results in 1. For example:
  3090. @example
  3091. bool a = 0;
  3092. bool b = 1;
  3093. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3094. @end example
  3095. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3096. the header file @file{stdbool.h}.
  3097. @node Integer Variations
  3098. @subsection Integer Variations
  3099. The integer types of C have standard @emph{names}, but what they
  3100. @emph{mean} varies depending on the kind of platform in use:
  3101. which kind of computer, which operating system, and which compiler.
  3102. It may even depend on the compiler options used.
  3103. Plain @code{char} may be signed or unsigned; this depends on the
  3104. platform, too. Even for GNU C, there is no general rule.
  3105. In theory, all of the integer types' sizes can vary. @code{char} is
  3106. always considered one ``byte'' for C, but it is not necessarily an
  3107. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3108. specifies only that none of these types is narrower than the ones
  3109. above it in the list in @ref{Basic Integers}, and that @code{short}
  3110. has at least 16 bits.
  3111. It is possible that in the future GNU C will support platforms where
  3112. @code{int} is 64 bits long. In practice, however, on today's real
  3113. computers, there is little variation; you can rely on the table
  3114. given previously (@pxref{Basic Integers}).
  3115. To be completely sure of the size of an integer type,
  3116. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3117. Their corresponding unsigned types add @samp{u} at the front:
  3118. @code{uint16_t}, @code{uint32_t} and @code{uint64_t}.
  3119. To define all these types, include the header file @file{stdint.h}.
  3120. The GNU C Compiler can compile for some embedded controllers that use two
  3121. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3122. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3123. 32 bits. These processors can't support an ordinary operating system
  3124. (they may have their own specialized operating systems), and most C
  3125. programs do not try to support them.
  3126. @node Floating-Point Data Types
  3127. @section Floating-Point Data Types
  3128. @cindex floating-point types
  3129. @cindex types, floating-point
  3130. @findex double
  3131. @findex float
  3132. @findex long double
  3133. @dfn{Floating point} is the binary analogue of scientific notation:
  3134. internally it represents a number as a fraction and a binary exponent;
  3135. the value is that fraction multiplied by the specified power of 2.
  3136. (The C standard nominally permits other bases, but in GNU C the base
  3137. is always 2.)
  3138. @c ???
  3139. For instance, to represent 6, the fraction would be 0.75 and the
  3140. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3141. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3142. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3143. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3144. @minus{}1 as the exponent.
  3145. These binary exponents are used by machine instructions. You can
  3146. write a floating-point constant this way if you wish, using
  3147. hexadecimal; but normally we write floating-point numbers in decimal (base 10).
  3148. @xref{Floating Constants}.
  3149. C has three floating-point data types:
  3150. @table @code
  3151. @item double
  3152. ``Double-precision'' floating point, which uses 64 bits. This is the
  3153. normal floating-point type, and modern computers normally do
  3154. their floating-point computations in this type, or some wider type.
  3155. Except when there is a special reason to do otherwise, this is the
  3156. type to use for floating-point values.
  3157. @item float
  3158. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3159. for floating-point values stored in structures and arrays, to save
  3160. space when the full precision of @code{double} is not needed. In
  3161. addition, single-precision arithmetic is faster on some computers, and
  3162. occasionally that is useful. But not often---most programs don't use
  3163. the type @code{float}.
  3164. C would be cleaner if @code{float} were the name of the type we
  3165. use for most floating-point values; however, for historical reasons,
  3166. that's not so.
  3167. @item long double
  3168. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3169. precision, depending on the machine in use. On some machines, which
  3170. have no floating-point format wider than @code{double}, this is
  3171. equivalent to @code{double}.
  3172. @end table
  3173. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3174. Point in Depth}, for more information.
  3175. @node Complex Data Types
  3176. @section Complex Data Types
  3177. @cindex complex numbers
  3178. @cindex types, complex
  3179. @cindex @code{_Complex} keyword
  3180. @cindex @code{__complex__} keyword
  3181. @findex _Complex
  3182. @findex __complex__
  3183. Complex numbers can include both a real part and an imaginary part.
  3184. The numeric constants covered above have real-numbered values. An
  3185. imaginary-valued constant is an ordinary real-valued constant followed
  3186. by @samp{i}.
  3187. To declare numeric variables as complex, use the @code{_Complex}
  3188. keyword.@footnote{For compatibility with older versions of GNU C, the
  3189. keyword @code{__complex__} is also allowed. Going forward, however,
  3190. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3191. standard C complex data types are floating point,
  3192. @example
  3193. _Complex float foo;
  3194. _Complex double bar;
  3195. _Complex long double quux;
  3196. @end example
  3197. @noindent
  3198. but GNU C supports integer complex types as well.
  3199. Since @code{_Complex} is a keyword just like @code{float} and
  3200. @code{double} and @code{long}, the keywords can appear in any order,
  3201. but the order shown above seems most logical.
  3202. GNU C supports constants for complex values; for instance, @code{4.0 +
  3203. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3204. @xref{Imaginary Constants}.
  3205. To pull the real and imaginary parts of the number back out, GNU C
  3206. provides the keywords @code{__real__} and @code{__imag__}:
  3207. @example
  3208. _Complex double foo = 4.0 + 3.0i;
  3209. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3210. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3211. @end example
  3212. @noindent
  3213. Standard C does not include these keywords, and instead relies on
  3214. functions defined in @code{complex.h} for accessing the real and
  3215. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3216. @code{creall} extract the real part of a float, double, or long double
  3217. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3218. @code{cimagl} extract the imaginary part.
  3219. @cindex complex conjugation
  3220. GNU C also defines @samp{~} as an operator for complex conjugation,
  3221. which means negating the imaginary part of a complex number:
  3222. @example
  3223. _Complex double foo = 4.0 + 3.0i;
  3224. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3225. @end example
  3226. @noindent
  3227. For standard C compatibility, you can use the appropriate library
  3228. function: @code{conjf}, @code{conj}, or @code{confl}.
  3229. @node The Void Type
  3230. @section The Void Type
  3231. @cindex void type
  3232. @cindex type, void
  3233. @findex void
  3234. The data type @code{void} is a dummy---it allows no operations. It
  3235. really means ``no value at all.'' When a function is meant to return
  3236. no value, we write @code{void} for its return type. Then
  3237. @code{return} statements in that function should not specify a value
  3238. (@pxref{return Statement}). Here's an example:
  3239. @example
  3240. void
  3241. print_if_positive (double x, double y)
  3242. @{
  3243. if (x <= 0)
  3244. return;
  3245. if (y <= 0)
  3246. return;
  3247. printf ("Next point is (%f,%f)\n", x, y);
  3248. @}
  3249. @end example
  3250. A @code{void}-returning function is comparable to what some other
  3251. languages (for instance, Fortran and Pascal) call a ``procedure''
  3252. instead of a ``function.''
  3253. @c ??? Already presented
  3254. @c @samp{%f} in an output template specifies to format a @code{double} value
  3255. @c as a decimal number, using a decimal point if needed.
  3256. @node Other Data Types
  3257. @section Other Data Types
  3258. Beyond the primitive types, C provides several ways to construct new
  3259. data types. For instance, you can define @dfn{pointers}, values that
  3260. represent the addresses of other data (@pxref{Pointers}). You can
  3261. define @dfn{structures}, as in many other languages
  3262. (@pxref{Structures}), and @dfn{unions}, which define multiple ways to
  3263. interpret the contents of the same memory space (@pxref{Unions}).
  3264. @dfn{Enumerations} are collections of named integer codes
  3265. (@pxref{Enumeration Types}).
  3266. @dfn{Array types} in C are used for allocating space for objects,
  3267. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3268. @node Type Designators
  3269. @section Type Designators
  3270. @cindex type designator
  3271. Some C constructs require a way to designate a specific data type
  3272. independent of any particular variable or expression which has that
  3273. type. The way to do this is with a @dfn{type designator}. The
  3274. constructs that need one include casts (@pxref{Explicit Type
  3275. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3276. We also use type designators to talk about the type of a value in C,
  3277. so you will see many type designators in this manual. When we say,
  3278. ``The value has type @code{int},'' @code{int} is a type designator.
  3279. To make the designator for any type, imagine a variable declaration
  3280. for a variable of that type and delete the variable name and the final
  3281. semicolon.
  3282. For example, to designate the type of full-word integers, we start
  3283. with the declaration for a variable @code{foo} with that type,
  3284. which is this:
  3285. @example
  3286. int foo;
  3287. @end example
  3288. @noindent
  3289. Then we delete the variable name @code{foo} and the semicolon, leaving
  3290. @code{int}---exactly the keyword used in such a declaration.
  3291. Therefore, the type designator for this type is @code{int}.
  3292. What about long unsigned integers? From the declaration
  3293. @example
  3294. unsigned long int foo;
  3295. @end example
  3296. @noindent
  3297. we determine that the designator is @code{unsigned long int}.
  3298. Following this procedure, the designator for any primitive type is
  3299. simply the set of keywords which specifies that type in a declaration.
  3300. The same is true for compound types such as structures, unions, and
  3301. enumerations.
  3302. Designators for pointer types do follow the rule of deleting the
  3303. variable name and semicolon, but the result is not so simple.
  3304. @xref{Pointer Type Designators}, as part of the chapter about
  3305. pointers. @xref{Array Type Designators}), for designators for array
  3306. types.
  3307. To understand what type a designator stands for, imagine a variable
  3308. name inserted into the right place in the designator to make a valid
  3309. declaration. What type would that variable be declared as? That is the
  3310. type the designator designates.
  3311. @node Constants
  3312. @chapter Constants
  3313. @cindex constants
  3314. A @dfn{constant} is an expression that stands for a specific value by
  3315. explicitly representing the desired value. C allows constants for
  3316. numbers, characters, and strings. We have already seen numeric and
  3317. string constants in the examples.
  3318. @menu
  3319. * Integer Constants:: Literal integer values.
  3320. * Integer Const Type:: Types of literal integer values.
  3321. * Floating Constants:: Literal floating-point values.
  3322. * Imaginary Constants:: Literal imaginary number values.
  3323. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3324. * Character Constants:: Literal character values.
  3325. * String Constants:: Literal string values.
  3326. * UTF-8 String Constants:: Literal UTF-8 string values.
  3327. * Unicode Character Codes:: Unicode characters represented
  3328. in either UTF-16 or UTF-32.
  3329. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3330. * Wide String Constants:: Literal string values made up of
  3331. 16- or 32-bit characters.
  3332. @end menu
  3333. @node Integer Constants
  3334. @section Integer Constants
  3335. @cindex integer constants
  3336. @cindex constants, integer
  3337. An integer constant consists of a number to specify the value,
  3338. followed optionally by suffix letters to specify the data type.
  3339. The simplest integer constants are numbers written in base 10
  3340. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3341. constant cannot start with the character @samp{0} (zero) because
  3342. that makes the constant octal.
  3343. You can get the effect of a negative integer constant by putting a
  3344. minus sign at the beginning. In grammatical terms, that is an
  3345. arithmetic expression rather than a constant, but it behaves just like
  3346. a true constant.
  3347. Integer constants can also be written in octal (base 8), hexadecimal
  3348. (base 16), or binary (base 2). An octal constant starts with the
  3349. character @samp{0} (zero), followed by any number of octal digits
  3350. (@samp{0} to @samp{7}):
  3351. @example
  3352. 0 // @r{zero}
  3353. 077 // @r{63}
  3354. 0403 // @r{259}
  3355. @end example
  3356. @noindent
  3357. Pedantically speaking, the constant @code{0} is an octal constant, but
  3358. we can think of it as decimal; it has the same value either way.
  3359. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3360. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3361. through @samp{f} in upper or lower case):
  3362. @example
  3363. 0xff // @r{255}
  3364. 0XA0 // @r{160}
  3365. 0xffFF // @r{65535}
  3366. @end example
  3367. @cindex binary integer constants
  3368. A binary constant starts with @samp{0b} (upper or lower case) followed
  3369. by bits (each represented by the characters @samp{0} or @samp{1}):
  3370. @example
  3371. 0b101 // @r{5}
  3372. @end example
  3373. @noindent
  3374. Binary constants are a GNU C extension, not part of the C standard.
  3375. Sometimes a space is needed after an integer constant to avoid
  3376. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3377. @node Integer Const Type
  3378. @section Integer Constant Data Types
  3379. @cindex integer constant data types
  3380. @cindex constant data types, integer
  3381. @cindex types of integer constants
  3382. The type of an integer constant is normally @code{int}, if the value
  3383. fits in that type, but here are the complete rules. The type
  3384. of an integer constant is the first one in this sequence that can
  3385. properly represent the value,
  3386. @enumerate
  3387. @item
  3388. @code{int}
  3389. @item
  3390. @code{unsigned int}
  3391. @item
  3392. @code{long int}
  3393. @item
  3394. @code{unsigned long int}
  3395. @item
  3396. @code{long long int}
  3397. @item
  3398. @code{unsigned long long int}
  3399. @end enumerate
  3400. @noindent
  3401. and that isn't excluded by the following rules.
  3402. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3403. first two types (non-@code{long}).
  3404. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3405. first four types (non-@code{long long}).
  3406. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3407. the signed types.
  3408. Otherwise, if the constant is decimal (not binary, octal, or
  3409. hexadecimal), that excludes the unsigned types.
  3410. @c ### This said @code{unsigned int} is excluded.
  3411. @c ### See 17 April 2016
  3412. Here are some examples of the suffixes.
  3413. @example
  3414. 3000000000u // @r{three billion as @code{unsigned int}.}
  3415. 0LL // @r{zero as a @code{long long int}.}
  3416. 0403l // @r{259 as a @code{long int}.}
  3417. @end example
  3418. Suffixes in integer constants are rarely used. When the precise type
  3419. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3420. Type Conversion}).
  3421. @xref{Integer Types}.
  3422. @node Floating Constants
  3423. @section Floating-Point Constants
  3424. @cindex floating-point constants
  3425. @cindex constants, floating-point
  3426. A floating-point constant must have either a decimal point, an
  3427. exponent-of-ten, or both; they distinguish it from an integer
  3428. constant.
  3429. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3430. value follows. It is always written as a decimal number; it can
  3431. optionally start with a sign. The exponent @var{n} means to multiply
  3432. the constant's value by ten to the @var{n}th power.
  3433. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3434. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3435. writing a floating-point number whose value is 1500. They are all
  3436. equivalent.
  3437. Here are more examples with decimal points:
  3438. @example
  3439. 1.0
  3440. 1000.
  3441. 3.14159
  3442. .05
  3443. .0005
  3444. @end example
  3445. For each of them, here are some equivalent constants written with
  3446. exponents:
  3447. @example
  3448. 1e0, 1.0000e0
  3449. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3450. 3.14159e0
  3451. 5e-2, .0005e+2, 5E-2, .0005E2
  3452. .05e-2
  3453. @end example
  3454. A floating-point constant normally has type @code{double}. You can
  3455. force it to type @code{float} by adding @samp{f} or @samp{F}
  3456. at the end. For example,
  3457. @example
  3458. 3.14159f
  3459. 3.14159e0f
  3460. 1000.f
  3461. 100E1F
  3462. .0005f
  3463. .05e-2f
  3464. @end example
  3465. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3466. to type @code{long double}.
  3467. You can use exponents in hexadecimal floating constants, but since
  3468. @samp{e} would be interpreted as a hexadecimal digit, the character
  3469. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3470. The exponent in a hexadecimal floating constant is an optionally signed
  3471. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3472. multiply into the number.
  3473. Here are some examples:
  3474. @example
  3475. @group
  3476. 0xAp2 // @r{40 in decimal}
  3477. 0xAp-1 // @r{5 in decimal}
  3478. 0x2.0Bp4 // @r{16.75 decimal}
  3479. 0xE.2p3 // @r{121 decimal}
  3480. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3481. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3482. 0x100p-8 // @r{1}
  3483. 0x10p-4 // @r{1}
  3484. 0x1p+4 // @r{16}
  3485. 0x1p+8 // @r{256}
  3486. @end group
  3487. @end example
  3488. @xref{Floating-Point Data Types}.
  3489. @node Imaginary Constants
  3490. @section Imaginary Constants
  3491. @cindex imaginary constants
  3492. @cindex complex constants
  3493. @cindex constants, imaginary
  3494. A complex number consists of a real part plus an imaginary part. (You
  3495. may omit one part if it is zero.) This section explains how to write
  3496. numeric constants with imaginary values. By adding these to ordinary
  3497. real-valued numeric constants, we can make constants with complex
  3498. values.
  3499. The simple way to write an imaginary-number constant is to attach the
  3500. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3501. floating-point constant. For example, @code{2.5fi} has type
  3502. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3503. The four alternative suffix letters are all equivalent.
  3504. @cindex _Complex_I
  3505. The other way to write an imaginary constant is to multiply a real
  3506. constant by @code{_Complex_I}, which represents the imaginary number
  3507. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3508. this clunky method is needed.
  3509. To write a complex constant with a nonzero real part and a nonzero
  3510. imaginary part, write the two separately and add them, like this:
  3511. @example
  3512. 4.0 + 3.0i
  3513. @end example
  3514. @noindent
  3515. That gives the value 4 + 3i, with type @code{_Complex double}.
  3516. Such a sum can include multiple real constants, or none. Likewise, it
  3517. can include multiple imaginary constants, or none. For example:
  3518. @example
  3519. _Complex double foo, bar, quux;
  3520. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3521. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3522. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3523. @end example
  3524. @xref{Complex Data Types}.
  3525. @node Invalid Numbers
  3526. @section Invalid Numbers
  3527. Some number-like constructs which are not really valid as numeric
  3528. constants are treated as numbers in preprocessing directives. If
  3529. these constructs appear outside of preprocessing, they are erroneous.
  3530. @xref{Preprocessing Tokens}.
  3531. Sometimes we need to insert spaces to separate tokens so that they
  3532. won't be combined into a single number-like construct. For example,
  3533. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3534. constant, so it is a syntax error. If what we want is the three
  3535. tokens @code{@w{0xE + 12}}, we have to insert two spaces as separators.
  3536. @node Character Constants
  3537. @section Character Constants
  3538. @cindex character constants
  3539. @cindex constants, character
  3540. @cindex escape sequence
  3541. A @dfn{character constant} is written with single quotes, as in
  3542. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3543. character that the constant should represent. The constant has type
  3544. @code{int}, and its value is the character code of that character.
  3545. For instance, @code{'a'} represents the character code for the letter
  3546. @samp{a}: 97, that is.
  3547. To put the @samp{'} character (single quote) in the character
  3548. constant, @dfn{escape} it with a backslash (@samp{\}). This character
  3549. constant looks like @code{'\''}. The backslash character here
  3550. functions as an @dfn{escape character}, and such a sequence,
  3551. starting with @samp{\}, is called an @dfn{escape sequence}.
  3552. To put the @samp{\} character (backslash) in the character constant,
  3553. escape it with @samp{\} (another backslash). This character
  3554. constant looks like @code{'\\'}.
  3555. @cindex bell character
  3556. @cindex @samp{\a}
  3557. @cindex backspace
  3558. @cindex @samp{\b}
  3559. @cindex tab (ASCII character)
  3560. @cindex @samp{\t}
  3561. @cindex vertical tab
  3562. @cindex @samp{\v}
  3563. @cindex formfeed
  3564. @cindex @samp{\f}
  3565. @cindex newline
  3566. @cindex @samp{\n}
  3567. @cindex return (ASCII character)
  3568. @cindex @samp{\r}
  3569. @cindex escape (ASCII character)
  3570. @cindex @samp{\e}
  3571. Here are all the escape sequences that represent specific
  3572. characters in a character constant. The numeric values shown are
  3573. the corresponding ASCII character codes, as decimal numbers.
  3574. @example
  3575. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3576. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3577. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3578. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3579. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3580. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3581. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3582. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3583. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3584. '\'' @result{} 39 /* @r{single quote character, @kbd{'}} */
  3585. '\"' @result{} 34 /* @r{double quote character, @kbd{"}} */
  3586. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3587. @end example
  3588. @samp{\e} is a GNU C extension; to stick to standard C, write
  3589. @samp{\33}. (The number after @samp{backslash} is octal.) To specify
  3590. a character constant using decimal, use a cast; for instance,
  3591. @code{(unsigned char) 27}.
  3592. You can also write octal and hex character codes as
  3593. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3594. option here, so octal codes do not need to start with @samp{0}.
  3595. The character constant's value has type @code{int}. However, the
  3596. character code is treated initially as a @code{char} value, which is
  3597. then converted to @code{int}. If the character code is greater than
  3598. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3599. on a platform where the type @code{char} is 8 bits long and signed.
  3600. @node String Constants
  3601. @section String Constants
  3602. @cindex string constants
  3603. @cindex constants, string
  3604. A @dfn{string constant} represents a series of characters. It starts
  3605. with @samp{"} and ends with @samp{"}; in between are the contents of
  3606. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3607. newline in the contents works in string constants as in character
  3608. constants. In a string constant, @samp{'} does not need to be quoted.
  3609. A string constant defines an array of characters which contains the
  3610. specified characters followed by the null character (code 0). Using
  3611. the string constant is equivalent to using the name of an array with
  3612. those contents. In simple cases, where there are no backslash escape
  3613. sequences, the length in bytes of the string constant is one greater
  3614. than the number of characters written in it.
  3615. As with any array in C, using the string constant in an expression
  3616. converts the array to a pointer (@pxref{Pointers}) to the array's
  3617. first element (@pxref{Accessing Array Elements}). This pointer will
  3618. have type @code{char *} because it points to an element of type
  3619. @code{char}. @code{char *} is an example of a type designator for a
  3620. pointer type (@pxref{Pointer Type Designators}). That type is used
  3621. for strings generally, not just the strings expressed as constants
  3622. in a program.
  3623. Thus, the string constant @code{"Foo!"} is almost
  3624. equivalent to declaring an array like this
  3625. @example
  3626. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3627. @end example
  3628. @noindent
  3629. and then using @code{string_array_1} in the program. There
  3630. are two differences, however:
  3631. @itemize @bullet
  3632. @item
  3633. The string constant doesn't define a name for the array.
  3634. @item
  3635. The string constant is probably stored in a read-only area of memory.
  3636. @end itemize
  3637. Newlines are not allowed in the text of a string constant. The motive
  3638. for this prohibition is to catch the error of omitting the closing
  3639. @samp{"}. To put a newline in a constant string, write it as
  3640. @samp{\n} in the string constant.
  3641. A real null character in the source code inside a string constant
  3642. causes a warning. To put a null character in the middle of a string
  3643. constant, write @samp{\0} or @samp{\000}.
  3644. Consecutive string constants are effectively concatenated. Thus,
  3645. @example
  3646. "Fo" "o!" @r{is equivalent to} "Foo!"
  3647. @end example
  3648. This is useful for writing a string containing multiple lines,
  3649. like this:
  3650. @example
  3651. "This message is so long that it needs more than\n"
  3652. "a single line of text. C does not allow a newline\n"
  3653. "to represent itself in a string constant, so we have to\n"
  3654. "write \\n to put it in the string. For readability of\n"
  3655. "the source code, it is advisable to put line breaks in\n"
  3656. "the source where they occur in the contents of the\n"
  3657. "constant.\n"
  3658. @end example
  3659. The sequence of a backslash and a newline is ignored anywhere
  3660. in a C program, and that includes inside a string constant.
  3661. Thus, you can write multi-line string constants this way:
  3662. @example
  3663. "This is another way to put newlines in a string constant\n\
  3664. and break the line after them in the source code."
  3665. @end example
  3666. @noindent
  3667. However, concatenation is the recommended way to do this.
  3668. You can also write perverse string constants like this,
  3669. @example
  3670. "Fo\
  3671. o!"
  3672. @end example
  3673. @noindent
  3674. but don't do that---write it like this instead:
  3675. @example
  3676. "Foo!"
  3677. @end example
  3678. Be careful to avoid passing a string constant to a function that
  3679. modifies the string it receives. The memory where the string constant
  3680. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3681. signal that normally terminates the function (@pxref{Signals}. Even
  3682. worse, the memory may not be read-only. Then the function might
  3683. modify the string constant, thus spoiling the contents of other string
  3684. constants that are supposed to contain the same value and are unified
  3685. by the compiler.
  3686. @node UTF-8 String Constants
  3687. @section UTF-8 String Constants
  3688. @cindex UTF-8 String Constants
  3689. Writing @samp{u8} immediately before a string constant, with no
  3690. intervening space, means to represent that string in UTF-8 encoding as
  3691. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3692. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3693. as multibyte sequences. Here is an example of a UTF-8 constant:
  3694. @example
  3695. u8"A cónstàñt"
  3696. @end example
  3697. This constant occupies 13 bytes plus the terminating null,
  3698. because each of the accented letters is a two-byte sequence.
  3699. Concatenating an ordinary string with a UTF-8 string conceptually
  3700. produces another UTF-8 string. However, if the ordinary string
  3701. contains character codes 128 and up, the results cannot be relied on.
  3702. @node Unicode Character Codes
  3703. @section Unicode Character Codes
  3704. @cindex Unicode character codes
  3705. @cindex universal character names
  3706. You can specify Unicode characters, for individual character constants
  3707. or as part of string constants (@pxref{String Constants}), using
  3708. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3709. hexadecimal Unicode character code. If the code value is too big for
  3710. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3711. Unicode character code. (These codes are called @dfn{universal
  3712. character names}.) For example,
  3713. @example
  3714. \u6C34 /* @r{16-bit code (UTF-16)} */
  3715. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3716. @end example
  3717. @noindent
  3718. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3719. Constants}). For instance,
  3720. @example
  3721. u8"fóó \u6C34 \U0010ABCD"
  3722. @end example
  3723. You can also use them in wide character constants (@pxref{Wide
  3724. Character Constants}), like this:
  3725. @example
  3726. u'\u6C34' /* @r{16-bit code} */
  3727. U'\U0010ABCD' /* @r{32-bit code} */
  3728. @end example
  3729. @noindent
  3730. and in wide string constants (@pxref{Wide String Constants}), like
  3731. this:
  3732. @example
  3733. u"\u6C34\u6C33" /* @r{16-bit code} */
  3734. U"\U0010ABCD" /* @r{32-bit code} */
  3735. @end example
  3736. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3737. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3738. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3739. actually ASCII control characters, and you can specify them with other
  3740. escape sequences (@pxref{Character Constants}).
  3741. @node Wide Character Constants
  3742. @section Wide Character Constants
  3743. @cindex wide character constants
  3744. @cindex constants, wide character
  3745. A @dfn{wide character constant} represents characters with more than 8
  3746. bits of character code. This is an obscure feature that we need to
  3747. document but that you probably won't ever use. If you're just
  3748. learning C, you may as well skip this section.
  3749. The original C wide character constant looks like @samp{L} (upper
  3750. case!) followed immediately by an ordinary character constant (with no
  3751. intervening space). Its data type is @code{wchar_t}, which is an
  3752. alias defined in @file{stddef.h} for one of the standard integer
  3753. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3754. it is 16 bits, these character constants use the UTF-16 form of
  3755. Unicode; if 32 bits, UTF-32.
  3756. There are also Unicode wide character constants which explicitly
  3757. specify the width. These constants start with @samp{u} or @samp{U}
  3758. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3759. character constant, and @samp{U} a 32-bit Unicode wide character
  3760. constant. Their types are, respectively, @code{char16_t} and
  3761. @w{@code{char32_t}}; they are declared in the header file
  3762. @file{uchar.h}. These character constants are valid even if
  3763. @file{uchar.h} is not included, but some uses of them may be
  3764. inconvenient without including it to declare those type names.
  3765. The character represented in a wide character constant can be an
  3766. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3767. are all valid, and they are all equal to @code{'a'}.
  3768. In all three kinds of wide character constants, you can write a
  3769. non-ASCII Unicode character in the constant itself; the constant's
  3770. value is the character's Unicode character code. Or you can specify
  3771. the Unicode character with an escape sequence (@pxref{Unicode
  3772. Character Codes}).
  3773. @node Wide String Constants
  3774. @section Wide String Constants
  3775. @cindex wide string constants
  3776. @cindex constants, wide string
  3777. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3778. characters. They are rarely used; if you're just
  3779. learning C, you may as well skip this section.
  3780. There are three kinds of wide string constants, which differ in the
  3781. data type used for each character in the string. Each wide string
  3782. constant is equivalent to an array of integers, but the data type of
  3783. those integers depends on the kind of wide string. Using the constant
  3784. in an expression will convert the array to a pointer to its first
  3785. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3786. For each kind of wide string constant, we state here what type that
  3787. pointer will be.
  3788. @table @code
  3789. @item char16_t
  3790. This is a 16-bit Unicode wide string constant: each element is a
  3791. 16-bit Unicode character code with type @code{char16_t}, so the string
  3792. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3793. @pxref{Pointer Type Designators}.) The constant is written as
  3794. @samp{u} (which must be lower case) followed (with no intervening
  3795. space) by a string constant with the usual syntax.
  3796. @item char32_t
  3797. This is a 32-bit Unicode wide string constant: each element is a
  3798. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3799. It's written as @samp{U} (which must be upper case) followed (with no
  3800. intervening space) by a string constant with the usual syntax.
  3801. @item wchar_t
  3802. This is the original kind of wide string constant. It's written as
  3803. @samp{L} (which must be upper case) followed (with no intervening
  3804. space) by a string constant with the usual syntax, and the string has
  3805. type @code{wchar_t@ *}.
  3806. The width of the data type @code{wchar_t} depends on the target
  3807. platform, which makes this kind of wide string somewhat less useful
  3808. than the newer kinds.
  3809. @end table
  3810. @code{char16_t} and @code{char32_t} are declared in the header file
  3811. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3812. Consecutive wide string constants of the same kind concatenate, just
  3813. like ordinary string constants. A wide string constant concatenated
  3814. with an ordinary string constant results in a wide string constant.
  3815. You can't concatenate two wide string constants of different kinds.
  3816. In addition, you can't concatenate a wide string constant (of any
  3817. kind) with a UTF-8 string constant.
  3818. @node Type Size
  3819. @chapter Type Size
  3820. @cindex type size
  3821. @cindex size of type
  3822. @findex sizeof
  3823. Each data type has a @dfn{size}, which is the number of bytes
  3824. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3825. a C program, use @code{sizeof}. There are two ways to use it:
  3826. @table @code
  3827. @item sizeof @var{expression}
  3828. This gives the size of @var{expression}, based on its data type. It
  3829. does not calculate the value of @var{expression}, only its size, so if
  3830. @var{expression} includes side effects or function calls, they do not
  3831. happen. Therefore, @code{sizeof} is always a compile-time operation
  3832. that has zero run-time cost.
  3833. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3834. operand of @code{sizeof}.
  3835. For example,
  3836. @example
  3837. double a;
  3838. i = sizeof a + 10;
  3839. @end example
  3840. @noindent
  3841. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3842. Here's how to determine the number of elements in an array
  3843. @code{array}:
  3844. @example
  3845. (sizeof array / sizeof array[0])
  3846. @end example
  3847. @noindent
  3848. The expression @code{sizeof array} gives the size of the array, not
  3849. the size of a pointer to an element. However, if @var{expression} is
  3850. a function parameter that was declared as an array, that
  3851. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3852. the result is the size of that pointer.
  3853. @item sizeof (@var{type})
  3854. This gives the size of @var{type}.
  3855. For example,
  3856. @example
  3857. i = sizeof (double) + 10;
  3858. @end example
  3859. @noindent
  3860. is equivalent to the previous example.
  3861. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3862. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3863. C, which makes adding an integer to a function pointer work as desired
  3864. (@pxref{Pointer Arithmetic}).
  3865. @end table
  3866. @strong{Warning}: When you use @code{sizeof} with a type
  3867. instead of an expression, you must write parentheses around the type.
  3868. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3869. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3870. the cast expression to avoid an ambiguity in the grammar of C@.
  3871. Specifically,
  3872. @example
  3873. sizeof (int) -x
  3874. @end example
  3875. @noindent
  3876. parses as
  3877. @example
  3878. (sizeof (int)) - x
  3879. @end example
  3880. @noindent
  3881. If what you want is
  3882. @example
  3883. sizeof ((int) -x)
  3884. @end example
  3885. @noindent
  3886. you must write it that way, with parentheses.
  3887. The data type of the value of the @code{sizeof} operator is always one
  3888. of the unsigned integer types; which one of those types depends on the
  3889. machine. The header file @code{stddef.h} defines the typedef name
  3890. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3891. Names}.
  3892. @node Pointers
  3893. @chapter Pointers
  3894. @cindex pointers
  3895. Among high-level languages, C is rather low level, close to the
  3896. machine. This is mainly because it has explicit @dfn{pointers}. A
  3897. pointer value is the numeric address of data in memory. The type of
  3898. data to be found at that address is specified by the data type of the
  3899. pointer itself. The unary operator @samp{*} gets the data that a
  3900. pointer points to---this is called @dfn{dereferencing the pointer}.
  3901. C also allows pointers to functions, but since there are some
  3902. differences in how they work, we treat them later. @xref{Function
  3903. Pointers}.
  3904. @menu
  3905. * Address of Data:: Using the ``address-of'' operator.
  3906. * Pointer Types:: For each type, there is a pointer type.
  3907. * Pointer Declarations:: Declaring variables with pointer types.
  3908. * Pointer Type Designators:: Designators for pointer types.
  3909. * Pointer Dereference:: Accessing what a pointer points at.
  3910. * Null Pointers:: Pointers which do not point to any object.
  3911. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3912. * Void Pointers:: Totally generic pointers, can cast to any.
  3913. * Pointer Comparison:: Comparing memory address values.
  3914. * Pointer Arithmetic:: Computing memory address values.
  3915. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3916. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3917. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3918. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3919. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3920. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3921. @end menu
  3922. @node Address of Data
  3923. @section Address of Data
  3924. @cindex address-of operator
  3925. The most basic way to make a pointer is with the ``address-of''
  3926. operator, @samp{&}. Let's suppose we have these variables available:
  3927. @example
  3928. int i;
  3929. double a[5];
  3930. @end example
  3931. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3932. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3933. address of the element 3 of @code{a}. (It is actually the fourth
  3934. element in the array, since the first element has index 0.)
  3935. The address-of operator is unusual because it operates on a place to
  3936. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3937. stored there. (The left argument of a simple assignment is unusual in
  3938. the same way.) You can use it on any lvalue except a bit field
  3939. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3940. Constructors}).
  3941. @node Pointer Types
  3942. @section Pointer Types
  3943. For each data type @var{t}, there is a type for pointers to type
  3944. @var{t}. For these variables,
  3945. @example
  3946. int i;
  3947. double a[5];
  3948. @end example
  3949. @itemize @bullet
  3950. @item
  3951. @code{i} has type @code{int}; we say
  3952. @code{&i} is a ``pointer to @code{int}.''
  3953. @item
  3954. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3955. arrays of five @code{double}s.''
  3956. @item
  3957. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3958. to @code{double}.''
  3959. @end itemize
  3960. @node Pointer Declarations
  3961. @section Pointer-Variable Declarations
  3962. The way to declare that a variable @code{foo} points to type @var{t} is
  3963. @example
  3964. @var{t} *foo;
  3965. @end example
  3966. To remember this syntax, think ``if you dereference @code{foo}, using
  3967. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3968. points to type @var{t}.''
  3969. Thus, we can declare variables that hold pointers to these three
  3970. types, like this:
  3971. @example
  3972. int *ptri; /* @r{Pointer to @code{int}.} */
  3973. double *ptrd; /* @r{Pointer to @code{double}.} */
  3974. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3975. @end example
  3976. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3977. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3978. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3979. @code{double}.'' The parentheses express the point that you would
  3980. dereference it first, then subscript it.
  3981. Contrast the last one with this:
  3982. @example
  3983. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3984. @end example
  3985. @noindent
  3986. Because @samp{*} has higher syntactic precedence than subscripting,
  3987. you would subscript @code{aptrd} then dereference it. Therefore, it
  3988. declares an array of pointers, not a pointer.
  3989. @node Pointer Type Designators
  3990. @section Pointer-Type Designators
  3991. Every type in C has a designator; you make it by deleting the variable
  3992. name and the semicolon from a declaration (@pxref{Type
  3993. Designators}). Here are the designators for the pointer
  3994. types of the example declarations in the previous section:
  3995. @example
  3996. int * /* @r{Pointer to @code{int}.} */
  3997. double * /* @r{Pointer to @code{double}.} */
  3998. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3999. @end example
  4000. Remember, to understand what type a designator stands for, imagine the
  4001. variable name that would be in the declaration, and figure out what
  4002. type it would declare that variable with. @code{double (*)[5]} can
  4003. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  4004. which, when dereferenced, gives an array of 5 @code{double}s.
  4005. @node Pointer Dereference
  4006. @section Dereferencing Pointers
  4007. @cindex dereferencing pointers
  4008. @cindex pointer dereferencing
  4009. The main use of a pointer value is to @dfn{dereference it} (access the
  4010. data it points at) with the unary @samp{*} operator. For instance,
  4011. @code{*&i} is the value at @code{i}'s address---which is just
  4012. @code{i}. The two expressions are equivalent, provided @code{&i} is
  4013. valid.
  4014. A pointer-dereference expression whose type is data (not a function)
  4015. is an lvalue.
  4016. Pointers become really useful when we store them somewhere and use
  4017. them later. Here's a simple example to illustrate the practice:
  4018. @example
  4019. @{
  4020. int i;
  4021. int *ptr;
  4022. ptr = &i;
  4023. i = 5;
  4024. @r{@dots{}}
  4025. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  4026. @}
  4027. @end example
  4028. This shows how to declare the variable @code{ptr} as type
  4029. @code{int *} (pointer to @code{int}), store a pointer value into it
  4030. (pointing at @code{i}), and use it later to get the value of the
  4031. object it points at (the value in @code{i}).
  4032. If anyone can provide a useful example which is this basic,
  4033. I would be grateful.
  4034. @node Null Pointers
  4035. @section Null Pointers
  4036. @cindex null pointers
  4037. @cindex pointers, null
  4038. @c ???stdio loads sttddef
  4039. A pointer value can be @dfn{null}, which means it does not point to
  4040. any object. The cleanest way to get a null pointer is by writing
  4041. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4042. also do it by casting 0 to the desired pointer type, as in
  4043. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4044. @xref{Explicit Type Conversion}.)
  4045. You can store a null pointer in any lvalue whose data type
  4046. is a pointer type:
  4047. @example
  4048. char *foo;
  4049. foo = NULL;
  4050. @end example
  4051. These two, if consecutive, can be combined into a declaration with
  4052. initializer,
  4053. @example
  4054. char *foo = NULL;
  4055. @end example
  4056. You can also explicitly cast @code{NULL} to the specific pointer type
  4057. you want---it makes no difference.
  4058. @example
  4059. char *foo;
  4060. foo = (char *) NULL;
  4061. @end example
  4062. To test whether a pointer is null, compare it with zero or
  4063. @code{NULL}, as shown here:
  4064. @example
  4065. if (p != NULL)
  4066. /* @r{@code{p} is not null.} */
  4067. operate (p);
  4068. @end example
  4069. Since testing a pointer for not being null is basic and frequent, all
  4070. but beginners in C will understand the conditional without need for
  4071. @code{!= NULL}:
  4072. @example
  4073. if (p)
  4074. /* @r{@code{p} is not null.} */
  4075. operate (p);
  4076. @end example
  4077. @node Invalid Dereference
  4078. @section Dereferencing Null or Invalid Pointers
  4079. Trying to dereference a null pointer is an error. On most platforms,
  4080. it generally causes a signal, usually @code{SIGSEGV}
  4081. (@pxref{Signals}).
  4082. @example
  4083. char *foo = NULL;
  4084. c = *foo; /* @r{This causes a signal and terminates.} */
  4085. @end example
  4086. @noindent
  4087. Likewise a pointer that has the wrong alignment for the target data type
  4088. (on most types of computer), or points to a part of memory that has
  4089. not been allocated in the process's address space.
  4090. The signal terminates the program, unless the program has arranged to
  4091. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4092. The GNU C Library Reference Manual}).
  4093. However, the signal might not happen if the dereference is optimized
  4094. away. In the example above, if you don't subsequently use the value
  4095. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4096. can prevent such optimization using the @code{volatile} qualifier, as
  4097. shown here:
  4098. @example
  4099. volatile char *p;
  4100. volatile char c;
  4101. c = *p;
  4102. @end example
  4103. You can use this to test whether @code{p} points to unallocated
  4104. memory. Set up a signal handler first, so the signal won't terminate
  4105. the program.
  4106. @node Void Pointers
  4107. @section Void Pointers
  4108. @cindex void pointers
  4109. @cindex pointers, void
  4110. The peculiar type @code{void *}, a pointer whose target type is
  4111. @code{void}, is used often in C@. It represents a pointer to
  4112. we-don't-say-what. Thus,
  4113. @example
  4114. void *numbered_slot_pointer (int);
  4115. @end example
  4116. @noindent
  4117. declares a function @code{numbered_slot_pointer} that takes an
  4118. integer parameter and returns a pointer, but we don't say what type of
  4119. data it points to.
  4120. With type @code{void *}, you can pass the pointer around and test
  4121. whether it is null. However, dereferencing it gives a @code{void}
  4122. value that can't be used (@pxref{The Void Type}). To dereference the
  4123. pointer, first convert it to some other pointer type.
  4124. Assignments convert @code{void *} automatically to any other pointer
  4125. type, if the left operand has a pointer type; for instance,
  4126. @example
  4127. @{
  4128. int *p;
  4129. /* @r{Converts return value to @code{int *}.} */
  4130. p = numbered_slot_pointer (5);
  4131. @r{@dots{}}
  4132. @}
  4133. @end example
  4134. Passing an argument of type @code{void *} for a parameter that has a
  4135. pointer type also converts. For example, supposing the function
  4136. @code{hack} is declared to require type @code{float *} for its
  4137. argument, this will convert the null pointer to that type.
  4138. @example
  4139. /* @r{Declare @code{hack} that way.}
  4140. @r{We assume it is defined somewhere else.} */
  4141. void hack (float *);
  4142. @dots{}
  4143. /* @r{Now call @code{hack}.} */
  4144. @{
  4145. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4146. @r{to @code{float *} to pass it to @code{hack}.} */
  4147. hack (numbered_slot_pointer (5));
  4148. @r{@dots{}}
  4149. @}
  4150. @end example
  4151. You can also convert to another pointer type with an explicit cast
  4152. (@pxref{Explicit Type Conversion}), like this:
  4153. @example
  4154. (int *) numbered_slot_pointer (5)
  4155. @end example
  4156. Here is an example which decides at run time which pointer
  4157. type to convert to:
  4158. @example
  4159. void
  4160. extract_int_or_double (void *ptr, bool its_an_int)
  4161. @{
  4162. if (its_an_int)
  4163. handle_an_int (*(int *)ptr);
  4164. else
  4165. handle_a_double (*(double *)ptr);
  4166. @}
  4167. @end example
  4168. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4169. to type @code{int *}, then dereference it.
  4170. @node Pointer Comparison
  4171. @section Pointer Comparison
  4172. @cindex pointer comparison
  4173. @cindex comparison, pointer
  4174. Two pointer values are equal if they point to the same location, or if
  4175. they are both null. You can test for this with @code{==} and
  4176. @code{!=}. Here's a trivial example:
  4177. @example
  4178. @{
  4179. int i;
  4180. int *p, *q;
  4181. p = &i;
  4182. q = &i;
  4183. if (p == q)
  4184. printf ("This will be printed.\n");
  4185. if (p != q)
  4186. printf ("This won't be printed.\n");
  4187. @}
  4188. @end example
  4189. Ordering comparisons such as @code{>} and @code{>=} operate on
  4190. pointers by converting them to unsigned integers. The C standard says
  4191. the two pointers must point within the same object in memory, but on
  4192. GNU/Linux systems these operations simply compare the numeric values
  4193. of the pointers.
  4194. The pointer values to be compared should in principle have the same type, but
  4195. they are allowed to differ in limited cases. First of all, if the two
  4196. pointers' target types are nearly compatible (@pxref{Compatible
  4197. Types}), the comparison is allowed.
  4198. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4199. the other is another pointer type, the comparison operator converts
  4200. the @code{void *} pointer to the other type so as to compare them.
  4201. (In standard C, this is not allowed if the other type is a function
  4202. pointer type, but that works in GNU C@.)
  4203. Comparison operators also allow comparing the integer 0 with a pointer
  4204. value. Thus works by converting 0 to a null pointer of the same type
  4205. as the other operand.
  4206. @node Pointer Arithmetic
  4207. @section Pointer Arithmetic
  4208. @cindex pointer arithmetic
  4209. @cindex arithmetic, pointer
  4210. Adding an integer (positive or negative) to a pointer is valid in C@.
  4211. It assumes that the pointer points to an element in an array, and
  4212. advances or retracts the pointer across as many array elements as the
  4213. integer specifies. Here is an example, in which adding a positive
  4214. integer advances the pointer to a later element in the same array.
  4215. @example
  4216. void
  4217. incrementing_pointers ()
  4218. @{
  4219. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4220. int elt0, elt1, elt4;
  4221. int *p = &array[0];
  4222. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4223. elt0 = *p;
  4224. ++p;
  4225. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4226. elt1 = *p;
  4227. p += 3;
  4228. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4229. elt4 = *p;
  4230. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4231. elt0, elt1, elt4);
  4232. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4233. @}
  4234. @end example
  4235. Here's an example where adding a negative integer retracts the pointer
  4236. to an earlier element in the same array.
  4237. @example
  4238. void
  4239. decrementing_pointers ()
  4240. @{
  4241. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4242. int elt0, elt3, elt4;
  4243. int *p = &array[4];
  4244. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4245. elt4 = *p;
  4246. --p;
  4247. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4248. elt3 = *p;
  4249. p -= 3;
  4250. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4251. elt0 = *p;
  4252. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4253. elt0, elt3, elt4);
  4254. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4255. @}
  4256. @end example
  4257. If one pointer value was made by adding an integer to another
  4258. pointer value, it should be possible to subtract the pointer values
  4259. and recover that integer. That works too in C@.
  4260. @example
  4261. void
  4262. subtract_pointers ()
  4263. @{
  4264. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4265. int *p0, *p3, *p4;
  4266. int *p = &array[4];
  4267. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4268. p4 = p;
  4269. --p;
  4270. /* @r{Now @code{p} points at element 3. Save the value.} */
  4271. p3 = p;
  4272. p -= 3;
  4273. /* @r{Now @code{p} points at element 0. Save the value.} */
  4274. p0 = p;
  4275. printf ("%d, %d, %d, %d\n",
  4276. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4277. /* @r{Prints 4, 0, 3, -3.} */
  4278. @}
  4279. @end example
  4280. The addition operation does not know where arrays are. All it does is
  4281. add the integer (multiplied by object size) to the value of the
  4282. pointer. When the initial pointer and the result point into a single
  4283. array, the result is well-defined.
  4284. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4285. into different memory objects.
  4286. The difference between two pointers has type @code{int}, or
  4287. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4288. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4289. file @file{stddef.h}.
  4290. This definition of pointer subtraction is consistent with
  4291. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4292. @code{p3}, as in ordinary algebra.
  4293. In standard C, addition and subtraction are not allowed on @code{void
  4294. *}, since the target type's size is not defined in that case.
  4295. Likewise, they are not allowed on pointers to function types.
  4296. However, these operations work in GNU C, and the ``size of the target
  4297. type'' is taken as 1.
  4298. @node Pointers and Arrays
  4299. @section Pointers and Arrays
  4300. @cindex pointers and arrays
  4301. @cindex arrays and pointers
  4302. The clean way to refer to an array element is
  4303. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4304. same job is to get the address of that element as a pointer, then
  4305. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4306. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4307. pointer to element zero, then increments it with @code{+} to point to
  4308. the desired element, then gets the value from there.
  4309. That pointer-arithmetic construct is the @emph{definition} of square
  4310. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4311. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4312. symmetrically, so one must be a pointer and the other an integer; it
  4313. does not matter which comes first.
  4314. Since indexing with square brackets is defined in terms of addition
  4315. and dereference, that too is symmetrical. Thus, you can write
  4316. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4317. would be foolish to write @code{3[array]}, since it has no advantage
  4318. and could confuse people who read the code.
  4319. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4320. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4321. instead. Why is this valid? The name of the array, when used by
  4322. itself as an expression (other than in @code{sizeof}), stands for a
  4323. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4324. converts @code{array} implicitly to @code{&array[0]}, and the result
  4325. is a pointer to element 3, equivalent to @code{&array[3]}.
  4326. Since square brackets are defined in terms of such addition,
  4327. @code{array[3]} first converts @code{array} to a pointer. That's why
  4328. it works to use an array directly in that construct.
  4329. @node Pointer Arithmetic Low Level
  4330. @section Pointer Arithmetic at Low Level
  4331. @cindex pointer arithmetic, low level
  4332. @cindex low level pointer arithmetic
  4333. The behavior of pointer arithmetic is theoretically defined only when
  4334. the pointer values all point within one object allocated in memory.
  4335. But the addition and subtraction operators can't tell whether the
  4336. pointer values are all within one object. They don't know where
  4337. objects start and end. So what do they really do?
  4338. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4339. address, which is in fact an integer---call it @var{pint}. It treats
  4340. @var{i} as a number of elements of the type that @var{p} points to.
  4341. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4342. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4343. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4344. If the starting pointer value @var{p} and the result do not point at
  4345. parts of the same object, the operation is not officially legitimate,
  4346. and C code is not ``supposed'' to do it. But you can do it anyway,
  4347. and it gives precisely the results described by the procedure above.
  4348. In some special situations it can do something useful, but non-wizards
  4349. should avoid it.
  4350. Here's a function to offset a pointer value @emph{as if} it pointed to
  4351. an object of any given size, by explicitly performing that calculation:
  4352. @example
  4353. #include <stdint.h>
  4354. void *
  4355. ptr_add (void *p, int i, int objsize)
  4356. @{
  4357. intptr_t p_address = (long) p;
  4358. intptr_t totalsize = i * objsize;
  4359. intptr_t new_address = p_address + totalsize;
  4360. return (void *) new_address;
  4361. @}
  4362. @end example
  4363. @noindent
  4364. @cindex @code{intptr_t}
  4365. This does the same job as @code{@var{p} + @var{i}} with the proper
  4366. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4367. defined in the header file @file{stdint.h}. (In practice, @code{long
  4368. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4369. @node Pointer Increment/Decrement
  4370. @section Pointer Increment and Decrement
  4371. @cindex pointer increment and decrement
  4372. @cindex incrementing pointers
  4373. @cindex decrementing pointers
  4374. The @samp{++} operator adds 1 to a variable. We have seen it for
  4375. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4376. For instance, suppose we have a series of positive integers,
  4377. terminated by a zero, and we want to add them all up.
  4378. @example
  4379. int
  4380. sum_array_till_0 (int *p)
  4381. @{
  4382. int sum = 0;
  4383. for (;;)
  4384. @{
  4385. /* @r{Fetch the next integer.} */
  4386. int next = *p++;
  4387. /* @r{Exit the loop if it's 0.} */
  4388. if (next == 0)
  4389. break;
  4390. /* @r{Add it into running total.} */
  4391. sum += next;
  4392. @}
  4393. return sum;
  4394. @}
  4395. @end example
  4396. @noindent
  4397. The statement @samp{break;} will be explained further on (@pxref{break
  4398. Statement}). Used in this way, it immediately exits the surrounding
  4399. @code{for} statement.
  4400. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4401. takes precedence over a prefix operator. Therefore, it dereferences
  4402. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4403. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4404. pointer, adding 1 to it advances it by the width of the datum it
  4405. points to---in this case, one @code{int}. Therefore, each iteration
  4406. of the loop picks up the next integer from the series and puts it into
  4407. @code{next}.
  4408. This @code{for}-loop has no initialization expression since @code{p}
  4409. and @code{sum} are already initialized, it has no end-test since the
  4410. @samp{break;} statement will exit it, and needs no expression to
  4411. advance it since that's done within the loop by incrementing @code{p}
  4412. and @code{sum}. Thus, those three expressions after @code{for} are
  4413. left empty.
  4414. Another way to write this function is by keeping the parameter value unchanged
  4415. and using indexing to access the integers in the table.
  4416. @example
  4417. int
  4418. sum_array_till_0_indexing (int *p)
  4419. @{
  4420. int i;
  4421. int sum = 0;
  4422. for (i = 0; ; i++)
  4423. @{
  4424. /* @r{Fetch the next integer.} */
  4425. int next = p[i];
  4426. /* @r{Exit the loop if it's 0.} */
  4427. if (next == 0)
  4428. break;
  4429. /* @r{Add it into running total.} */
  4430. sum += next;
  4431. @}
  4432. return sum;
  4433. @}
  4434. @end example
  4435. In this program, instead of advancing @code{p}, we advance @code{i}
  4436. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4437. i)}.) Either way, it uses the same address to get the next integer.
  4438. It makes no difference in this program whether we write @code{i++} or
  4439. @code{++i}, because the value is not used. All that matters is the
  4440. effect, to increment @code{i}.
  4441. The @samp{--} operator also works on pointers; it can be used
  4442. to scan backwards through an array, like this:
  4443. @example
  4444. int
  4445. after_last_nonzero (int *p, int len)
  4446. @{
  4447. /* @r{Set up @code{q} to point just after the last array element.} */
  4448. int *q = p + len;
  4449. while (q != p)
  4450. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4451. if (*--q != 0)
  4452. /* @r{Return the index of the element after that nonzero.} */
  4453. return q - p + 1;
  4454. return 0;
  4455. @}
  4456. @end example
  4457. That function returns the length of the nonzero part of the
  4458. array specified by its arguments; that is, the index of the
  4459. first zero of the run of zeros at the end.
  4460. @node Pointer Arithmetic Drawbacks
  4461. @section Drawbacks of Pointer Arithmetic
  4462. @cindex drawbacks of pointer arithmetic
  4463. @cindex pointer arithmetic, drawbacks
  4464. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4465. major security flaw in the C language. Theoretically, it is only
  4466. valid to adjust a pointer within one object allocated as a unit in
  4467. memory. However, if you unintentionally adjust a pointer across the
  4468. bounds of the object and into some other object, the system has no way
  4469. to detect this error.
  4470. A bug which does that can easily result in clobbering part of another
  4471. object. For example, with @code{array[-1]} you can read or write the
  4472. nonexistent element before the beginning of an array---probably part
  4473. of some other data.
  4474. Combining pointer arithmetic with casts between pointer types, you can
  4475. create a pointer that fails to be properly aligned for its type. For
  4476. example,
  4477. @example
  4478. int a[2];
  4479. char *pa = (char *)a;
  4480. int *p = (int *)(pa + 1);
  4481. @end example
  4482. @noindent
  4483. gives @code{p} a value pointing to an ``integer'' that includes part
  4484. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4485. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4486. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4487. ``works,'' it may be quite slow. It can also cause aliasing
  4488. confusions (@pxref{Aliasing}).
  4489. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4490. unless it is really necessary.
  4491. @node Pointer-Integer Conversion
  4492. @section Pointer-Integer Conversion
  4493. @cindex pointer-integer conversion
  4494. @cindex conversion between pointers and integers
  4495. @cindex @code{uintptr_t}
  4496. On modern computers, an address is simply a number. It occupies the
  4497. same space as some size of integer. In C, you can convert a pointer
  4498. to the appropriate integer types and vice versa, without losing
  4499. information. The appropriate integer types are @code{uintptr_t} (an
  4500. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4501. in @file{stdint.h}.
  4502. For instance,
  4503. @example
  4504. #include <stdint.h>
  4505. #include <stdio.h>
  4506. void
  4507. print_pointer (void *ptr)
  4508. @{
  4509. uintptr_t converted = (uintptr_t) ptr;
  4510. printf ("Pointer value is 0x%x\n",
  4511. (unsigned int) converted);
  4512. @}
  4513. @end example
  4514. @noindent
  4515. The specification @samp{%x} in the template (the first argument) for
  4516. @code{printf} means to represent this argument using hexadecimal
  4517. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4518. printing treats the number as unsigned, but it won't actually matter:
  4519. all @code{printf} gets to see is the series of bits in the number.
  4520. @strong{Warning:} Converting pointers to integers is risky---don't do
  4521. it unless it is really necessary.
  4522. @node Printing Pointers
  4523. @section Printing Pointers
  4524. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4525. For example:
  4526. @example
  4527. void
  4528. print_pointer (void *ptr)
  4529. @{
  4530. printf ("Pointer value is %p\n", ptr);
  4531. @}
  4532. @end example
  4533. The specification @samp{%p} works with any pointer type. It prints
  4534. @samp{0x} followed by the address in hexadecimal, printed as the
  4535. appropriate unsigned integer type.
  4536. @node Structures
  4537. @chapter Structures
  4538. @cindex structures
  4539. @findex struct
  4540. @cindex fields in structures
  4541. A @dfn{structure} is a user-defined data type that holds various
  4542. @dfn{fields} of data. Each field has a name and a data type specified
  4543. in the structure's definition.
  4544. Here we define a structure suitable for storing a linked list of
  4545. integers. Each list item will hold one integer, plus a pointer
  4546. to the next item.
  4547. @example
  4548. struct intlistlink
  4549. @{
  4550. int datum;
  4551. struct intlistlink *next;
  4552. @};
  4553. @end example
  4554. The structure definition has a @dfn{type tag} so that the code can
  4555. refer to this structure. The type tag here is @code{intlistlink}.
  4556. The definition refers recursively to the same structure through that
  4557. tag.
  4558. You can define a structure without a type tag, but then you can't
  4559. refer to it again. That is useful only in some special contexts, such
  4560. as inside a @code{typedef} or a @code{union}.
  4561. The contents of the structure are specified by the @dfn{field
  4562. declarations} inside the braces. Each field in the structure needs a
  4563. declaration there. The fields in one structure definition must have
  4564. distinct names, but these names do not conflict with any other names
  4565. in the program.
  4566. A field declaration looks just like a variable declaration. You can
  4567. combine field declarations with the same beginning, just as you can
  4568. combine variable declarations.
  4569. This structure has two fields. One, named @code{datum}, has type
  4570. @code{int} and will hold one integer in the list. The other, named
  4571. @code{next}, is a pointer to another @code{struct intlistlink}
  4572. which would be the rest of the list. In the last list item, it would
  4573. be @code{NULL}.
  4574. This structure definition is recursive, since the type of the
  4575. @code{next} field refers to the structure type. Such recursion is not
  4576. a problem; in fact, you can use the type @code{struct intlistlink *}
  4577. before the definition of the type @code{struct intlistlink} itself.
  4578. That works because pointers to all kinds of structures really look the
  4579. same at the machine level.
  4580. After defining the structure, you can declare a variable of type
  4581. @code{struct intlistlink} like this:
  4582. @example
  4583. struct intlistlink foo;
  4584. @end example
  4585. The structure definition itself can serve as the beginning of a
  4586. variable declaration, so you can declare variables immediately after,
  4587. like this:
  4588. @example
  4589. struct intlistlink
  4590. @{
  4591. int datum;
  4592. struct intlistlink *next;
  4593. @} foo;
  4594. @end example
  4595. @noindent
  4596. But that is ugly. It is almost always clearer to separate the
  4597. definition of the structure from its uses.
  4598. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4599. the scope of the structure type name to that block. That means the
  4600. structure type is recognized only within that block. Declaring it in
  4601. a function parameter list, as here,
  4602. @example
  4603. int f (struct foo @{int a, b@} parm);
  4604. @end example
  4605. @noindent
  4606. (assuming that @code{struct foo} is not already defined) limits the
  4607. scope of the structure type @code{struct foo} to that parameter list;
  4608. that is basically useless, so it triggers a warning.
  4609. Standard C requires at least one field in a structure.
  4610. GNU C does not require this.
  4611. @menu
  4612. * Referencing Fields:: Accessing field values in a structure object.
  4613. * Dynamic Memory Allocation:: Allocating space for objects
  4614. while the program is running.
  4615. * Field Offset:: Memory layout of fields within a structure.
  4616. * Structure Layout:: Planning the memory layout of fields.
  4617. * Packed Structures:: Packing structure fields as close as possible.
  4618. * Bit Fields:: Dividing integer fields
  4619. into fields with fewer bits.
  4620. * Bit Field Packing:: How bit fields pack together in integers.
  4621. * const Fields:: Making structure fields immutable.
  4622. * Zero Length:: Zero-length array as a variable-length object.
  4623. * Flexible Array Fields:: Another approach to variable-length objects.
  4624. * Overlaying Structures:: Casting one structure type
  4625. over an object of another structure type.
  4626. * Structure Assignment:: Assigning values to structure objects.
  4627. * Unions:: Viewing the same object in different types.
  4628. * Packing With Unions:: Using a union type to pack various types into
  4629. the same memory space.
  4630. * Cast to Union:: Casting a value one of the union's alternative
  4631. types to the type of the union itself.
  4632. * Structure Constructors:: Building new structure objects.
  4633. * Unnamed Types as Fields:: Fields' types do not always need names.
  4634. * Incomplete Types:: Types which have not been fully defined.
  4635. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4636. * Type Tags:: Scope of structure and union type tags.
  4637. @end menu
  4638. @node Referencing Fields
  4639. @section Referencing Structure Fields
  4640. @cindex referencing structure fields
  4641. @cindex structure fields, referencing
  4642. To make a structure useful, there has to be a way to examine and store
  4643. its fields. The @samp{.} (period) operator does that; its use looks
  4644. like @code{@var{object}.@var{field}}.
  4645. Given this structure and variable,
  4646. @example
  4647. struct intlistlink
  4648. @{
  4649. int datum;
  4650. struct intlistlink *next;
  4651. @};
  4652. struct intlistlink foo;
  4653. @end example
  4654. @noindent
  4655. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4656. fields in the value of @code{foo}. These fields are lvalues, so you
  4657. can store values into them, and read the values out again.
  4658. Most often, structures are dynamically allocated (see the next
  4659. section), and we refer to the objects via pointers.
  4660. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4661. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4662. contains this declaration:
  4663. @example
  4664. struct intlistlink *ptr;
  4665. @end example
  4666. @noindent
  4667. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4668. to the two fields in the object that @code{ptr} points to.
  4669. If a unary operator precedes an expression using @samp{->},
  4670. the @samp{->} nests inside:
  4671. @example
  4672. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4673. @end example
  4674. You can intermix @samp{->} and @samp{.} without parentheses,
  4675. as shown here:
  4676. @example
  4677. struct @{ double d; struct intlistlink l; @} foo;
  4678. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4679. @end example
  4680. @node Dynamic Memory Allocation
  4681. @section Dynamic Memory Allocation
  4682. @cindex dynamic memory allocation
  4683. @cindex memory allocation, dynamic
  4684. @cindex allocating memory dynamically
  4685. To allocate an object dynamically, call the library function
  4686. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4687. Reference Manual}). Here is how to allocate an object of type
  4688. @code{struct intlistlink}. To make this code work, include the file
  4689. @file{stdlib.h}, like this:
  4690. @example
  4691. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4692. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4693. @dots{}
  4694. struct intlistlink *
  4695. alloc_intlistlink ()
  4696. @{
  4697. struct intlistlink *p;
  4698. p = malloc (sizeof (struct intlistlink));
  4699. if (p == NULL)
  4700. fatal ("Ran out of storage");
  4701. /* @r{Initialize the contents.} */
  4702. p->datum = 0;
  4703. p->next = NULL;
  4704. return p;
  4705. @}
  4706. @end example
  4707. @noindent
  4708. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4709. will automatically convert it to type @code{struct intlistlink *}.
  4710. The return value of @code{malloc} is always sufficiently aligned
  4711. (@pxref{Type Alignment}) that it is valid for any data type.
  4712. The test for @code{p == NULL} is necessary because @code{malloc}
  4713. returns a null pointer if it cannot get any storage. We assume that
  4714. the program defines the function @code{fatal} to report a fatal error
  4715. to the user.
  4716. Here's how to add one more integer to the front of such a list:
  4717. @example
  4718. struct intlistlink *my_list = NULL;
  4719. void
  4720. add_to_mylist (int my_int)
  4721. @{
  4722. struct intlistlink *p = alloc_intlistlink ();
  4723. p->datum = my_int;
  4724. p->next = mylist;
  4725. mylist = p;
  4726. @}
  4727. @end example
  4728. The way to free the objects is by calling @code{free}. Here's
  4729. a function to free all the links in one of these lists:
  4730. @example
  4731. void
  4732. free_intlist (struct intlistlink *p)
  4733. @{
  4734. while (p)
  4735. @{
  4736. struct intlistlink *q = p;
  4737. p = p->next;
  4738. free (q);
  4739. @}
  4740. @}
  4741. @end example
  4742. We must extract the @code{next} pointer from the object before freeing
  4743. it, because @code{free} can clobber the data that was in the object.
  4744. For the same reason, the program must not use the list any more after
  4745. freeing its elements. To make sure it won't, it is best to clear out
  4746. the variable where the list was stored, like this:
  4747. @example
  4748. free_intlist (mylist);
  4749. mylist = NULL;
  4750. @end example
  4751. @node Field Offset
  4752. @section Field Offset
  4753. @cindex field offset
  4754. @cindex structure field offset
  4755. @cindex offset of structure fields
  4756. To determine the offset of a given field @var{field} in a structure
  4757. type @var{type}, use the macro @code{offsetof}, which is defined in
  4758. the file @file{stddef.h}. It is used like this:
  4759. @example
  4760. offsetof (@var{type}, @var{field})
  4761. @end example
  4762. Here is an example:
  4763. @example
  4764. struct foo
  4765. @{
  4766. int element;
  4767. struct foo *next;
  4768. @};
  4769. offsetof (struct foo, next)
  4770. /* @r{On most machines that is 4. It may be 8.} */
  4771. @end example
  4772. @node Structure Layout
  4773. @section Structure Layout
  4774. @cindex structure layout
  4775. @cindex layout of structures
  4776. The rest of this chapter covers advanced topics about structures. If
  4777. you are just learning C, you can skip it.
  4778. The precise layout of a @code{struct} type is crucial when using it to
  4779. overlay hardware registers, to access data structures in shared
  4780. memory, or to assemble and disassemble packets for network
  4781. communication. It is also important for avoiding memory waste when
  4782. the program makes many objects of that type. However, the layout
  4783. depends on the target platform. Each platform has conventions for
  4784. structure layout, which compilers need to follow.
  4785. Here are the conventions used on most platforms.
  4786. The structure's fields appear in the structure layout in the order
  4787. they are declared. When possible, consecutive fields occupy
  4788. consecutive bytes within the structure. However, if a field's type
  4789. demands more alignment than it would get that way, C gives it the
  4790. alignment it requires by leaving a gap after the previous field.
  4791. Once all the fields have been laid out, it is possible to determine
  4792. the structure's alignment and size. The structure's alignment is the
  4793. maximum alignment of any of the fields in it. Then the structure's
  4794. size is rounded up to a multiple of its alignment. That may require
  4795. leaving a gap at the end of the structure.
  4796. Here are some examples, where we assume that @code{char} has size and
  4797. alignment 1 (always true), and @code{int} has size and alignment 4
  4798. (true on most kinds of computers):
  4799. @example
  4800. struct foo
  4801. @{
  4802. char a, b;
  4803. int c;
  4804. @};
  4805. @end example
  4806. @noindent
  4807. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4808. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4809. There is a gap of 2 bytes before @code{c}.
  4810. Contrast that with this structure:
  4811. @example
  4812. struct foo
  4813. @{
  4814. char a;
  4815. int c;
  4816. char b;
  4817. @};
  4818. @end example
  4819. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4820. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4821. gaps: three bytes before @code{c}, and three bytes at the end.
  4822. These two structures have the same contents at the C level, but one
  4823. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4824. fields. A reliable way to avoid this sort of wastage is to order the
  4825. fields by size, biggest fields first.
  4826. @node Packed Structures
  4827. @section Packed Structures
  4828. @cindex packed structures
  4829. @cindex @code{__attribute__((packed))}
  4830. In GNU C you can force a structure to be laid out with no gaps by
  4831. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4832. end of the structure type declaration). Here's an example:
  4833. @example
  4834. struct __attribute__((packed)) foo
  4835. @{
  4836. char a;
  4837. int c;
  4838. char b;
  4839. @};
  4840. @end example
  4841. Without @code{__attribute__((packed))}, this structure occupies 12
  4842. bytes (as described in the previous section), assuming 4-byte
  4843. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4844. only 6 bytes long---the sum of the lengths of its fields.
  4845. Use of @code{__attribute__((packed))} often results in fields that
  4846. don't have the normal alignment for their types. Taking the address
  4847. of such a field can result in an invalid pointer because of its
  4848. improper alignment. Dereferencing such a pointer can cause a
  4849. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4850. unaligned pointers.
  4851. @xref{Attributes}.
  4852. @node Bit Fields
  4853. @section Bit Fields
  4854. @cindex bit fields
  4855. A structure field declaration with an integer type can specify the
  4856. number of bits the field should occupy. We call that a @dfn{bit
  4857. field}. These are useful because consecutive bit fields are packed
  4858. into a larger storage unit. For instance,
  4859. @example
  4860. unsigned char opcode: 4;
  4861. @end example
  4862. @noindent
  4863. specifies that this field takes just 4 bits.
  4864. Since it is unsigned, its possible values range
  4865. from 0 to 15. A signed field with 4 bits, such as this,
  4866. @example
  4867. signed char small: 4;
  4868. @end example
  4869. @noindent
  4870. can hold values from -8 to 7.
  4871. You can subdivide a single byte into those two parts by writing
  4872. @example
  4873. unsigned char opcode: 4;
  4874. signed char small: 4;
  4875. @end example
  4876. @noindent
  4877. in the structure. With bit fields, these two numbers fit into
  4878. a single @code{char}.
  4879. Here's how to declare a one-bit field that can hold either 0 or 1:
  4880. @example
  4881. unsigned char special_flag: 1;
  4882. @end example
  4883. You can also use the @code{bool} type for bit fields:
  4884. @example
  4885. bool special_flag: 1;
  4886. @end example
  4887. Except when using @code{bool} (which is always unsigned,
  4888. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4889. for a bit field. There is a default, if that's not specified: the bit
  4890. field is signed if plain @code{char} is signed, except that the option
  4891. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4892. is cleaner not to depend on this default.
  4893. Bit fields are special in that you cannot take their address with
  4894. @samp{&}. They are not stored with the size and alignment appropriate
  4895. for the specified type, so they cannot be addressed through pointers
  4896. to that type.
  4897. @node Bit Field Packing
  4898. @section Bit Field Packing
  4899. Programs to communicate with low-level hardware interfaces need to
  4900. define bit fields laid out to match the hardware data. This section
  4901. explains how to do that.
  4902. Consecutive bit fields are packed together, but each bit field must
  4903. fit within a single object of its specified type. In this example,
  4904. @example
  4905. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4906. @end example
  4907. @noindent
  4908. all five fields fit consecutively into one two-byte @code{short}.
  4909. They need 15 bits, and one @code{short} provides 16. By contrast,
  4910. @example
  4911. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4912. @end example
  4913. @noindent
  4914. needs three bytes. It fits @code{a} and @code{b} into one
  4915. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4916. add up to 9 bits). So @code{c} and @code{d} go into a second
  4917. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4918. Then @code{e} needs a third @code{char}. By contrast,
  4919. @example
  4920. unsigned char a : 3, b : 3;
  4921. unsigned int c : 3;
  4922. unsigned char d : 3, e : 3;
  4923. @end example
  4924. @noindent
  4925. needs only two bytes: the type @code{unsigned int}
  4926. allows @code{c} to straddle bytes that are in the same word.
  4927. You can leave a gap of a specified number of bits by defining a
  4928. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4929. It is allocated space in the structure just as a named bit field would
  4930. be allocated.
  4931. You can force the following bit field to advance to the following
  4932. aligned memory object with @code{@var{type} : 0;}.
  4933. Both of these constructs can syntactically share @var{type} with
  4934. ordinary bit fields. This example illustrates both:
  4935. @example
  4936. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4937. @end example
  4938. @noindent
  4939. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4940. between them. Then @code{: 0} advances to the next @code{int},
  4941. so @code{c} and @code{d} fit into that one.
  4942. These rules for packing bit fields apply to most target platforms,
  4943. including all the usual real computers. A few embedded controllers
  4944. have special layout rules.
  4945. @node const Fields
  4946. @section @code{const} Fields
  4947. @cindex const fields
  4948. @cindex structure fields, constant
  4949. @c ??? Is this a C standard feature?
  4950. A structure field declared @code{const} cannot be assigned to
  4951. (@pxref{const}). For instance, let's define this modified version of
  4952. @code{struct intlistlink}:
  4953. @example
  4954. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4955. @{
  4956. const int datum;
  4957. struct intlistlink *next;
  4958. @};
  4959. @end example
  4960. This structure can be used to prevent part of the code from modifying
  4961. the @code{datum} field:
  4962. @example
  4963. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4964. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4965. struct intlistlink_ro *q
  4966. = (struct intlistlink_ro *) p;
  4967. q->datum = 5; /* @r{Error!} */
  4968. p->datum = 5; /* @r{Valid since @code{*p} is}
  4969. @r{not a @code{struct intlistlink_ro}.} */
  4970. @end example
  4971. A @code{const} field can get a value in two ways: by initialization of
  4972. the whole structure, and by making a pointer-to-structure point to an object
  4973. in which that field already has a value.
  4974. Any @code{const} field in a structure type makes assignment impossible
  4975. for structures of that type (@pxref{Structure Assignment}). That is
  4976. because structure assignment works by assigning the structure's
  4977. fields, one by one.
  4978. @node Zero Length
  4979. @section Arrays of Length Zero
  4980. @cindex array of length zero
  4981. @cindex zero-length arrays
  4982. @cindex length-zero arrays
  4983. GNU C allows zero-length arrays. They are useful as the last element
  4984. of a structure that is really a header for a variable-length object.
  4985. Here's an example, where we construct a variable-size structure
  4986. to hold a line which is @code{this_length} characters long:
  4987. @example
  4988. struct line @{
  4989. int length;
  4990. char contents[0];
  4991. @};
  4992. struct line *thisline
  4993. = ((struct line *)
  4994. malloc (sizeof (struct line)
  4995. + this_length));
  4996. thisline->length = this_length;
  4997. @end example
  4998. In ISO C90, we would have to give @code{contents} a length of 1, which
  4999. means either wasting space or complicating the argument to @code{malloc}.
  5000. @node Flexible Array Fields
  5001. @section Flexible Array Fields
  5002. @cindex flexible array fields
  5003. @cindex array fields, flexible
  5004. The C99 standard adopted a more complex equivalent of zero-length
  5005. array fields. It's called a @dfn{flexible array}, and it's indicated
  5006. by omitting the length, like this:
  5007. @example
  5008. struct line
  5009. @{
  5010. int length;
  5011. char contents[];
  5012. @};
  5013. @end example
  5014. The flexible array has to be the last field in the structure, and there
  5015. must be other fields before it.
  5016. Under the C standard, a structure with a flexible array can't be part
  5017. of another structure, and can't be an element of an array.
  5018. GNU C allows static initialization of flexible array fields. The effect
  5019. is to ``make the array long enough'' for the initializer.
  5020. @example
  5021. struct f1 @{ int x; int y[]; @} f1
  5022. = @{ 1, @{ 2, 3, 4 @} @};
  5023. @end example
  5024. @noindent
  5025. This defines a structure variable named @code{f1}
  5026. whose type is @code{struct f1}. In C, a variable name or function name
  5027. never conflicts with a structure type tag.
  5028. Omitting the flexible array field's size lets the initializer
  5029. determine it. This is allowed only when the flexible array is defined
  5030. in the outermost structure and you declare a variable of that
  5031. structure type. For example:
  5032. @example
  5033. struct foo @{ int x; int y[]; @};
  5034. struct bar @{ struct foo z; @};
  5035. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  5036. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5037. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  5038. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  5039. @end example
  5040. @node Overlaying Structures
  5041. @section Overlaying Different Structures
  5042. @cindex overlaying structures
  5043. @cindex structures, overlaying
  5044. Be careful about using different structure types to refer to the same
  5045. memory within one function, because GNU C can optimize code assuming
  5046. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5047. aliasing that can cause the problem:
  5048. @example
  5049. struct a @{ int size; char *data; @};
  5050. struct b @{ int size; char *data; @};
  5051. struct a foo;
  5052. struct b *q = (struct b *) &foo;
  5053. @end example
  5054. Here @code{q} points to the same memory that the variable @code{foo}
  5055. occupies, but they have two different types. The two types
  5056. @code{struct a} and @code{struct b} are defined alike, but they are
  5057. not the same type. Interspersing references using the two types,
  5058. like this,
  5059. @example
  5060. p->size = 0;
  5061. q->size = 1;
  5062. x = p->size;
  5063. @end example
  5064. @noindent
  5065. allows GNU C to assume that @code{p->size} is still zero when it is
  5066. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5067. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5068. Other compilers might also do this optimization. The ISO C standard
  5069. considers such code erroneous, precisely so that this optimization
  5070. will be valid.
  5071. @node Structure Assignment
  5072. @section Structure Assignment
  5073. @cindex structure assignment
  5074. @cindex assigning structures
  5075. Assignment operating on a structure type copies the structure. The
  5076. left and right operands must have the same type. Here is an example:
  5077. @example
  5078. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5079. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5080. @r{@dots{}}
  5081. struct point @{ double x, y; @};
  5082. struct point *
  5083. copy_point (struct point point)
  5084. @{
  5085. struct point *p
  5086. = (struct point *) malloc (sizeof (struct point));
  5087. if (p == NULL)
  5088. fatal ("Out of memory");
  5089. *p = point;
  5090. return p;
  5091. @}
  5092. @end example
  5093. Notionally, assignment on a structure type works by copying each of
  5094. the fields. Thus, if any of the fields has the @code{const}
  5095. qualifier, that structure type does not allow assignment:
  5096. @example
  5097. struct point @{ const double x, y; @};
  5098. struct point a, b;
  5099. a = b; /* @r{Error!} */
  5100. @end example
  5101. @xref{Assignment Expressions}.
  5102. @node Unions
  5103. @section Unions
  5104. @cindex unions
  5105. @findex union
  5106. A @dfn{union type} defines alternative ways of looking at the same
  5107. piece of memory. Each alternative view is defined with a data type,
  5108. and identified by a name. A union definition looks like this:
  5109. @example
  5110. union @var{name}
  5111. @{
  5112. @var{alternative declarations}@r{@dots{}}
  5113. @};
  5114. @end example
  5115. Each alternative declaration looks like a structure field declaration,
  5116. except that it can't be a bit field. For instance,
  5117. @example
  5118. union number
  5119. @{
  5120. long int integer;
  5121. double float;
  5122. @}
  5123. @end example
  5124. @noindent
  5125. lets you store either an integer (type @code{long int}) or a floating
  5126. point number (type @code{double}) in the same place in memory. The
  5127. length and alignment of the union type are the maximum of all the
  5128. alternatives---they do not have to be the same. In this union
  5129. example, @code{double} probably takes more space than @code{long int},
  5130. but that doesn't cause a problem in programs that use the union in the
  5131. normal way.
  5132. The members don't have to be different in data type. Sometimes
  5133. each member pertains to a way the data will be used. For instance,
  5134. @example
  5135. union datum
  5136. @{
  5137. double latitude;
  5138. double longitude;
  5139. double height;
  5140. double weight;
  5141. int continent;
  5142. @}
  5143. @end example
  5144. This union holds one of several kinds of data; most kinds are floating
  5145. points, but the value can also be a code for a continent which is an
  5146. integer. You @emph{could} use one member of type @code{double} to
  5147. access all the values which have that type, but the different member
  5148. names will make the program clearer.
  5149. The alignment of a union type is the maximum of the alignments of the
  5150. alternatives. The size of the union type is the maximum of the sizes
  5151. of the alternatives, rounded up to a multiple of the alignment
  5152. (because every type's size must be a multiple of its alignment).
  5153. All the union alternatives start at the address of the union itself.
  5154. If an alternative is shorter than the union as a whole, it occupies
  5155. the first part of the union's storage, leaving the last part unused
  5156. @emph{for that alternative}.
  5157. @strong{Warning:} if the code stores data using one union alternative
  5158. and accesses it with another, the results depend on the kind of
  5159. computer in use. Only wizards should try to do this. However, when
  5160. you need to do this, a union is a clean way to do it.
  5161. Assignment works on any union type by copying the entire value.
  5162. @node Packing With Unions
  5163. @section Packing With Unions
  5164. Sometimes we design a union with the intention of packing various
  5165. kinds of objects into a certain amount of memory space. For example.
  5166. @example
  5167. union bytes8
  5168. @{
  5169. long long big_int_elt;
  5170. double double_elt;
  5171. struct @{ int first, second; @} two_ints;
  5172. struct @{ void *first, *second; @} two_ptrs;
  5173. @};
  5174. union bytes8 *p;
  5175. @end example
  5176. This union makes it possible to look at 8 bytes of data that @code{p}
  5177. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5178. single floating-point number (@code{p->double_elt}), as a pair of
  5179. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5180. as a pair of pointers (@code{p->two_ptrs.first} and
  5181. @code{p->two_ptrs.second}).
  5182. To pack storage with such a union makes assumptions about the sizes of
  5183. all the types involved. This particular union was written expecting a
  5184. pointer to have the same size as @code{int}. On a machine where one
  5185. pointer takes 8 bytes, the code using this union probably won't work
  5186. as expected. The union, as such, will function correctly---if you
  5187. store two values through @code{two_ints} and extract them through
  5188. @code{two_ints}, you will get the same integers back---but the part of
  5189. the program that expects the union to be 8 bytes long could
  5190. malfunction, or at least use too much space.
  5191. The above example shows one case where a @code{struct} type with no
  5192. tag can be useful. Another way to get effectively the same result
  5193. is with arrays as members of the union:
  5194. @example
  5195. union eight_bytes
  5196. @{
  5197. long long big_int_elt;
  5198. double double_elt;
  5199. int two_ints[2];
  5200. void *two_ptrs[2];
  5201. @};
  5202. @end example
  5203. @node Cast to Union
  5204. @section Cast to a Union Type
  5205. @cindex cast to a union
  5206. @cindex union, casting to a
  5207. In GNU C, you can explicitly cast any of the alternative types to the
  5208. union type; for instance,
  5209. @example
  5210. (union eight_bytes) (long long) 5
  5211. @end example
  5212. @noindent
  5213. makes a value of type @code{union eight_bytes} which gets its contents
  5214. through the alternative named @code{big_int_elt}.
  5215. The value being cast must exactly match the type of the alternative,
  5216. so this is not valid:
  5217. @example
  5218. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5219. @end example
  5220. A cast to union type looks like any other cast, except that the type
  5221. specified is a union type. You can specify the type either with
  5222. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5223. Typedef Names}).
  5224. Using the cast as the right-hand side of an assignment to a variable of
  5225. union type is equivalent to storing in an alternative of the union:
  5226. @example
  5227. union foo u;
  5228. u = (union foo) x @r{means} u.i = x
  5229. u = (union foo) y @r{means} u.d = y
  5230. @end example
  5231. You can also use the union cast as a function argument:
  5232. @example
  5233. void hack (union foo);
  5234. @r{@dots{}}
  5235. hack ((union foo) x);
  5236. @end example
  5237. @node Structure Constructors
  5238. @section Structure Constructors
  5239. @cindex structure constructors
  5240. @cindex constructors, structure
  5241. You can construct a structure value by writing its type in
  5242. parentheses, followed by an initializer that would be valid in a
  5243. declaration for that type. For instance, given this declaration,
  5244. @example
  5245. struct foo @{int a; char b[2];@} structure;
  5246. @end example
  5247. @noindent
  5248. you can create a @code{struct foo} value as follows:
  5249. @example
  5250. ((struct foo) @{x + y, 'a', 0@})
  5251. @end example
  5252. @noindent
  5253. This specifies @code{x + y} for field @code{a},
  5254. the character @samp{a} for field @code{b}'s element 0,
  5255. and the null character for field @code{b}'s element 1.
  5256. The parentheses around that constructor are to necessary, but we
  5257. recommend writing them to make the nesting of the containing
  5258. expression clearer.
  5259. You can also show the nesting of the two by writing it like
  5260. this:
  5261. @example
  5262. ((struct foo) @{x + y, @{'a', 0@} @})
  5263. @end example
  5264. Each of those is equivalent to writing the following statement
  5265. expression (@pxref{Statement Exprs}):
  5266. @example
  5267. (@{
  5268. struct foo temp = @{x + y, 'a', 0@};
  5269. temp;
  5270. @})
  5271. @end example
  5272. You can also create a union value this way, but it is not especially
  5273. useful since that is equivalent to doing a cast:
  5274. @example
  5275. ((union whosis) @{@var{value}@})
  5276. @r{is equivalent to}
  5277. ((union whosis) (@var{value}))
  5278. @end example
  5279. @node Unnamed Types as Fields
  5280. @section Unnamed Types as Fields
  5281. @cindex unnamed structures
  5282. @cindex unnamed unions
  5283. @cindex structures, unnamed
  5284. @cindex unions, unnamed
  5285. A structure or a union can contain, as fields,
  5286. unnamed structures and unions. Here's an example:
  5287. @example
  5288. struct
  5289. @{
  5290. int a;
  5291. union
  5292. @{
  5293. int b;
  5294. float c;
  5295. @};
  5296. int d;
  5297. @} foo;
  5298. @end example
  5299. @noindent
  5300. You can access the fields of the unnamed union within @code{foo} as if they
  5301. were individual fields at the same level as the union definition:
  5302. @example
  5303. foo.a = 42;
  5304. foo.b = 47;
  5305. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5306. foo.d = 314;
  5307. @end example
  5308. Avoid using field names that could cause ambiguity. For example, with
  5309. this definition:
  5310. @example
  5311. struct
  5312. @{
  5313. int a;
  5314. struct
  5315. @{
  5316. int a;
  5317. float b;
  5318. @};
  5319. @} foo;
  5320. @end example
  5321. @noindent
  5322. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5323. an error when a definition is ambiguous in this way.
  5324. @node Incomplete Types
  5325. @section Incomplete Types
  5326. @cindex incomplete types
  5327. @cindex types, incomplete
  5328. A type that has not been fully defined is called an @dfn{incomplete
  5329. type}. Structure and union types are incomplete when the code makes a
  5330. forward reference, such as @code{struct foo}, before defining the
  5331. type. An array type is incomplete when its length is unspecified.
  5332. You can't use an incomplete type to declare a variable or field, or
  5333. use it for a function parameter or return type. The operators
  5334. @code{sizeof} and @code{_Alignof} give errors when used on an
  5335. incomplete type.
  5336. However, you can define a pointer to an incomplete type, and declare a
  5337. variable or field with such a pointer type. In general, you can do
  5338. everything with such pointers except dereference them. For example:
  5339. @example
  5340. extern void bar (struct mysterious_value *);
  5341. void
  5342. foo (struct mysterious_value *arg)
  5343. @{
  5344. bar (arg);
  5345. @}
  5346. @r{@dots{}}
  5347. @{
  5348. struct mysterious_value *p, **q;
  5349. p = *q;
  5350. foo (p);
  5351. @}
  5352. @end example
  5353. @noindent
  5354. These examples are valid because the code doesn't try to understand
  5355. what @code{p} points to; it just passes the pointer around.
  5356. (Presumably @code{bar} is defined in some other file that really does
  5357. have a definition for @code{struct mysterious_value}.) However,
  5358. dereferencing the pointer would get an error; that requires a
  5359. definition for the structure type.
  5360. @node Intertwined Incomplete Types
  5361. @section Intertwined Incomplete Types
  5362. When several structure types contain pointers to each other, you can
  5363. define the types in any order because pointers to types that come
  5364. later are incomplete types. Thus,
  5365. Here is an example.
  5366. @example
  5367. /* @r{An employee record points to a group.} */
  5368. struct employee
  5369. @{
  5370. char *name;
  5371. @r{@dots{}}
  5372. struct group *group; /* @r{incomplete type.} */
  5373. @r{@dots{}}
  5374. @};
  5375. /* @r{An employee list points to employees.} */
  5376. struct employee_list
  5377. @{
  5378. struct employee *this_one;
  5379. struct employee_list *next; /* @r{incomplete type.} */
  5380. @r{@dots{}}
  5381. @};
  5382. /* @r{A group points to one employee_list.} */
  5383. struct group
  5384. @{
  5385. char *name;
  5386. @r{@dots{}}
  5387. struct employee_list *employees;
  5388. @r{@dots{}}
  5389. @};
  5390. @end example
  5391. @node Type Tags
  5392. @section Type Tags
  5393. @cindex type tags
  5394. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5395. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5396. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5397. name or function name; the type tags have a separate @dfn{name space}.
  5398. Thus, there is no name conflict in this code:
  5399. @example
  5400. struct pair @{ int a, b; @};
  5401. int pair = 1;
  5402. @end example
  5403. @noindent
  5404. nor in this one:
  5405. @example
  5406. struct pair @{ int a, b; @} pair;
  5407. @end example
  5408. @noindent
  5409. where @code{pair} is both a structure type tag and a variable name.
  5410. However, @code{struct}, @code{union}, and @code{enum} share the same
  5411. name space of tags, so this is a conflict:
  5412. @example
  5413. struct pair @{ int a, b; @};
  5414. enum pair @{ c, d @};
  5415. @end example
  5416. @noindent
  5417. and so is this:
  5418. @example
  5419. struct pair @{ int a, b; @};
  5420. struct pair @{ int c, d; @};
  5421. @end example
  5422. When the code defines a type tag inside a block, the tag's scope is
  5423. limited to that block (as for local variables). Two definitions for
  5424. one type tag do not conflict if they are in different scopes; rather,
  5425. each is valid in its scope. For example,
  5426. @example
  5427. struct pair @{ int a, b; @};
  5428. void
  5429. pair_up_doubles (int len, double array[])
  5430. @{
  5431. struct pair @{ double a, b; @};
  5432. @r{@dots{}}
  5433. @}
  5434. @end example
  5435. @noindent
  5436. has two definitions for @code{struct pair} which do not conflict. The
  5437. one inside the function applies only within the definition of
  5438. @code{pair_up_doubles}. Within its scope, that definition
  5439. @dfn{shadows} the outer definition.
  5440. If @code{struct pair} appears inside the function body, before the
  5441. inner definition, it refers to the outer definition---the only one
  5442. that has been seen at that point. Thus, in this code,
  5443. @example
  5444. struct pair @{ int a, b; @};
  5445. void
  5446. pair_up_doubles (int len, double array[])
  5447. @{
  5448. struct two_pairs @{ struct pair *p, *q; @};
  5449. struct pair @{ double a, b; @};
  5450. @r{@dots{}}
  5451. @}
  5452. @end example
  5453. @noindent
  5454. the structure @code{two_pairs} has pointers to the outer definition of
  5455. @code{struct pair}, which is probably not desirable.
  5456. To prevent that, you can write @code{struct pair;} inside the function
  5457. body as a variable declaration with no variables. This is a
  5458. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5459. type tag local to the current block, with the details of the type to
  5460. come later. Here's an example:
  5461. @example
  5462. void
  5463. pair_up_doubles (int len, double array[])
  5464. @{
  5465. /* @r{Forward declaration for @code{pair}.} */
  5466. struct pair;
  5467. struct two_pairs @{ struct pair *p, *q; @};
  5468. /* @r{Give the details.} */
  5469. struct pair @{ double a, b; @};
  5470. @r{@dots{}}
  5471. @}
  5472. @end example
  5473. However, the cleanest practice is to avoid shadowing type tags.
  5474. @node Arrays
  5475. @chapter Arrays
  5476. @cindex array
  5477. @cindex elements of arrays
  5478. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5479. all of the same data type. Each element is identified by its numeric
  5480. @var{index} within the array.
  5481. We presented arrays of numbers in the sample programs early in this
  5482. manual (@pxref{Array Example}). However, arrays can have elements of
  5483. any data type, including pointers, structures, unions, and other
  5484. arrays.
  5485. If you know another programming language, you may suppose that you know all
  5486. about arrays, but C arrays have special quirks, so in this chapter we
  5487. collect all the information about arrays in C@.
  5488. The elements of a C array are allocated consecutively in memory,
  5489. with no gaps between them. Each element is aligned as required
  5490. for its data type (@pxref{Type Alignment}).
  5491. @menu
  5492. * Accessing Array Elements:: How to access individual elements of an array.
  5493. * Declaring an Array:: How to name and reserve space for a new array.
  5494. * Strings:: A string in C is a special case of array.
  5495. * Array Type Designators:: Referring to a specific array type.
  5496. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5497. * Limitations of C Arrays:: Arrays are not first-class objects.
  5498. * Multidimensional Arrays:: Arrays of arrays.
  5499. * Constructing Array Values:: Assigning values to an entire array at once.
  5500. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5501. @end menu
  5502. @node Accessing Array Elements
  5503. @section Accessing Array Elements
  5504. @cindex accessing array elements
  5505. @cindex array elements, accessing
  5506. If the variable @code{a} is an array, the @var{n}th element of
  5507. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5508. an element's value or to assign to it:
  5509. @example
  5510. x = a[5];
  5511. a[6] = 1;
  5512. @end example
  5513. @noindent
  5514. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5515. lvalue.
  5516. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5517. valid index is one less than the number of elements.
  5518. The C language does not check whether array indices are in bounds, so
  5519. if the code uses an out-of-range index, it will access memory outside the
  5520. array.
  5521. @strong{Warning:} Using only valid index values in C is the
  5522. programmer's responsibility.
  5523. Array indexing in C is not a primitive operation: it is defined in
  5524. terms of pointer arithmetic and dereferencing. Now that we know
  5525. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5526. its job.
  5527. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5528. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5529. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5530. When an expression with array type (such as @code{a}) appears as part
  5531. of a larger C expression, it is converted automatically to a pointer
  5532. to element zero of that array. For instance, @code{a} in an
  5533. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5534. computed as @code{*(&a[0]+i)}.
  5535. Now we can analyze how that expression gives us the desired element of
  5536. the array. It makes a pointer to element 0 of @code{a}, advances it
  5537. by the value of @code{i}, and dereferences that pointer.
  5538. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5539. @node Declaring an Array
  5540. @section Declaring an Array
  5541. @cindex declaring an array
  5542. @cindex array, declaring
  5543. To make an array declaration, write @code{[@var{length}]} after the
  5544. name being declared. This construct is valid in the declaration of a
  5545. variable, a function parameter, a function value type (the value can't
  5546. be an array, but it can be a pointer to one), a structure field, or a
  5547. union alternative.
  5548. The surrounding declaration specifies the element type of the array;
  5549. that can be any type of data, but not @code{void} or a function type.
  5550. For instance,
  5551. @example
  5552. double a[5];
  5553. @end example
  5554. @noindent
  5555. declares @code{a} as an array of 5 @code{double}s.
  5556. @example
  5557. struct foo bstruct[length];
  5558. @end example
  5559. @noindent
  5560. declares @code{bstruct} as an array of @code{length} objects of type
  5561. @code{struct foo}. A variable array size like this is allowed when
  5562. the array is not file-scope.
  5563. Other declaration constructs can nest within the array declaration
  5564. construct. For instance:
  5565. @example
  5566. struct foo *b[length];
  5567. @end example
  5568. @noindent
  5569. declares @code{b} as an array of @code{length} pointers to
  5570. @code{struct foo}. This shows that the length need not be a constant
  5571. (@pxref{Arrays of Variable Length}).
  5572. @example
  5573. double (*c)[5];
  5574. @end example
  5575. @noindent
  5576. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5577. @example
  5578. char *(*f (int))[5];
  5579. @end example
  5580. @noindent
  5581. declares @code{f} as a function taking an @code{int} argument and
  5582. returning a pointer to an array of 5 strings (pointers to
  5583. @code{char}s).
  5584. @example
  5585. double aa[5][10];
  5586. @end example
  5587. @noindent
  5588. declares @code{aa} as an array of 5 elements, each of which is an
  5589. array of 10 @code{double}s. This shows how to declare a
  5590. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5591. All these declarations specify the array's length, which is needed in
  5592. these cases in order to allocate storage for the array.
  5593. @node Strings
  5594. @section Strings
  5595. @cindex string
  5596. A string in C is a sequence of elements of type @code{char},
  5597. terminated with the null character, the character with code zero.
  5598. Programs often need to use strings with specific, fixed contents. To
  5599. write one in a C program, use a @dfn{string constant} such as
  5600. @code{"Take me to your leader!"}. The data type of a string constant
  5601. is @code{char *}. For the full syntactic details of writing string
  5602. constants, @ref{String Constants}.
  5603. To declare a place to store a non-constant string, declare an array of
  5604. @code{char}. Keep in mind that it must include one extra @code{char}
  5605. for the terminating null. For instance,
  5606. @example
  5607. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5608. @end example
  5609. @noindent
  5610. declares an array named @samp{text} with six elements---five letters
  5611. and the terminating null character. An equivalent way to get the same
  5612. result is this,
  5613. @example
  5614. char text[] = "Hello";
  5615. @end example
  5616. @noindent
  5617. which copies the elements of the string constant, including @emph{its}
  5618. terminating null character.
  5619. @example
  5620. char message[200];
  5621. @end example
  5622. @noindent
  5623. declares an array long enough to hold a string of 199 ASCII characters
  5624. plus the terminating null character.
  5625. When you store a string into @code{message} be sure to check or prove
  5626. that the length does not exceed its size. For example,
  5627. @example
  5628. void
  5629. set_message (char *text)
  5630. @{
  5631. int i;
  5632. for (i = 0; i < sizeof (message); i++)
  5633. @{
  5634. message[i] = text[i];
  5635. if (text[i] == 0)
  5636. return;
  5637. @}
  5638. fatal_error ("Message is too long for `message');
  5639. @}
  5640. @end example
  5641. It's easy to do this with the standard library function
  5642. @code{strncpy}, which fills out the whole destination array (up to a
  5643. specified length) with null characters. Thus, if the last character
  5644. of the destination is not null, the string did not fit. Many system
  5645. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5646. to run faster than an explicit @code{for}-loop.
  5647. Here's what the code looks like:
  5648. @example
  5649. void
  5650. set_message (char *text)
  5651. @{
  5652. strncpy (message, text, sizeof (message));
  5653. if (message[sizeof (message) - 1] != 0)
  5654. fatal_error ("Message is too long for `message');
  5655. @}
  5656. @end example
  5657. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5658. Library Reference Manual}, for more information about the standard
  5659. library functions for operating on strings.
  5660. You can avoid putting a fixed length limit on strings you construct or
  5661. operate on by allocating the space for them dynamically.
  5662. @xref{Dynamic Memory Allocation}.
  5663. @node Array Type Designators
  5664. @section Array Type Designators
  5665. Every C type has a type designator, which you make by deleting the
  5666. variable name and the semicolon from a declaration (@pxref{Type
  5667. Designators}). The designators for array types follow this rule, but
  5668. they may appear surprising.
  5669. @example
  5670. @r{type} int a[5]; @r{designator} int [5]
  5671. @r{type} double a[5][3]; @r{designator} double [5][3]
  5672. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5673. @end example
  5674. @node Incomplete Array Types
  5675. @section Incomplete Array Types
  5676. @cindex incomplete array types
  5677. @cindex array types, incomplete
  5678. An array is equivalent, for most purposes, to a pointer to its zeroth
  5679. element. When that is true, the length of the array is irrelevant.
  5680. The length needs to be known only for allocating space for the array, or
  5681. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5682. contexts C allows
  5683. @itemize @bullet
  5684. @item
  5685. An @code{extern} declaration says how to refer to a variable allocated
  5686. elsewhere. It does not need to allocate space for the variable,
  5687. so if it is an array, you can omit the length. For example,
  5688. @example
  5689. extern int foo[];
  5690. @end example
  5691. @item
  5692. When declaring a function parameter as an array, the argument value
  5693. passed to the function is really a pointer to the array's zeroth
  5694. element. This value does not say how long the array really is, there
  5695. is no need to declare it. For example,
  5696. @example
  5697. int
  5698. func (int foo[])
  5699. @end example
  5700. @end itemize
  5701. These declarations are examples of @dfn{incomplete} array types, types
  5702. that are not fully specified. The incompleteness makes no difference
  5703. for accessing elements of the array, but it matters for some other
  5704. things. For instance, @code{sizeof} is not allowed on an incomplete
  5705. type.
  5706. With multidimensional arrays, only the first dimension can be omitted:
  5707. @example
  5708. extern struct chesspiece *funnyboard foo[][8];
  5709. @end example
  5710. In other words, the code doesn't have to say how many rows there are,
  5711. but it must state how big each row is.
  5712. @node Limitations of C Arrays
  5713. @section Limitations of C Arrays
  5714. @cindex limitations of C arrays
  5715. @cindex first-class object
  5716. Arrays have quirks in C because they are not ``first-class objects'':
  5717. there is no way in C to operate on an array as a unit.
  5718. The other composite objects in C, structures and unions, are
  5719. first-class objects: a C program can copy a structure or union value
  5720. in an assignment, or pass one as an argument to a function, or make a
  5721. function return one. You can't do those things with an array in C@.
  5722. That is because a value you can operate on never has an array type.
  5723. An expression in C can have an array type, but that doesn't produce
  5724. the array as a value. Instead it is converted automatically to a
  5725. pointer to the array's element at index zero. The code can operate
  5726. on the pointer, and through that on individual elements of the array,
  5727. but it can't get and operate on the array as a unit.
  5728. There are three exceptions to this conversion rule, but none of them
  5729. offers a way to operate on the array as a whole.
  5730. First, @samp{&} applied to an expression with array type gives you the
  5731. address of the array, as an array type. However, you can't operate on the
  5732. whole array that way---if you apply @samp{*} to get the array back,
  5733. that expression converts, as usual, to a pointer to its zeroth
  5734. element.
  5735. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5736. @code{typeof} do not convert the array to a pointer; they leave it as
  5737. an array. But they don't operate on the array's data---they only give
  5738. information about its type.
  5739. Third, a string constant used as an initializer for an array is not
  5740. converted to a pointer---rather, the declaration copies the
  5741. @emph{contents} of that string in that one special case.
  5742. You @emph{can} copy the contents of an array, just not with an
  5743. assignment operator. You can do it by calling the library function
  5744. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5745. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5746. when a structure contains just an array, you can copy that structure.
  5747. An array itself is an lvalue if it is a declared variable, or part of
  5748. a structure or union that is an lvalue. When you construct an array
  5749. from elements (@pxref{Constructing Array Values}), that array is not
  5750. an lvalue.
  5751. @node Multidimensional Arrays
  5752. @section Multidimensional Arrays
  5753. @cindex multidimensional arrays
  5754. @cindex array, multidimensional
  5755. Strictly speaking, all arrays in C are unidimensional. However, you
  5756. can create an array of arrays, which is more or less equivalent to a
  5757. multidimensional array. For example,
  5758. @example
  5759. struct chesspiece *board[8][8];
  5760. @end example
  5761. @noindent
  5762. declares an array of 8 arrays of 8 pointers to @code{struct
  5763. chesspiece}. This data type could represent the state of a chess
  5764. game. To access one square's contents requires two array index
  5765. operations, one for each dimension. For instance, you can write
  5766. @code{board[row][column]}, assuming @code{row} and @code{column}
  5767. are variables with integer values in the proper range.
  5768. How does C understand @code{board[row][column]}? First of all,
  5769. @code{board} is converted automatically to a pointer to the zeroth
  5770. element (at index zero) of @code{board}. Adding @code{row} to that
  5771. makes it point to the desired element. Thus, @code{board[row]}'s
  5772. value is an element of @code{board}---an array of 8 pointers.
  5773. However, as an expression with array type, it is converted
  5774. automatically to a pointer to the array's zeroth element. The second
  5775. array index operation, @code{[column]}, accesses the chosen element
  5776. from that array.
  5777. As this shows, pointer-to-array types are meaningful in C@.
  5778. You can declare a variable that points to a row in a chess board
  5779. like this:
  5780. @example
  5781. struct chesspiece *(*rowptr)[8];
  5782. @end example
  5783. @noindent
  5784. This points to an array of 8 pointers to @code{struct chesspiece}.
  5785. You can assign to it as follows:
  5786. @example
  5787. rowptr = &board[5];
  5788. @end example
  5789. The dimensions don't have to be equal in length. Here we declare
  5790. @code{statepop} as an array to hold the population of each state in
  5791. the United States for each year since 1900:
  5792. @example
  5793. #define NSTATES 50
  5794. @{
  5795. int nyears = current_year - 1900 + 1;
  5796. int statepop[NSTATES][nyears];
  5797. @r{@dots{}}
  5798. @}
  5799. @end example
  5800. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5801. each indexed by the year (counting from 1900). Thus, to get the
  5802. element for a particular state and year, we must subscript it first
  5803. by the number that indicates the state, and second by the index for
  5804. the year:
  5805. @example
  5806. statepop[state][year - 1900]
  5807. @end example
  5808. @cindex array, layout in memory
  5809. The subarrays within the multidimensional array are allocated
  5810. consecutively in memory, and within each subarray, its elements are
  5811. allocated consecutively in memory. The most efficient way to process
  5812. all the elements in the array is to scan the last subscript in the
  5813. innermost loop. This means consecutive accesses go to consecutive
  5814. memory locations, which optimizes use of the processor's memory cache.
  5815. For example:
  5816. @example
  5817. int total = 0;
  5818. float average;
  5819. for (int state = 0; state < NSTATES, ++state)
  5820. @{
  5821. for (int year = 0; year < nyears; ++year)
  5822. @{
  5823. total += statepop[state][year];
  5824. @}
  5825. @}
  5826. average = total / nyears;
  5827. @end example
  5828. C's layout for multidimensional arrays is different from Fortran's
  5829. layout. In Fortran, a multidimensional array is not an array of
  5830. arrays; rather, multidimensional arrays are a primitive feature, and
  5831. it is the first index that varies most rapidly between consecutive
  5832. memory locations. Thus, the memory layout of a 50x114 array in C
  5833. matches that of a 114x50 array in Fortran.
  5834. @node Constructing Array Values
  5835. @section Constructing Array Values
  5836. @cindex constructing array values
  5837. @cindex array values, constructing
  5838. You can construct an array from elements by writing them inside
  5839. braces, and preceding all that with the array type's designator in
  5840. parentheses. There is no need to specify the array length, since the
  5841. number of elements determines that. The constructor looks like this:
  5842. @example
  5843. (@var{elttype}[]) @{ @var{elements} @};
  5844. @end example
  5845. Here is an example, which constructs an array of string pointers:
  5846. @example
  5847. (char *[]) @{ "x", "y", "z" @};
  5848. @end example
  5849. That's equivalent in effect to declaring an array with the same
  5850. initializer, like this:
  5851. @example
  5852. char *array[] = @{ "x", "y", "z" @};
  5853. @end example
  5854. and then using the array.
  5855. If all the elements are simple constant expressions, or made up of
  5856. such, then the compound literal can be coerced to a pointer to its
  5857. zeroth element and used to initialize a file-scope variable
  5858. (@pxref{File-Scope Variables}), as shown here:
  5859. @example
  5860. char **foo = (char *[]) @{ "x", "y", "z" @};
  5861. @end example
  5862. @noindent
  5863. The data type of @code{foo} is @code{char **}, which is a pointer
  5864. type, not an array type. The declaration is equivalent to defining
  5865. and then using an array-type variable:
  5866. @example
  5867. char *nameless_array[] = @{ "x", "y", "z" @};
  5868. char **foo = &nameless_array[0];
  5869. @end example
  5870. @node Arrays of Variable Length
  5871. @section Arrays of Variable Length
  5872. @cindex array of variable length
  5873. @cindex variable-length arrays
  5874. In GNU C, you can declare variable-length arrays like any other
  5875. arrays, but with a length that is not a constant expression. The
  5876. storage is allocated at the point of declaration and deallocated when
  5877. the block scope containing the declaration exits. For example:
  5878. @example
  5879. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5880. #include <string.h> /* @r{Declares @code{str}.} */
  5881. FILE *
  5882. concat_fopen (char *s1, char *s2, char *mode)
  5883. @{
  5884. char str[strlen (s1) + strlen (s2) + 1];
  5885. strcpy (str, s1);
  5886. strcat (str, s2);
  5887. return fopen (str, mode);
  5888. @}
  5889. @end example
  5890. @noindent
  5891. (This uses some standard library functions; see @ref{String and Array
  5892. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5893. The length of an array is computed once when the storage is allocated
  5894. and is remembered for the scope of the array in case it is used in
  5895. @code{sizeof}.
  5896. @strong{Warning:} don't allocate a variable-length array if the size
  5897. might be very large (more than 100,000), or in a recursive function,
  5898. because that is likely to cause stack overflow. Allocate the array
  5899. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5900. Jumping or breaking out of the scope of the array name deallocates the
  5901. storage. Jumping into the scope is not allowed; that gives an error
  5902. message.
  5903. You can also use variable-length arrays as arguments to functions:
  5904. @example
  5905. struct entry
  5906. tester (int len, char data[len][len])
  5907. @{
  5908. @r{@dots{}}
  5909. @}
  5910. @end example
  5911. As usual, a function argument declared with an array type
  5912. is really a pointer to an array that already exists.
  5913. Calling the function does not allocate the array, so there's no
  5914. particular danger of stack overflow in using this construct.
  5915. To pass the array first and the length afterward, use a forward
  5916. declaration in the function's parameter list (another GNU extension).
  5917. For example,
  5918. @example
  5919. struct entry
  5920. tester (int len; char data[len][len], int len)
  5921. @{
  5922. @r{@dots{}}
  5923. @}
  5924. @end example
  5925. The @code{int len} before the semicolon is a @dfn{parameter forward
  5926. declaration}, and it serves the purpose of making the name @code{len}
  5927. known when the declaration of @code{data} is parsed.
  5928. You can write any number of such parameter forward declarations in the
  5929. parameter list. They can be separated by commas or semicolons, but
  5930. the last one must end with a semicolon, which is followed by the
  5931. ``real'' parameter declarations. Each forward declaration must match
  5932. a ``real'' declaration in parameter name and data type. ISO C11 does
  5933. not support parameter forward declarations.
  5934. @node Enumeration Types
  5935. @chapter Enumeration Types
  5936. @cindex enumeration types
  5937. @cindex types, enumeration
  5938. @cindex enumerator
  5939. An @dfn{enumeration type} represents a limited set of integer values,
  5940. each with a name. It is effectively equivalent to a primitive integer
  5941. type.
  5942. Suppose we have a list of possible emotional states to store in an
  5943. integer variable. We can give names to these alternative values with
  5944. an enumeration:
  5945. @example
  5946. enum emotion_state @{ neutral, happy, sad, worried,
  5947. calm, nervous @};
  5948. @end example
  5949. @noindent
  5950. (Never mind that this is a simplistic way to classify emotional states;
  5951. it's just a code example.)
  5952. The names inside the enumeration are called @dfn{enumerators}. The
  5953. enumeration type defines them as constants, and their values are
  5954. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5955. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5956. the enumerators explicitly like this:
  5957. @example
  5958. enum emotion_state @{ neutral = 2, happy = 5,
  5959. sad = 20, worried = 10,
  5960. calm = -5, nervous = -300 @};
  5961. @end example
  5962. Each enumerator which does not specify a value gets value zero
  5963. (if it is at the beginning) or the next consecutive integer.
  5964. @example
  5965. /* @r{@code{neutral} is 0 by default,}
  5966. @r{and @code{worried} is 21 by default.} */
  5967. enum emotion_state @{ neutral,
  5968. happy = 5, sad = 20, worried,
  5969. calm = -5, nervous = -300 @};
  5970. @end example
  5971. If an enumerator is obsolete, you can specify that using it should
  5972. cause a warning, by including an attribute in the enumerator's
  5973. declaration. Here is how @code{happy} would look with this
  5974. attribute:
  5975. @example
  5976. happy __attribute__
  5977. ((deprecated
  5978. ("impossible under plutocratic rule")))
  5979. = 5,
  5980. @end example
  5981. @xref{Attributes}.
  5982. You can declare variables with the enumeration type:
  5983. @example
  5984. enum emotion_state feelings_now;
  5985. @end example
  5986. In the C code itself, this is equivalent to declaring the variable
  5987. @code{int}. (If all the enumeration values are positive, it is
  5988. equivalent to @code{unsigned int}.) However, declaring it with the
  5989. enumeration type has an advantage in debugging, because GDB knows it
  5990. should display the current value of the variable using the
  5991. corresponding name. If the variable's type is @code{int}, GDB can
  5992. only show the value as a number.
  5993. The identifier that follows @code{enum} is called a @dfn{type tag}
  5994. since it distinguishes different enumeration types. Type tags are in
  5995. a separate name space and belong to scopes like most other names in C@.
  5996. @xref{Type Tags}, for explanation.
  5997. You can predeclare an @code{enum} type tag like a structure or union
  5998. type tag, like this:
  5999. @example
  6000. enum foo;
  6001. @end example
  6002. @noindent
  6003. The @code{enum} type is incomplete until you finish defining it.
  6004. You can optionally include a trailing comma at the end of a list of
  6005. enumeration values:
  6006. @example
  6007. enum emotion_state @{ neutral, happy, sad, worried,
  6008. calm, nervous, @};
  6009. @end example
  6010. @noindent
  6011. This is useful in some macro definitions, since it enables you to
  6012. assemble the list of enumerators without knowing which one is last.
  6013. The extra comma does not change the meaning of the enumeration in any
  6014. way.
  6015. @node Defining Typedef Names
  6016. @chapter Defining Typedef Names
  6017. @cindex typedef names
  6018. @findex typedef
  6019. You can define a data type keyword as an alias for any type, and then
  6020. use the alias syntactically like a built-in type keyword such as
  6021. @code{int}. You do this using @code{typedef}, so these aliases are
  6022. also called @dfn{typedef names}.
  6023. @code{typedef} is followed by text that looks just like a variable
  6024. declaration, but instead of declaring variables it defines data type
  6025. keywords.
  6026. Here's how to define @code{fooptr} as a typedef alias for the type
  6027. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  6028. with that type:
  6029. @example
  6030. typedef struct foo *fooptr;
  6031. fooptr x, y;
  6032. @end example
  6033. @noindent
  6034. That declaration is equivalent to the following one:
  6035. @example
  6036. struct foo *x, *y;
  6037. @end example
  6038. You can define a typedef alias for any type. For instance, this makes
  6039. @code{frobcount} an alias for type @code{int}:
  6040. @example
  6041. typedef int frobcount;
  6042. @end example
  6043. @noindent
  6044. This doesn't define a new type distinct from @code{int}. Rather,
  6045. @code{frobcount} is another name for the type @code{int}. Once the
  6046. variable is declared, it makes no difference which name the
  6047. declaration used.
  6048. There is a syntactic difference, however, between @code{frobcount} and
  6049. @code{int}: A typedef name cannot be used with
  6050. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6051. to specify the type all by itself. So you can't write this:
  6052. @example
  6053. unsigned frobcount f1; /* @r{Error!} */
  6054. @end example
  6055. But you can write this:
  6056. @example
  6057. typedef unsigned int unsigned_frobcount;
  6058. unsigned_frobcount f1;
  6059. @end example
  6060. In other words, a typedef name is not an alias for @emph{a keyword}
  6061. such as @code{int}. It stands for a @emph{type}, and that could be
  6062. the type @code{int}.
  6063. Typedef names are in the same namespace as functions and variables, so
  6064. you can't use the same name for a typedef and a function, or a typedef
  6065. and a variable. When a typedef is declared inside a code block, it is
  6066. in scope only in that block.
  6067. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6068. because many of these have standard meanings.
  6069. You can redefine a typedef name to the exact same type as its first
  6070. definition, but you cannot redefine a typedef name to a
  6071. different type, even if the two types are compatible. For example, this
  6072. is valid:
  6073. @example
  6074. typedef int frobcount;
  6075. typedef int frotzcount;
  6076. typedef frotzcount frobcount;
  6077. typedef frobcount frotzcount;
  6078. @end example
  6079. @noindent
  6080. because each typedef name is always defined with the same type
  6081. (@code{int}), but this is not valid:
  6082. @example
  6083. enum foo @{f1, f2, f3@};
  6084. typedef enum foo frobcount;
  6085. typedef int frobcount;
  6086. @end example
  6087. @noindent
  6088. Even though the type @code{enum foo} is compatible with @code{int},
  6089. they are not the @emph{same} type.
  6090. @node Statements
  6091. @chapter Statements
  6092. @cindex statements
  6093. A @dfn{statement} specifies computations to be done for effect; it
  6094. does not produce a value, as an expression would. In general a
  6095. statement ends with a semicolon (@samp{;}), but blocks (which are
  6096. statements, more or less) are an exception to that rule.
  6097. @ifnottex
  6098. @xref{Blocks}.
  6099. @end ifnottex
  6100. The places to use statements are inside a block, and inside a
  6101. complex statement. A @dfn{complex statement} contains one or two
  6102. components that are nested statements. Each such component must
  6103. consist of one and only one statement. The way to put multiple
  6104. statements in such a component is to group them into a @dfn{block}
  6105. (@pxref{Blocks}), which counts as one statement.
  6106. The following sections describe the various kinds of statement.
  6107. @menu
  6108. * Expression Statement:: Evaluate an expression, as a statement,
  6109. usually done for a side effect.
  6110. * if Statement:: Basic conditional execution.
  6111. * if-else Statement:: Multiple branches for conditional execution.
  6112. * Blocks:: Grouping multiple statements together.
  6113. * return Statement:: Return a value from a function.
  6114. * Loop Statements:: Repeatedly executing a statement or block.
  6115. * switch Statement:: Multi-way conditional choices.
  6116. * switch Example:: A plausible example of using @code{switch}.
  6117. * Duffs Device:: A special way to use @code{switch}.
  6118. * Case Ranges:: Ranges of values for @code{switch} cases.
  6119. * Null Statement:: A statement that does nothing.
  6120. * goto Statement:: Jump to another point in the source code,
  6121. identified by a label.
  6122. * Local Labels:: Labels with limited scope.
  6123. * Labels as Values:: Getting the address of a label.
  6124. * Statement Exprs:: A series of statements used as an expression.
  6125. @end menu
  6126. @node Expression Statement
  6127. @section Expression Statement
  6128. @cindex expression statement
  6129. @cindex statement, expression
  6130. The most common kind of statement in C is an @dfn{expression statement}.
  6131. It consists of an expression followed by a
  6132. semicolon. The expression's value is discarded, so the expressions
  6133. that are useful are those that have side effects: assignment
  6134. expressions, increment and decrement expressions, and function calls.
  6135. Here are examples of expression statements:
  6136. @smallexample
  6137. x = 5; /* @r{Assignment expression.} */
  6138. p++; /* @r{Increment expression.} */
  6139. printf ("Done\n"); /* @r{Function call expression.} */
  6140. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6141. x + y; /* @r{Useless statement without effect.} */
  6142. @end smallexample
  6143. In very unusual circumstances we use an expression statement
  6144. whose purpose is to get a fault if an address is invalid:
  6145. @smallexample
  6146. volatile char *p;
  6147. @r{@dots{}}
  6148. *p; /* @r{Cause signal if @code{p} is null.} */
  6149. @end smallexample
  6150. If the target of @code{p} is not declared @code{volatile}, the
  6151. compiler might optimize away the memory access, since it knows that
  6152. the value isn't really used. @xref{volatile}.
  6153. @node if Statement
  6154. @section @code{if} Statement
  6155. @cindex @code{if} statement
  6156. @cindex statement, @code{if}
  6157. @findex if
  6158. An @code{if} statement computes an expression to decide
  6159. whether to execute the following statement or not.
  6160. It looks like this:
  6161. @example
  6162. if (@var{condition})
  6163. @var{execute-if-true}
  6164. @end example
  6165. The first thing this does is compute the value of @var{condition}. If
  6166. that is true (nonzero), then it executes the statement
  6167. @var{execute-if-true}. If the value of @var{condition} is false
  6168. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6169. nothing.
  6170. This is a @dfn{complex statement} because it contains a component
  6171. @var{if-true-substatement} that is a nested statement. It must be one
  6172. and only one statement. The way to put multiple statements there is
  6173. to group them into a @dfn{block} (@pxref{Blocks}).
  6174. @node if-else Statement
  6175. @section @code{if-else} Statement
  6176. @cindex @code{if}@dots{}@code{else} statement
  6177. @cindex statement, @code{if}@dots{}@code{else}
  6178. @findex else
  6179. An @code{if}-@code{else} statement computes an expression to decide
  6180. which of two nested statements to execute.
  6181. It looks like this:
  6182. @example
  6183. if (@var{condition})
  6184. @var{if-true-substatement}
  6185. else
  6186. @var{if-false-substatement}
  6187. @end example
  6188. The first thing this does is compute the value of @var{condition}. If
  6189. that is true (nonzero), then it executes the statement
  6190. @var{if-true-substatement}. If the value of @var{condition} is false
  6191. (zero), then it executes the statement @var{if-false-substatement} instead.
  6192. This is a @dfn{complex statement} because it contains components
  6193. @var{if-true-substatement} and @var{if-else-substatement} that are
  6194. nested statements. Each must be one and only one statement. The way
  6195. to put multiple statements in such a component is to group them into a
  6196. @dfn{block} (@pxref{Blocks}).
  6197. @node Blocks
  6198. @section Blocks
  6199. @cindex block
  6200. @cindex compound statement
  6201. A @dfn{block} is a construct that contains multiple statements of any
  6202. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6203. series of statements and declarations in between. Another name for
  6204. blocks is @dfn{compound statements}.
  6205. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6206. normal statement---it does not end with a semicolon. But you can
  6207. @emph{use} it like a statement; anywhere that a statement is required
  6208. or allowed, you can write a block and consider that block a statement.
  6209. So far it seems that a block is a kind of statement with an unusual
  6210. syntax. But that is not entirely true: a function body is also a
  6211. block, and that block is definitely not a statement. The text after a
  6212. function header is not treated as a statement; only a function body is
  6213. allowed there, and nothing else would be meaningful there.
  6214. In a formal grammar we would have to choose---either a block is a kind
  6215. of statement or it is not. But this manual is meant for humans, not
  6216. for parser generators. The clearest answer for humans is, ``a block
  6217. is a statement, in some ways.''
  6218. @cindex nested block
  6219. @cindex internal block
  6220. A block that isn't a function body is called an @dfn{internal block}
  6221. or a @dfn{nested block}. You can put a nested block directly inside
  6222. another block, but more often the nested block is inside some complex
  6223. statement, such as a @code{for} statement or an @code{if} statement.
  6224. There are two uses for nested blocks in C:
  6225. @itemize @bullet
  6226. @item
  6227. To specify the scope for local declarations. For instance, a local
  6228. variable's scope is the rest of the innermost containing block.
  6229. @item
  6230. To write a series of statements where, syntactically, one statement is
  6231. called for. For instance, the @var{execute-if-true} of an @code{if}
  6232. statement is one statement. To put multiple statements there, they
  6233. have to be wrapped in a block, like this:
  6234. @example
  6235. if (x < 0)
  6236. @{
  6237. printf ("x was negative\n");
  6238. x = -x;
  6239. @}
  6240. @end example
  6241. @end itemize
  6242. This example (repeated from above) shows a nested block which serves
  6243. both purposes: it includes two statements (plus a declaration) in the
  6244. body of a @code{while} statement, and it provides the scope for the
  6245. declaration of @code{q}.
  6246. @example
  6247. void
  6248. free_intlist (struct intlistlink *p)
  6249. @{
  6250. while (p)
  6251. @{
  6252. struct intlistlink *q = p;
  6253. p = p->next;
  6254. free (q);
  6255. @}
  6256. @}
  6257. @end example
  6258. @node return Statement
  6259. @section @code{return} Statement
  6260. @cindex @code{return} statement
  6261. @cindex statement, @code{return}
  6262. @findex return
  6263. The @code{return} statement makes the containing function return
  6264. immediately. It has two forms. This one specifies no value to
  6265. return:
  6266. @example
  6267. return;
  6268. @end example
  6269. @noindent
  6270. That form is meant for functions whose return type is @code{void}
  6271. (@pxref{The Void Type}). You can also use it in a function that
  6272. returns nonvoid data, but that's a bad idea, since it makes the
  6273. function return garbage.
  6274. The form that specifies a value looks like this:
  6275. @example
  6276. return @var{value};
  6277. @end example
  6278. @noindent
  6279. which computes the expression @var{value} and makes the function
  6280. return that. If necessary, the value undergoes type conversion to
  6281. the function's declared return value type, which works like
  6282. assigning the value to a variable of that type.
  6283. @node Loop Statements
  6284. @section Loop Statements
  6285. @cindex loop statements
  6286. @cindex statements, loop
  6287. @cindex iteration
  6288. You can use a loop statement when you need to execute a series of
  6289. statements repeatedly, making an @dfn{iteration}. C provides several
  6290. different kinds of loop statements, described in the following
  6291. subsections.
  6292. Every kind of loop statement is a complex statement because contains a
  6293. component, here called @var{body}, which is a nested statement.
  6294. Most often the body is a block.
  6295. @menu
  6296. * while Statement:: Loop as long as a test expression is true.
  6297. * do-while Statement:: Execute a loop once, with further looping
  6298. as long as a test expression is true.
  6299. * break Statement:: End a loop immediately.
  6300. * for Statement:: Iterative looping.
  6301. * Example of for:: An example of iterative looping.
  6302. * Omitted for-Expressions:: for-loop expression options.
  6303. * for-Index Declarations:: for-loop declaration options.
  6304. * continue Statement:: Begin the next cycle of a loop.
  6305. @end menu
  6306. @node while Statement
  6307. @subsection @code{while} Statement
  6308. @cindex @code{while} statement
  6309. @cindex statement, @code{while}
  6310. @findex while
  6311. The @code{while} statement is the simplest loop construct.
  6312. It looks like this:
  6313. @example
  6314. while (@var{test})
  6315. @var{body}
  6316. @end example
  6317. Here, @var{body} is a statement (often a nested block) to repeat, and
  6318. @var{test} is the test expression that controls whether to repeat it again.
  6319. Each iteration of the loop starts by computing @var{test} and, if it
  6320. is true (nonzero), that means the loop should execute @var{body} again
  6321. and then start over.
  6322. Here's an example of advancing to the last structure in a chain of
  6323. structures chained through the @code{next} field:
  6324. @example
  6325. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6326. @r{@dots{}}
  6327. while (chain->next != NULL)
  6328. chain = chain->next;
  6329. @end example
  6330. @noindent
  6331. This code assumes the chain isn't empty to start with; if the chain is
  6332. empty (that is, if @code{chain} is a null pointer), the code gets a
  6333. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6334. @node do-while Statement
  6335. @subsection @code{do-while} Statement
  6336. @cindex @code{do}--@code{while} statement
  6337. @cindex statement, @code{do}--@code{while}
  6338. @findex do
  6339. The @code{do}--@code{while} statement is a simple loop construct that
  6340. performs the test at the end of the iteration.
  6341. @example
  6342. do
  6343. @var{body}
  6344. while (@var{test});
  6345. @end example
  6346. Here, @var{body} is a statement (possibly a block) to repeat, and
  6347. @var{test} is an expression that controls whether to repeat it again.
  6348. Each iteration of the loop starts by executing @var{body}. Then it
  6349. computes @var{test} and, if it is true (nonzero), that means to go
  6350. back and start over with @var{body}. If @var{test} is false (zero),
  6351. then the loop stops repeating and execution moves on past it.
  6352. @node break Statement
  6353. @subsection @code{break} Statement
  6354. @cindex @code{break} statement
  6355. @cindex statement, @code{break}
  6356. @findex break
  6357. The @code{break} statement looks like @samp{break;}. Its effect is to
  6358. exit immediately from the innermost loop construct or @code{switch}
  6359. statement (@pxref{switch Statement}).
  6360. For example, this loop advances @code{p} until the next null
  6361. character or newline.
  6362. @example
  6363. while (*p)
  6364. @{
  6365. /* @r{End loop if we have reached a newline.} */
  6366. if (*p == '\n')
  6367. break;
  6368. p++
  6369. @}
  6370. @end example
  6371. When there are nested loops, the @code{break} statement exits from the
  6372. innermost loop containing it.
  6373. @example
  6374. struct list_if_tuples
  6375. @{
  6376. struct list_if_tuples next;
  6377. int length;
  6378. data *contents;
  6379. @};
  6380. void
  6381. process_all_elements (struct list_if_tuples *list)
  6382. @{
  6383. while (list)
  6384. @{
  6385. /* @r{Process all the elements in this node's vector,}
  6386. @r{stopping when we reach one that is null.} */
  6387. for (i = 0; i < list->length; i++
  6388. @{
  6389. /* @r{Null element terminates this node's vector.} */
  6390. if (list->contents[i] == NULL)
  6391. /* @r{Exit the @code{for} loop.} */
  6392. break;
  6393. /* @r{Operate on the next element.} */
  6394. process_element (list->contents[i]);
  6395. @}
  6396. list = list->next;
  6397. @}
  6398. @}
  6399. @end example
  6400. The only way in C to exit from an outer loop is with
  6401. @code{goto} (@pxref{goto Statement}).
  6402. @node for Statement
  6403. @subsection @code{for} Statement
  6404. @cindex @code{for} statement
  6405. @cindex statement, @code{for}
  6406. @findex for
  6407. A @code{for} statement uses three expressions written inside a
  6408. parenthetical group to define the repetition of the loop. The first
  6409. expression says how to prepare to start the loop. The second says how
  6410. to test, before each iteration, whether to continue looping. The
  6411. third says how to advance, at the end of an iteration, for the next
  6412. iteration. All together, it looks like this:
  6413. @example
  6414. for (@var{start}; @var{continue-test}; @var{advance})
  6415. @var{body}
  6416. @end example
  6417. The first thing the @code{for} statement does is compute @var{start}.
  6418. The next thing it does is compute the expression @var{continue-test}.
  6419. If that expression is false (zero), the @code{for} statement finishes
  6420. immediately, so @var{body} is executed zero times.
  6421. However, if @var{continue-test} is true (nonzero), the @code{for}
  6422. statement executes @var{body}, then @var{advance}. Then it loops back
  6423. to the not-quite-top to test @var{continue-test} again. But it does
  6424. not compute @var{start} again.
  6425. @node Example of for
  6426. @subsection Example of @code{for}
  6427. Here is the @code{for} statement from the iterative Fibonacci
  6428. function:
  6429. @example
  6430. int i;
  6431. for (i = 1; i < n; ++i)
  6432. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6433. /* @r{since @code{i < n} is false the first time.} */
  6434. @{
  6435. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6436. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6437. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6438. int next = prev + last;
  6439. /* @r{Shift the values down.} */
  6440. prev = last;
  6441. last = next;
  6442. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6443. @r{and @var{prev} is @code{fib (@var{i})}.}
  6444. @r{But that won't stay true for long,}
  6445. @r{because we are about to increment @var{i}.} */
  6446. @}
  6447. @end example
  6448. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6449. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6450. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6451. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6452. that contains a declaration and two statements.
  6453. @node Omitted for-Expressions
  6454. @subsection Omitted @code{for}-Expressions
  6455. A fully-fleshed @code{for} statement contains all these parts,
  6456. @example
  6457. for (@var{start}; @var{continue-test}; @var{advance})
  6458. @var{body}
  6459. @end example
  6460. @noindent
  6461. but you can omit any of the three expressions inside the parentheses.
  6462. The parentheses and the two semicolons are required syntactically, but
  6463. the expressions between them may be missing. A missing expression
  6464. means this loop doesn't use that particular feature of the @code{for}
  6465. statement.
  6466. @c ??? You can't do this if START is a declaration.
  6467. Instead of using @var{start}, you can do the loop preparation
  6468. before the @code{for} statement: the effect is the same. So we
  6469. could have written the beginning of the previous example this way:
  6470. @example
  6471. int i = 0;
  6472. for (; i < n; ++i)
  6473. @end example
  6474. @noindent
  6475. instead of this way:
  6476. @example
  6477. int i;
  6478. for (i = 0; i < n; ++i)
  6479. @end example
  6480. Omitting @var{continue-test} means the loop runs forever (or until
  6481. something else causes exit from it). Statements inside the loop can
  6482. test conditions for termination and use @samp{break;} to exit. This
  6483. is more flexible since you can put those tests anywhere in the loop,
  6484. not solely at the beginning.
  6485. Putting an expression in @var{advance} is almost equivalent to writing
  6486. it at the end of the loop body; it does almost the same thing. The
  6487. only difference is for the @code{continue} statement (@pxref{continue
  6488. Statement}). So we could have written this:
  6489. @example
  6490. for (i = 0; i < n;)
  6491. @{
  6492. @r{@dots{}}
  6493. ++i;
  6494. @}
  6495. @end example
  6496. @noindent
  6497. instead of this:
  6498. @example
  6499. for (i = 0; i < n; ++i)
  6500. @{
  6501. @r{@dots{}}
  6502. @}
  6503. @end example
  6504. The choice is mainly a matter of what is more readable for
  6505. programmers. However, there is also a syntactic difference:
  6506. @var{advance} is an expression, not a statement. It can't include
  6507. loops, blocks, declarations, etc.
  6508. @node for-Index Declarations
  6509. @subsection @code{for}-Index Declarations
  6510. You can declare loop-index variables directly in the @var{start}
  6511. portion of the @code{for}-loop, like this:
  6512. @example
  6513. for (int i = 0; i < n; ++i)
  6514. @{
  6515. @r{@dots{}}
  6516. @}
  6517. @end example
  6518. This kind of @var{start} is limited to a single declaration; it can
  6519. declare one or more variables, separated by commas, all of which are
  6520. the same @var{basetype} (@code{int}, in this example):
  6521. @example
  6522. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6523. @{
  6524. @r{@dots{}}
  6525. @}
  6526. @end example
  6527. @noindent
  6528. The scope of these variables is the @code{for} statement as a whole.
  6529. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6530. Variables declared in @code{for} statements should have initializers.
  6531. Omitting the initialization gives the variables unpredictable initial
  6532. values, so this code is erroneous.
  6533. @example
  6534. for (int i; i < n; ++i)
  6535. @{
  6536. @r{@dots{}}
  6537. @}
  6538. @end example
  6539. @node continue Statement
  6540. @subsection @code{continue} Statement
  6541. @cindex @code{continue} statement
  6542. @cindex statement, @code{continue}
  6543. @findex continue
  6544. The @code{continue} statement looks like @samp{continue;}, and its
  6545. effect is to jump immediately to the end of the innermost loop
  6546. construct. If it is a @code{for}-loop, the next thing that happens
  6547. is to execute the loop's @var{advance} expression.
  6548. For example, this loop increments @code{p} until the next null character
  6549. or newline, and operates (in some way not shown) on all the characters
  6550. in the line except for spaces. All it does with spaces is skip them.
  6551. @example
  6552. for (;*p; ++p)
  6553. @{
  6554. /* @r{End loop if we have reached a newline.} */
  6555. if (*p == '\n')
  6556. break;
  6557. /* @r{Pay no attention to spaces.} */
  6558. if (*p == ' ')
  6559. continue;
  6560. /* @r{Operate on the next character.} */
  6561. @r{@dots{}}
  6562. @}
  6563. @end example
  6564. @noindent
  6565. Executing @samp{continue;} skips the loop body but it does not
  6566. skip the @var{advance} expression, @code{p++}.
  6567. We could also write it like this:
  6568. @example
  6569. for (;*p; ++p)
  6570. @{
  6571. /* @r{Exit if we have reached a newline.} */
  6572. if (*p == '\n')
  6573. break;
  6574. /* @r{Pay no attention to spaces.} */
  6575. if (*p != ' ')
  6576. @{
  6577. /* @r{Operate on the next character.} */
  6578. @r{@dots{}}
  6579. @}
  6580. @}
  6581. @end example
  6582. The advantage of using @code{continue} is that it reduces the
  6583. depth of nesting.
  6584. Contrast @code{continue} with the @code{break} statement. @xref{break
  6585. Statement}.
  6586. @node switch Statement
  6587. @section @code{switch} Statement
  6588. @cindex @code{switch} statement
  6589. @cindex statement, @code{switch}
  6590. @findex switch
  6591. @findex case
  6592. @findex default
  6593. The @code{switch} statement selects code to run according to the value
  6594. of an expression. The expression, in parentheses, follows the keyword
  6595. @code{switch}. After that come all the cases to select among,
  6596. inside braces. It looks like this:
  6597. @example
  6598. switch (@var{selector})
  6599. @{
  6600. @var{cases}@r{@dots{}}
  6601. @}
  6602. @end example
  6603. A case can look like this:
  6604. @example
  6605. case @var{value}:
  6606. @var{statements}
  6607. break;
  6608. @end example
  6609. @noindent
  6610. which means ``come here if @var{selector} happens to have the value
  6611. @var{value},'' or like this (a GNU C extension):
  6612. @example
  6613. case @var{rangestart} ... @var{rangeend}:
  6614. @var{statements}
  6615. break;
  6616. @end example
  6617. @noindent
  6618. which means ``come here if @var{selector} happens to have a value
  6619. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6620. Ranges}.
  6621. The values in @code{case} labels must reduce to integer constants.
  6622. They can use arithmetic, and @code{enum} constants, but they cannot
  6623. refer to data in memory, because they have to be computed at compile
  6624. time. It is an error if two @code{case} labels specify the same
  6625. value, or ranges that overlap, or if one is a range and the other is a
  6626. value in that range.
  6627. You can also define a default case to handle ``any other value,'' like
  6628. this:
  6629. @example
  6630. default:
  6631. @var{statements}
  6632. break;
  6633. @end example
  6634. If the @code{switch} statement has no @code{default:} label, then it
  6635. does nothing when the value matches none of the cases.
  6636. The brace-group inside the @code{switch} statement is a block, and you
  6637. can declare variables with that scope just as in any other block
  6638. (@pxref{Blocks}). However, initializers in these declarations won't
  6639. necessarily be executed every time the @code{switch} statement runs,
  6640. so it is best to avoid giving them initializers.
  6641. @code{break;} inside a @code{switch} statement exits immediately from
  6642. the @code{switch} statement. @xref{break Statement}.
  6643. If there is no @code{break;} at the end of the code for a case,
  6644. execution continues into the code for the following case. This
  6645. happens more often by mistake than intentionally, but since this
  6646. feature is used in real code, we cannot eliminate it.
  6647. @strong{Warning:} When one case is intended to fall through to the
  6648. next, write a comment like @samp{falls through} to say it's
  6649. intentional. That way, other programmers won't assume it was an error
  6650. and ``fix'' it erroneously.
  6651. Consecutive @code{case} statements could, pedantically, be considered
  6652. an instance of falling through, but we don't consider or treat them that
  6653. way because they won't confuse anyone.
  6654. @node switch Example
  6655. @section Example of @code{switch}
  6656. Here's an example of using the @code{switch} statement
  6657. to distinguish among characters:
  6658. @cindex counting vowels and punctuation
  6659. @example
  6660. struct vp @{ int vowels, punct; @};
  6661. struct vp
  6662. count_vowels_and_punct (char *string)
  6663. @{
  6664. int c;
  6665. int vowels = 0;
  6666. int punct = 0;
  6667. /* @r{Don't change the parameter itself.} */
  6668. /* @r{That helps in debugging.} */
  6669. char *p = string;
  6670. struct vp value;
  6671. while (c = *p++)
  6672. switch (c)
  6673. @{
  6674. case 'y':
  6675. case 'Y':
  6676. /* @r{We assume @code{y_is_consonant} will check surrounding
  6677. letters to determine whether this y is a vowel.} */
  6678. if (y_is_consonant (p - 1))
  6679. break;
  6680. /* @r{Falls through} */
  6681. case 'a':
  6682. case 'e':
  6683. case 'i':
  6684. case 'o':
  6685. case 'u':
  6686. case 'A':
  6687. case 'E':
  6688. case 'I':
  6689. case 'O':
  6690. case 'U':
  6691. vowels++;
  6692. break;
  6693. case '.':
  6694. case ',':
  6695. case ':':
  6696. case ';':
  6697. case '?':
  6698. case '!':
  6699. case '\"':
  6700. case '\'':
  6701. punct++;
  6702. break;
  6703. @}
  6704. value.vowels = vowels;
  6705. value.punct = punct;
  6706. return value;
  6707. @}
  6708. @end example
  6709. @node Duffs Device
  6710. @section Duff's Device
  6711. @cindex Duff's device
  6712. The cases in a @code{switch} statement can be inside other control
  6713. constructs. For instance, we can use a technique known as @dfn{Duff's
  6714. device} to optimize this simple function,
  6715. @example
  6716. void
  6717. copy (char *to, char *from, int count)
  6718. @{
  6719. while (count > 0)
  6720. *to++ = *from++, count--;
  6721. @}
  6722. @end example
  6723. @noindent
  6724. which copies memory starting at @var{from} to memory starting at
  6725. @var{to}.
  6726. Duff's device involves unrolling the loop so that it copies
  6727. several characters each time around, and using a @code{switch} statement
  6728. to enter the loop body at the proper point:
  6729. @example
  6730. void
  6731. copy (char *to, char *from, int count)
  6732. @{
  6733. if (count <= 0)
  6734. return;
  6735. int n = (count + 7) / 8;
  6736. switch (count % 8)
  6737. @{
  6738. do @{
  6739. case 0: *to++ = *from++;
  6740. case 7: *to++ = *from++;
  6741. case 6: *to++ = *from++;
  6742. case 5: *to++ = *from++;
  6743. case 4: *to++ = *from++;
  6744. case 3: *to++ = *from++;
  6745. case 2: *to++ = *from++;
  6746. case 1: *to++ = *from++;
  6747. @} while (--n > 0);
  6748. @}
  6749. @}
  6750. @end example
  6751. @node Case Ranges
  6752. @section Case Ranges
  6753. @cindex case ranges
  6754. @cindex ranges in case statements
  6755. You can specify a range of consecutive values in a single @code{case} label,
  6756. like this:
  6757. @example
  6758. case @var{low} ... @var{high}:
  6759. @end example
  6760. @noindent
  6761. This has the same effect as the proper number of individual @code{case}
  6762. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6763. This feature is especially useful for ranges of ASCII character codes:
  6764. @example
  6765. case 'A' ... 'Z':
  6766. @end example
  6767. @strong{Be careful:} with integers, write spaces around the @code{...}
  6768. to prevent it from being parsed wrong. For example, write this:
  6769. @example
  6770. case 1 ... 5:
  6771. @end example
  6772. @noindent
  6773. rather than this:
  6774. @example
  6775. case 1...5:
  6776. @end example
  6777. @node Null Statement
  6778. @section Null Statement
  6779. @cindex null statement
  6780. @cindex statement, null
  6781. A @dfn{null statement} is just a semicolon. It does nothing.
  6782. A null statement is a placeholder for use where a statement is
  6783. grammatically required, but there is nothing to be done. For
  6784. instance, sometimes all the work of a @code{for}-loop is done in the
  6785. @code{for}-header itself, leaving no work for the body. Here is an
  6786. example that searches for the first newline in @code{array}:
  6787. @example
  6788. for (p = array; *p != '\n'; p++)
  6789. ;
  6790. @end example
  6791. @node goto Statement
  6792. @section @code{goto} Statement and Labels
  6793. @cindex @code{goto} statement
  6794. @cindex statement, @code{goto}
  6795. @cindex label
  6796. @findex goto
  6797. The @code{goto} statement looks like this:
  6798. @example
  6799. goto @var{label};
  6800. @end example
  6801. @noindent
  6802. Its effect is to transfer control immediately to another part of the
  6803. current function---where the label named @var{label} is defined.
  6804. An ordinary label definition looks like this:
  6805. @example
  6806. @var{label}:
  6807. @end example
  6808. @noindent
  6809. and it can appear before any statement. You can't use @code{default}
  6810. as a label, since that has a special meaning for @code{switch}
  6811. statements.
  6812. An ordinary label doesn't need a separate declaration; defining it is
  6813. enough.
  6814. Here's an example of using @code{goto} to implement a loop
  6815. equivalent to @code{do}--@code{while}:
  6816. @example
  6817. @{
  6818. loop_restart:
  6819. @var{body}
  6820. if (@var{condition})
  6821. goto loop_restart;
  6822. @}
  6823. @end example
  6824. The name space of labels is separate from that of variables and functions.
  6825. Thus, there is no error in using a single name in both ways:
  6826. @example
  6827. @{
  6828. int foo; // @r{Variable @code{foo}.}
  6829. foo: // @r{Label @code{foo}.}
  6830. @var{body}
  6831. if (foo > 0) // @r{Variable @code{foo}.}
  6832. goto foo; // @r{Label @code{foo}.}
  6833. @}
  6834. @end example
  6835. Blocks have no effect on ordinary labels; each label name is defined
  6836. throughout the whole of the function it appears in. It looks strange to
  6837. jump into a block with @code{goto}, but it works. For example,
  6838. @example
  6839. if (x < 0)
  6840. goto negative;
  6841. if (y < 0)
  6842. @{
  6843. negative:
  6844. printf ("Negative\n");
  6845. return;
  6846. @}
  6847. @end example
  6848. If the goto jumps into the scope of a variable, it does not
  6849. initialize the variable. For example, if @code{x} is negative,
  6850. @example
  6851. if (x < 0)
  6852. goto negative;
  6853. if (y < 0)
  6854. @{
  6855. int i = 5;
  6856. negative:
  6857. printf ("Negative, and i is %d\n", i);
  6858. return;
  6859. @}
  6860. @end example
  6861. @noindent
  6862. prints junk because @code{i} was not initialized.
  6863. If the block declares a variable-length automatic array, jumping into
  6864. it gives a compilation error. However, jumping out of the scope of a
  6865. variable-length array works fine, and deallocates its storage.
  6866. A label can't come directly before a declaration, so the code can't
  6867. jump directly to one. For example, this is not allowed:
  6868. @example
  6869. @{
  6870. goto foo;
  6871. foo:
  6872. int x = 5;
  6873. bar(&x);
  6874. @}
  6875. @end example
  6876. @noindent
  6877. The workaround is to add a statement, even an empty statement,
  6878. directly after the label. For example:
  6879. @example
  6880. @{
  6881. goto foo;
  6882. foo:
  6883. ;
  6884. int x = 5;
  6885. bar(&x);
  6886. @}
  6887. @end example
  6888. Likewise, a label can't be the last thing in a block. The workaround
  6889. solution is the same: add a semicolon after the label.
  6890. These unnecessary restrictions on labels make no sense, and ought in
  6891. principle to be removed; but they do only a little harm since labels
  6892. and @code{goto} are rarely the best way to write a program.
  6893. These examples are all artificial; it would be more natural to
  6894. write them in other ways, without @code{goto}. For instance,
  6895. the clean way to write the example that prints @samp{Negative} is this:
  6896. @example
  6897. if (x < 0 || y < 0)
  6898. @{
  6899. printf ("Negative\n");
  6900. return;
  6901. @}
  6902. @end example
  6903. @noindent
  6904. It is hard to construct simple examples where @code{goto} is actually
  6905. the best way to write a program. Its rare good uses tend to be in
  6906. complex code, thus not apt for the purpose of explaining the meaning
  6907. of @code{goto}.
  6908. The only good time to use @code{goto} is when it makes the code
  6909. simpler than any alternative. Jumping backward is rarely desirable,
  6910. because usually the other looping and control constructs give simpler
  6911. code. Using @code{goto} to jump forward is more often desirable, for
  6912. instance when a function needs to do some processing in an error case
  6913. and errors can occur at various different places within the function.
  6914. @node Local Labels
  6915. @section Locally Declared Labels
  6916. @cindex local labels
  6917. @cindex macros, local labels
  6918. @findex __label__
  6919. In GNU C you can declare @dfn{local labels} in any nested block
  6920. scope. A local label is used in a @code{goto} statement just like an
  6921. ordinary label, but you can only reference it within the block in
  6922. which it was declared.
  6923. A local label declaration looks like this:
  6924. @example
  6925. __label__ @var{label};
  6926. @end example
  6927. @noindent
  6928. or
  6929. @example
  6930. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6931. @end example
  6932. Local label declarations must come at the beginning of the block,
  6933. before any ordinary declarations or statements.
  6934. The label declaration declares the label @emph{name}, but does not define
  6935. the label itself. That's done in the usual way, with
  6936. @code{@var{label}:}, before one of the statements in the block.
  6937. The local label feature is useful for complex macros. If a macro
  6938. contains nested loops, a @code{goto} can be useful for breaking out of
  6939. them. However, an ordinary label whose scope is the whole function
  6940. cannot be used: if the macro can be expanded several times in one
  6941. function, the label will be multiply defined in that function. A
  6942. local label avoids this problem. For example:
  6943. @example
  6944. #define SEARCH(value, array, target) \
  6945. do @{ \
  6946. __label__ found; \
  6947. __auto_type _SEARCH_target = (target); \
  6948. __auto_type _SEARCH_array = (array); \
  6949. int i, j; \
  6950. int value; \
  6951. for (i = 0; i < max; i++) \
  6952. for (j = 0; j < max; j++) \
  6953. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6954. @{ (value) = i; goto found; @} \
  6955. (value) = -1; \
  6956. found:; \
  6957. @} while (0)
  6958. @end example
  6959. This could also be written using a statement expression
  6960. (@pxref{Statement Exprs}):
  6961. @example
  6962. #define SEARCH(array, target) \
  6963. (@{ \
  6964. __label__ found; \
  6965. __auto_type _SEARCH_target = (target); \
  6966. __auto_type _SEARCH_array = (array); \
  6967. int i, j; \
  6968. int value; \
  6969. for (i = 0; i < max; i++) \
  6970. for (j = 0; j < max; j++) \
  6971. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6972. @{ value = i; goto found; @} \
  6973. value = -1; \
  6974. found: \
  6975. value; \
  6976. @})
  6977. @end example
  6978. Ordinary labels are visible throughout the function where they are
  6979. defined, and only in that function. However, explicitly declared
  6980. local labels of a block are visible in nested function definitions
  6981. inside that block. @xref{Nested Functions}, for details.
  6982. @xref{goto Statement}.
  6983. @node Labels as Values
  6984. @section Labels as Values
  6985. @cindex labels as values
  6986. @cindex computed gotos
  6987. @cindex goto with computed label
  6988. @cindex address of a label
  6989. In GNU C, you can get the address of a label defined in the current
  6990. function (or a local label defined in the containing function) with
  6991. the unary operator @samp{&&}. The value has type @code{void *}. This
  6992. value is a constant and can be used wherever a constant of that type
  6993. is valid. For example:
  6994. @example
  6995. void *ptr;
  6996. @r{@dots{}}
  6997. ptr = &&foo;
  6998. @end example
  6999. To use these values requires a way to jump to one. This is done
  7000. with the computed goto statement@footnote{The analogous feature in
  7001. Fortran is called an assigned goto, but that name seems inappropriate in
  7002. C, since you can do more with label addresses than store them in special label
  7003. variables.}, @code{goto *@var{exp};}. For example,
  7004. @example
  7005. goto *ptr;
  7006. @end example
  7007. @noindent
  7008. Any expression of type @code{void *} is allowed.
  7009. @xref{goto Statement}.
  7010. @menu
  7011. * Label Value Uses:: Examples of using label values.
  7012. * Label Value Caveats:: Limitations of label values.
  7013. @end menu
  7014. @node Label Value Uses
  7015. @subsection Label Value Uses
  7016. One use for label-valued constants is to initialize a static array to
  7017. serve as a jump table:
  7018. @example
  7019. static void *array[] = @{ &&foo, &&bar, &&hack @};
  7020. @end example
  7021. Then you can select a label with indexing, like this:
  7022. @example
  7023. goto *array[i];
  7024. @end example
  7025. @noindent
  7026. Note that this does not check whether the subscript is in bounds---array
  7027. indexing in C never checks that.
  7028. You can make the table entries offsets instead of addresses
  7029. by subtracting one label from the others. Here is an example:
  7030. @example
  7031. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  7032. &&hack - &&foo @};
  7033. goto *(&&foo + array[i]);
  7034. @end example
  7035. @noindent
  7036. Using offsets is preferable in shared libraries, as it avoids the need
  7037. for dynamic relocation of the array elements; therefore, the array can
  7038. be read-only.
  7039. An array of label values or offsets serves a purpose much like that of
  7040. the @code{switch} statement. The @code{switch} statement is cleaner,
  7041. so use @code{switch} by preference when feasible.
  7042. Another use of label values is in an interpreter for threaded code.
  7043. The labels within the interpreter function can be stored in the
  7044. threaded code for super-fast dispatching.
  7045. @node Label Value Caveats
  7046. @subsection Label Value Caveats
  7047. Jumping to a label defined in another function does not work.
  7048. It can cause unpredictable results.
  7049. The best way to avoid this is to store label values only in
  7050. automatic variables, or static variables whose names are declared
  7051. within the function. Never pass them as arguments.
  7052. @cindex cloning
  7053. An optimization known as @dfn{cloning} generates multiple simplified
  7054. variants of a function's code, for use with specific fixed arguments.
  7055. Using label values in certain ways, such as saving the address in one
  7056. call to the function and using it again in another call, would make cloning
  7057. give incorrect results. These functions must disable cloning.
  7058. Inlining calls to the function would also result in multiple copies of
  7059. the code, each with its own value of the same label. Using the label
  7060. in a computed goto is no problem, because the computed goto inhibits
  7061. inlining. However, using the label value in some other way, such as
  7062. an indication of where an error occurred, would be optimized wrong.
  7063. These functions must disable inlining.
  7064. To prevent inlining or cloning of a function, specify
  7065. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7066. @xref{Attributes}.
  7067. When a function uses a label value in a static variable initializer,
  7068. that automatically prevents inlining or cloning the function.
  7069. @node Statement Exprs
  7070. @section Statements and Declarations in Expressions
  7071. @cindex statements inside expressions
  7072. @cindex declarations inside expressions
  7073. @cindex expressions containing statements
  7074. @c the above section title wrapped and causes an underfull hbox.. i
  7075. @c changed it from "within" to "in". --mew 4feb93
  7076. A block enclosed in parentheses can be used as an expression in GNU
  7077. C@. This provides a way to use local variables, loops and switches within
  7078. an expression. We call it a @dfn{statement expression}.
  7079. Recall that a block is a sequence of statements
  7080. surrounded by braces. In this construct, parentheses go around the
  7081. braces. For example:
  7082. @example
  7083. (@{ int y = foo (); int z;
  7084. if (y > 0) z = y;
  7085. else z = - y;
  7086. z; @})
  7087. @end example
  7088. @noindent
  7089. is a valid (though slightly more complex than necessary) expression
  7090. for the absolute value of @code{foo ()}.
  7091. The last statement in the block should be an expression statement; an
  7092. expression followed by a semicolon, that is. The value of this
  7093. expression serves as the value of statement expression. If the last
  7094. statement is anything else, the statement expression's value is
  7095. @code{void}.
  7096. This feature is mainly useful in making macro definitions compute each
  7097. operand exactly once. @xref{Macros and Auto Type}.
  7098. Statement expressions are not allowed in expressions that must be
  7099. constant, such as the value for an enumerator, the width of a
  7100. bit-field, or the initial value of a static variable.
  7101. Jumping into a statement expression---with @code{goto}, or using a
  7102. @code{switch} statement outside the statement expression---is an
  7103. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7104. compiler can't detect the error, but it still won't work.
  7105. Jumping out of a statement expression is permitted, but since
  7106. subexpressions in C are not computed in a strict order, it is
  7107. unpredictable which other subexpressions will have been computed by
  7108. then. For example,
  7109. @example
  7110. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7111. @end example
  7112. @noindent
  7113. calls @code{foo} and @code{bar1} before it jumps, and never
  7114. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7115. does get called, that occurs after @code{foo} and before @code{bar1}.
  7116. @node Variables
  7117. @chapter Variables
  7118. @cindex variables
  7119. Every variable used in a C program needs to be made known by a
  7120. @dfn{declaration}. It can be used only after it has been declared.
  7121. It is an error to declare a variable name more than once in the same
  7122. scope; an exception is that @code{extern} declarations and tentative
  7123. definitions can coexist with another declaration of the same
  7124. variable.
  7125. Variables can be declared anywhere within a block or file. (Older
  7126. versions of C required that all variable declarations within a block
  7127. occur before any statements.)
  7128. Variables declared within a function or block are @dfn{local} to
  7129. it. This means that the variable name is visible only until the end
  7130. of that function or block, and the memory space is allocated only
  7131. while control is within it.
  7132. Variables declared at the top level in a file are called @dfn{file-scope}.
  7133. They are assigned fixed, distinct memory locations, so they retain
  7134. their values for the whole execution of the program.
  7135. @menu
  7136. * Variable Declarations:: Name a variable and and reserve space for it.
  7137. * Initializers:: Assigning inital values to variables.
  7138. * Designated Inits:: Assigning initial values to array elements
  7139. at particular array indices.
  7140. * Auto Type:: Obtaining the type of a variable.
  7141. * Local Variables:: Variables declared in function definitions.
  7142. * File-Scope Variables:: Variables declared outside of
  7143. function definitions.
  7144. * Static Local Variables:: Variables declared within functions,
  7145. but with permanent storage allocation.
  7146. * Extern Declarations:: Declaring a variable
  7147. which is allocated somewhere else.
  7148. * Allocating File-Scope:: When is space allocated
  7149. for file-scope variables?
  7150. * auto and register:: Historically used storage directions.
  7151. * Omitting Types:: The bad practice of declaring variables
  7152. with implicit type.
  7153. @end menu
  7154. @node Variable Declarations
  7155. @section Variable Declarations
  7156. @cindex variable declarations
  7157. @cindex declaration of variables
  7158. Here's what a variable declaration looks like:
  7159. @example
  7160. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7161. @end example
  7162. The @var{keywords} specify how to handle the scope of the variable
  7163. name and the allocation of its storage. Most declarations have
  7164. no keywords because the defaults are right for them.
  7165. C allows these keywords to come before or after @var{basetype}, or
  7166. even in the middle of it as in @code{unsigned static int}, but don't
  7167. do that---it would surprise other programmers. Always write the
  7168. keywords first.
  7169. The @var{basetype} can be any of the predefined types of C, or a type
  7170. keyword defined with @code{typedef}. It can also be @code{struct
  7171. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7172. addition, it can include type qualifiers such as @code{const} and
  7173. @code{volatile} (@pxref{Type Qualifiers}).
  7174. In the simplest case, @var{decorated-variable} is just the variable
  7175. name. That declares the variable with the type specified by
  7176. @var{basetype}. For instance,
  7177. @example
  7178. int foo;
  7179. @end example
  7180. @noindent
  7181. uses @code{int} as the @var{basetype} and @code{foo} as the
  7182. @var{decorated-variable}. It declares @code{foo} with type
  7183. @code{int}.
  7184. @example
  7185. struct tree_node foo;
  7186. @end example
  7187. @noindent
  7188. declares @code{foo} with type @code{struct tree_node}.
  7189. @menu
  7190. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7191. array and pointer types.
  7192. * Combining Variable Declarations:: More than one variable declaration
  7193. in a single statement.
  7194. @end menu
  7195. @node Declaring Arrays and Pointers
  7196. @subsection Declaring Arrays and Pointers
  7197. @cindex declaring arrays and pointers
  7198. @cindex array, declaring
  7199. @cindex pointers, declaring
  7200. To declare a variable that is an array, write
  7201. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7202. @example
  7203. int foo[5];
  7204. @end example
  7205. To declare a variable that has a pointer type, write
  7206. @code{*@var{variable}} for @var{decorated-variable}:
  7207. @example
  7208. struct list_elt *foo;
  7209. @end example
  7210. These constructs nest. For instance,
  7211. @example
  7212. int foo[3][5];
  7213. @end example
  7214. @noindent
  7215. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7216. @example
  7217. struct list_elt *foo[5];
  7218. @end example
  7219. @noindent
  7220. declares @code{foo} as an array of 5 pointers to structures, and
  7221. @example
  7222. struct list_elt **foo;
  7223. @end example
  7224. @noindent
  7225. declares @code{foo} as a pointer to a pointer to a structure.
  7226. @example
  7227. int **(*foo[30])(int, double);
  7228. @end example
  7229. @noindent
  7230. declares @code{foo} as an array of 30 pointers to functions
  7231. (@pxref{Function Pointers}), each of which must accept two arguments
  7232. (one @code{int} and one @code{double}) and return type @code{int **}.
  7233. @example
  7234. void
  7235. bar (int size)
  7236. @{
  7237. int foo[size];
  7238. @r{@dots{}}
  7239. @}
  7240. @end example
  7241. @noindent
  7242. declares @code{foo} as an array of integers with a size specified at
  7243. run time when the function @code{bar} is called.
  7244. @node Combining Variable Declarations
  7245. @subsection Combining Variable Declarations
  7246. @cindex combining variable declarations
  7247. @cindex variable declarations, combining
  7248. @cindex declarations, combining
  7249. When multiple declarations have the same @var{keywords} and
  7250. @var{basetype}, you can combine them using commas. Thus,
  7251. @example
  7252. @var{keywords} @var{basetype}
  7253. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7254. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7255. @end example
  7256. @noindent
  7257. is equivalent to
  7258. @example
  7259. @var{keywords} @var{basetype}
  7260. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7261. @var{keywords} @var{basetype}
  7262. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7263. @end example
  7264. Here are some simple examples:
  7265. @example
  7266. int a, b;
  7267. int a = 1, b = 2;
  7268. int a, *p, array[5];
  7269. int a = 0, *p = &a, array[5] = @{1, 2@};
  7270. @end example
  7271. @noindent
  7272. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7273. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7274. Since the initializer for @code{array} specifies only two elements,
  7275. the other three elements are initialized to zero.
  7276. @node Initializers
  7277. @section Initializers
  7278. @cindex initializers
  7279. A variable's declaration, unless it is @code{extern}, should also
  7280. specify its initial value. For numeric and pointer-type variables,
  7281. the initializer is an expression for the value. If necessary, it is
  7282. converted to the variable's type, just as in an assignment.
  7283. You can also initialize a local structure-type (@pxref{Structures}) or
  7284. local union-type (@pxref{Unions}) variable this way, from an
  7285. expression whose value has the same type. But you can't initialize an
  7286. array this way (@pxref{Arrays}), since arrays are not first-class
  7287. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7288. assignment.
  7289. You can initialize arrays and structures componentwise,
  7290. with a list of the elements or components. You can initialize
  7291. a union with any one of its alternatives.
  7292. @itemize @bullet
  7293. @item
  7294. A component-wise initializer for an array consists of element values
  7295. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7296. don't cover all the elements in the array, the remaining elements are
  7297. initialized to zero.
  7298. You can omit the size of the array when you declare it, and let
  7299. the initializer specify the size:
  7300. @example
  7301. int array[] = @{ 3, 9, 12 @};
  7302. @end example
  7303. @item
  7304. A component-wise initializer for a structure consists of field values
  7305. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7306. order as the fields are declared in the structure. If the values in
  7307. the initializer don't cover all the fields in the structure, the
  7308. remaining fields are initialized to zero.
  7309. @item
  7310. The initializer for a union-type variable has the form @code{@{
  7311. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7312. in the union definition.
  7313. @end itemize
  7314. For an array of arrays, a structure containing arrays, an array of
  7315. structures, etc., you can nest these constructs. For example,
  7316. @example
  7317. struct point @{ double x, y; @};
  7318. struct point series[]
  7319. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7320. @end example
  7321. You can omit a pair of inner braces if they contain the right
  7322. number of elements for the sub-value they initialize, so that
  7323. no elements or fields need to be filled in with zeros.
  7324. But don't do that very much, as it gets confusing.
  7325. An array of @code{char} can be initialized using a string constant.
  7326. Recall that the string constant includes an implicit null character at
  7327. the end (@pxref{String Constants}). Using a string constant as
  7328. initializer means to use its contents as the initial values of the
  7329. array elements. Here are examples:
  7330. @example
  7331. char text[6] = "text!"; /* @r{Includes the null.} */
  7332. char text[5] = "text!"; /* @r{Excludes the null.} */
  7333. char text[] = "text!"; /* @r{Gets length 6.} */
  7334. char text[]
  7335. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7336. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7337. @end example
  7338. @noindent
  7339. and this kind of initializer can be nested inside braces to initialize
  7340. structures or arrays that contain a @code{char}-array.
  7341. In like manner, you can use a wide string constant to initialize
  7342. an array of @code{wchar_t}.
  7343. @node Designated Inits
  7344. @section Designated Initializers
  7345. @cindex initializers with labeled elements
  7346. @cindex labeled elements in initializers
  7347. @cindex case labels in initializers
  7348. @cindex designated initializers
  7349. In a complex structure or long array, it's useful to indicate
  7350. which field or element we are initializing.
  7351. To designate specific array elements during initialization, include
  7352. the array index in brackets, and an assignment operator, for each
  7353. element:
  7354. @example
  7355. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7356. @end example
  7357. @noindent
  7358. This does the same thing as:
  7359. @example
  7360. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7361. @end example
  7362. The array initialization can include non-designated element values
  7363. alongside designated indices; these follow the expected ordering
  7364. of the array initialization, so that
  7365. @example
  7366. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7367. @end example
  7368. @noindent
  7369. does the same thing as:
  7370. @example
  7371. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7372. @end example
  7373. Note that you can only use constant expressions as array index values,
  7374. not variables.
  7375. If you need to initialize a subsequence of sequential array elements to
  7376. the same value, you can specify a range:
  7377. @example
  7378. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7379. @end example
  7380. @noindent
  7381. Using a range this way is a GNU C extension.
  7382. When subsequence ranges overlap, each element is initialized by the
  7383. last specification that applies to it. Thus, this initialization is
  7384. equivalent to the previous one.
  7385. @example
  7386. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7387. @end example
  7388. @noindent
  7389. as the second overrides the first for elements 0 through 19.
  7390. The value used to initialize a range of elements is evaluated only
  7391. once, for the first element in the range. So for example, this code
  7392. @example
  7393. int random_values[100]
  7394. = @{ [0 ... 99] = get_random_number() @};
  7395. @end example
  7396. @noindent
  7397. would initialize all 100 elements of the array @code{random_values} to
  7398. the same value---probably not what is intended.
  7399. Similarly, you can initialize specific fields of a structure variable
  7400. by specifying the field name prefixed with a dot:
  7401. @example
  7402. struct point @{ int x; int y; @};
  7403. struct point foo = @{ .y = 42; @};
  7404. @end example
  7405. @noindent
  7406. The same syntax works for union variables as well:
  7407. @example
  7408. union int_double @{ int i; double d; @};
  7409. union int_double foo = @{ .d = 34 @};
  7410. @end example
  7411. @noindent
  7412. This casts the integer value 34 to a double and stores it
  7413. in the union variable @code{foo}.
  7414. You can designate both array elements and structure elements in
  7415. the same initialization; for example, here's an array of point
  7416. structures:
  7417. @example
  7418. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7419. @end example
  7420. Along with the capability to specify particular array and structure
  7421. elements to initialize comes the possibility of initializing the same
  7422. element more than once:
  7423. @example
  7424. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7425. @end example
  7426. @noindent
  7427. In such a case, the last initialization value is retained.
  7428. @node Auto Type
  7429. @section Referring to a Type with @code{__auto_type}
  7430. @findex __auto_type
  7431. @findex typeof
  7432. @cindex macros, types of arguments
  7433. You can declare a variable copying the type from
  7434. the initializer by using @code{__auto_type} instead of a particular type.
  7435. Here's an example:
  7436. @example
  7437. #define max(a,b) \
  7438. (@{ __auto_type _a = (a); \
  7439. __auto_type _b = (b); \
  7440. _a > _b ? _a : _b @})
  7441. @end example
  7442. This defines @code{_a} to be of the same type as @code{a}, and
  7443. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7444. to do in a macro that ought to be able to handle any type of data
  7445. (@pxref{Macros and Auto Type}).
  7446. The original GNU C method for obtaining the type of a value is to use
  7447. @code{typeof}, which takes as an argument either a value or the name of
  7448. a type. The previous example could also be written as:
  7449. @example
  7450. #define max(a,b) \
  7451. (@{ typeof(a) _a = (a); \
  7452. typeof(b) _b = (b); \
  7453. _a > _b ? _a : _b @})
  7454. @end example
  7455. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7456. principal use case for @code{typeof} is in variable declarations with
  7457. initialization, which is exactly what @code{__auto_type} handles.
  7458. @node Local Variables
  7459. @section Local Variables
  7460. @cindex local variables
  7461. @cindex variables, local
  7462. Declaring a variable inside a function definition (@pxref{Function
  7463. Definitions}) makes the variable name @dfn{local} to the containing
  7464. block---that is, the containing pair of braces. More precisely, the
  7465. variable's name is visible starting just after where it appears in the
  7466. declaration, and its visibility continues until the end of the block.
  7467. Local variables in C are generally @dfn{automatic} variables: each
  7468. variable's storage exists only from the declaration to the end of the
  7469. block. Execution of the declaration allocates the storage, computes
  7470. the initial value, and stores it in the variable. The end of the
  7471. block deallocates the storage.@footnote{Due to compiler optimizations,
  7472. allocation and deallocation don't necessarily really happen at
  7473. those times.}
  7474. @strong{Warning:} Two declarations for the same local variable
  7475. in the same scope are an error.
  7476. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7477. The total space for the program's stack may be limited; therefore,
  7478. in using very large arrays, it may be necessary to allocate
  7479. them in some other way to stop the program from crashing.
  7480. @strong{Warning:} If the declaration of an automatic variable does not
  7481. specify an initial value, the variable starts out containing garbage.
  7482. In this example, the value printed could be anything at all:
  7483. @example
  7484. @{
  7485. int i;
  7486. printf ("Print junk %d\n", i);
  7487. @}
  7488. @end example
  7489. In a simple test program, that statement is likely to print 0, simply
  7490. because every process starts with memory zeroed. But don't rely on it
  7491. to be zero---that is erroneous.
  7492. @strong{Note:} Make sure to store a value into each local variable (by
  7493. assignment, or by initialization) before referring to its value.
  7494. @node File-Scope Variables
  7495. @section File-Scope Variables
  7496. @cindex file-scope variables
  7497. @cindex global variables
  7498. @cindex variables, file-scope
  7499. @cindex variables, global
  7500. A variable declaration at the top level in a file (not inside a
  7501. function definition) declares a @dfn{file-scope variable}. Loading a
  7502. program allocates the storage for all the file-scope variables in it,
  7503. and initializes them too.
  7504. Each file-scope variable is either @dfn{static} (limited to one
  7505. compilation module) or @dfn{global} (shared with all compilation
  7506. modules in the program). To make the variable static, write the
  7507. keyword @code{static} at the start of the declaration. Omitting
  7508. @code{static} makes the variable global.
  7509. The initial value for a file-scope variable can't depend on the
  7510. contents of storage, and can't call any functions.
  7511. @example
  7512. int foo = 5; /* @r{Valid.} */
  7513. int bar = foo; /* @r{Invalid!} */
  7514. int bar = sin (1.0); /* @r{Invalid!} */
  7515. @end example
  7516. But it can use the address of another file-scope variable:
  7517. @example
  7518. int foo;
  7519. int *bar = &foo; /* @r{Valid.} */
  7520. int arr[5];
  7521. int *bar3 = &arr[3]; /* @r{Valid.} */
  7522. int *bar4 = arr + 4; /* @r{Valid.} */
  7523. @end example
  7524. It is valid for a module to have multiple declarations for a
  7525. file-scope variable, as long as they are all global or all static, but
  7526. at most one declaration can specify an initial value for it.
  7527. @node Static Local Variables
  7528. @section Static Local Variables
  7529. @cindex static local variables
  7530. @cindex variables, static local
  7531. @findex static
  7532. The keyword @code{static} in a local variable declaration says to
  7533. allocate the storage for the variable permanently, just like a
  7534. file-scope variable, even if the declaration is within a function.
  7535. Here's an example:
  7536. @example
  7537. int
  7538. increment_counter ()
  7539. @{
  7540. static int counter = 0;
  7541. return ++counter;
  7542. @}
  7543. @end example
  7544. The scope of the name @code{counter} runs from the declaration to the
  7545. end of the containing block, just like an automatic local variable,
  7546. but its storage is permanent, so the value persists from one call to
  7547. the next. As a result, each call to @code{increment_counter}
  7548. returns a different, unique value.
  7549. The initial value of a static local variable has the same limitations
  7550. as for file-scope variables: it can't depend on the contents of
  7551. storage or call any functions. It can use the address of a file-scope
  7552. variable or a static local variable, because those addresses are
  7553. determined before the program runs.
  7554. @node Extern Declarations
  7555. @section @code{extern} Declarations
  7556. @cindex @code{extern} declarations
  7557. @cindex declarations, @code{extern}
  7558. @findex extern
  7559. An @code{extern} declaration is used to refer to a global variable
  7560. whose principal declaration comes elsewhere---in the same module, or in
  7561. another compilation module. It looks like this:
  7562. @example
  7563. extern @var{basetype} @var{decorated-variable};
  7564. @end example
  7565. Its meaning is that, in the current scope, the variable name refers to
  7566. the file-scope variable of that name---which needs to be declared in a
  7567. non-@code{extern}, non-@code{static} way somewhere else.
  7568. For instance, if one compilation module has this global variable
  7569. declaration
  7570. @example
  7571. int error_count = 0;
  7572. @end example
  7573. @noindent
  7574. then other compilation modules can specify this
  7575. @example
  7576. extern int error_count;
  7577. @end example
  7578. @noindent
  7579. to allow reference to the same variable.
  7580. The usual place to write an @code{extern} declaration is at top level
  7581. in a source file, but you can write an @code{extern} declaration
  7582. inside a block to make a global or static file-scope variable
  7583. accessible in that block.
  7584. Since an @code{extern} declaration does not allocate space for the
  7585. variable, it can omit the size of an array:
  7586. @example
  7587. extern int array[];
  7588. @end example
  7589. You can use @code{array} normally in all contexts where it is
  7590. converted automatically to a pointer. However, to use it as the
  7591. operand of @code{sizeof} is an error, since the size is unknown.
  7592. It is valid to have multiple @code{extern} declarations for the same
  7593. variable, even in the same scope, if they give the same type. They do
  7594. not conflict---they agree. For an array, it is legitimate for some
  7595. @code{extern} declarations can specify the size while others omit it.
  7596. However, if two declarations give different sizes, that is an error.
  7597. Likewise, you can use @code{extern} declarations at file scope
  7598. (@pxref{File-Scope Variables}) followed by an ordinary global
  7599. (non-static) declaration of the same variable. They do not conflict,
  7600. because they say compatible things about the same meaning of the variable.
  7601. @node Allocating File-Scope
  7602. @section Allocating File-Scope Variables
  7603. @cindex allocation file-scope variables
  7604. @cindex file-scope variables, allocating
  7605. Some file-scope declarations allocate space for the variable, and some
  7606. don't.
  7607. A file-scope declaration with an initial value @emph{must} allocate
  7608. space for the variable; if there are two of such declarations for the
  7609. same variable, even in different compilation modules, they conflict.
  7610. An @code{extern} declaration @emph{never} allocates space for the variable.
  7611. If all the top-level declarations of a certain variable are
  7612. @code{extern}, the variable never gets memory space. If that variable
  7613. is used anywhere in the program, the use will be reported as an error,
  7614. saying that the variable is not defined.
  7615. @cindex tentative definition
  7616. A file-scope declaration without an initial value is called a
  7617. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7618. allocate space for the variable, but does not insist. So it causes no
  7619. conflict, no error, if the variable has another declaration that
  7620. allocates space for it, perhaps in another compilation module. But if
  7621. nothing else allocates space for the variable, the tentative
  7622. definition will do it. Any number of compilation modules can declare
  7623. the same variable in this way, and that is sufficient for all of them
  7624. to use the variable.
  7625. @c @opindex -fno-common
  7626. @c @opindex --warn_common
  7627. In programs that are very large or have many contributors, it may be
  7628. wise to adopt the convention of never using tentative definitions.
  7629. You can use the compilation option @option{-fno-common} to make them
  7630. an error, or @option{--warn-common} to warn about them.
  7631. If a file-scope variable gets its space through a tentative
  7632. definition, it starts out containing all zeros.
  7633. @node auto and register
  7634. @section @code{auto} and @code{register}
  7635. @cindex @code{auto} declarations
  7636. @cindex @code{register} declarations
  7637. @findex auto
  7638. @findex register
  7639. For historical reasons, you can write @code{auto} or @code{register}
  7640. before a local variable declaration. @code{auto} merely emphasizes
  7641. that the variable isn't static; it changes nothing.
  7642. @code{register} suggests to the compiler storing this variable in a
  7643. register. However, GNU C ignores this suggestion, since it can
  7644. choose the best variables to store in registers without any hints.
  7645. It is an error to take the address of a variable declared
  7646. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7647. If the variable is an array, you can't use it at all (other than as
  7648. the operand of @code{sizeof}), which makes it rather useless.
  7649. @node Omitting Types
  7650. @section Omitting Types in Declarations
  7651. @cindex omitting types in declarations
  7652. The syntax of C traditionally allows omitting the data type in a
  7653. declaration if it specifies a storage class, a type qualifier (see the
  7654. next chapter), or @code{auto} or @code{register}. Then the type
  7655. defaults to @code{int}. For example:
  7656. @example
  7657. auto foo = 42;
  7658. @end example
  7659. This is bad practice; if you see it, fix it.
  7660. @node Type Qualifiers
  7661. @chapter Type Qualifiers
  7662. A declaration can include type qualifiers to advise the compiler
  7663. about how the variable will be used. There are three different
  7664. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7665. pertain to different issues, so you can use more than one together.
  7666. For instance, @code{const volatile} describes a value that the
  7667. program is not allowed to change, but might have a different value
  7668. each time the program examines it. (This might perhaps be a special
  7669. hardware register, or part of shared memory.)
  7670. If you are just learning C, you can skip this chapter.
  7671. @menu
  7672. * const:: Variables whose values don't change.
  7673. * volatile:: Variables whose values may be accessed
  7674. or changed outside of the control of
  7675. this program.
  7676. * restrict Pointers:: Restricted pointers for code optimization.
  7677. * restrict Pointer Example:: Example of how that works.
  7678. @end menu
  7679. @node const
  7680. @section @code{const} Variables and Fields
  7681. @cindex @code{const} variables and fields
  7682. @cindex variables, @code{const}
  7683. @findex const
  7684. You can mark a variable as ``constant'' by writing @code{const} in
  7685. front of the declaration. This says to treat any assignment to that
  7686. variable as an error. It may also permit some compiler
  7687. optimizations---for instance, to fetch the value only once to satisfy
  7688. multiple references to it. The construct looks like this:
  7689. @example
  7690. const double pi = 3.14159;
  7691. @end example
  7692. After this definition, the code can use the variable @code{pi}
  7693. but cannot assign a different value to it.
  7694. @example
  7695. pi = 3.0; /* @r{Error!} */
  7696. @end example
  7697. Simple variables that are constant can be used for the same purposes
  7698. as enumeration constants, and they are not limited to integers. The
  7699. constantness of the variable propagates into pointers, too.
  7700. A pointer type can specify that the @emph{target} is constant. For
  7701. example, the pointer type @code{const double *} stands for a pointer
  7702. to a constant @code{double}. That's the type that results from taking
  7703. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7704. left side of an assignment.
  7705. @example
  7706. *(&pi) = 3.0; /* @r{Error!} */
  7707. @end example
  7708. Nonconstant pointers can be converted automatically to constant
  7709. pointers, but not vice versa. For instance,
  7710. @example
  7711. const double *cptr;
  7712. double *ptr;
  7713. cptr = &pi; /* @r{Valid.} */
  7714. cptr = ptr; /* @r{Valid.} */
  7715. ptr = cptr; /* @r{Error!} */
  7716. ptr = &pi; /* @r{Error!} */
  7717. @end example
  7718. This is not an ironclad protection against modifying the value. You
  7719. can always cast the constant pointer to a nonconstant pointer type:
  7720. @example
  7721. ptr = (double *)cptr; /* @r{Valid.} */
  7722. ptr = (double *)&pi; /* @r{Valid.} */
  7723. @end example
  7724. However, @code{const} provides a way to show that a certain function
  7725. won't modify the data structure whose address is passed to it. Here's
  7726. an example:
  7727. @example
  7728. int
  7729. string_length (const char *string)
  7730. @{
  7731. int count = 0;
  7732. while (*string++)
  7733. count++;
  7734. return count;
  7735. @}
  7736. @end example
  7737. @noindent
  7738. Using @code{const char *} for the parameter is a way of saying this
  7739. function never modifies the memory of the string itself.
  7740. In calling @code{string_length}, you can specify an ordinary
  7741. @code{char *} since that can be converted automatically to @code{const
  7742. char *}.
  7743. @node volatile
  7744. @section @code{volatile} Variables and Fields
  7745. @cindex @code{volatile} variables and fields
  7746. @cindex variables, @code{volatile}
  7747. @findex volatile
  7748. The GNU C compiler often performs optimizations that eliminate the
  7749. need to write or read a variable. For instance,
  7750. @example
  7751. int foo;
  7752. foo = 1;
  7753. foo++;
  7754. @end example
  7755. @noindent
  7756. might simply store the value 2 into @code{foo}, without ever storing 1.
  7757. These optimizations can also apply to structure fields in some cases.
  7758. If the memory containing @code{foo} is shared with another program,
  7759. or if it is examined asynchronously by hardware, such optimizations
  7760. could confuse the communication. Using @code{volatile} is one way
  7761. to prevent them.
  7762. Writing @code{volatile} with the type in a variable or field declaration
  7763. says that the value may be examined or changed for reasons outside the
  7764. control of the program at any moment. Therefore, the program must
  7765. execute in a careful way to assure correct interaction with those
  7766. accesses, whenever they may occur.
  7767. The simplest use looks like this:
  7768. @example
  7769. volatile int lock;
  7770. @end example
  7771. This directs the compiler not to do certain common optimizations on
  7772. use of the variable @code{lock}. All the reads and writes for a volatile
  7773. variable or field are really done, and done in the order specified
  7774. by the source code. Thus, this code:
  7775. @example
  7776. lock = 1;
  7777. list = list->next;
  7778. if (lock)
  7779. lock_broken (&lock);
  7780. lock = 0;
  7781. @end example
  7782. @noindent
  7783. really stores the value 1 in @code{lock}, even though there is no
  7784. sign it is really used, and the @code{if} statement reads and
  7785. checks the value of @code{lock}, rather than assuming it is still 1.
  7786. A limited amount of optimization can be done, in principle, on
  7787. @code{volatile} variables and fields: multiple references between two
  7788. sequence points (@pxref{Sequence Points}) can be simplified together.
  7789. Use of @code{volatile} does not eliminate the flexibility in ordering
  7790. the computation of the operands of most operators. For instance, in
  7791. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7792. @code{foo} is not specified, so they may be done in either order; the
  7793. fact that @code{lock} is @code{volatile} has no effect on that.
  7794. @node restrict Pointers
  7795. @section @code{restrict}-Qualified Pointers
  7796. @cindex @code{restrict} pointers
  7797. @cindex pointers, @code{restrict}-qualified
  7798. @findex restrict
  7799. You can declare a pointer as ``restricted'' using the @code{restrict}
  7800. type qualifier, like this:
  7801. @example
  7802. int *restrict p = x;
  7803. @end example
  7804. @noindent
  7805. This enables better optimization of code that uses the pointer.
  7806. If @code{p} is declared with @code{restrict}, and then the code
  7807. references the object that @code{p} points to (using @code{*p} or
  7808. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7809. code will not access that object in any other way---only through
  7810. @code{p}.
  7811. For instance, it means the code must not use another pointer
  7812. to access the same space, as shown here:
  7813. @example
  7814. int *restrict p = @var{whatever};
  7815. int *q = p;
  7816. foo (*p, *q);
  7817. @end example
  7818. @noindent
  7819. That contradicts the @code{restrict} promise by accessing the object
  7820. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7821. Likewise, it must not do this:
  7822. @example
  7823. int *restrict p = @var{whatever};
  7824. struct @{ int *a, *b; @} s;
  7825. s.a = p;
  7826. foo (*p, *s.a);
  7827. @end example
  7828. @noindent
  7829. This example uses a structure field instead of the variable @code{q}
  7830. to hold the other pointer, and that contradicts the promise just the
  7831. same.
  7832. The keyword @code{restrict} also promises that @code{p} won't point to
  7833. the allocated space of any automatic or static variable. So the code
  7834. must not do this:
  7835. @example
  7836. int a;
  7837. int *restrict p = &a;
  7838. foo (*p, a);
  7839. @end example
  7840. @noindent
  7841. because that does direct access to the object (@code{a}) that @code{p}
  7842. points to, which bypasses @code{p}.
  7843. If the code makes such promises with @code{restrict} then breaks them,
  7844. execution is unpredictable.
  7845. @node restrict Pointer Example
  7846. @section @code{restrict} Pointer Example
  7847. Here are examples where @code{restrict} enables real optimization.
  7848. In this example, @code{restrict} assures GCC that the array @code{out}
  7849. points to does not overlap with the array @code{in} points to.
  7850. @example
  7851. void
  7852. process_data (const char *in,
  7853. char * restrict out,
  7854. size_t size)
  7855. @{
  7856. for (i = 0; i < size; i++)
  7857. out[i] = in[i] + in[i + 1];
  7858. @}
  7859. @end example
  7860. Here's a simple tree structure, where each tree node holds data of
  7861. type @code{PAYLOAD} plus two subtrees.
  7862. @example
  7863. struct foo
  7864. @{
  7865. PAYLOAD payload;
  7866. struct foo *left;
  7867. struct foo *right;
  7868. @};
  7869. @end example
  7870. Now here's a function to null out both pointers in the @code{left}
  7871. subtree.
  7872. @example
  7873. void
  7874. null_left (struct foo *a)
  7875. @{
  7876. a->left->left = NULL;
  7877. a->left->right = NULL;
  7878. @}
  7879. @end example
  7880. Since @code{*a} and @code{*a->left} have the same data type,
  7881. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7882. the compiled code for @code{null_left} must read @code{a->left}
  7883. again from memory when executing the second assignment statement.
  7884. We can enable optimization, so that it does not need to read
  7885. @code{a->left} again, by writing @code{null_left} in a less
  7886. obvious way.
  7887. @example
  7888. void
  7889. null_left (struct foo *a)
  7890. @{
  7891. struct foo *b = a->left;
  7892. b->left = NULL;
  7893. b->right = NULL;
  7894. @}
  7895. @end example
  7896. A more elegant way to fix this is with @code{restrict}.
  7897. @example
  7898. void
  7899. null_left (struct foo *restrict a)
  7900. @{
  7901. a->left->left = NULL;
  7902. a->left->right = NULL;
  7903. @}
  7904. @end example
  7905. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7906. as @code{a->left} will not point to the same memory space as @code{a}.
  7907. Therefore, the memory location @code{a->left->left} cannot be the same
  7908. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7909. reloading @code{a->left} for the second statement.
  7910. @node Functions
  7911. @chapter Functions
  7912. @cindex functions
  7913. We have already presented many examples of functions, so if you've
  7914. read this far, you basically understand the concept of a function. It
  7915. is vital, nonetheless, to have a chapter in the manual that collects
  7916. all the information about functions.
  7917. @menu
  7918. * Function Definitions:: Writing the body of a function.
  7919. * Function Declarations:: Declaring the interface of a function.
  7920. * Function Calls:: Using functions.
  7921. * Function Call Semantics:: Call-by-value argument passing.
  7922. * Function Pointers:: Using references to functions.
  7923. * The main Function:: Where execution of a GNU C program begins.
  7924. * Advanced Definitions:: Advanced features of function definitions.
  7925. * Obsolete Definitions:: Obsolete features still used
  7926. in function definitions in old code.
  7927. @end menu
  7928. @node Function Definitions
  7929. @section Function Definitions
  7930. @cindex function definitions
  7931. @cindex defining functions
  7932. We have already presented many examples of function definitions. To
  7933. summarize the rules, a function definition looks like this:
  7934. @example
  7935. @var{returntype}
  7936. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7937. @{
  7938. @var{body}
  7939. @}
  7940. @end example
  7941. The part before the open-brace is called the @dfn{function header}.
  7942. Write @code{void} as the @var{returntype} if the function does
  7943. not return a value.
  7944. @menu
  7945. * Function Parameter Variables:: Syntax and semantics
  7946. of function parameters.
  7947. * Forward Function Declarations:: Functions can only be called after
  7948. they have been defined or declared.
  7949. * Static Functions:: Limiting visibility of a function.
  7950. * Arrays as Parameters:: Functions that accept array arguments.
  7951. * Structs as Parameters:: Functions that accept structure arguments.
  7952. @end menu
  7953. @node Function Parameter Variables
  7954. @subsection Function Parameter Variables
  7955. @cindex function parameter variables
  7956. @cindex parameter variables in functions
  7957. @cindex parameter list
  7958. A function parameter variable is a local variable (@pxref{Local
  7959. Variables}) used within the function to store the value passed as an
  7960. argument in a call to the function. Usually we say ``function
  7961. parameter'' or ``parameter'' for short, not mentioning the fact that
  7962. it's a variable.
  7963. We declare these variables in the beginning of the function
  7964. definition, in the @dfn{parameter list}. For example,
  7965. @example
  7966. fib (int n)
  7967. @end example
  7968. @noindent
  7969. has a parameter list with one function parameter @code{n}, which has
  7970. type @code{int}.
  7971. Function parameter declarations differ from ordinary variable
  7972. declarations in several ways:
  7973. @itemize @bullet
  7974. @item
  7975. Inside the function definition header, commas separate parameter
  7976. declarations, and each parameter needs a complete declaration
  7977. including the type. For instance, if a function @code{foo} has two
  7978. @code{int} parameters, write this:
  7979. @example
  7980. foo (int a, int b)
  7981. @end example
  7982. You can't share the common @code{int} between the two declarations:
  7983. @example
  7984. foo (int a, b) /* @r{Invalid!} */
  7985. @end example
  7986. @item
  7987. A function parameter variable is initialized to whatever value is
  7988. passed in the function call, so its declaration cannot specify an
  7989. initial value.
  7990. @item
  7991. Writing an array type in a function parameter declaration has the
  7992. effect of declaring it as a pointer. The size specified for the array
  7993. has no effect at all, and we normally omit the size. Thus,
  7994. @example
  7995. foo (int a[5])
  7996. foo (int a[])
  7997. foo (int *a)
  7998. @end example
  7999. @noindent
  8000. are equivalent.
  8001. @item
  8002. The scope of the parameter variables is the entire function body,
  8003. notwithstanding the fact that they are written in the function header,
  8004. which is just outside the function body.
  8005. @end itemize
  8006. If a function has no parameters, it would be most natural for the
  8007. list of parameters in its definition to be empty. But that, in C, has
  8008. a special meaning for historical reasons: ``Do not check that calls to
  8009. this function have the right number of arguments.'' Thus,
  8010. @example
  8011. int
  8012. foo ()
  8013. @{
  8014. return 5;
  8015. @}
  8016. int
  8017. bar (int x)
  8018. @{
  8019. return foo (x);
  8020. @}
  8021. @end example
  8022. @noindent
  8023. would not report a compilation error in passing @code{x} as an
  8024. argument to @code{foo}. By contrast,
  8025. @example
  8026. int
  8027. foo (void)
  8028. @{
  8029. return 5;
  8030. @}
  8031. int
  8032. bar (int x)
  8033. @{
  8034. return foo (x);
  8035. @}
  8036. @end example
  8037. @noindent
  8038. would report an error because @code{foo} is supposed to receive
  8039. no arguments.
  8040. @node Forward Function Declarations
  8041. @subsection Forward Function Declarations
  8042. @cindex forward function declarations
  8043. @cindex function declarations, forward
  8044. The order of the function definitions in the source code makes no
  8045. difference, except that each function needs to be defined or declared
  8046. before code uses it.
  8047. The definition of a function also declares its name for the rest of
  8048. the containing scope. But what if you want to call the function
  8049. before its definition? To permit that, write a compatible declaration
  8050. of the same function, before the first call. A declaration that
  8051. prefigures a subsequent definition in this way is called a
  8052. @dfn{forward declaration}. The function declaration can be at top
  8053. @c ??? file scope
  8054. level or within a block, and it applies until the end of the containing
  8055. scope.
  8056. @xref{Function Declarations}, for more information about these
  8057. declarations.
  8058. @node Static Functions
  8059. @subsection Static Functions
  8060. @cindex static functions
  8061. @cindex functions, static
  8062. @findex static
  8063. The keyword @code{static} in a function definition limits the
  8064. visibility of the name to the current compilation module. (That's the
  8065. same thing @code{static} does in variable declarations;
  8066. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8067. contains this code:
  8068. @example
  8069. static int
  8070. foo (void)
  8071. @{
  8072. @r{@dots{}}
  8073. @}
  8074. @end example
  8075. @noindent
  8076. then the code of that compilation module can call @code{foo} anywhere
  8077. after the definition, but other compilation modules cannot refer to it
  8078. at all.
  8079. @cindex forward declaration
  8080. @cindex static function, declaration
  8081. To call @code{foo} before its definition, it needs a forward
  8082. declaration, which should use @code{static} since the function
  8083. definition does. For this function, it looks like this:
  8084. @example
  8085. static int foo (void);
  8086. @end example
  8087. It is generally wise to use @code{static} on the definitions of
  8088. functions that won't be called from outside the same compilation
  8089. module. This makes sure that calls are not added in other modules.
  8090. If programmers decide to change the function's calling convention, or
  8091. understand all the consequences of its use, they will only have to
  8092. check for calls in the same compilation module.
  8093. @node Arrays as Parameters
  8094. @subsection Arrays as Parameters
  8095. @cindex array as parameters
  8096. @cindex functions with array parameters
  8097. Arrays in C are not first-class objects: it is impossible to copy
  8098. them. So they cannot be passed as arguments like other values.
  8099. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8100. a special way.
  8101. @menu
  8102. * Array Parm Pointer::
  8103. * Passing Array Args::
  8104. * Array Parm Qualifiers::
  8105. @end menu
  8106. @node Array Parm Pointer
  8107. @subsubsection Array parameters are pointers
  8108. Declaring a function parameter variable as an array really gives it a
  8109. pointer type. C does this because an expression with array type, if
  8110. used as an argument in a function call, is converted automatically to
  8111. a pointer (to the zeroth element of the array). If you declare the
  8112. corresponding parameter as an ``array'', it will work correctly with
  8113. the pointer value that really gets passed.
  8114. This relates to the fact that C does not check array bounds in access
  8115. to elements of the array (@pxref{Accessing Array Elements}).
  8116. For example, in this function,
  8117. @example
  8118. void
  8119. clobber4 (int array[20])
  8120. @{
  8121. array[4] = 0;
  8122. @}
  8123. @end example
  8124. @noindent
  8125. the parameter @code{array}'s real type is @code{int *}; the specified
  8126. length, 20, has no effect on the program. You can leave out the length
  8127. and write this:
  8128. @example
  8129. void
  8130. clobber4 (int array[])
  8131. @{
  8132. array[4] = 0;
  8133. @}
  8134. @end example
  8135. @noindent
  8136. or write the parameter declaration explicitly as a pointer:
  8137. @example
  8138. void
  8139. clobber4 (int *array)
  8140. @{
  8141. array[4] = 0;
  8142. @}
  8143. @end example
  8144. They are all equivalent.
  8145. @node Passing Array Args
  8146. @subsubsection Passing array arguments
  8147. The function call passes this pointer by
  8148. value, like all argument values in C@. However, the result is
  8149. paradoxical in that the array itself is passed by reference: its
  8150. contents are treated as shared memory---shared between the caller and
  8151. the called function, that is. When @code{clobber4} assigns to element
  8152. 4 of @code{array}, the effect is to alter element 4 of the array
  8153. specified in the call.
  8154. @example
  8155. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8156. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8157. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8158. int
  8159. main (void)
  8160. @{
  8161. int data[] = @{1, 2, 3, 4, 5, 6@};
  8162. int i;
  8163. /* @r{Show the initial value of element 4.} */
  8164. for (i = 0; i < 6; i++)
  8165. printf ("data[%d] = %d\n", i, data[i]);
  8166. printf ("\n");
  8167. clobber4 (data);
  8168. /* @r{Show that element 4 has been changed.} */
  8169. for (i = 0; i < 6; i++)
  8170. printf ("data[%d] = %d\n", i, data[i]);
  8171. printf ("\n");
  8172. return EXIT_SUCCESS;
  8173. @}
  8174. @end example
  8175. @noindent
  8176. shows that @code{data[4]} has become zero after the call to
  8177. @code{clobber4}.
  8178. The array @code{data} has 6 elements, but passing it to a function
  8179. whose argument type is written as @code{int [20]} is not an error,
  8180. because that really stands for @code{int *}. The pointer that is the
  8181. real argument carries no indication of the length of the array it
  8182. points into. It is not required to point to the beginning of the
  8183. array, either. For instance,
  8184. @example
  8185. clobber4 (data+1);
  8186. @end example
  8187. @noindent
  8188. passes an ``array'' that starts at element 1 of @code{data}, and the
  8189. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8190. If all calls to the function will provide an array of a particular
  8191. size, you can specify the size of the array to be @code{static}:
  8192. @example
  8193. void
  8194. clobber4 (int array[static 20])
  8195. @r{@dots{}}
  8196. @end example
  8197. @noindent
  8198. This is a promise to the compiler that the function will always be
  8199. called with an array of 20 elements, so that the compiler can optimize
  8200. code accordingly. If the code breaks this promise and calls the
  8201. function with, for example, a shorter array, unpredictable things may
  8202. happen.
  8203. @node Array Parm Qualifiers
  8204. @subsubsection Type qualifiers on array parameters
  8205. You can use the type qualifiers @code{const}, @code{restrict}, and
  8206. @code{volatile} with array parameters; for example:
  8207. @example
  8208. void
  8209. clobber4 (volatile int array[20])
  8210. @r{@dots{}}
  8211. @end example
  8212. @noindent
  8213. denotes that @code{array} is equivalent to a pointer to a volatile
  8214. @code{int}. Alternatively:
  8215. @example
  8216. void
  8217. clobber4 (int array[const 20])
  8218. @r{@dots{}}
  8219. @end example
  8220. @noindent
  8221. makes the array parameter equivalent to a constant pointer to an
  8222. @code{int}. If we want the @code{clobber4} function to succeed, it
  8223. would not make sense to write
  8224. @example
  8225. void
  8226. clobber4 (const int array[20])
  8227. @r{@dots{}}
  8228. @end example
  8229. @noindent
  8230. as this would tell the compiler that the parameter should point to an
  8231. array of constant @code{int} values, and then we would not be able to
  8232. store zeros in them.
  8233. In a function with multiple array parameters, you can use @code{restrict}
  8234. to tell the compiler that each array parameter passed in will be distinct:
  8235. @example
  8236. void
  8237. foo (int array1[restrict 10], int array2[restrict 10])
  8238. @r{@dots{}}
  8239. @end example
  8240. @noindent
  8241. Using @code{restrict} promises the compiler that callers will
  8242. not pass in the same array for more than one @code{restrict} array
  8243. parameter. Knowing this enables the compiler to perform better code
  8244. optimization. This is the same effect as using @code{restrict}
  8245. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8246. the code that an array of a specific size is expected.
  8247. @node Structs as Parameters
  8248. @subsection Functions That Accept Structure Arguments
  8249. Structures in GNU C are first-class objects, so using them as function
  8250. parameters and arguments works in the natural way. This function
  8251. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8252. and returns a structure of the same type but with the fields
  8253. exchanged.
  8254. @example
  8255. struct foo @{ int a, b; @};
  8256. struct foo x;
  8257. struct foo
  8258. swapfoo (struct foo inval)
  8259. @{
  8260. struct foo outval;
  8261. outval.a = inval.b;
  8262. outval.b = inval.a;
  8263. return outval;
  8264. @}
  8265. @end example
  8266. This simpler definition of @code{swapfoo} avoids using a local
  8267. variable to hold the result about to be return, by using a structure
  8268. constructor (@pxref{Structure Constructors}), like this:
  8269. @example
  8270. struct foo
  8271. swapfoo (struct foo inval)
  8272. @{
  8273. return (struct foo) @{ inval.b, inval.a @};
  8274. @}
  8275. @end example
  8276. It is valid to define a structure type in a function's parameter list,
  8277. as in
  8278. @example
  8279. int
  8280. frob_bar (struct bar @{ int a, b; @} inval)
  8281. @{
  8282. @var{body}
  8283. @}
  8284. @end example
  8285. @noindent
  8286. and @var{body} can access the fields of @var{inval} since the
  8287. structure type @code{struct bar} is defined for the whole function
  8288. body. However, there is no way to create a @code{struct bar} argument
  8289. to pass to @code{frob_bar}, except with kludges. As a result,
  8290. defining a structure type in a parameter list is useless in practice.
  8291. @node Function Declarations
  8292. @section Function Declarations
  8293. @cindex function declarations
  8294. @cindex declararing functions
  8295. To call a function, or use its name as a pointer, a @dfn{function
  8296. declaration} for the function name must be in effect at that point in
  8297. the code. The function's definition serves as a declaration of that
  8298. function for the rest of the containing scope, but to use the function
  8299. in code before the definition, or from another compilation module, a
  8300. separate function declaration must precede the use.
  8301. A function declaration looks like the start of a function definition.
  8302. It begins with the return value type (@code{void} if none) and the
  8303. function name, followed by argument declarations in parentheses
  8304. (though these can sometimes be omitted). But that's as far as the
  8305. similarity goes: instead of the function body, the declaration uses a
  8306. semicolon.
  8307. @cindex function prototype
  8308. @cindex prototype of a function
  8309. A declaration that specifies argument types is called a @dfn{function
  8310. prototype}. You can include the argument names or omit them. The
  8311. names, if included in the declaration, have no effect, but they may
  8312. serve as documentation.
  8313. This form of prototype specifies fixed argument types:
  8314. @example
  8315. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8316. @end example
  8317. @noindent
  8318. This form says the function takes no arguments:
  8319. @example
  8320. @var{rettype} @var{function} (void);
  8321. @end example
  8322. @noindent
  8323. This form declares types for some arguments, and allows additional
  8324. arguments whose types are not specified:
  8325. @example
  8326. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8327. @end example
  8328. For a parameter that's an array of variable length, you can write
  8329. its declaration with @samp{*} where the ``length'' of the array would
  8330. normally go; for example, these are all equivalent.
  8331. @example
  8332. double maximum (int n, int m, double a[n][m]);
  8333. double maximum (int n, int m, double a[*][*]);
  8334. double maximum (int n, int m, double a[ ][*]);
  8335. double maximum (int n, int m, double a[ ][m]);
  8336. @end example
  8337. @noindent
  8338. The old-fashioned form of declaration, which is not a prototype, says
  8339. nothing about the types of arguments or how many they should be:
  8340. @example
  8341. @var{rettype} @var{function} ();
  8342. @end example
  8343. @strong{Warning:} Arguments passed to a function declared without a
  8344. prototype are converted with the default argument promotions
  8345. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8346. types are unspecified.
  8347. Function declarations are usually written at the top level in a source file,
  8348. but you can also put them inside code blocks. Then the function name
  8349. is visible for the rest of the containing scope. For example:
  8350. @example
  8351. void
  8352. foo (char *file_name)
  8353. @{
  8354. void save_file (char *);
  8355. save_file (file_name);
  8356. @}
  8357. @end example
  8358. If another part of the code tries to call the function
  8359. @code{save_file}, this declaration won't be in effect there. So the
  8360. function will get an implicit declaration of the form @code{extern int
  8361. save_file ();}. That conflicts with the explicit declaration
  8362. here, and the discrepancy generates a warning.
  8363. The syntax of C traditionally allows omitting the data type in a
  8364. function declaration if it specifies a storage class or a qualifier.
  8365. Then the type defaults to @code{int}. For example:
  8366. @example
  8367. static foo (double x);
  8368. @end example
  8369. @noindent
  8370. defaults the return type to @code{int}.
  8371. This is bad practice; if you see it, fix it.
  8372. Calling a function that is undeclared has the effect of an creating
  8373. @dfn{implicit} declaration in the innermost containing scope,
  8374. equivalent to this:
  8375. @example
  8376. extern int @dfn{function} ();
  8377. @end example
  8378. @noindent
  8379. This declaration says that the function returns @code{int} but leaves
  8380. its argument types unspecified. If that does not accurately fit the
  8381. function, then the program @strong{needs} an explicit declaration of
  8382. the function with argument types in order to call it correctly.
  8383. Implicit declarations are deprecated, and a function call that creates one
  8384. causes a warning.
  8385. @node Function Calls
  8386. @section Function Calls
  8387. @cindex function calls
  8388. @cindex calling functions
  8389. Starting a program automatically calls the function named @code{main}
  8390. (@pxref{The main Function}). Aside from that, a function does nothing
  8391. except when it is @dfn{called}. That occurs during the execution of a
  8392. function-call expression specifying that function.
  8393. A function-call expression looks like this:
  8394. @example
  8395. @var{function} (@var{arguments}@r{@dots{}})
  8396. @end example
  8397. Most of the time, @var{function} is a function name. However, it can
  8398. also be an expression with a function pointer value; that way, the
  8399. program can determine at run time which function to call.
  8400. The @var{arguments} are a series of expressions separated by commas.
  8401. Each expression specifies one argument to pass to the function.
  8402. The list of arguments in a function call looks just like use of the
  8403. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8404. the parentheses of a function call gives it a different meaning.
  8405. Here's an example of a function call, taken from an example near the
  8406. beginning (@pxref{Complete Program}).
  8407. @example
  8408. printf ("Fibonacci series item %d is %d\n",
  8409. 19, fib (19));
  8410. @end example
  8411. The three arguments given to @code{printf} are a constant string, the
  8412. integer 19, and the integer returned by @code{fib (19)}.
  8413. @node Function Call Semantics
  8414. @section Function Call Semantics
  8415. @cindex function call semantics
  8416. @cindex semantics of function calls
  8417. @cindex call-by-value
  8418. The meaning of a function call is to compute the specified argument
  8419. expressions, convert their values according to the function's
  8420. declaration, then run the function giving it copies of the converted
  8421. values. (This method of argument passing is known as
  8422. @dfn{call-by-value}.) When the function finishes, the value it
  8423. returns becomes the value of the function-call expression.
  8424. Call-by-value implies that an assignment to the function argument
  8425. variable has no direct effect on the caller. For instance,
  8426. @example
  8427. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8428. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8429. void
  8430. subroutine (int x)
  8431. @{
  8432. x = 5;
  8433. @}
  8434. void
  8435. main (void)
  8436. @{
  8437. int y = 20;
  8438. subroutine (y);
  8439. printf ("y is %d\n", y);
  8440. return EXIT_SUCCESS;
  8441. @}
  8442. @end example
  8443. @noindent
  8444. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8445. from the value of @code{y}, but this does not establish any other
  8446. relationship between the two variables. Thus, the assignment to
  8447. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8448. If an argument's type is specified by the function's declaration, the
  8449. function call converts the argument expression to that type if
  8450. possible. If the conversion is impossible, that is an error.
  8451. If the function's declaration doesn't specify the type of that
  8452. argument, then the @emph{default argument promotions} apply.
  8453. @xref{Argument Promotions}.
  8454. @node Function Pointers
  8455. @section Function Pointers
  8456. @cindex function pointers
  8457. @cindex pointers to functions
  8458. A function name refers to a fixed function. Sometimes it is useful to
  8459. call a function to be determined at run time; to do this, you can use
  8460. a @dfn{function pointer value} that points to the chosen function
  8461. (@pxref{Pointers}).
  8462. Pointer-to-function types can be used to declare variables and other
  8463. data, including array elements, structure fields, and union
  8464. alternatives. They can also be used for function arguments and return
  8465. values. These types have the peculiarity that they are never
  8466. converted automatically to @code{void *} or vice versa. However, you
  8467. can do that conversion with a cast.
  8468. @menu
  8469. * Declaring Function Pointers:: How to declare a pointer to a function.
  8470. * Assigning Function Pointers:: How to assign values to function pointers.
  8471. * Calling Function Pointers:: How to call functions through pointers.
  8472. @end menu
  8473. @node Declaring Function Pointers
  8474. @subsection Declaring Function Pointers
  8475. @cindex declaring function pointers
  8476. @cindex function pointers, declaring
  8477. The declaration of a function pointer variable (or structure field)
  8478. looks almost like a function declaration, except it has an additional
  8479. @samp{*} just before the variable name. Proper nesting requires a
  8480. pair of parentheses around the two of them. For instance, @code{int
  8481. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8482. an @code{int}-returning function.''
  8483. Contrast these three declarations:
  8484. @example
  8485. /* @r{Declare a function returning @code{char *}.} */
  8486. char *a (char *);
  8487. /* @r{Declare a pointer to a function returning @code{char}.} */
  8488. char (*a) (char *);
  8489. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8490. char *(*a) (char *);
  8491. @end example
  8492. The possible argument types of the function pointed to are the same
  8493. as in a function declaration. You can write a prototype
  8494. that specifies all the argument types:
  8495. @example
  8496. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8497. @end example
  8498. @noindent
  8499. or one that specifies some and leaves the rest unspecified:
  8500. @example
  8501. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8502. @end example
  8503. @noindent
  8504. or one that says there are no arguments:
  8505. @example
  8506. @var{rettype} (*@var{function}) (void);
  8507. @end example
  8508. You can also write a non-prototype declaration that says
  8509. nothing about the argument types:
  8510. @example
  8511. @var{rettype} (*@var{function}) ();
  8512. @end example
  8513. For example, here's a declaration for a variable that should
  8514. point to some arithmetic function that operates on two @code{double}s:
  8515. @example
  8516. double (*binary_op) (double, double);
  8517. @end example
  8518. Structure fields, union alternatives, and array elements can be
  8519. function pointers; so can parameter variables. The function pointer
  8520. declaration construct can also be combined with other operators
  8521. allowed in declarations. For instance,
  8522. @example
  8523. int **(*foo)();
  8524. @end example
  8525. @noindent
  8526. declares @code{foo} as a pointer to a function that returns
  8527. type @code{int **}, and
  8528. @example
  8529. int **(*foo[30])();
  8530. @end example
  8531. @noindent
  8532. declares @code{foo} as an array of 30 pointers to functions that
  8533. return type @code{int **}.
  8534. @example
  8535. int **(**foo)();
  8536. @end example
  8537. @noindent
  8538. declares @code{foo} as a pointer to a pointer to a function that
  8539. returns type @code{int **}.
  8540. @node Assigning Function Pointers
  8541. @subsection Assigning Function Pointers
  8542. @cindex assigning function pointers
  8543. @cindex function pointers, assigning
  8544. Assuming we have declared the variable @code{binary_op} as in the
  8545. previous section, giving it a value requires a suitable function to
  8546. use. So let's define a function suitable for the variable to point
  8547. to. Here's one:
  8548. @example
  8549. double
  8550. double_add (double a, double b)
  8551. @{
  8552. return a+b;
  8553. @}
  8554. @end example
  8555. Now we can give it a value:
  8556. @example
  8557. binary_op = double_add;
  8558. @end example
  8559. The target type of the function pointer must be upward compatible with
  8560. the type of the function (@pxref{Compatible Types}).
  8561. There is no need for @samp{&} in front of @code{double_add}.
  8562. Using a function name such as @code{double_add} as an expression
  8563. automatically converts it to the function's address, with the
  8564. appropriate function pointer type. However, it is ok to use
  8565. @samp{&} if you feel that is clearer:
  8566. @example
  8567. binary_op = &double_add;
  8568. @end example
  8569. @node Calling Function Pointers
  8570. @subsection Calling Function Pointers
  8571. @cindex calling function pointers
  8572. @cindex function pointers, calling
  8573. To call the function specified by a function pointer, just write the
  8574. function pointer value in a function call. For instance, here's a
  8575. call to the function @code{binary_op} points to:
  8576. @example
  8577. binary_op (x, 5)
  8578. @end example
  8579. Since the data type of @code{binary_op} explicitly specifies type
  8580. @code{double} for the arguments, the call converts @code{x} and 5 to
  8581. @code{double}.
  8582. The call conceptually dereferences the pointer @code{binary_op} to
  8583. ``get'' the function it points to, and calls that function. If you
  8584. wish, you can explicitly represent the derefence by writing the
  8585. @code{*} operator:
  8586. @example
  8587. (*binary_op) (x, 5)
  8588. @end example
  8589. The @samp{*} reminds people reading the code that @code{binary_op} is
  8590. a function pointer rather than the name of a specific function.
  8591. @node The main Function
  8592. @section The @code{main} Function
  8593. @cindex @code{main} function
  8594. @findex main
  8595. Every complete executable program requires at least one function,
  8596. called @code{main}, which is where execution begins. You do not have
  8597. to explicitly declare @code{main}, though GNU C permits you to do so.
  8598. Conventionally, @code{main} should be defined to follow one of these
  8599. calling conventions:
  8600. @example
  8601. int main (void) @{@r{@dots{}}@}
  8602. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8603. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8604. @end example
  8605. @noindent
  8606. Using @code{void} as the parameter list means that @code{main} does
  8607. not use the arguments. You can write @code{char **argv} instead of
  8608. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8609. constructs are equivalent.
  8610. @ignore @c Not so at present
  8611. Defining @code{main} in any other way generates a warning. Your
  8612. program will still compile, but you may get unexpected results when
  8613. executing it.
  8614. @end ignore
  8615. You can call @code{main} from C code, as you can call any other
  8616. function, though that is an unusual thing to do. When you do that,
  8617. you must write the call to pass arguments that match the parameters in
  8618. the definition of @code{main}.
  8619. The @code{main} function is not actually the first code that runs when
  8620. a program starts. In fact, the first code that runs is system code
  8621. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8622. code, but in GNU we replaced it with C code. Its job is to find
  8623. the arguments for @code{main} and call that.
  8624. @menu
  8625. * Values from main:: Returning values from the main function.
  8626. * Command-line Parameters:: Accessing command-line parameters
  8627. provided to the program.
  8628. * Environment Variables:: Accessing system environment variables.
  8629. @end menu
  8630. @node Values from main
  8631. @subsection Returning Values from @code{main}
  8632. @cindex returning values from @code{main}
  8633. @cindex success
  8634. @cindex failure
  8635. @cindex exit status
  8636. When @code{main} returns, the process terminates. Whatever value
  8637. @code{main} returns becomes the exit status which is reported to the
  8638. parent process. While nominally the return value is of type
  8639. @code{int}, in fact the exit status gets truncated to eight bits; if
  8640. @code{main} returns the value 256, the exit status is 0.
  8641. Normally, programs return only one of two values: 0 for success,
  8642. and 1 for failure. For maximum portability, use the macro
  8643. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8644. @code{stdlib.h}. Here's an example:
  8645. @cindex @code{EXIT_FAILURE}
  8646. @cindex @code{EXIT_SUCCESS}
  8647. @example
  8648. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8649. /* @r{and @code{EXIT_FAILURE}.} */
  8650. int
  8651. main (void)
  8652. @{
  8653. @r{@dots{}}
  8654. if (foo)
  8655. return EXIT_SUCCESS;
  8656. else
  8657. return EXIT_FAILURE;
  8658. @}
  8659. @end example
  8660. Some types of programs maintain special conventions for various return
  8661. values; for example, comparison programs including @code{cmp} and
  8662. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8663. the comparison couldn't be performed.
  8664. @node Command-line Parameters
  8665. @subsection Accessing Command-line Parameters
  8666. @cindex command-line parameters
  8667. @cindex parameters, command-line
  8668. If the program was invoked with any command-line arguments, it can
  8669. access them through the arguments of @code{main}, @code{argc} and
  8670. @code{argv}. (You can give these arguments any names, but the names
  8671. @code{argc} and @code{argv} are customary.)
  8672. The value of @code{argv} is an array containing all of the
  8673. command-line arguments as strings, with the name of the command
  8674. invoked as the first string. @code{argc} is an integer that says how
  8675. many strings @code{argv} contains. Here is an example of accessing
  8676. the command-line parameters, retrieving the program's name and
  8677. checking for the standard @option{--version} and @option{--help} options:
  8678. @example
  8679. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8680. int
  8681. main (int argc, char *argv[])
  8682. @{
  8683. char *program_name = argv[0];
  8684. for (int i = 1; i < argc; i++)
  8685. @{
  8686. if (!strcmp (argv[i], "--version"))
  8687. @{
  8688. /* @r{Print version information and exit.} */
  8689. @r{@dots{}}
  8690. @}
  8691. else if (!strcmp (argv[i], "--help"))
  8692. @{
  8693. /* @r{Print help information and exit.} */
  8694. @r{@dots{}}
  8695. @}
  8696. @}
  8697. @r{@dots{}}
  8698. @}
  8699. @end example
  8700. @node Environment Variables
  8701. @subsection Accessing Environment Variables
  8702. @cindex environment variables
  8703. You can optionally include a third parameter to @code{main}, another
  8704. array of strings, to capture the environment variables available to
  8705. the program. Unlike what happens with @code{argv}, there is no
  8706. additional parameter for the count of environment variables; rather,
  8707. the array of environment variables concludes with a null pointer.
  8708. @example
  8709. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8710. int
  8711. main (int argc, char *argv[], char *envp[])
  8712. @{
  8713. /* @r{Print out all environment variables.} */
  8714. int i = 0;
  8715. while (envp[i])
  8716. @{
  8717. printf ("%s\n", envp[i]);
  8718. i++;
  8719. @}
  8720. @}
  8721. @end example
  8722. Another method of retrieving environment variables is to use the
  8723. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8724. Using @code{getenv} does not require defining @code{main} to accept the
  8725. @code{envp} pointer. For example, here is a program that fetches and prints
  8726. the user's home directory (if defined):
  8727. @example
  8728. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8729. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8730. int
  8731. main (void)
  8732. @{
  8733. char *home_directory = getenv ("HOME");
  8734. if (home_directory)
  8735. printf ("My home directory is: %s\n", home_directory);
  8736. else
  8737. printf ("My home directory is not defined!\n");
  8738. @}
  8739. @end example
  8740. @node Advanced Definitions
  8741. @section Advanced Function Features
  8742. This section describes some advanced or obscure features for GNU C
  8743. function definitions. If you are just learning C, you can skip the
  8744. rest of this chapter.
  8745. @menu
  8746. * Variable-Length Array Parameters:: Functions that accept arrays
  8747. of variable length.
  8748. * Variable Number of Arguments:: Variadic functions.
  8749. * Nested Functions:: Defining functions within functions.
  8750. * Inline Function Definitions:: A function call optimization technique.
  8751. @end menu
  8752. @node Variable-Length Array Parameters
  8753. @subsection Variable-Length Array Parameters
  8754. @cindex variable-length array parameters
  8755. @cindex array parameters, variable-length
  8756. @cindex functions that accept variable-length arrays
  8757. An array parameter can have variable length: simply declare the array
  8758. type with a size that isn't constant. In a nested function, the
  8759. length can refer to a variable defined in a containing scope. In any
  8760. function, it can refer to a previous parameter, like this:
  8761. @example
  8762. struct entry
  8763. tester (int len, char data[len][len])
  8764. @{
  8765. @r{@dots{}}
  8766. @}
  8767. @end example
  8768. Alternatively, in function declarations (but not in function
  8769. definitions), you can use @code{[*]} to denote that the array
  8770. parameter is of a variable length, such that these two declarations
  8771. mean the same thing:
  8772. @example
  8773. struct entry
  8774. tester (int len, char data[len][len]);
  8775. @end example
  8776. @example
  8777. struct entry
  8778. tester (int len, char data[*][*]);
  8779. @end example
  8780. @noindent
  8781. The two forms of input are equivalent in GNU C, but emphasizing that
  8782. the array parameter is variable-length may be helpful to those
  8783. studying the code.
  8784. You can also omit the length parameter, and instead use some other
  8785. in-scope variable for the length in the function definition:
  8786. @example
  8787. struct entry
  8788. tester (char data[*][*]);
  8789. @r{@dots{}}
  8790. int dataLength = 20;
  8791. @r{@dots{}}
  8792. struct entry
  8793. tester (char data[dataLength][dataLength])
  8794. @{
  8795. @r{@dots{}}
  8796. @}
  8797. @end example
  8798. @c ??? check text above
  8799. @cindex parameter forward declaration
  8800. In GNU C, to pass the array first and the length afterward, you can
  8801. use a @dfn{parameter forward declaration}, like this:
  8802. @example
  8803. struct entry
  8804. tester (int len; char data[len][len], int len)
  8805. @{
  8806. @r{@dots{}}
  8807. @}
  8808. @end example
  8809. The @samp{int len} before the semicolon is the parameter forward
  8810. declaration; it serves the purpose of making the name @code{len} known
  8811. when the declaration of @code{data} is parsed.
  8812. You can write any number of such parameter forward declarations in the
  8813. parameter list. They can be separated by commas or semicolons, but
  8814. the last one must end with a semicolon, which is followed by the
  8815. ``real'' parameter declarations. Each forward declaration must match
  8816. a subsequent ``real'' declaration in parameter name and data type.
  8817. Standard C does not support parameter forward declarations.
  8818. @node Variable Number of Arguments
  8819. @subsection Variable-Length Parameter Lists
  8820. @cindex variable-length parameter lists
  8821. @cindex parameters lists, variable length
  8822. @cindex function parameter lists, variable length
  8823. @cindex variadic function
  8824. A function that takes a variable number of arguments is called a
  8825. @dfn{variadic function}. In C, a variadic function must specify at
  8826. least one fixed argument with an explicitly declared data type.
  8827. Additional arguments can follow, and can vary in both quantity and
  8828. data type.
  8829. In the function header, declare the fixed parameters in the normal
  8830. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8831. example of a variadic function header:
  8832. @example
  8833. int add_multiple_values (int number, ...)
  8834. @end example
  8835. @cindex @code{va_list}
  8836. @cindex @code{va_start}
  8837. @cindex @code{va_end}
  8838. The function body can refer to fixed arguments by their parameter
  8839. names, but the additional arguments have no names. Accessing them in
  8840. the function body uses certain standard macros. They are defined in
  8841. the library header file @file{stdarg.h}, so the code must
  8842. @code{#include} that file.
  8843. In the body, write
  8844. @example
  8845. va_list ap;
  8846. va_start (ap, @var{last_fixed_parameter});
  8847. @end example
  8848. @noindent
  8849. This declares the variable @code{ap} (you can use any name for it)
  8850. and then sets it up to point before the first additional argument.
  8851. Then, to fetch the next consecutive additional argument, write this:
  8852. @example
  8853. va_arg (ap, @var{type})
  8854. @end example
  8855. After fetching all the additional arguments (or as many as need to be
  8856. used), write this:
  8857. @example
  8858. va_end (ap);
  8859. @end example
  8860. Here's an example of a variadic function definition that adds any
  8861. number of @code{int} arguments. The first (fixed) argument says how
  8862. many more arguments follow.
  8863. @example
  8864. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8865. @r{@dots{}}
  8866. int
  8867. add_multiple_values (int argcount, ...)
  8868. @{
  8869. int counter, total = 0;
  8870. /* @r{Declare a variable of type @code{va_list}.} */
  8871. va_list argptr;
  8872. /* @r{Initialize that variable..} */
  8873. va_start (argptr, argcount);
  8874. for (counter = 0; counter < argcount; counter++)
  8875. @{
  8876. /* @r{Get the next additional argument.} */
  8877. total += va_arg (argptr, int);
  8878. @}
  8879. /* @r{End use of the @code{argptr} variable.} */
  8880. va_end (argptr);
  8881. return total;
  8882. @}
  8883. @end example
  8884. With GNU C, @code{va_end} is superfluous, but some other compilers
  8885. might make @code{va_start} allocate memory so that calling
  8886. @code{va_end} is necessary to avoid a memory leak. Before doing
  8887. @code{va_start} again with the same variable, do @code{va_end}
  8888. first.
  8889. @cindex @code{va_copy}
  8890. Because of this possible memory allocation, it is risky (in principle)
  8891. to copy one @code{va_list} variable to another with assignment.
  8892. Instead, use @code{va_copy}, which copies the substance but allocates
  8893. separate memory in the variable you copy to. The call looks like
  8894. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8895. @var{from} should be variables of type @code{va_list}. In principle,
  8896. do @code{va_end} on each of these variables before its scope ends.
  8897. Since the additional arguments' types are not specified in the
  8898. function's definition, the default argument promotions
  8899. (@pxref{Argument Promotions}) apply to them in function calls. The
  8900. function definition must take account of this; thus, if an argument
  8901. was passed as @code{short}, the function should get it as @code{int}.
  8902. If an argument was passed as @code{float}, the function should get it
  8903. as @code{double}.
  8904. C has no mechanism to tell the variadic function how many arguments
  8905. were passed to it, so its calling convention must give it a way to
  8906. determine this. That's why @code{add_multiple_values} takes a fixed
  8907. argument that says how many more arguments follow. Thus, you can
  8908. call the function like this:
  8909. @example
  8910. sum = add_multiple_values (3, 12, 34, 190);
  8911. /* @r{Value is 12+34+190.} */
  8912. @end example
  8913. In GNU C, there is no actual need to use the @code{va_end} function.
  8914. In fact, it does nothing. It's used for compatibility with other
  8915. compilers, when that matters.
  8916. It is a mistake to access variables declared as @code{va_list} except
  8917. in the specific ways described here. Just what that type consists of
  8918. is an implementation detail, which could vary from one platform to
  8919. another.
  8920. @node Nested Functions
  8921. @subsection Nested Functions
  8922. @cindex nested functions
  8923. @cindex functions, nested
  8924. @cindex downward funargs
  8925. @cindex thunks
  8926. A @dfn{nested function} is a function defined inside another function.
  8927. (The ability to do this indispensable for automatic translation of
  8928. certain programming languages into C.) The nested function's name is
  8929. local to the block where it is defined. For example, here we define a
  8930. nested function named @code{square}, then call it twice:
  8931. @example
  8932. @group
  8933. foo (double a, double b)
  8934. @{
  8935. double square (double z) @{ return z * z; @}
  8936. return square (a) + square (b);
  8937. @}
  8938. @end group
  8939. @end example
  8940. The nested function definition can access all the variables of the containing
  8941. function that are visible at the point of its definition. This is
  8942. called @dfn{lexical scoping}. For example, here we show a nested
  8943. function that uses an inherited variable named @code{offset}:
  8944. @example
  8945. @group
  8946. bar (int *array, int offset, int size)
  8947. @{
  8948. int access (int *array, int index)
  8949. @{ return array[index + offset]; @}
  8950. int i;
  8951. @r{@dots{}}
  8952. for (i = 0; i < size; i++)
  8953. @r{@dots{}} access (array, i) @r{@dots{}}
  8954. @}
  8955. @end group
  8956. @end example
  8957. Nested function definitions can appear wherever automatic variable
  8958. declarations are allowed; that is, in any block, interspersed with the
  8959. other declarations and statements in the block.
  8960. The nested function's name is visible only within the parent block;
  8961. the name's scope starts from its definition and continues to the end
  8962. of the containing block. If the nested function's name
  8963. is the same as the parent function's name, there wil be
  8964. no way to refer to the parent function inside the scope of the
  8965. name of the nested function.
  8966. Using @code{extern} or @code{static} on a nested function definition
  8967. is an error.
  8968. It is possible to call the nested function from outside the scope of its
  8969. name by storing its address or passing the address to another function.
  8970. You can do this safely, but you must be careful:
  8971. @example
  8972. @group
  8973. hack (int *array, int size, int addition)
  8974. @{
  8975. void store (int index, int value)
  8976. @{ array[index] = value + addition; @}
  8977. intermediate (store, size);
  8978. @}
  8979. @end group
  8980. @end example
  8981. Here, the function @code{intermediate} receives the address of
  8982. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8983. the arguments given to @code{store} are used to store into @code{array}.
  8984. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8985. It is safe for @code{intermediate} to call @code{store} because
  8986. @code{hack}'s stack frame, with its arguments and local variables,
  8987. continues to exist during the call to @code{intermediate}.
  8988. Calling the nested function through its address after the containing
  8989. function has exited is asking for trouble. If it is called after a
  8990. containing scope level has exited, and if it refers to some of the
  8991. variables that are no longer in scope, it will refer to memory
  8992. containing junk or other data. It's not wise to take the risk.
  8993. The GNU C Compiler implements taking the address of a nested function
  8994. using a technique called @dfn{trampolines}. This technique was
  8995. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8996. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8997. A nested function can jump to a label inherited from a containing
  8998. function, provided the label was explicitly declared in the containing
  8999. function (@pxref{Local Labels}). Such a jump returns instantly to the
  9000. containing function, exiting the nested function that did the
  9001. @code{goto} and any intermediate function invocations as well. Here
  9002. is an example:
  9003. @example
  9004. @group
  9005. bar (int *array, int offset, int size)
  9006. @{
  9007. /* @r{Explicitly declare the label @code{failure}.} */
  9008. __label__ failure;
  9009. int access (int *array, int index)
  9010. @{
  9011. if (index > size)
  9012. /* @r{Exit this function,}
  9013. @r{and return to @code{bar}.} */
  9014. goto failure;
  9015. return array[index + offset];
  9016. @}
  9017. @end group
  9018. @group
  9019. int i;
  9020. @r{@dots{}}
  9021. for (i = 0; i < size; i++)
  9022. @r{@dots{}} access (array, i) @r{@dots{}}
  9023. @r{@dots{}}
  9024. return 0;
  9025. /* @r{Control comes here from @code{access}
  9026. if it does the @code{goto}.} */
  9027. failure:
  9028. return -1;
  9029. @}
  9030. @end group
  9031. @end example
  9032. To declare the nested function before its definition, use
  9033. @code{auto} (which is otherwise meaningless for function declarations;
  9034. @pxref{auto and register}). For example,
  9035. @example
  9036. bar (int *array, int offset, int size)
  9037. @{
  9038. auto int access (int *, int);
  9039. @r{@dots{}}
  9040. @r{@dots{}} access (array, i) @r{@dots{}}
  9041. @r{@dots{}}
  9042. int access (int *array, int index)
  9043. @{
  9044. @r{@dots{}}
  9045. @}
  9046. @r{@dots{}}
  9047. @}
  9048. @end example
  9049. @node Inline Function Definitions
  9050. @subsection Inline Function Definitions
  9051. @cindex inline function definitions
  9052. @cindex function definitions, inline
  9053. @findex inline
  9054. To declare a function inline, use the @code{inline} keyword in its
  9055. definition. Here's a simple function that takes a pointer-to-@code{int}
  9056. and increments the integer stored there---declared inline.
  9057. @example
  9058. struct list
  9059. @{
  9060. struct list *first, *second;
  9061. @};
  9062. inline struct list *
  9063. list_first (struct list *p)
  9064. @{
  9065. return p->first;
  9066. @}
  9067. inline struct list *
  9068. list_second (struct list *p)
  9069. @{
  9070. return p->second;
  9071. @}
  9072. @end example
  9073. optimized compilation can substitute the inline function's body for
  9074. any call to it. This is called @emph{inlining} the function. It
  9075. makes the code that contains the call run faster, significantly so if
  9076. the inline function is small.
  9077. Here's a function that uses @code{pair_second}:
  9078. @example
  9079. int
  9080. pairlist_length (struct list *l)
  9081. @{
  9082. int length = 0;
  9083. while (l)
  9084. @{
  9085. length++;
  9086. l = pair_second (l);
  9087. @}
  9088. return length;
  9089. @}
  9090. @end example
  9091. Substituting the code of @code{pair_second} into the definition of
  9092. @code{pairlist_length} results in this code, in effect:
  9093. @example
  9094. int
  9095. pairlist_length (struct list *l)
  9096. @{
  9097. int length = 0;
  9098. while (l)
  9099. @{
  9100. length++;
  9101. l = l->second;
  9102. @}
  9103. return length;
  9104. @}
  9105. @end example
  9106. Since the definition of @code{pair_second} does not say @code{extern}
  9107. or @code{static}, that definition is used only for inlining. It
  9108. doesn't generate code that can be called at run time. If not all the
  9109. calls to the function are inlined, there must be a definition of the
  9110. same function name in another module for them to call.
  9111. @cindex inline functions, omission of
  9112. @c @opindex fkeep-inline-functions
  9113. Adding @code{static} to an inline function definition means the
  9114. function definition is limited to this compilation module. Also, it
  9115. generates run-time code if necessary for the sake of any calls that
  9116. were not inlined. If all calls are inlined then the function
  9117. definition does not generate run-time code, but you can force
  9118. generation of run-time code with the option
  9119. @option{-fkeep-inline-functions}.
  9120. @cindex extern inline function
  9121. Specifying @code{extern} along with @code{inline} means the function is
  9122. external and generates run-time code to be called from other
  9123. separately compiled modules, as well as inlined. You can define the
  9124. function as @code{inline} without @code{extern} in other modules so as
  9125. to inline calls to the same function in those modules.
  9126. Why are some calls not inlined? First of all, inlining is an
  9127. optimization, so non-optimized compilation does not inline.
  9128. Some calls cannot be inlined for technical reasons. Also, certain
  9129. usages in a function definition can make it unsuitable for inline
  9130. substitution. Among these usages are: variadic functions, use of
  9131. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9132. use of nonlocal goto. The option @option{-Winline} requests a warning
  9133. when a function marked @code{inline} is unsuitable to be inlined. The
  9134. warning explains what obstacle makes it unsuitable.
  9135. Just because a call @emph{can} be inlined does not mean it
  9136. @emph{should} be inlined. The GNU C compiler weighs costs and
  9137. benefits to decide whether inlining a particular call is advantageous.
  9138. You can force inlining of all calls to a given function that can be
  9139. inlined, even in a non-optimized compilation. by specifying the
  9140. @samp{always_inline} attribute for the function, like this:
  9141. @example
  9142. /* @r{Prototype.} */
  9143. inline void foo (const char) __attribute__((always_inline));
  9144. @end example
  9145. @noindent
  9146. This is a GNU C extension. @xref{Attributes}.
  9147. A function call may be inlined even if not declared @code{inline} in
  9148. special cases where the compiler can determine this is correct and
  9149. desirable. For instance, when a static function is called only once,
  9150. it will very likely be inlined. With @option{-flto}, link-time
  9151. optimization, any function might be inlined. To absolutely prevent
  9152. inlining of a specific function, specify
  9153. @code{__attribute__((__noinline__))} in the function's definition.
  9154. @node Obsolete Definitions
  9155. @section Obsolete Function Features
  9156. These features of function definitions are still used in old
  9157. programs, but you shouldn't write code this way today.
  9158. If you are just learning C, you can skip this section.
  9159. @menu
  9160. * Old GNU Inlining:: An older inlining technique.
  9161. * Old-Style Function Definitions:: Original K&R style functions.
  9162. @end menu
  9163. @node Old GNU Inlining
  9164. @subsection Older GNU C Inlining
  9165. The GNU C spec for inline functions, before GCC version 5, defined
  9166. @code{extern inline} on a function definition to mean to inline calls
  9167. to it but @emph{not} generate code for the function that could be
  9168. called at run time. By contrast, @code{inline} without @code{extern}
  9169. specified to generate run-time code for the function. In effect, ISO
  9170. incompatibly flipped the meanings of these two cases. We changed GCC
  9171. in version 5 to adopt the ISO specification.
  9172. Many programs still use these cases with the previous GNU C meanings.
  9173. You can specify use of those meanings with the option
  9174. @option{-fgnu89-inline}. You can also specify this for a single
  9175. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9176. @example
  9177. inline __attribute__ ((gnu_inline))
  9178. int
  9179. inc (int *a)
  9180. @{
  9181. (*a)++;
  9182. @}
  9183. @end example
  9184. @node Old-Style Function Definitions
  9185. @subsection Old-Style Function Definitions
  9186. @cindex old-style function definitions
  9187. @cindex function definitions, old-style
  9188. @cindex K&R-style function definitions
  9189. The syntax of C traditionally allows omitting the data type in a
  9190. function declaration if it specifies a storage class or a qualifier.
  9191. Then the type defaults to @code{int}. For example:
  9192. @example
  9193. static foo (double x);
  9194. @end example
  9195. @noindent
  9196. defaults the return type to @code{int}. This is bad practice; if you
  9197. see it, fix it.
  9198. An @dfn{old-style} (or ``K&R'') function definition is the way
  9199. function definitions were written in the 1980s. It looks like this:
  9200. @example
  9201. @var{rettype}
  9202. @var{function} (@var{parmnames})
  9203. @var{parm_declarations}
  9204. @{
  9205. @var{body}
  9206. @}
  9207. @end example
  9208. In @var{parmnames}, only the parameter names are listed, separated by
  9209. commas. Then @var{parm_declarations} declares their data types; these
  9210. declarations look just like variable declarations. If a parameter is
  9211. listed in @var{parmnames} but has no declaration, it is implicitly
  9212. declared @code{int}.
  9213. There is no reason to write a definition this way nowadays, but they
  9214. can still be seen in older GNU programs.
  9215. An old-style variadic function definition looks like this:
  9216. @example
  9217. #include <varargs.h>
  9218. int
  9219. add_multiple_values (va_alist)
  9220. va_dcl
  9221. @{
  9222. int argcount;
  9223. int counter, total = 0;
  9224. /* @r{Declare a variable of type @code{va_list}.} */
  9225. va_list argptr;
  9226. /* @r{Initialize that variable.} */
  9227. va_start (argptr);
  9228. /* @r{Get the first argument (fixed).} */
  9229. argcount = va_arg (int);
  9230. for (counter = 0; counter < argcount; counter++)
  9231. @{
  9232. /* @r{Get the next additional argument.} */
  9233. total += va_arg (argptr, int);
  9234. @}
  9235. /* @r{End use of the @code{argptr} variable.} */
  9236. va_end (argptr);
  9237. return total;
  9238. @}
  9239. @end example
  9240. Note that the old-style variadic function definition has no fixed
  9241. parameter variables; all arguments must be obtained with
  9242. @code{va_arg}.
  9243. @node Compatible Types
  9244. @chapter Compatible Types
  9245. @cindex compatible types
  9246. @cindex types, compatible
  9247. Declaring a function or variable twice is valid in C only if the two
  9248. declarations specify @dfn{compatible} types. In addition, some
  9249. operations on pointers require operands to have compatible target
  9250. types.
  9251. In C, two different primitive types are never compatible. Likewise for
  9252. the defined types @code{struct}, @code{union} and @code{enum}: two
  9253. separately defined types are incompatible unless they are defined
  9254. exactly the same way.
  9255. However, there are a few cases where different types can be
  9256. compatible:
  9257. @itemize @bullet
  9258. @item
  9259. Every enumeration type is compatible with some integer type. In GNU
  9260. C, the choice of integer type depends on the largest enumeration
  9261. value.
  9262. @c ??? Which one, in GCC?
  9263. @c ??? ... it varies, depending on the enum values. Testing on
  9264. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9265. @c ??? then moves on to an 8-byte signed integer. These details
  9266. @c ??? might be platform-dependent, as the C standard says that even
  9267. @c ??? char could be used as an enum type, but it's at least true
  9268. @c ??? that GCC chooses a type that is at least large enough to
  9269. @c ??? hold the largest enum value.
  9270. @item
  9271. Array types are compatible if the element types are compatible
  9272. and the sizes (when specified) match.
  9273. @item
  9274. Pointer types are compatible if the pointer target types are
  9275. compatible.
  9276. @item
  9277. Function types that specify argument types are compatible if the
  9278. return types are compatible and the argument types are compatible,
  9279. argument by argument. In addition, they must all agree in whether
  9280. they use @code{...} to allow additional arguments.
  9281. @item
  9282. Function types that don't specify argument types are compatible if the
  9283. return types are.
  9284. @item
  9285. Function types that specify the argument types are compatible with
  9286. function types that omit them, if the return types are compatible and
  9287. the specified argument types are unaltered by the argument promotions
  9288. (@pxref{Argument Promotions}).
  9289. @end itemize
  9290. In order for types to be compatible, they must agree in their type
  9291. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9292. It follows that @code{const int *} and @code{int *} are incompatible
  9293. too (they are pointers to types that are not compatible).
  9294. If two types are compatible ignoring the qualifiers, we call them
  9295. @dfn{nearly compatible}. (If they are array types, we ignore
  9296. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9297. Comparison of pointers is valid if the pointers' target types are
  9298. nearly compatible. Likewise, the two branches of a conditional
  9299. expression may be pointers to nearly compatible target types.
  9300. If two types are compatible ignoring the qualifiers, and the first
  9301. type has all the qualifiers of the second type, we say the first is
  9302. @dfn{upward compatible} with the second. Assignment of pointers
  9303. requires the assigned pointer's target type to be upward compatible
  9304. with the right operand (the new value)'s target type.
  9305. @node Type Conversions
  9306. @chapter Type Conversions
  9307. @cindex type conversions
  9308. @cindex conversions, type
  9309. C converts between data types automatically when that seems clearly
  9310. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9311. @menu
  9312. * Explicit Type Conversion:: Casting a value from one type to another.
  9313. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9314. * Argument Promotions:: Automatic conversion of function parameters.
  9315. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9316. * Common Type:: When operand types differ, which one is used?
  9317. @end menu
  9318. @node Explicit Type Conversion
  9319. @section Explicit Type Conversion
  9320. @cindex cast
  9321. @cindex explicit type conversion
  9322. You can do explicit conversions using the unary @dfn{cast} operator,
  9323. which is written as a type designator (@pxref{Type Designators}) in
  9324. parentheses. For example, @code{(int)} is the operator to cast to
  9325. type @code{int}. Here's an example of using it:
  9326. @example
  9327. @{
  9328. double d = 5.5;
  9329. printf ("Floating point value: %f\n", d);
  9330. printf ("Rounded to integer: %d\n", (int) d);
  9331. @}
  9332. @end example
  9333. Using @code{(int) d} passes an @code{int} value as argument to
  9334. @code{printf}, so you can print it with @samp{%d}. Using just
  9335. @code{d} without the cast would pass the value as @code{double}.
  9336. That won't work at all with @samp{%d}; the results would be gibberish.
  9337. To divide one integer by another without rounding,
  9338. cast either of the integers to @code{double} first:
  9339. @example
  9340. (double) @var{dividend} / @var{divisor}
  9341. @var{dividend} / (double) @var{divisor}
  9342. @end example
  9343. It is enough to cast one of them, because that forces the common type
  9344. to @code{double} so the other will be converted automatically.
  9345. The valid cast conversions are:
  9346. @itemize @bullet
  9347. @item
  9348. One numerical type to another.
  9349. @item
  9350. One pointer type to another.
  9351. (Converting between pointers that point to functions
  9352. and pointers that point to data is not standard C.)
  9353. @item
  9354. A pointer type to an integer type.
  9355. @item
  9356. An integer type to a pointer type.
  9357. @item
  9358. To a union type, from the type of any alternative in the union
  9359. (@pxref{Unions}). (This is a GNU extension.)
  9360. @item
  9361. Anything, to @code{void}.
  9362. @end itemize
  9363. @node Assignment Type Conversions
  9364. @section Assignment Type Conversions
  9365. @cindex assignment type conversions
  9366. Certain type conversions occur automatically in assignments
  9367. and certain other contexts. These are the conversions
  9368. assignments can do:
  9369. @itemize @bullet
  9370. @item
  9371. Converting any numeric type to any other numeric type.
  9372. @item
  9373. Converting @code{void *} to any other pointer type
  9374. (except pointer-to-function types).
  9375. @item
  9376. Converting any other pointer type to @code{void *}.
  9377. (except pointer-to-function types).
  9378. @item
  9379. Converting 0 (a null pointer constant) to any pointer type.
  9380. @item
  9381. Converting any pointer type to @code{bool}. (The result is
  9382. 1 if the pointer is not null.)
  9383. @item
  9384. Converting between pointer types when the left-hand target type is
  9385. upward compatible with the right-hand target type. @xref{Compatible
  9386. Types}.
  9387. @end itemize
  9388. These type conversions occur automatically in certain contexts,
  9389. which are:
  9390. @itemize @bullet
  9391. @item
  9392. An assignment converts the type of the right-hand expression
  9393. to the type wanted by the left-hand expression. For example,
  9394. @example
  9395. double i;
  9396. i = 5;
  9397. @end example
  9398. @noindent
  9399. converts 5 to @code{double}.
  9400. @item
  9401. A function call, when the function specifies the type for that
  9402. argument, converts the argument value to that type. For example,
  9403. @example
  9404. void foo (double);
  9405. foo (5);
  9406. @end example
  9407. @noindent
  9408. converts 5 to @code{double}.
  9409. @item
  9410. A @code{return} statement converts the specified value to the type
  9411. that the function is declared to return. For example,
  9412. @example
  9413. double
  9414. foo ()
  9415. @{
  9416. return 5;
  9417. @}
  9418. @end example
  9419. @noindent
  9420. also converts 5 to @code{double}.
  9421. @end itemize
  9422. In all three contexts, if the conversion is impossible, that
  9423. constitutes an error.
  9424. @node Argument Promotions
  9425. @section Argument Promotions
  9426. @cindex argument promotions
  9427. @cindex promotion of arguments
  9428. When a function's definition or declaration does not specify the type
  9429. of an argument, that argument is passed without conversion in whatever
  9430. type it has, with these exceptions:
  9431. @itemize @bullet
  9432. @item
  9433. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9434. expression is a narrow integer, such as @code{char} or @code{short},
  9435. the call converts it automatically to @code{int} (@pxref{Integer
  9436. Types}).@footnote{On an embedded controller where @code{char}
  9437. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9438. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9439. never occurs in GNU C on real computers.}
  9440. In this example, the expression @code{c} is passed as an @code{int}:
  9441. @example
  9442. char c = '$';
  9443. printf ("Character c is '%c'\n", c);
  9444. @end example
  9445. @item
  9446. If the expression
  9447. has type @code{float}, the call converts it automatically to
  9448. @code{double}.
  9449. @item
  9450. An array as argument is converted to a pointer to its zeroth element.
  9451. @item
  9452. A function name as argument is converted to a pointer to that function.
  9453. @end itemize
  9454. @node Operand Promotions
  9455. @section Operand Promotions
  9456. @cindex operand promotions
  9457. The operands in arithmetic operations undergo type conversion automatically.
  9458. These @dfn{operand promotions} are the same as the argument promotions
  9459. except without converting @code{float} to @code{double}. In other words,
  9460. the operand promotions convert
  9461. @itemize @bullet
  9462. @item
  9463. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9464. @item
  9465. an array to a pointer to its zeroth element, and
  9466. @item
  9467. a function name to a pointer to that function.
  9468. @end itemize
  9469. @node Common Type
  9470. @section Common Type
  9471. @cindex common type
  9472. Arithmetic binary operators (except the shift operators) convert their
  9473. operands to the @dfn{common type} before operating on them.
  9474. Conditional expressions also convert the two possible results to their
  9475. common type. Here are the rules for determining the common type.
  9476. If one of the numbers has a floating-point type and the other is an
  9477. integer, the common type is that floating-point type. For instance,
  9478. @example
  9479. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9480. @end example
  9481. If both are floating point, the type with the larger range is the
  9482. common type.
  9483. If both are integers but of different widths, the common type
  9484. is the wider of the two.
  9485. If they are integer types of the same width, the common type is
  9486. unsigned if either operand is unsigned, and it's @code{long} if either
  9487. operand is @code{long}. It's @code{long long} if either operand is
  9488. @code{long long}.
  9489. These rules apply to addition, subtraction, multiplication, division,
  9490. remainder, comparisons, and bitwise operations. They also apply to
  9491. the two branches of a conditional expression, and to the arithmetic
  9492. done in a modifying assignment operation.
  9493. @node Scope
  9494. @chapter Scope
  9495. @cindex scope
  9496. @cindex block scope
  9497. @cindex function scope
  9498. @cindex function prototype scope
  9499. Each definition or declaration of an identifier is visible
  9500. in certain parts of the program, which is typically less than the whole
  9501. of the program. The parts where it is visible are called its @dfn{scope}.
  9502. Normally, declarations made at the top-level in the source -- that is,
  9503. not within any blocks and function definitions -- are visible for the
  9504. entire contents of the source file after that point. This is called
  9505. @dfn{file scope} (@pxref{File-Scope Variables}).
  9506. Declarations made within blocks of code, including within function
  9507. definitions, are visible only within those blocks. This is called
  9508. @dfn{block scope}. Here is an example:
  9509. @example
  9510. @group
  9511. void
  9512. foo (void)
  9513. @{
  9514. int x = 42;
  9515. @}
  9516. @end group
  9517. @end example
  9518. @noindent
  9519. In this example, the variable @code{x} has block scope; it is visible
  9520. only within the @code{foo} function definition block. Thus, other
  9521. blocks could have their own variables, also named @code{x}, without
  9522. any conflict between those variables.
  9523. A variable declared inside a subblock has a scope limited to
  9524. that subblock,
  9525. @example
  9526. @group
  9527. void
  9528. foo (void)
  9529. @{
  9530. @{
  9531. int x = 42;
  9532. @}
  9533. // @r{@code{x} is out of scope here.}
  9534. @}
  9535. @end group
  9536. @end example
  9537. If a variable declared within a block has the same name as a variable
  9538. declared outside of that block, the definition within the block
  9539. takes precedence during its scope:
  9540. @example
  9541. @group
  9542. int x = 42;
  9543. void
  9544. foo (void)
  9545. @{
  9546. int x = 17;
  9547. printf ("%d\n", x);
  9548. @}
  9549. @end group
  9550. @end example
  9551. @noindent
  9552. This prints 17, the value of the variable @code{x} declared in the
  9553. function body block, rather than the value of the variable @code{x} at
  9554. file scope. We say that the inner declaration of @code{x}
  9555. @dfn{shadows} the outer declaration, for the extent of the inner
  9556. declaration's scope.
  9557. A declaration with block scope can be shadowed by another declaration
  9558. with the same name in a subblock.
  9559. @example
  9560. @group
  9561. void
  9562. foo (void)
  9563. @{
  9564. char *x = "foo";
  9565. @{
  9566. int x = 42;
  9567. @r{@dots{}}
  9568. exit (x / 6);
  9569. @}
  9570. @}
  9571. @end group
  9572. @end example
  9573. A function parameter's scope is the entire function body, but it can
  9574. be shadowed. For example:
  9575. @example
  9576. @group
  9577. int x = 42;
  9578. void
  9579. foo (int x)
  9580. @{
  9581. printf ("%d\n", x);
  9582. @}
  9583. @end group
  9584. @end example
  9585. @noindent
  9586. This prints the value of @code{x} the function parameter, rather than
  9587. the value of the file-scope variable @code{x}. However,
  9588. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9589. is visible for the whole of the containing function body, both before
  9590. and after the label declaration:
  9591. @example
  9592. @group
  9593. void
  9594. foo (void)
  9595. @{
  9596. @r{@dots{}}
  9597. goto bar;
  9598. @r{@dots{}}
  9599. @{ // @r{Subblock does not affect labels.}
  9600. bar:
  9601. @r{@dots{}}
  9602. @}
  9603. goto bar;
  9604. @}
  9605. @end group
  9606. @end example
  9607. Except for labels, a declared identifier is not
  9608. visible to code before its declaration. For example:
  9609. @example
  9610. @group
  9611. int x = 5;
  9612. int y = x + 10;
  9613. @end group
  9614. @end example
  9615. @noindent
  9616. will work, but:
  9617. @example
  9618. @group
  9619. int x = y + 10;
  9620. int y = 5;
  9621. @end group
  9622. @end example
  9623. @noindent
  9624. cannot refer to the variable @code{y} before its declaration.
  9625. @include cpp.texi
  9626. @node Integers in Depth
  9627. @chapter Integers in Depth
  9628. This chapter explains the machine-level details of integer types: how
  9629. they are represented as bits in memory, and the range of possible
  9630. values for each integer type.
  9631. @menu
  9632. * Integer Representations:: How integer values appear in memory.
  9633. * Maximum and Minimum Values:: Value ranges of integer types.
  9634. @end menu
  9635. @node Integer Representations
  9636. @section Integer Representations
  9637. @cindex integer representations
  9638. @cindex representation of integers
  9639. Modern computers store integer values as binary (base-2) numbers that
  9640. occupy a single unit of storage, typically either as an 8-bit
  9641. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9642. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9643. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9644. any of these types could have some other size, bit it's not worth even
  9645. a minute to cater to that possibility. It never happens on
  9646. GNU/Linux.}
  9647. @cindex @code{CHAR_BIT}
  9648. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9649. of bits in type @code{char}. On any real operating system, the value
  9650. is 8.
  9651. The fixed sizes of numeric types necessarily limits their @dfn{range
  9652. of values}, and the particular encoding of integers decides what that
  9653. range is.
  9654. @cindex two's-complement representation
  9655. For unsigned integers, the entire space is used to represent a
  9656. nonnegative value. Signed integers are stored using
  9657. @dfn{two's-complement representation}: a signed integer with @var{n}
  9658. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9659. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9660. high-order, bit is called the @dfn{sign bit}.
  9661. @c ??? Needs correcting
  9662. There is only one value that means zero, and the most negative number
  9663. lacks a positive counterpart. As a result, negating that number
  9664. causes overflow; in practice, its result is that number back again.
  9665. For example, a two's-complement signed 8-bit integer can represent all
  9666. decimal numbers from @minus{}128 to +127. We will revisit that
  9667. peculiarity shortly.
  9668. Decades ago, there were computers that didn't use two's-complement
  9669. representation for integers (@pxref{Integers in Depth}), but they are
  9670. long gone and not worth any effort to support.
  9671. @c ??? Is this duplicate?
  9672. When an arithmetic operation produces a value that is too big to
  9673. represent, the operation is said to @dfn{overflow}. In C, integer
  9674. overflow does not interrupt the control flow or signal an error.
  9675. What it does depends on signedness.
  9676. For unsigned arithmetic, the result of an operation that overflows is
  9677. the @var{n} low-order bits of the correct value. If the correct value
  9678. is representable in @var{n} bits, that is always the result;
  9679. thus we often say that ``integer arithmetic is exact,'' omitting the
  9680. crucial qualifying phrase ``as long as the exact result is
  9681. representable.''
  9682. In principle, a C program should be written so that overflow never
  9683. occurs for signed integers, but in GNU C you can specify various ways
  9684. of handling such overflow (@pxref{Integer Overflow}).
  9685. Integer representations are best understood by looking at a table for
  9686. a tiny integer size; here are the possible values for an integer with
  9687. three bits:
  9688. @multitable @columnfractions .25 .25 .25 .25
  9689. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9690. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9691. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9692. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9693. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9694. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9695. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9696. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9697. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9698. @end multitable
  9699. The parenthesized decimal numbers in the last column represent the
  9700. signed meanings of the two's-complement of the line's value. Recall
  9701. that, in two's-complement encoding, the high-order bit is 0 when
  9702. the number is nonnegative.
  9703. We can now understand the peculiar behavior of negation of the
  9704. most negative two's-complement integer: start with 0b100,
  9705. invert the bits to get 0b011, and add 1: we get
  9706. 0b100, the value we started with.
  9707. We can also see overflow behavior in two's-complement:
  9708. @example
  9709. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9710. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9711. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9712. @end example
  9713. @noindent
  9714. A sum of two nonnegative signed values that overflows has a 1 in the
  9715. sign bit, so the exact positive result is truncated to a negative
  9716. value.
  9717. @c =====================================================================
  9718. @node Maximum and Minimum Values
  9719. @section Maximum and Minimum Values
  9720. @cindex maximum integer values
  9721. @cindex minimum integer values
  9722. @cindex integer ranges
  9723. @cindex ranges of integer types
  9724. @findex INT_MAX
  9725. @findex UINT_MAX
  9726. @findex SHRT_MAX
  9727. @findex LONG_MAX
  9728. @findex LLONG_MAX
  9729. @findex USHRT_MAX
  9730. @findex ULONG_MAX
  9731. @findex ULLONG_MAX
  9732. @findex CHAR_MAX
  9733. @findex SCHAR_MAX
  9734. @findex UCHAR_MAX
  9735. For each primitive integer type, there is a standard macro defined in
  9736. @file{limits.h} that gives the largest value that type can hold. For
  9737. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9738. On a 32-bit computer, that is equal to 2,147,483,647. The
  9739. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9740. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9741. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9742. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9743. @code{ULLONG_MAX}.
  9744. Since there are three ways to specify a @code{char} type, there are
  9745. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9746. @code{UCHAR_MAX}.
  9747. For each type that is or might be signed, there is another symbol that
  9748. gives the minimum value it can hold. (Just replace @code{MAX} with
  9749. @code{MIN} in the names listed above.) There is no minimum limit
  9750. symbol for types specified with @code{unsigned} because the
  9751. minimum for them is universally zero.
  9752. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9753. two's-complement representation, the most negative number is 1 less
  9754. than the negative of the most positive number. Thus, @code{INT_MIN}
  9755. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9756. actually write the value that way in C, since it would overflow.
  9757. That's a good reason to use @code{INT_MIN} to specify
  9758. that value. Its definition is written to avoid overflow.
  9759. @include fp.texi
  9760. @node Compilation
  9761. @chapter Compilation
  9762. @cindex object file
  9763. @cindex compilation module
  9764. @cindex make rules
  9765. @cindex link
  9766. Early in the manual we explained how to compile a simple C program
  9767. that consists of a single source file (@pxref{Compile Example}).
  9768. However, we handle only short programs that way. A typical C program
  9769. consists of many source files, each of which is usually a separate
  9770. @dfn{compilation module}---meaning that it has to be compiled
  9771. separately. (The source files that are not separate compilation
  9772. modules are those that are used via @code{#include}; see @ref{Header
  9773. Files}.)
  9774. To compile a multi-module program, you compile each of the program's
  9775. compilation modules, making an @dfn{object file} for that module. The
  9776. last step is to @dfn{link} the many object files together into a
  9777. single executable for the whole program.
  9778. The full details of how to compile C programs (and other programs)
  9779. with GCC are documented in xxxx.
  9780. @c ??? ref
  9781. Here we give only a simple introduction.
  9782. These commands compile two compilation modules, @file{foo.c} and
  9783. @file{bar.c}, running the compiler for each module:
  9784. @example
  9785. gcc -c -O -g foo.c
  9786. gcc -c -O -g bar.c
  9787. @end example
  9788. @noindent
  9789. In these commands, @option{-g} says to generate debugging information,
  9790. @option{-O} says to do some optimization, and @option{-c} says to put
  9791. the compiled code for that module into a corresponding object file and
  9792. go no further. The object file for @file{foo.c} is automatically
  9793. called @file{foo.o}, and so on.
  9794. If you wish, you can specify the additional compilation options. For
  9795. instance, @option{-Wformat -Wparenthesis -Wstrict-prototypes} request
  9796. additional warnings.
  9797. @cindex linking object files
  9798. After you compile all the program's modules, you link the object files
  9799. into a combined executable, like this:
  9800. @example
  9801. gcc -o foo foo.o bar.o
  9802. @end example
  9803. @noindent
  9804. In this command, @option{-o foo} species the file name for the
  9805. executable file, and the other arguments are the object files to link.
  9806. Always specify the executable file name in a command that generates
  9807. one.
  9808. One reason to divide a large program into multiple compilation modules
  9809. is to control how each module can access the internals of the others.
  9810. When a module declares a function or variable @code{extern}, other
  9811. modules can access it. The other functions and variables defined in a
  9812. module can't be accessed from outside that module.
  9813. The other reason for using multiple modules is so that changing one
  9814. source file does not require recompiling all of them in order to try
  9815. the modified program. It is sufficient to recompile the source file
  9816. that you changed, then link them all again. Dividing a large program
  9817. into many substantial modules in this way typically makes
  9818. recompilation much faster.
  9819. Normally we don't run any of these commands directly. Instead we
  9820. write a set of @dfn{make rules} for the program, then use the
  9821. @command{make} program to recompile only the source files that need to
  9822. be recompiled, by following those rules. @xref{Top, The GNU Make
  9823. Mamual, , Make, The GNU Make Manual}.
  9824. @node Directing Compilation
  9825. @chapter Directing Compilation
  9826. This chapter describes C constructs that don't alter the program's
  9827. meaning @emph{as such}, but rather direct the compiler how to treat
  9828. some aspects of the program.
  9829. @menu
  9830. * Pragmas:: Controling compilation of some constructs.
  9831. * Static Assertions:: Compile-time tests for conditions.
  9832. @end menu
  9833. @node Pragmas
  9834. @section Pragmas
  9835. A @dfn{pragma} is an annotation in a program that gives direction to
  9836. the compiler.
  9837. @menu
  9838. * Pragma Basics:: Pragma syntax and usage.
  9839. * Severity Pragmas:: Settings for compile-time pragma output.
  9840. * Optimization Pragmas:: Controlling optimizations.
  9841. @end menu
  9842. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9843. @node Pragma Basics
  9844. @subsection Pragma Basics
  9845. C defines two syntactical forms for pragmas, the line form and the
  9846. token form. You can write any pragma in either form, with the same
  9847. meaning.
  9848. The line form is a line in the source code, like this:
  9849. @example
  9850. #pragma @var{line}
  9851. @end example
  9852. @noindent
  9853. The line pragma has no effect on the parsing of the lines around it.
  9854. This form has the drawback that it can't be generated by a macro expansion.
  9855. The token form is a series of tokens; it can appear anywhere in the
  9856. program between the other tokens.
  9857. @example
  9858. _Pragma (@var{stringconstant})
  9859. @end example
  9860. @noindent
  9861. The pragma has no effect on the syntax of the tokens that surround it;
  9862. thus, here's a pragma in the middle of an @code{if} statement:
  9863. @example
  9864. if _Pragma ("hello") (x > 1)
  9865. @end example
  9866. @noindent
  9867. However, that's an unclear thing to do; for the sake of
  9868. understandability, it is better to put a pragma on a line by itself
  9869. and not embedded in the middle of another construct.
  9870. Both forms of pragma have a textual argument. In a line pragma, the
  9871. text is the rest of the line. The textual argument to @code{_Pragma}
  9872. uses the same syntax as a C string constant: surround the text with
  9873. two @samp{"} characters, and add a backslash before each @samp{"} or
  9874. @samp{\} character in it.
  9875. With either syntax, the textual argument specifies what to do.
  9876. It begins with one or several words that specify the operation.
  9877. If the compiler does not recognize them, it ignores the pragma.
  9878. Here are the pragma operations supported in GNU C@.
  9879. @c ??? Verify font for []
  9880. @table @code
  9881. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9882. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9883. Declares that the current source file depends on @var{file}, so GNU C
  9884. compares the file times and gives a warning if @var{file} is newer
  9885. than the current source file.
  9886. This directive searches for @var{file} the way @code{#include}
  9887. searches for a non-system header file.
  9888. If @var{message} is given, the warning message includes that text.
  9889. Examples:
  9890. @example
  9891. #pragma GCC dependency "parse.y"
  9892. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9893. rerun fixincludes")
  9894. @end example
  9895. @item #pragma GCC poison @var{identifiers}
  9896. @itemx _Pragma ("GCC poison @var{identifiers}")
  9897. Poisons the identifiers listed in @var{identifiers}.
  9898. This is useful to make sure all mention of @var{identifiers} has been
  9899. deleted from the program and that no reference to them creeps back in.
  9900. If any of those identifiers appears anywhere in the source after the
  9901. directive, it causes a compilation error. For example,
  9902. @example
  9903. #pragma GCC poison printf sprintf fprintf
  9904. sprintf(some_string, "hello");
  9905. @end example
  9906. @noindent
  9907. generates an error.
  9908. If a poisoned identifier appears as part of the expansion of a macro
  9909. that was defined before the identifier was poisoned, it will @emph{not}
  9910. cause an error. Thus, system headers that define macros that use
  9911. the identifier will not cause errors.
  9912. For example,
  9913. @example
  9914. #define strrchr rindex
  9915. _Pragma ("GCC poison rindex")
  9916. strrchr(some_string, 'h');
  9917. @end example
  9918. @noindent
  9919. does not cause a compilation error.
  9920. @item #pragma GCC system_header
  9921. @itemx _Pragma ("GCC system_header")
  9922. Specify treating the rest of the current source file as if it came
  9923. from a system header file. @xref{System Headers, System Headers,
  9924. System Headers, gcc, Using the GNU Compiler Collection}.
  9925. @item #pragma GCC warning @var{message}
  9926. @itemx _Pragma ("GCC warning @var{message}")
  9927. Equivalent to @code{#warning}. Its advantage is that the
  9928. @code{_Pragma} form can be included in a macro definition.
  9929. @item #pragma GCC error @var{message}
  9930. @itemx _Pragma ("GCC error @var{message}")
  9931. Equivalent to @code{#error}. Its advantage is that the
  9932. @code{_Pragma} form can be included in a macro definition.
  9933. @item #pragma GCC message @var{message}
  9934. @itemx _Pragma ("GCC message @var{message}")
  9935. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9936. informational message, and could be used to include additional warning
  9937. or error text without triggering more warnings or errors. (Note that
  9938. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9939. @samp{GCC} as part of the pragma.)
  9940. @end table
  9941. @node Severity Pragmas
  9942. @subsection Severity Pragmas
  9943. These pragmas control the severity of classes of diagnostics.
  9944. You can specify the class of diagnostic with the GCC option that causes
  9945. those diagnostics to be generated.
  9946. @table @code
  9947. @item #pragma GCC diagnostic error @var{option}
  9948. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9949. For code following this pragma, treat diagnostics of the variety
  9950. specified by @var{option} as errors. For example:
  9951. @example
  9952. _Pragma ("GCC diagnostic error -Wformat")
  9953. @end example
  9954. @noindent
  9955. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9956. as errors rather than warnings.
  9957. @item #pragma GCC diagnostic warning @var{option}
  9958. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9959. For code following this pragma, treat diagnostics of the variety
  9960. specified by @var{option} as warnings. This overrides the
  9961. @var{-Werror} option which says to treat warnings as errors.
  9962. @item #pragma GCC diagnostic ignore @var{option}
  9963. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9964. For code following this pragma, refrain from reporting any diagnostics
  9965. of the variety specified by @var{option}.
  9966. @item #pragma GCC diagnostic push
  9967. @itemx _Pragma ("GCC diagnostic push")
  9968. @itemx #pragma GCC diagnostic pop
  9969. @itemx _Pragma ("GCC diagnostic pop")
  9970. These pragmas maintain a stack of states for severity settings.
  9971. @samp{GCC diagnostic push} saves the current settings on the stack,
  9972. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9973. the current settings from that.
  9974. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9975. restores the settings to what they were at the start of compilation.
  9976. Here is an example:
  9977. @example
  9978. _Pragma ("GCC diagnostic error -Wformat")
  9979. /* @r{@option{-Wformat} messages treated as errors. } */
  9980. _Pragma ("GCC diagnostic push")
  9981. _Pragma ("GCC diagnostic warning -Wformat")
  9982. /* @r{@option{-Wformat} messages treated as warnings. } */
  9983. _Pragma ("GCC diagnostic push")
  9984. _Pragma ("GCC diagnostic ignored -Wformat")
  9985. /* @r{@option{-Wformat} messages suppressed. } */
  9986. _Pragma ("GCC diagnostic pop")
  9987. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9988. _Pragma ("GCC diagnostic pop")
  9989. /* @r{@option{-Wformat} messages treated as errors again. } */
  9990. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9991. _Pragma ("GCC diagnostic pop")
  9992. /* @r{@option{-Wformat} messages treated once again}
  9993. @r{as specified by the GCC command-line options.} */
  9994. @end example
  9995. @end table
  9996. @node Optimization Pragmas
  9997. @subsection Optimization Pragmas
  9998. These pragmas enable a particular optimization for specific function
  9999. definitions. The settings take effect at the end of a function
  10000. definition, so the clean place to use these pragmas is between
  10001. function definitions.
  10002. @table @code
  10003. @item #pragma GCC optimize @var{optimization}
  10004. @itemx _Pragma ("GCC optimize @var{optimization}")
  10005. These pragmas enable the optimization @var{optimization} for the
  10006. following functions. For example,
  10007. @example
  10008. _Pragma ("GCC optimize -fforward-propagate")
  10009. @end example
  10010. @noindent
  10011. says to apply the @samp{forward-propagate} optimization to all
  10012. following function definitions. Specifying optimizations for
  10013. individual functions, rather than for the entire program, is rare but
  10014. can be useful for getting around a bug in the compiler.
  10015. If @var{optimization} does not correspond to a defined optimization
  10016. option, the pragma is erroneous. To turn off an optimization, use the
  10017. corresponding @samp{-fno-} option, such as
  10018. @samp{-fno-forward-propagate}.
  10019. @item #pragma GCC target @var{optimizations}
  10020. @itemx _Pragma ("GCC target @var{optimizations}")
  10021. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  10022. used for platform-specific optimizations. Thus,
  10023. @example
  10024. _Pragma ("GCC target popcnt")
  10025. @end example
  10026. @noindent
  10027. activates the optimization @samp{popcnt} for all
  10028. following function definitions. This optimization is supported
  10029. on a few common targets but not on others.
  10030. @item #pragma GCC push_options
  10031. @itemx _Pragma ("GCC push_options")
  10032. The @samp{push_options} pragma saves on a stack the current settings
  10033. specified with the @samp{target} and @samp{optimize} pragmas.
  10034. @item #pragma GCC pop_options
  10035. @itemx _Pragma ("GCC pop_options")
  10036. The @samp{pop_options} pragma pops saved settings from that stack.
  10037. Here's an example of using this stack.
  10038. @example
  10039. _Pragma ("GCC push_options")
  10040. _Pragma ("GCC optimize forward-propagate")
  10041. /* @r{Functions to compile}
  10042. @r{with the @code{forward-propagate} optimization.} */
  10043. _Pragma ("GCC pop_options")
  10044. /* @r{Ends enablement of @code{forward-propagate}.} */
  10045. @end example
  10046. @item #pragma GCC reset_options
  10047. @itemx _Pragma ("GCC reset_options")
  10048. Clears all pragma-defined @samp{target} and @samp{optimize}
  10049. optimization settings.
  10050. @end table
  10051. @node Static Assertions
  10052. @section Static Assertions
  10053. @cindex static assertions
  10054. @findex _Static_assert
  10055. You can add compiler-time tests for necessary conditions into your
  10056. code using @code{_Static_assert}. This can be useful, for example, to
  10057. check that the compilation target platform supports the type sizes
  10058. that the code expects. For example,
  10059. @example
  10060. _Static_assert ((sizeof (long int) >= 8),
  10061. "long int needs to be at least 8 bytes");
  10062. @end example
  10063. @noindent
  10064. reports a compile-time error if compiled on a system with long
  10065. integers smaller than 8 bytes, with @samp{long int needs to be at
  10066. least 8 bytes} as the error message.
  10067. Since calls @code{_Static_assert} are processed at compile time, the
  10068. expression must be computable at compile time and the error message
  10069. must be a literal string. The expression can refer to the sizes of
  10070. variables, but can't refer to their values. For example, the
  10071. following static assertion is invalid for two reasons:
  10072. @example
  10073. char *error_message
  10074. = "long int needs to be at least 8 bytes";
  10075. int size_of_long_int = sizeof (long int);
  10076. _Static_assert (size_of_long_int == 8, error_message);
  10077. @end example
  10078. @noindent
  10079. The expression @code{size_of_long_int == 8} isn't computable at
  10080. compile time, and the error message isn't a literal string.
  10081. You can, though, use preprocessor definition values with
  10082. @code{_Static_assert}:
  10083. @example
  10084. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10085. at least 8 bytes"
  10086. _Static_assert ((sizeof (long int) == 8),
  10087. LONG_INT_ERROR_MESSAGE);
  10088. @end example
  10089. Static assertions are permitted wherever a statement or declaration is
  10090. permitted, including at top level in the file, and also inside the
  10091. definition of a type.
  10092. @example
  10093. union y
  10094. @{
  10095. int i;
  10096. int *ptr;
  10097. _Static_assert (sizeof (int *) == sizeof (int),
  10098. "Pointer and int not same size");
  10099. @};
  10100. @end example
  10101. @node Type Alignment
  10102. @appendix Type Alignment
  10103. @cindex type alignment
  10104. @cindex alignment of type
  10105. @findex _Alignof
  10106. @findex __alignof__
  10107. Code for device drivers and other communication with low-level
  10108. hardware sometimes needs to be concerned with the alignment of
  10109. data objects in memory.
  10110. Each data type has a required @dfn{alignment}, always a power of 2,
  10111. that says at which memory addresses an object of that type can validly
  10112. start. A valid address for the type must be a multiple of its
  10113. alignment. If a type's alignment is 1, that means it can validly
  10114. start at any address. If a type's alignment is 2, that means it can
  10115. only start at an even address. If a type's alignment is 4, that means
  10116. it can only start at an address that is a multiple of 4.
  10117. The alignment of a type (except @code{char}) can vary depending on the
  10118. kind of computer in use. To refer to the alignment of a type in a C
  10119. program, use @code{_Alignof}, whose syntax parallels that of
  10120. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10121. operation, and it doesn't compute the value of the expression used
  10122. as its argument.
  10123. Nominally, each integer and floating-point type has an alignment equal to
  10124. the largest power of 2 that divides its size. Thus, @code{int} with
  10125. size 4 has a nominal alignment of 4, and @code{long long int} with
  10126. size 8 has a nominal alignment of 8.
  10127. However, each kind of computer generally has a maximum alignment, and
  10128. no type needs more alignment than that. If the computer's maximum
  10129. alignment is 4 (which is common), then no type's alignment is more
  10130. than 4.
  10131. The size of any type is always a multiple of its alignment; that way,
  10132. in an array whose elements have that type, all the elements are
  10133. properly aligned if the first one is.
  10134. These rules apply to all real computers today, but some embedded
  10135. controllers have odd exceptions. We don't have references to cite for
  10136. them.
  10137. @c We can't cite a nonfree manual as documentation.
  10138. Ordinary C code guarantees that every object of a given type is in
  10139. fact aligned as that type requires.
  10140. If the operand of @code{_Alignof} is a structure field, the value
  10141. is the alignment it requires. It may have a greater alignment by
  10142. coincidence, due to the other fields, but @code{_Alignof} is not
  10143. concerned about that. @xref{Structures}.
  10144. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10145. but now that the feature has been standardized, it is better
  10146. to use the standard keyword @code{_Alignof}.
  10147. @findex _Alignas
  10148. @findex __aligned__
  10149. You can explicitly specify an alignment requirement for a particular
  10150. variable or structure field by adding @code{_Alignas
  10151. (@var{alignment})} to the declaration, where @var{alignment} is a
  10152. power of 2 or a type name. For instance:
  10153. @example
  10154. char _Alignas (8) x;
  10155. @end example
  10156. @noindent
  10157. or
  10158. @example
  10159. char _Alignas (double) x;
  10160. @end example
  10161. @noindent
  10162. specifies that @code{x} must start on an address that is a multiple of
  10163. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10164. machine, that maximum is how much alignment @code{x} will get.
  10165. The older GNU C syntax for this feature looked like
  10166. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10167. declaration, and was added after the variable. For instance:
  10168. @example
  10169. char x __attribute__ ((__aligned__ 8));
  10170. @end example
  10171. @xref{Attributes}.
  10172. @node Aliasing
  10173. @appendix Aliasing
  10174. @cindex aliasing (of storage)
  10175. @cindex pointer type conversion
  10176. @cindex type conversion, pointer
  10177. We have already presented examples of casting a @code{void *} pointer
  10178. to another pointer type, and casting another pointer type to
  10179. @code{void *}.
  10180. One common kind of pointer cast is guaranteed safe: casting the value
  10181. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10182. Allocation}). It is safe because these functions do not save the
  10183. pointer anywhere else; the only way the program will access the newly
  10184. allocated memory is via the pointer just returned.
  10185. In fact, C allows casting any pointer type to any other pointer type.
  10186. Using this to access the same place in memory using two
  10187. different data types is called @dfn{aliasing}.
  10188. Aliasing is necessary in some programs that do sophisticated memory
  10189. management, such as GNU Emacs, but most C programs don't need to do
  10190. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10191. aliasing correctly requires following the rules stated below.
  10192. Otherwise, the aliasing may result in malfunctions when the program
  10193. runs.
  10194. The rest of this appendix explains the pitfalls and rules of aliasing.
  10195. @menu
  10196. * Aliasing Alignment:: Memory alignment considerations for
  10197. casting between pointer types.
  10198. * Aliasing Length:: Type size considerations for
  10199. casting between pointer types.
  10200. * Aliasing Type Rules:: Even when type alignment and size matches,
  10201. aliasing can still have surprising results.
  10202. @end menu
  10203. @node Aliasing Alignment
  10204. @appendixsection Aliasing and Alignment
  10205. In order for a type-converted pointer to be valid, it must have the
  10206. alignment that the new pointer type requires. For instance, on most
  10207. computers, @code{int} has alignment 4; the address of an @code{int}
  10208. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10209. address of a @code{char} is usually not a multiple of 4. Taking the
  10210. address of such a @code{char} and casting it to @code{int *} probably
  10211. results in an invalid pointer. Trying to dereference it may cause a
  10212. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10213. @example
  10214. foo ()
  10215. @{
  10216. char i[4];
  10217. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10218. return *p; /* @r{Crash!} */
  10219. @}
  10220. @end example
  10221. This requirement is never a problem when casting the return value
  10222. of @code{malloc} because that function always returns a pointer
  10223. with as much alignment as any type can require.
  10224. @node Aliasing Length
  10225. @appendixsection Aliasing and Length
  10226. When converting a pointer to a different pointer type, make sure the
  10227. object it really points to is at least as long as the target of the
  10228. converted pointer. For instance, suppose @code{p} has type @code{int
  10229. *} and it's cast as follows:
  10230. @example
  10231. int *p;
  10232. struct
  10233. @{
  10234. double d, e, f;
  10235. @} foo;
  10236. struct foo *q = (struct foo *)p;
  10237. q->f = 5.14159;
  10238. @end example
  10239. @noindent
  10240. the value @code{q->f} will run past the end of the @code{int} that
  10241. @code{p} points to. If @code{p} was initialized to the start of an
  10242. array of type @code{int[6]}, the object is long enough for three
  10243. @code{double}s. But if @code{p} points to something shorter,
  10244. @code{q->f} will run on beyond the end of that, overlaying some other
  10245. data. Storing that will garble that other data. Or it could extend
  10246. past the end of memory space and cause a @code{SIGSEGV} signal
  10247. (@pxref{Signals}).
  10248. @node Aliasing Type Rules
  10249. @appendixsection Type Rules for Aliasing
  10250. C code that converts a pointer to a different pointer type can use the
  10251. pointers to access the same memory locations with two different data
  10252. types. If the same address is accessed with different types in a
  10253. single control thread, optimization can make the code do surprising
  10254. things (in effect, make it malfunction).
  10255. Here's a concrete example where aliasing that can change the code's
  10256. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10257. long, like @code{int}, and so is every pointer. Thus, the structures
  10258. @code{struct a} and @code{struct b} are both 8 bytes.
  10259. @example
  10260. #include <stdio.h>
  10261. struct a @{ int size; char *data; @};
  10262. struct b @{ float size; char *data; @};
  10263. void sub (struct a *p, struct b *q)
  10264. @{
  10265.   int x;
  10266.   p->size = 0;
  10267.   q->size = 1;
  10268.   x = p->size;
  10269.   printf("x       =%d\n", x);
  10270.   printf("p->size =%d\n", (int)p->size);
  10271.   printf("q->size =%d\n", (int)q->size);
  10272. @}
  10273. int main(void)
  10274. @{
  10275.   struct a foo;
  10276.   struct a *p = &foo;
  10277.   struct b *q = (struct b *) &foo;
  10278.   sub (p, q);
  10279. @}
  10280. @end example
  10281. This code works as intended when compiled without optimization. All
  10282. the operations are carried out sequentially as written. The code
  10283. sets @code{x} to @code{p->size}, but what it actually gets is the
  10284. bits of the floating point number 1, as type @code{int}.
  10285. However, when optimizing, the compiler is allowed to assume
  10286. (mistakenly, here) that @code{q} does not point to the same storage as
  10287. @code{p}, because their data types are not allowed to alias.
  10288. From this assumption, the compiler can deduce (falsely, here) that the
  10289. assignment into @code{q->size} has no effect on the value of
  10290. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10291. be set to 0.
  10292. GNU C, following the C standard, @emph{defines} this optimization as
  10293. legitimate. Code that misbehaves when optimized following these rules
  10294. is, by definition, incorrect C code.
  10295. The rules for storage aliasing in C are based on the two data types:
  10296. the type of the object, and the type it is accessed through. The
  10297. rules permit accessing part of a storage object of type @var{t} using
  10298. only these types:
  10299. @itemize @bullet
  10300. @item
  10301. @var{t}.
  10302. @item
  10303. A type compatible with @var{t}. @xref{Compatible Types}.
  10304. @item
  10305. A signed or unsigned version of one of the above.
  10306. @item
  10307. A qualifed version of one of the above.
  10308. @xref{Type Qualifiers}.
  10309. @item
  10310. An array, structure (@pxref{Structures}), or union type
  10311. (@code{Unions}) that contains one of the above, either directly as a
  10312. field or through multiple levels of fields. If @var{t} is
  10313. @code{double}, this would include @code{struct s @{ union @{ double
  10314. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10315. inside it somewhere.
  10316. @item
  10317. A character type.
  10318. @end itemize
  10319. What do these rules say about the example in this subsection?
  10320. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10321. @code{int}. The type @code{float} is not allowed as an aliasing type
  10322. by those rules, so @code{b->size} is not supposed to alias with
  10323. elements of @code{j}. Based on that assumption, GNU C makes a
  10324. permitted optimization that was not, in this case, consistent with
  10325. what the programmer intended the program to do.
  10326. Whether GCC actually performs type-based aliasing analysis depends on
  10327. the details of the code. GCC has other ways to determine (in some cases)
  10328. whether objects alias, and if it gets a reliable answer that way, it won't
  10329. fall back on type-based heuristics.
  10330. @c @opindex -fno-strict-aliasing
  10331. The importance of knowing the type-based aliasing rules is not so as
  10332. to ensure that the optimization is done where it would be safe, but so
  10333. as to ensure it is @emph{not} done in a way that would break the
  10334. program. You can turn off type-based aliasing analysis by giving GCC
  10335. the option @option{-fno-strict-aliasing}.
  10336. @node Digraphs
  10337. @appendix Digraphs
  10338. @cindex digraphs
  10339. C accepts aliases for certain characters. Apparently in the 1990s
  10340. some computer systems had trouble inputting these characters, or
  10341. trouble displaying them. These digraphs almost never appear in C
  10342. programs nowadays, but we mention them for completeness.
  10343. @table @samp
  10344. @item <:
  10345. An alias for @samp{[}.
  10346. @item :>
  10347. An alias for @samp{]}.
  10348. @item <%
  10349. An alias for @samp{@{}.
  10350. @item %>
  10351. An alias for @samp{@}}.
  10352. @item %:
  10353. An alias for @samp{#},
  10354. used for preprocessing directives (@pxref{Directives}) and
  10355. macros (@pxref{Macros}).
  10356. @end table
  10357. @node Attributes
  10358. @appendix Attributes in Declarations
  10359. @cindex attributes
  10360. @findex __attribute__
  10361. You can specify certain additional requirements in a declaration, to
  10362. get fine-grained control over code generation, and helpful
  10363. informational messages during compilation. We use a few attributes in
  10364. code examples throughout this manual, including
  10365. @table @code
  10366. @item aligned
  10367. The @code{aligned} attribute specifies a minimum alignment for a
  10368. variable or structure field, measured in bytes:
  10369. @example
  10370. int foo __attribute__ ((aligned (8))) = 0;
  10371. @end example
  10372. @noindent
  10373. This directs GNU C to allocate @code{foo} at an address that is a
  10374. multiple of 8 bytes. However, you can't force an alignment bigger
  10375. than the computer's maximum meaningful alignment.
  10376. @item packed
  10377. The @code{packed} attribute specifies to compact the fields of a
  10378. structure by not leaving gaps between fields. For example,
  10379. @example
  10380. struct __attribute__ ((packed)) bar
  10381. @{
  10382. char a;
  10383. int b;
  10384. @};
  10385. @end example
  10386. @noindent
  10387. allocates the integer field @code{b} at byte 1 in the structure,
  10388. immediately after the character field @code{a}. The packed structure
  10389. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10390. alignment is 1, that of @code{char}.
  10391. @item deprecated
  10392. Applicable to both variables and functions, the @code{deprecated}
  10393. attribute tells the compiler to issue a warning if the variable or
  10394. function is ever used in the source file.
  10395. @example
  10396. int old_foo __attribute__ ((deprecated));
  10397. int old_quux () __attribute__ ((deprecated));
  10398. @end example
  10399. @item __noinline__
  10400. The @code{__noinline__} attribute, in a function's declaration or
  10401. definition, specifies never to inline calls to that function. All
  10402. calls to that function, in a compilation unit where it has this
  10403. attribute, will be compiled to invoke the separately compiled
  10404. function. @xref{Inline Function Definitions}.
  10405. @item __noclone__
  10406. The @code{__noclone__} attribute, in a function's declaration or
  10407. definition, specifies never to clone that function. Thus, there will
  10408. be only one compiled version of the function. @xref{Label Value
  10409. Caveats}, for more information about cloning.
  10410. @item always_inline
  10411. The @code{always_inline} attribute, in a function's declaration or
  10412. definition, specifies to inline all calls to that function (unless
  10413. something about the function makes inlining impossible). This applies
  10414. to all calls to that function in a compilation unit where it has this
  10415. attribute. @xref{Inline Function Definitions}.
  10416. @item gnu_inline
  10417. The @code{gnu_inline} attribute, in a function's declaration or
  10418. definition, specifies to handle the @code{inline} keyword the way GNU
  10419. C originally implemented it, many years before ISO C said anything
  10420. about inlining. @xref{Inline Function Definitions}.
  10421. @end table
  10422. For full documentation of attributes, see the GCC manual.
  10423. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10424. the GNU Compiler Collection}.
  10425. @node Signals
  10426. @appendix Signals
  10427. @cindex signal
  10428. @cindex handler (for signal)
  10429. @cindex @code{SIGSEGV}
  10430. @cindex @code{SIGFPE}
  10431. @cindex @code{SIGBUS}
  10432. Some program operations bring about an error condition called a
  10433. @dfn{signal}. These signals terminate the program, by default.
  10434. There are various different kinds of signals, each with a name. We
  10435. have seen several such error conditions through this manual:
  10436. @table @code
  10437. @item SIGSEGV
  10438. This signal is generated when a program tries to read or write outside
  10439. the memory that is allocated for it, or to write memory that can only
  10440. be read. The name is an abbreviation for ``segmentation violation''.
  10441. @item SIGFPE
  10442. This signal indicates a fatal arithmetic error. The name is an
  10443. abbreviation for ``floating-point exception'', but covers all types of
  10444. arithmetic errors, including division by zero and overflow.
  10445. @item SIGBUS
  10446. This signal is generated when an invalid pointer is dereferenced,
  10447. typically the result of dereferencing an uninintalized pointer. It is
  10448. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10449. invalid access to valid memory, while @code{SIGBUS} indicates an
  10450. attempt to access an invalid address.
  10451. @end table
  10452. These kinds of signal allow the program to specify a function as a
  10453. @dfn{signal handler}. When a signal has a handler, it doesn't
  10454. terminate the program; instead it calls the handler.
  10455. There are many other kinds of signal; here we list only those that
  10456. come from run-time errors in C operations. The rest have to do with
  10457. the functioning of the operating system. The GNU C Library Reference
  10458. Manual gives more explanation about signals (@pxref{Program Signal
  10459. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10460. Manual}).
  10461. @node GNU Free Documentation License
  10462. @appendix GNU Free Documentation License
  10463. @include fdl.texi
  10464. @node Symbol Index
  10465. @unnumbered Index of Symbols and Keywords
  10466. @printindex fn
  10467. @node Concept Index
  10468. @unnumbered Concept Index
  10469. @printindex cp
  10470. @bye