c.texi 419 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010
  1. \input texinfo
  2. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  3. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Intro and Reference Manual}
  34. @sp 4
  35. @c @center @value{EDITION} Edition
  36. @sp 5
  37. @center Richard Stallman
  38. @center and
  39. @center Trevis Rothwell
  40. @center plus Nelson Beebe
  41. @center on floating point
  42. @page
  43. @vskip 0pt plus 1filll
  44. @insertcopying
  45. @sp 2
  46. @ignore
  47. WILL BE Published by the Free Software Foundation @*
  48. 51 Franklin Street, Fifth Floor @*
  49. Boston, MA 02110-1301 USA @*
  50. ISBN ?-??????-??-?
  51. @ignore
  52. @ignore
  53. @sp 1
  54. Cover art by J. Random Artist
  55. @end ignore
  56. @end titlepage
  57. @summarycontents
  58. @contents
  59. @node Top
  60. @ifnottex
  61. @top GNU C Manual
  62. @end ifnottex
  63. @iftex
  64. @top Preface
  65. @end iftex
  66. This manual explains the C language for use with the GNU Compiler
  67. Collection (GCC) on the GNU/Linux system and other systems. We refer
  68. to this dialect as GNU C. If you already know C, you can use this as
  69. a reference manual.
  70. If you understand basic concepts of programming but know nothing about
  71. C, you can read this manual sequentially from the beginning to learn
  72. the C language.
  73. If you are a beginner to programming, we recommend you first learn a
  74. language with automatic garbage collection and no explicit pointers,
  75. rather than starting with C@. Good choices include Lisp, Scheme,
  76. Python and Java. C's explicit pointers mean that programmers must be
  77. careful to avoid certain kinds of errors.
  78. C is a venerable language; it was first used in 1973. The GNU C
  79. Compiler, which was subsequently extended into the GNU Compiler
  80. Collection, was first released in 1987. Other important languages
  81. were designed based on C: once you know C, it gives you a useful base
  82. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  83. The special advantage of C is that it is fairly simple while allowing
  84. close access to the computer's hardware, which previously required
  85. writing in assembler language to describe the individual machine
  86. instructions. Some have called C a ``high-level assembler language''
  87. because of its explicit pointers and lack of automatic management of
  88. storage. As one wag put it, ``C combines the power of assembler
  89. language with the convenience of assembler language.'' However, C is
  90. far more portable, and much easier to read and write, than assembler
  91. language.
  92. This manual focuses on the GNU C language supported by the GNU
  93. Compiler Collection, version ???. When a construct may be absent or
  94. work differently in other C compilers, we say so. When it is not part
  95. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  96. useful to know that; however, other dialects and standards are not the
  97. focus of this manual. We keep those notes short, unless it is vital
  98. to say more. For the same reason, we hardly mention C@t{++} or other
  99. languages that the GNU Compiler Collection supports.
  100. Some aspects of the meaning of C programs depend on the target
  101. platform: which computer, and which operating system, the compiled
  102. code will run on. Where this is the case, we say so.
  103. The C language provides no built-in facilities for performing such
  104. common operations as input/output, memory management, string
  105. manipulation, and the like. Instead, these facilities are defined in
  106. a standard library, which is automatically available in every C
  107. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  108. Reference Manual}.
  109. This manual incorporates the former GNU C Preprocessor Manual, which
  110. was among the earliest GNU Manuals. It also uses some text from the
  111. earlier GNU C Manual that was written by Trevis Rothwell and James
  112. Youngman.
  113. GNU C has many obscure features, each one either for historical
  114. compatibility or meant for very special situations. We have left them
  115. to a companion manual, the GNU C Obscurities Manual, which will be
  116. published digitally later.
  117. Please report errors and suggestions to c-manual@@gnu.org.
  118. @menu
  119. * The First Example:: Getting started with basic C code.
  120. * Complete Program:: A whole example program
  121. that can be compiled and run.
  122. * Storage:: Basic layout of storage; bytes.
  123. * Beyond Integers:: Exploring different numeric types.
  124. * Lexical Syntax:: The various lexical components of C programs.
  125. * Arithmetic:: Numeric computations.
  126. * Assignment Expressions:: Storing values in variables.
  127. * Execution Control Expressions:: Expressions combining values in various ways.
  128. * Binary Operator Grammar:: An overview of operator precedence.
  129. * Order of Execution:: The order of program execution.
  130. * Primitive Types:: More details about primitive data types.
  131. * Constants:: Explicit constant values:
  132. details and examples.
  133. * Type Size:: The memory space occupied by a type.
  134. * Pointers:: Creating and manipulating memory pointers.
  135. * Structures:: Compound data types built
  136. by grouping other types.
  137. * Arrays:: Creating and manipulating arrays.
  138. * Enumeration Types:: Sets of integers with named values.
  139. * Defining Typedef Names:: Using @code{typedef} to define type names.
  140. * Statements:: Controling program flow.
  141. * Variables:: Details about declaring, initializing,
  142. and using variables.
  143. * Type Qualifiers:: Mark variables for certain intended uses.
  144. * Functions:: Declaring, defining, and calling functions.
  145. * Compatible Types:: How to tell if two types are compatible
  146. with each other.
  147. * Type Conversions:: Converting between types.
  148. * Scope:: Different categories of identifier scope.
  149. * Preprocessing:: Using the GNU C preprocessor.
  150. * Integers in Depth:: How integer numbers are represented.
  151. * Floating Point in Depth:: How floating-point numbers are represented.
  152. * Compilation:: How to compile multi-file programs.
  153. * Directing Compilation:: Operations that affect compilation
  154. but don't change the program.
  155. Appendices
  156. * Type Alignment:: Where in memory a type can validly start.
  157. * Aliasing:: Accessing the same data in two types.
  158. * Digraphs:: Two-character aliases for some characters.
  159. * Attributes:: Specifying additional information
  160. in a declaration.
  161. * Signals:: Fatal errors triggered in various scenarios.
  162. * GNU Free Documentation License:: The license for this manual.
  163. * Symbol Index:: Keyword and symbol index.
  164. * Concept Index:: Detailed topical index.
  165. @detailmenu
  166. --- The Detailed Node Listing ---
  167. * Recursive Fibonacci:: Writing a simple function recursively.
  168. * Stack:: Each function call uses space in the stack.
  169. * Iterative Fibonacci:: Writing the same function iteratively.
  170. * Complete Example:: Turn the simple function into a full program.
  171. * Complete Explanation:: Explanation of each part of the example.
  172. * Complete Line-by-Line:: Explaining each line of the example.
  173. * Compile Example:: Using GCC to compile the example.
  174. * Float Example:: A function that uses floating-point numbers.
  175. * Array Example:: A function that works with arrays.
  176. * Array Example Call:: How to call that function.
  177. * Array Example Variations:: Different ways to write the call example.
  178. Lexical Syntax
  179. * English:: Write programs in English!
  180. * Characters:: The characters allowed in C programs.
  181. * Whitespace:: The particulars of whitespace characters.
  182. * Comments:: How to include comments in C code.
  183. * Identifiers:: How to form identifiers (names).
  184. * Operators/Punctuation:: Characters used as operators or punctuation.
  185. * Line Continuation:: Splitting one line into multiple lines.
  186. * Digraphs:: Two-character substitutes for some characters.
  187. Arithmetic
  188. * Basic Arithmetic:: Addition, subtraction, multiplication,
  189. and division.
  190. * Integer Arithmetic:: How C performs arithmetic with integer values.
  191. * Integer Overflow:: When an integer value exceeds the range
  192. of its type.
  193. * Mixed Mode:: Calculating with both integer values
  194. and floating-point values.
  195. * Division and Remainder:: How integer division works.
  196. * Numeric Comparisons:: Comparing numeric values for
  197. equality or order.
  198. * Shift Operations:: Shift integer bits left or right.
  199. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  200. Assignment Expressions
  201. * Simple Assignment:: The basics of storing a value.
  202. * Lvalues:: Expressions into which a value can be stored.
  203. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  204. * Increment/Decrement:: Shorthand for incrementing and decrementing
  205. an lvalue's contents.
  206. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  207. * Assignment in Subexpressions:: How to avoid ambiguity.
  208. * Write Assignments Separately:: Write assignments as separate statements.
  209. Execution Control Expressions
  210. * Logical Operators:: Logical conjunction, disjunction, negation.
  211. * Logicals and Comparison:: Logical operators with comparison operators.
  212. * Logicals and Assignments:: Assignments with logical operators.
  213. * Conditional Expression:: An if/else construct inside expressions.
  214. * Comma Operator:: Build a sequence of subexpressions.
  215. Order of Execution
  216. * Reordering of Operands:: Operations in C are not necessarily computed
  217. in the order they are written.
  218. * Associativity and Ordering:: Some associative operations are performed
  219. in a particular order; others are not.
  220. * Sequence Points:: Some guarantees about the order of operations.
  221. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  222. * Ordering of Operands:: Evaluation order of operands
  223. and function arguments.
  224. * Optimization and Ordering:: Compiler optimizations can reorder operations
  225. only if it has no impact on program results.
  226. Primitive Data Types
  227. * Integer Types:: Description of integer types.
  228. * Floating-Point Data Types:: Description of floating-point types.
  229. * Complex Data Types:: Description of complex number types.
  230. * The Void Type:: A type indicating no value at all.
  231. * Other Data Types:: A brief summary of other types.
  232. Constants
  233. * Integer Constants:: Literal integer values.
  234. * Integer Const Type:: Types of literal integer values.
  235. * Floating Constants:: Literal floating-point values.
  236. * Imaginary Constants:: Literal imaginary number values.
  237. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  238. * Character Constants:: Literal character values.
  239. * Unicode Character Codes:: Unicode characters represented
  240. in either UTF-16 or UTF-32.
  241. * Wide Character Constants:: Literal characters values larger than 8 bits.
  242. * String Constants:: Literal string values.
  243. * UTF-8 String Constants:: Literal UTF-8 string values.
  244. * Wide String Constants:: Literal string values made up of
  245. 16- or 32-bit characters.
  246. Pointers
  247. * Address of Data:: Using the ``address-of'' operator.
  248. * Pointer Types:: For each type, there is a pointer type.
  249. * Pointer Declarations:: Declaring variables with pointer types.
  250. * Pointer Type Designators:: Designators for pointer types.
  251. * Pointer Dereference:: Accessing what a pointer points at.
  252. * Null Pointers:: Pointers which do not point to any object.
  253. * Invalid Dereference:: Dereferencing null or invalid pointers.
  254. * Void Pointers:: Totally generic pointers, can cast to any.
  255. * Pointer Comparison:: Comparing memory address values.
  256. * Pointer Arithmetic:: Computing memory address values.
  257. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  258. * Pointer Arithmetic Low Level:: More about computing memory address values.
  259. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  260. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  261. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  262. * Printing Pointers:: Using @code{printf} for a pointer's value.
  263. Structures
  264. * Referencing Fields:: Accessing field values in a structure object.
  265. * Dynamic Memory Allocation:: Allocating space for objects
  266. while the program is running.
  267. * Field Offset:: Memory layout of fields within a structure.
  268. * Structure Layout:: Planning the memory layout of fields.
  269. * Packed Structures:: Packing structure fields as close as possible.
  270. * Bit Fields:: Dividing integer fields
  271. into fields with fewer bits.
  272. * Bit Field Packing:: How bit fields pack together in integers.
  273. * const Fields:: Making structure fields immutable.
  274. * Zero Length:: Zero-length array as a variable-length object.
  275. * Flexible Array Fields:: Another approach to variable-length objects.
  276. * Overlaying Structures:: Casting one structure type
  277. over an object of another structure type.
  278. * Structure Assignment:: Assigning values to structure objects.
  279. * Unions:: Viewing the same object in different types.
  280. * Packing With Unions:: Using a union type to pack various types into
  281. the same memory space.
  282. * Cast to Union:: Casting a value one of the union's alternative
  283. types to the type of the union itself.
  284. * Structure Constructors:: Building new structure objects.
  285. * Unnamed Types as Fields:: Fields' types do not always need names.
  286. * Incomplete Types:: Types which have not been fully defined.
  287. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  288. * Type Tags:: Scope of structure and union type tags.
  289. Arrays
  290. * Accessing Array Elements:: How to access individual elements of an array.
  291. * Declaring an Array:: How to name and reserve space for a new array.
  292. * Strings:: A string in C is a special case of array.
  293. * Incomplete Array Types:: Naming, but not allocating, a new array.
  294. * Limitations of C Arrays:: Arrays are not first-class objects.
  295. * Multidimensional Arrays:: Arrays of arrays.
  296. * Constructing Array Values:: Assigning values to an entire array at once.
  297. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  298. Statements
  299. * Expression Statement:: Evaluate an expression, as a statement,
  300. usually done for a side effect.
  301. * if Statement:: Basic conditional execution.
  302. * if-else Statement:: Multiple branches for conditional execution.
  303. * Blocks:: Grouping multiple statements together.
  304. * return Statement:: Return a value from a function.
  305. * Loop Statements:: Repeatedly executing a statement or block.
  306. * switch Statement:: Multi-way conditional choices.
  307. * switch Example:: A plausible example of using @code{switch}.
  308. * Duffs Device:: A special way to use @code{switch}.
  309. * Case Ranges:: Ranges of values for @code{switch} cases.
  310. * Null Statement:: A statement that does nothing.
  311. * goto Statement:: Jump to another point in the source code,
  312. identified by a label.
  313. * Local Labels:: Labels with limited scope.
  314. * Labels as Values:: Getting the address of a label.
  315. * Statement Exprs:: A series of statements used as an expression.
  316. Variables
  317. * Variable Declarations:: Name a variable and and reserve space for it.
  318. * Initializers:: Assigning inital values to variables.
  319. * Designated Inits:: Assigning initial values to array elements
  320. at particular array indices.
  321. * Auto Type:: Obtaining the type of a variable.
  322. * Local Variables:: Variables declared in function definitions.
  323. * File-Scope Variables:: Variables declared outside of
  324. function definitions.
  325. * Static Local Variables:: Variables declared within functions,
  326. but with permanent storage allocation.
  327. * Extern Declarations:: Declaring a variable
  328. which is allocated somewhere else.
  329. * Allocating File-Scope:: When is space allocated
  330. for file-scope variables?
  331. * auto and register:: Historically used storage directions.
  332. * Omitting Types:: The bad practice of declaring variables
  333. with implicit type.
  334. Type Qualifiers
  335. * const:: Variables whose values don't change.
  336. * volatile:: Variables whose values may be accessed
  337. or changed outside of the control of
  338. this program.
  339. * restrict Pointers:: Restricted pointers for code optimization.
  340. * restrict Pointer Example:: Example of how that works.
  341. Functions
  342. * Function Definitions:: Writing the body of a function.
  343. * Function Declarations:: Declaring the interface of a function.
  344. * Function Calls:: Using functions.
  345. * Function Call Semantics:: Call-by-value argument passing.
  346. * Function Pointers:: Using references to functions.
  347. * The main Function:: Where execution of a GNU C program begins.
  348. Type Conversions
  349. * Explicit Type Conversion:: Casting a value from one type to another.
  350. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  351. * Argument Promotions:: Automatic conversion of function parameters.
  352. * Operand Promotions:: Automatic conversion of arithmetic operands.
  353. * Common Type:: When operand types differ, which one is used?
  354. Scope
  355. * Scope:: Different categories of identifier scope.
  356. Preprocessing
  357. * Preproc Overview:: Introduction to the C preprocessor.
  358. * Directives:: The form of preprocessor directives.
  359. * Preprocessing Tokens:: The lexical elements of preprocessing.
  360. * Header Files:: Including one source file in another.
  361. * Macros:: Macro expansion by the preprocessor.
  362. * Conditionals:: Controling whether to compile some lines
  363. or ignore them.
  364. * Diagnostics:: Reporting warnings and errors.
  365. * Line Control:: Reporting source line numbers.
  366. * Null Directive:: A preprocessing no-op.
  367. Integers in Depth
  368. * Integer Representations:: How integer values appear in memory.
  369. * Maximum and Minimum Values:: Value ranges of integer types.
  370. Floating Point in Depth
  371. * Floating Representations:: How floating-point values appear in memory.
  372. * Floating Type Specs:: Precise details of memory representations.
  373. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  374. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  375. * Exception Flags:: Handling certain conditions in floating point.
  376. * Exact Floating-Point:: Not all floating calculations lose precision.
  377. * Rounding:: When a floating result can't be represented
  378. exactly in the floating-point type in use.
  379. * Rounding Issues:: Avoid magnifying rounding errors.
  380. * Significance Loss:: Subtracting numbers that are almost equal.
  381. * Fused Multiply-Add:: Taking advantage of a special floating-point
  382. instruction for faster execution.
  383. * Error Recovery:: Determining rounding errors.
  384. * Exact Floating Constants:: Precisely specified floating-point numbers.
  385. * Handling Infinity:: When floating calculation is out of range.
  386. * Handling NaN:: What floating calculation is undefined.
  387. * Signed Zeros:: Positive zero vs. negative zero.
  388. * Scaling by the Base:: A useful exact floating-point operation.
  389. * Rounding Control:: Specifying some rounding behaviors.
  390. * Machine Epsilon:: The smallest number you can add to 1.0
  391. and get a sum which is larger than 1.0.
  392. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  393. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  394. * Further Reading:: References for floating-point numbers.
  395. Directing Compilation
  396. * Pragmas:: Controling compilation of some constructs.
  397. * Static Assertions:: Compile-time tests for conditions.
  398. @end detailmenu
  399. @end menu
  400. @node The First Example
  401. @chapter The First Example
  402. This chapter presents the source code for a very simple C program and
  403. uses it to explain a few features of the language. If you already
  404. know the basic points of C presented in this chapter, you can skim it
  405. or skip it.
  406. @menu
  407. * Recursive Fibonacci:: Writing a simple function recursively.
  408. * Stack:: Each function call uses space in the stack.
  409. * Iterative Fibonacci:: Writing the same function iteratively.
  410. @end menu
  411. @node Recursive Fibonacci
  412. @section Example: Recursive Fibonacci
  413. @cindex recursive Fibonacci function
  414. @cindex Fibonacci function, recursive
  415. To introduce the most basic features of C, let's look at code for a
  416. simple mathematical function that does calculations on integers. This
  417. function calculates the @var{n}th number in the Fibonacci series, in
  418. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  419. 13, 21, 34, 55, @dots{}.
  420. @example
  421. int
  422. fib (int n)
  423. @{
  424. if (n <= 2) /* @r{This avoids infinite recursion.} */
  425. return 1;
  426. else
  427. return fib (n - 1) + fib (n - 2);
  428. @}
  429. @end example
  430. This very simple program illustrates several features of C:
  431. @itemize @bullet
  432. @item
  433. A function definition, whose first two lines constitute the function
  434. header. @xref{Function Definitions}.
  435. @item
  436. A function parameter @code{n}, referred to as the variable @code{n}
  437. inside the function body. @xref{Function Parameter Variables}.
  438. A function definition uses parameters to refer to the argument
  439. values provided in a call to that function.
  440. @item
  441. Arithmetic. C programs add with @samp{+} and subtract with
  442. @samp{-}. @xref{Arithmetic}.
  443. @item
  444. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  445. equal.'' @xref{Numeric Comparisons}.
  446. @item
  447. Integer constants written in base 10.
  448. @xref{Integer Constants}.
  449. @item
  450. A function call. The function call @code{fib (n - 1)} calls the
  451. function @code{fib}, passing as its argument the value @code{n - 1}.
  452. @xref{Function Calls}.
  453. @item
  454. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  455. comment has no effect on the execution of the program. Its purpose is
  456. to provide explanations to people reading the source code. Including
  457. comments in the code is tremendously important---they provide
  458. background information so others can understand the code more quickly.
  459. @xref{Comments}.
  460. @item
  461. Two kinds of statements, the @code{return} statement and the
  462. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  463. @item
  464. Recursion. The function @code{fib} calls itself; that is called a
  465. @dfn{recursive call}. These are valid in C, and quite common.
  466. The @code{fib} function would not be useful if it didn't return.
  467. Thus, recursive definitions, to be of any use, must avoid infinite
  468. recursion.
  469. This function definition prevents infinite recursion by specially
  470. handling the case where @code{n} is two or less. Thus the maximum
  471. depth of recursive calls is less than @code{n}.
  472. @end itemize
  473. @menu
  474. * Function Header:: The function's name and how it is called.
  475. * Function Body:: Declarations and statements that implement the function.
  476. @end menu
  477. @node Function Header
  478. @subsection Function Header
  479. @cindex function header
  480. In our example, the first two lines of the function definition are the
  481. @dfn{header}. Its purpose is to state the function's name and say how
  482. it is called:
  483. @example
  484. int
  485. fib (int n)
  486. @end example
  487. @noindent
  488. says that the function returns an integer (type @code{int}), its name is
  489. @code{fib}, and it takes one argument named @code{n} which is also an
  490. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  491. @node Function Body
  492. @subsection Function Body
  493. @cindex function body
  494. @cindex recursion
  495. The rest of the function definition is called the @dfn{function body}.
  496. Like every function body, this one starts with @samp{@{}, ends with
  497. @samp{@}}, and contains zero or more @dfn{statements} and
  498. @dfn{declarations}. Statements specify actions to take, whereas
  499. declarations define names of variables, functions, and so on. Each
  500. statement and each declaration ends with a semicolon (@samp{;}).
  501. Statements and declarations often contain @dfn{expressions}; an
  502. expression is a construct whose execution produces a @dfn{value} of
  503. some data type, but may also take actions through ``side effects''
  504. that alter subsequent execution. A statement, by contrast, does not
  505. have a value; it affects further execution of the program only through
  506. the actions it takes.
  507. This function body contains no declarations, and just one statement,
  508. but that one is a complex statement in that it contains nested
  509. statements. This function uses two kinds of statements:
  510. @table @code
  511. @item return
  512. The @code{return} statement makes the function return immediately.
  513. It looks like this:
  514. @example
  515. return @var{value};
  516. @end example
  517. Its meaning is to compute the expression @var{value} and exit the
  518. function, making it return whatever value that expression produced.
  519. For instance,
  520. @example
  521. return 1;
  522. @end example
  523. @noindent
  524. returns the integer 1 from the function, and
  525. @example
  526. return fib (n - 1) + fib (n - 2);
  527. @end example
  528. @noindent
  529. returns a value computed by performing two function calls
  530. as specified and adding their results.
  531. @item @code{if}@dots{}@code{else}
  532. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  533. Each time it executes, it chooses one of its two substatements to execute
  534. and ignores the other. It looks like this:
  535. @example
  536. if (@var{condition})
  537. @var{if-true-statement}
  538. else
  539. @var{if-false-statement}
  540. @end example
  541. Its meaning is to compute the expression @var{condition} and, if it's
  542. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  543. @var{if-false-statement}. @xref{if-else Statement}.
  544. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  545. simply an expression. It's considered ``true'' if its value is
  546. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  547. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  548. Comparisons}.) Thus,
  549. @example
  550. if (n <= 2)
  551. return 1;
  552. else
  553. return fib (n - 1) + fib (n - 2);
  554. @end example
  555. @noindent
  556. first tests whether the value of @code{n} is less than or equal to 2.
  557. If so, the expression @code{n <= 2} has the value 1. So execution
  558. continues with the statement
  559. @example
  560. return 1;
  561. @end example
  562. @noindent
  563. Otherwise, execution continues with this statement:
  564. @example
  565. return fib (n - 1) + fib (n - 2);
  566. @end example
  567. Each of these statements ends the execution of the function and
  568. provides a value for it to return. @xref{return Statement}.
  569. @end table
  570. Calculating @code{fib} using ordinary integers in C works only for
  571. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  572. in type @code{int}. The addition operation that tries to add
  573. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  574. This occurrence is called @dfn{integer overflow}.
  575. Overflow can manifest itself in various ways, but one thing that can't
  576. possibly happen is to produce the correct value, since that can't fit
  577. in the space for the value. @xref{Integer Overflow}.
  578. @xref{Functions}, for a full explanation about functions.
  579. @node Stack
  580. @section The Stack, And Stack Overflow
  581. @cindex stack
  582. @cindex stack frame
  583. @cindex stack overflow
  584. @cindex recursion, drawbacks of
  585. @cindex stack frame
  586. Recursion has a drawback: there are limits to how many nested function
  587. calls a program can make. In C, each function call allocates a block
  588. of memory which it uses until the call returns. C allocates these
  589. blocks consecutively within a large area of memory known as the
  590. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  591. The size of the stack is limited; if the program tries to use too
  592. much, that causes the program to fail because the stack is full. This
  593. is called @dfn{stack overflow}.
  594. @cindex crash
  595. @cindex segmentation fault
  596. Stack overflow on GNU/Linux typically manifests itself as the
  597. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  598. fault.'' By default, this signal terminates the program immediately,
  599. rather than letting the program try to recover, or reach an expected
  600. ending point. (We commonly say in this case that the program
  601. ``crashes''). @xref{Signals}.
  602. It is inconvenient to observe a crash by passing too large
  603. an argument to recursive Fibonacci, because the program would run a
  604. long time before it crashes. This algorithm is simple but
  605. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  606. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  607. the final result.
  608. However, you can observe stack overflow very quickly if you use
  609. this function instead:
  610. @example
  611. int
  612. fill_stack (int n)
  613. @{
  614. if (n <= 1) /* @r{This limits the depth of recursion.} */
  615. return 1;
  616. else
  617. return fill_stack (n - 1);
  618. @}
  619. @end example
  620. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  621. and using the default configuration, an experiment showed there is
  622. enough stack space to do 261906 nested calls to that function. One
  623. more, and the stack overflows and the program crashes. On another
  624. platform, with a different configuration, or with a different
  625. function, the limit might be bigger or smaller.
  626. @node Iterative Fibonacci
  627. @section Example: Iterative Fibonacci
  628. @cindex iterative Fibonacci function
  629. @cindex Fibonacci function, iterative
  630. Here's a much faster algorithm for computing the same Fibonacci
  631. series. It is faster for two reasons. First, it uses @dfn{iteration}
  632. (that is, repetition or looping) rather than recursion, so it doesn't
  633. take time for a large number of function calls. But mainly, it is
  634. faster because the number of repetitions is small---only @code{@var{n}}.
  635. @c If you change this, change the duplicate in node Example of for.
  636. @example
  637. int
  638. fib (int n)
  639. @{
  640. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  641. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  642. int i;
  643. for (i = 1; i < n; ++i)
  644. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  645. /* @r{since @code{i < n} is false the first time.} */
  646. @{
  647. /* @r{Now @code{last} is @code{fib (@code{i})}}
  648. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  649. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  650. int next = prev + last;
  651. /* @r{Shift the values down.} */
  652. prev = last;
  653. last = next;
  654. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  655. @r{and @code{prev} is @code{fib (@code{i})}.}
  656. @r{But that won't stay true for long,}
  657. @r{because we are about to increment @code{i}.} */
  658. @}
  659. return last;
  660. @}
  661. @end example
  662. This definition computes @code{fib (@var{n})} in a time proportional
  663. to @code{@var{n}}. The comments in the definition explain how it works: it
  664. advances through the series, always keeps the last two values in
  665. @code{last} and @code{prev}, and adds them to get the next value.
  666. Here are the additional C features that this definition uses:
  667. @table @asis
  668. @item Internal blocks
  669. Within a function, wherever a statement is called for, you can write a
  670. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  671. more statements and declarations. (You can also use additional
  672. blocks as statements in a block.)
  673. The function body also counts as a block, which is why it can contain
  674. statements and declarations.
  675. @xref{Blocks}.
  676. @item Declarations of local variables
  677. This function body contains declarations as well as statements. There
  678. are three declarations directly in the function body, as well as a
  679. fourth declaration in an internal block. Each starts with @code{int}
  680. because it declares a variable whose type is integer. One declaration
  681. can declare several variables, but each of these declarations is
  682. simple and declares just one variable.
  683. Variables declared inside a block (either a function body or an
  684. internal block) are @dfn{local variables}. These variables exist only
  685. within that block; their names are not defined outside the block, and
  686. exiting the block deallocates their storage. This example declares
  687. four local variables: @code{last}, @code{prev}, @code{i}, and
  688. @code{next}.
  689. The most basic local variable declaration looks like this:
  690. @example
  691. @var{type} @var{variablename};
  692. @end example
  693. For instance,
  694. @example
  695. int i;
  696. @end example
  697. @noindent
  698. declares the local variable @code{i} as an integer.
  699. @xref{Variable Declarations}.
  700. @item Initializers
  701. When you declare a variable, you can also specify its initial value,
  702. like this:
  703. @example
  704. @var{type} @var{variablename} = @var{value};
  705. @end example
  706. For instance,
  707. @example
  708. int last = 1;
  709. @end example
  710. @noindent
  711. declares the local variable @code{last} as an integer (type
  712. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  713. @item Assignment
  714. Assignment: a specific kind of expression, written with the @samp{=}
  715. operator, that stores a new value in a variable or other place. Thus,
  716. @example
  717. @var{variable} = @var{value}
  718. @end example
  719. @noindent
  720. is an expression that computes @code{@var{value}} and stores the value in
  721. @code{@var{variable}}. @xref{Assignment Expressions}.
  722. @item Expression statements
  723. An expression statement is an expression followed by a semicolon.
  724. That computes the value of the expression, then ignores the value.
  725. An expression statement is useful when the expression changes some
  726. data or has other side effects---for instance, with function calls, or
  727. with assignments as in this example. @xref{Expression Statement}.
  728. Using an expression with no side effects in an expression statement is
  729. pointless except in very special cases. For instance, the expression
  730. statement @code{x;} would examine the value of @code{x} and ignore it.
  731. That is not useful.
  732. @item Increment operator
  733. The increment operator is @samp{++}. @code{++i} is an
  734. expression that is short for @code{i = i + 1}.
  735. @xref{Increment/Decrement}.
  736. @item @code{for} statements
  737. A @code{for} statement is a clean way of executing a statement
  738. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  739. @example
  740. for (i = 1; i < n; ++i)
  741. @var{body}
  742. @end example
  743. @noindent
  744. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  745. for the loop. The loop itself consists of
  746. @itemize @bullet
  747. @item
  748. Testing @code{i < n} and exiting the loop if that's false.
  749. @item
  750. Executing @var{body}.
  751. @item
  752. Advancing the loop (executing @code{++i}, which increments @code{i}).
  753. @end itemize
  754. The net result is to execute @var{body} with 0 in @code{i},
  755. then with 1 in @code{i}, and so on, stopping just before the repetition
  756. where @code{i} would equal @code{n}.
  757. The body of the @code{for} statement must be one and only one
  758. statement. You can't write two statements in a row there; if you try
  759. to, only the first of them will be treated as part of the loop.
  760. The way to put multiple statements in those places is to group them
  761. with a block, and that's what we do in this example.
  762. @end table
  763. @node Complete Program
  764. @chapter A Complete Program
  765. @cindex complete example program
  766. @cindex example program, complete
  767. It's all very well to write a Fibonacci function, but you cannot run
  768. it by itself. It is a useful program, but it is not a complete
  769. program.
  770. In this chapter we present a complete program that contains the
  771. @code{fib} function. This example shows how to make the program
  772. start, how to make it finish, how to do computation, and how to print
  773. a result.
  774. @menu
  775. * Complete Example:: Turn the simple function into a full program.
  776. * Complete Explanation:: Explanation of each part of the example.
  777. * Complete Line-by-Line:: Explaining each line of the example.
  778. * Compile Example:: Using GCC to compile the example.
  779. @end menu
  780. @node Complete Example
  781. @section Complete Program Example
  782. Here is the complete program that uses the simple, recursive version
  783. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  784. @example
  785. #include <stdio.h>
  786. int
  787. fib (int n)
  788. @{
  789. if (n <= 2) /* @r{This avoids infinite recursion.} */
  790. return 1;
  791. else
  792. return fib (n - 1) + fib (n - 2);
  793. @}
  794. int
  795. main (void)
  796. @{
  797. printf ("Fibonacci series item %d is %d\n",
  798. 20, fib (20));
  799. return 0;
  800. @}
  801. @end example
  802. @noindent
  803. This program prints a message that shows the value of @code{fib (20)}.
  804. Now for an explanation of what that code means.
  805. @node Complete Explanation
  806. @section Complete Program Explanation
  807. @ifnottex
  808. Here's the explanation of the code of the example in the
  809. previous section.
  810. @end ifnottex
  811. This sample program prints a message that shows the value of @code{fib
  812. (20)}, and exits with code 0 (which stands for successful execution).
  813. Every C program is started by running the function named @code{main}.
  814. Therefore, the example program defines a function named @code{main} to
  815. provide a way to start it. Whatever that function does is what the
  816. program does. @xref{The main Function}.
  817. The @code{main} function is the first one called when the program
  818. runs, but it doesn't come first in the example code. The order of the
  819. function definitions in the source code makes no difference to the
  820. program's meaning.
  821. The initial call to @code{main} always passes certain arguments, but
  822. @code{main} does not have to pay attention to them. To ignore those
  823. arguments, define @code{main} with @code{void} as the parameter list.
  824. (@code{void} as a function's parameter list normally means ``call with
  825. no arguments,'' but @code{main} is a special case.)
  826. The function @code{main} returns 0 because that is
  827. the conventional way for @code{main} to indicate successful execution.
  828. It could instead return a positive integer to indicate failure, and
  829. some utility programs have specific conventions for the meaning of
  830. certain numeric @dfn{failure codes}. @xref{Values from main}.
  831. @cindex @code{printf}
  832. The simplest way to print text in C is by calling the @code{printf}
  833. function, so here we explain what that does.
  834. @cindex standard output
  835. The first argument to @code{printf} is a @dfn{string constant}
  836. (@pxref{String Constants}) that is a template for output. The
  837. function @code{printf} copies most of that string directly as output,
  838. including the newline character at the end of the string, which is
  839. written as @samp{\n}. The output goes to the program's @dfn{standard
  840. output} destination, which in the usual case is the terminal.
  841. @samp{%} in the template introduces a code that substitutes other text
  842. into the output. Specifically, @samp{%d} means to take the next
  843. argument to @code{printf} and substitute it into the text as a decimal
  844. number. (The argument for @samp{%d} must be of type @code{int}; if it
  845. isn't, @code{printf} will malfunction.) So the output is a line that
  846. looks like this:
  847. @example
  848. Fibonacci series item 20 is 6765
  849. @end example
  850. This program does not contain a definition for @code{printf} because
  851. it is defined by the C library, which makes it available in all C
  852. programs. However, each program does need to @dfn{declare}
  853. @code{printf} so it will be called correctly. The @code{#include}
  854. line takes care of that; it includes a @dfn{header file} called
  855. @file{stdio.h} into the program's code. That file is provided by the
  856. operating system and it contains declarations for the many standard
  857. input/output functions in the C library, one of which is
  858. @code{printf}.
  859. Don't worry about header files for now; we'll explain them later in
  860. @ref{Header Files}.
  861. The first argument of @code{printf} does not have to be a string
  862. constant; it can be any string (@pxref{Strings}). However, using a
  863. constant is the most common case.
  864. To learn more about @code{printf} and other facilities of the C
  865. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  866. Reference Manual}.
  867. @node Complete Line-by-Line
  868. @section Complete Program, Line by Line
  869. Here's the same example, explained line by line.
  870. @strong{Beginners, do you find this helpful or not?
  871. Would you prefer a different layout for the example?
  872. Please tell rms@@gnu.org.}
  873. @example
  874. #include <stdio.h> /* @r{Include declaration of usual} */
  875. /* @r{I/O functions such as @code{printf}.} */
  876. /* @r{Most programs need these.} */
  877. int /* @r{This function returns an @code{int}.} */
  878. fib (int n) /* @r{Its name is @code{fib};} */
  879. /* @r{its argument is called @code{n}.} */
  880. @{ /* @r{Start of function body.} */
  881. /* @r{This stops the recursion from being infinite.} */
  882. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  883. return 1; /* @r{make @code{fib} return 1.} */
  884. else /* @r{otherwise, add the two previous} */
  885. /* @r{fibonacci numbers.} */
  886. return fib (n - 1) + fib (n - 2);
  887. @}
  888. int /* @r{This function returns an @code{int}.} */
  889. main (void) /* @r{Start here; ignore arguments.} */
  890. @{ /* @r{Print message with numbers in it.} */
  891. printf ("Fibonacci series item %d is %d\n",
  892. 20, fib (20));
  893. return 0; /* @r{Terminate program, report success.} */
  894. @}
  895. @end example
  896. @node Compile Example
  897. @section Compiling the Example Program
  898. @cindex compiling
  899. @cindex executable file
  900. To run a C program requires converting the source code into an
  901. @dfn{executable file}. This is called @dfn{compiling} the program,
  902. and the command to do that using GNU C is @command{gcc}.
  903. This example program consists of a single source file. If we
  904. call that file @file{fib1.c}, the complete command to compile it is
  905. this:
  906. @example
  907. gcc -g -O -o fib1 fib1.c
  908. @end example
  909. @noindent
  910. Here, @option{-g} says to generate debugging information, @option{-O}
  911. says to optimize at the basic level, and @option{-o fib1} says to put
  912. the executable program in the file @file{fib1}.
  913. To run the program, use its file name as a shell command.
  914. For instance,
  915. @example
  916. ./fib1
  917. @end example
  918. @noindent
  919. However, unless you are sure the program is correct, you should
  920. expect to need to debug it. So use this command,
  921. @example
  922. gdb fib1
  923. @end example
  924. @noindent
  925. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  926. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  927. debug the executable program @code{fib1}.
  928. @xref{Compilation}, for an introduction to compiling more complex
  929. programs which consist of more than one source file.
  930. @node Storage
  931. @chapter Storage and Data
  932. @cindex bytes
  933. @cindex storage organization
  934. @cindex memory organization
  935. Storage in C programs is made up of units called @dfn{bytes}. On
  936. nearly all computers, a byte consists of 8 bits, but there are a few
  937. peculiar computers (mostly ``embedded controllers'' for very small
  938. systems) where a byte is longer than that. This manual does not try
  939. to explain the peculiarity of those computers; we assume that a byte
  940. is 8 bits.
  941. Every C data type is made up of a certain number of bytes; that number
  942. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  943. types @code{signed char} and @code{unsigned char} are one byte long;
  944. use those types to operate on data byte by byte. @xref{Signed and
  945. Unsigned Types}. You can refer to a series of consecutive bytes as an
  946. array of @code{char} elements; that's what an ASCII string looks like
  947. in memory. @xref{String Constants}.
  948. @node Beyond Integers
  949. @chapter Beyond Integers
  950. So far we've presented programs that operate on integers. In this
  951. chapter we'll present examples of handling non-integral numbers and
  952. arrays of numbers.
  953. @menu
  954. * Float Example:: A function that uses floating-point numbers.
  955. * Array Example:: A function that works with arrays.
  956. * Array Example Call:: How to call that function.
  957. * Array Example Variations:: Different ways to write the call example.
  958. @end menu
  959. @node Float Example
  960. @section An Example with Non-Integer Numbers
  961. @cindex floating point example
  962. Here's a function that operates on and returns @dfn{floating point}
  963. numbers that don't have to be integers. Floating point represents a
  964. number as a fraction together with a power of 2. (For more detail,
  965. @pxref{Floating-Point Data Types}.) This example calculates the
  966. average of three floating point numbers that are passed to it as
  967. arguments:
  968. @example
  969. double
  970. average_of_three (double a, double b, double c)
  971. @{
  972. return (a + b + c) / 3;
  973. @}
  974. @end example
  975. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  976. integers, and even when they happen to be integers, most likely their
  977. average is not an integer.
  978. @code{double} is the usual data type in C for calculations on
  979. floating-point numbers.
  980. To print a @code{double} with @code{printf}, we must use @samp{%f}
  981. instead of @samp{%d}:
  982. @example
  983. printf ("Average is %f\n",
  984. average_of_three (1.1, 9.8, 3.62));
  985. @end example
  986. The code that calls @code{printf} must pass a @code{double} for
  987. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  988. If the argument has the wrong type, @code{printf} will produce garbage
  989. output.
  990. Here's a complete program that computes the average of three
  991. specific numbers and prints the result:
  992. @example
  993. double
  994. average_of_three (double a, double b, double c)
  995. @{
  996. return (a + b + c) / 3;
  997. @}
  998. int
  999. main (void)
  1000. @{
  1001. printf ("Average is %f\n",
  1002. average_of_three (1.1, 9.8, 3.62));
  1003. return 0;
  1004. @}
  1005. @end example
  1006. From now on we will not present examples of calls to @code{main}.
  1007. Instead we encourage you to write them for yourself when you want
  1008. to test executing some code.
  1009. @node Array Example
  1010. @section An Example with Arrays
  1011. @cindex array example
  1012. A function to take the average of three numbers is very specific and
  1013. limited. A more general function would take the average of any number
  1014. of numbers. That requires passing the numbers in an array. An array
  1015. is an object in memory that contains a series of values of the same
  1016. data type. This chapter presents the basic concepts and use of arrays
  1017. through an example; for the full explanation, see @ref{Arrays}.
  1018. Here's a function definition to take the average of several
  1019. floating-point numbers, passed as type @code{double}. The first
  1020. parameter, @code{length}, specifies how many numbers are passed. The
  1021. second parameter, @code{input_data}, is an array that holds those
  1022. numbers.
  1023. @example
  1024. double
  1025. avg_of_double (int length, double input_data[])
  1026. @{
  1027. double sum = 0;
  1028. int i;
  1029. for (i = 0; i < length; i++)
  1030. sum = sum + input_data[i];
  1031. return sum / length;
  1032. @}
  1033. @end example
  1034. This introduces the expression to refer to an element of an array:
  1035. @code{input_data[i]} means the element at index @code{i} in
  1036. @code{input_data}. The index of the element can be any expression
  1037. with an integer value; in this case, the expression is @code{i}.
  1038. @xref{Accessing Array Elements}.
  1039. @cindex zero-origin indexing
  1040. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1041. valid index is one less than the number of elements. (This is known
  1042. as @dfn{zero-origin indexing}.)
  1043. This example also introduces the way to declare that a function
  1044. parameter is an array. Such declarations are modeled after the syntax
  1045. for an element of the array. Just as @code{double foo} declares that
  1046. @code{foo} is of type @code{double}, @code{double input_data[]}
  1047. declares that each element of @code{input_data} is of type
  1048. @code{double}. Therefore, @code{input_data} itself has type ``array
  1049. of @code{double}.''
  1050. When declaring an array parameter, it's not necessary to say how long
  1051. the array is. In this case, the parameter @code{input_data} has no
  1052. length information. That's why the function needs another parameter,
  1053. @code{length}, for the caller to provide that information to the
  1054. function @code{avg_of_double}.
  1055. @node Array Example Call
  1056. @section Calling the Array Example
  1057. To call the function @code{avg_of_double} requires making an
  1058. array and then passing it as an argument. Here is an example.
  1059. @example
  1060. @{
  1061. /* @r{The array of values to average.} */
  1062. double nums_to_average[5];
  1063. /* @r{The average, once we compute it.} */
  1064. double average;
  1065. /* @r{Fill in elements of @code{nums_to_average}.} */
  1066. nums_to_average[0] = 58.7;
  1067. nums_to_average[1] = 5.1;
  1068. nums_to_average[2] = 7.7;
  1069. nums_to_average[3] = 105.2;
  1070. nums_to_average[4] = -3.14159;
  1071. average = avg_of_double (5, nums_to_average);
  1072. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1073. @}
  1074. @end example
  1075. This shows an array subscripting expression again, this time
  1076. on the left side of an assignment, storing a value into an
  1077. element of an array.
  1078. It also shows how to declare a local variable that is an array:
  1079. @code{double nums_to_average[5];}. Since this declaration allocates the
  1080. space for the array, it needs to know the array's length. You can
  1081. specify the length with any expression whose value is an integer, but
  1082. in this declaration the length is a constant, the integer 5.
  1083. The name of the array, when used by itself as an expression, stands
  1084. for the address of the array's data, and that's what gets passed to
  1085. the function @code{avg_of_double} in @code{avg_of_double (5,
  1086. nums_to_average)}.
  1087. We can make the code easier to maintain by avoiding the need to write
  1088. 5, the array length, when calling @code{avg_of_double}. That way, if
  1089. we change the array to include more elements, we won't have to change
  1090. that call. One way to do this is with the @code{sizeof} operator:
  1091. @example
  1092. average = avg_of_double ((sizeof (nums_to_average)
  1093. / sizeof (nums_to_average[0])),
  1094. nums_to_average);
  1095. @end example
  1096. This computes the number of elements in @code{nums_to_average} by dividing
  1097. its total size by the size of one element. @xref{Type Size}, for more
  1098. details of using @code{sizeof}.
  1099. We don't show in this example what happens after storing the result of
  1100. @code{avg_of_double} in the variable @code{average}. Presumably
  1101. more code would follow that uses that result somehow. (Why compute
  1102. the average and not use it?) But that isn't part of this topic.
  1103. @node Array Example Variations
  1104. @section Variations for Array Example
  1105. The code to call @code{avg_of_double} has two declarations that
  1106. start with the same data type:
  1107. @example
  1108. /* @r{The array of values to average.} */
  1109. double nums_to_average[5];
  1110. /* @r{The average, once we compute it.} */
  1111. double average;
  1112. @end example
  1113. In C, you can combine the two, like this:
  1114. @example
  1115. double nums_to_average[5], average;
  1116. @end example
  1117. This declares @code{nums_to_average} so each of its elements is a
  1118. @code{double}, and @code{average} so that it simply is a
  1119. @code{double}.
  1120. However, while you @emph{can} combine them, that doesn't mean you
  1121. @emph{should}. If it is useful to write comments about the variables,
  1122. and usually it is, then it's clearer to keep the declarations separate
  1123. so you can put a comment on each one.
  1124. We set all of the elements of the array @code{nums_to_average} with
  1125. assignments, but it is more convenient to use an initializer in the
  1126. declaration:
  1127. @example
  1128. @{
  1129. /* @r{The array of values to average.} */
  1130. double nums_to_average[]
  1131. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1132. /* @r{The average, once we compute it.} */
  1133. average = avg_of_double ((sizeof (nums_to_average)
  1134. / sizeof (nums_to_average[0])),
  1135. nums_to_average);
  1136. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1137. @}
  1138. @end example
  1139. The array initializer is a comma-separated list of values, delimited
  1140. by braces. @xref{Initializers}.
  1141. Note that the declaration does not specify a size for
  1142. @code{nums_to_average}, so the size is determined from the
  1143. initializer. There are five values in the initializer, so
  1144. @code{nums_to_average} gets length 5. If we add another element to
  1145. the initializer, @code{nums_to_average} will have six elements.
  1146. Because the code computes the number of elements from the size of
  1147. the array, using @code{sizeof}, the program will operate on all the
  1148. elements in the initializer, regardless of how many those are.
  1149. @node Lexical Syntax
  1150. @chapter Lexical Syntax
  1151. @cindex lexical syntax
  1152. @cindex token
  1153. To start the full description of the C language, we explain the
  1154. lexical syntax and lexical units of C code. The lexical units of a
  1155. programming language are known as @dfn{tokens}. This chapter covers
  1156. all the tokens of C except for constants, which are covered in a later
  1157. chapter (@pxref{Constants}). One vital kind of token is the
  1158. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1159. kind.
  1160. @menu
  1161. * English:: Write programs in English!
  1162. * Characters:: The characters allowed in C programs.
  1163. * Whitespace:: The particulars of whitespace characters.
  1164. * Comments:: How to include comments in C code.
  1165. * Identifiers:: How to form identifiers (names).
  1166. * Operators/Punctuation:: Characters used as operators or punctuation.
  1167. * Line Continuation:: Splitting one line into multiple lines.
  1168. @end menu
  1169. @node English
  1170. @section Write Programs in English!
  1171. In principle, you can write the function and variable names in a
  1172. program, and the comments, in any human language. C allows any kinds
  1173. of characters in comments, and you can put non-ASCII characters into
  1174. identifiers with a special prefix. However, to enable programmers in
  1175. all countries to understand and develop the program, it is best given
  1176. today's circumstances to write identifiers and comments in
  1177. English.
  1178. English is the one language that programmers in all countries
  1179. generally study. If a program's names are in English, most
  1180. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1181. understand them. Most programmers in those countries can speak
  1182. English, or at least read it, but they do not read each other's
  1183. languages at all. In India, with so many languages, two programmers
  1184. may have no common language other than English.
  1185. If you don't feel confident in writing English, do the best you can,
  1186. and follow each English comment with a version in a language you
  1187. write better; add a note asking others to translate that to English.
  1188. Someone will eventually do that.
  1189. The program's user interface is a different matter. We don't need to
  1190. choose one language for that; it is easy to support multiple languages
  1191. and let each user choose the language to use. This requires writing
  1192. the program to support localization of its interface. (The
  1193. @code{gettext} package exists to support this; @pxref{Message
  1194. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1195. Manual}.) Then a community-based translation effort can provide
  1196. support for all the languages users want to use.
  1197. @node Characters
  1198. @section Characters
  1199. @cindex character set
  1200. @cindex Unicode
  1201. @c ??? How to express ¶?
  1202. GNU C source files are usually written in the
  1203. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1204. was defined in the 1960s for English. However, they can also include
  1205. Unicode characters represented in the
  1206. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1207. This makes it possible to represent accented letters such as @samp{á},
  1208. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1209. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1210. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1211. manual.}
  1212. In C source code, non-ASCII characters are valid in comments, in wide
  1213. character constants (@pxref{Wide Character Constants}), and in string
  1214. constants (@pxref{String Constants}).
  1215. @c ??? valid in identifiers?
  1216. Another way to specify non-ASCII characters in constants (character or
  1217. string) and identifiers is with an escape sequence starting with
  1218. backslash, specifying the intended Unicode character. (@xref{Unicode
  1219. Character Codes}.) This specifies non-ASCII characters without
  1220. putting a real non-ASCII character in the source file itself.
  1221. C accepts two-character aliases called @dfn{digraphs} for certain
  1222. characters. @xref{Digraphs}.
  1223. @node Whitespace
  1224. @section Whitespace
  1225. @cindex whitespace characters in source files
  1226. @cindex space character in source
  1227. @cindex tab character in source
  1228. @cindex formfeed in source
  1229. @cindex linefeed in source
  1230. @cindex newline in source
  1231. @cindex carriage return in source
  1232. @cindex vertical tab in source
  1233. Whitespace means characters that exist in a file but appear blank in a
  1234. printed listing of a file (or traditionally did appear blank, several
  1235. decades ago). The C language requires whitespace in order to separate
  1236. two consecutive identifiers, or to separate an identifier from a
  1237. numeric constant. Other than that, and a few special situations
  1238. described later, whitespace is optional; you can put it in when you
  1239. wish, to make the code easier to read.
  1240. Space and tab in C code are treated as whitespace characters. So are
  1241. line breaks. You can represent a line break with the newline
  1242. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1243. the CRLF sequence (two characters: carriage return followed by a
  1244. newline character).
  1245. The @dfn{formfeed} character, Control-L, was traditionally used to
  1246. divide a file into pages. It is still used this way in source code,
  1247. and the tools that generate nice printouts of source code still start
  1248. a new page after each ``formfeed'' character. Dividing code into
  1249. pages separated by formfeed characters is a good way to break it up
  1250. into comprehensible pieces and show other programmers where they start
  1251. and end.
  1252. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1253. make printing advance down to the next section of a page. We know of
  1254. no particular reason to use it in source code, but it is still
  1255. accepted as whitespace in C.
  1256. Comments are also syntactically equivalent to whitespace.
  1257. @ifinfo
  1258. @xref{Comments}.
  1259. @end ifinfo
  1260. @node Comments
  1261. @section Comments
  1262. @cindex comments
  1263. A comment encapsulates text that has no effect on the program's
  1264. execution or meaning.
  1265. The purpose of comments is to explain the code to people that read it.
  1266. Writing good comments for your code is tremendously important---they
  1267. should provide background information that helps programmers
  1268. understand the reasons why the code is written the way it is. You,
  1269. returning to the code six months from now, will need the help of these
  1270. comments to remember why you wrote it this way.
  1271. Outdated comments that become incorrect are counterproductive, so part
  1272. of the software developer's responsibility is to update comments as
  1273. needed to correspond with changes to the program code.
  1274. C allows two kinds of comment syntax, the traditional style and the
  1275. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1276. with @samp{*/}. For instance,
  1277. @example
  1278. /* @r{This is a comment in traditional C syntax.} */
  1279. @end example
  1280. A traditional comment can contain @samp{/*}, but these delimiters do
  1281. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1282. whether it contains @samp{/*} sequences.
  1283. @example
  1284. /* @r{This} /* @r{is a comment} */ But this is not! */
  1285. @end example
  1286. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1287. For instance,
  1288. @example
  1289. // @r{This is a comment in C@t{++} style.}
  1290. @end example
  1291. Line comments do nest, in effect, because @samp{//} inside a line
  1292. comment is part of that comment:
  1293. @example
  1294. // @r{this whole line is} // @r{one comment}
  1295. This is code, not comment.
  1296. @end example
  1297. It is safe to put line comments inside block comments, or vice versa.
  1298. @example
  1299. @group
  1300. /* @r{traditional comment}
  1301. // @r{contains line comment}
  1302. @r{more traditional comment}
  1303. */ text here is not a comment
  1304. // @r{line comment} /* @r{contains traditional comment} */
  1305. @end group
  1306. @end example
  1307. But beware of commenting out one end of a traditional comment with a line
  1308. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1309. inside an already-started comment.
  1310. @example
  1311. @group
  1312. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1313. Oops! The line comment has ended;
  1314. this isn't a comment any more. */
  1315. @end group
  1316. @end example
  1317. Comments are not recognized within string constants. @t{@w{"/* blah
  1318. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1319. string.
  1320. In this manual we show the text in comments in a variable-width font,
  1321. for readability, but this font distinction does not exist in source
  1322. files.
  1323. A comment is syntactically equivalent to whitespace, so it always
  1324. separates tokens. Thus,
  1325. @example
  1326. @group
  1327. int/* @r{comment} */foo;
  1328. @r{is equivalent to}
  1329. int foo;
  1330. @end group
  1331. @end example
  1332. @noindent
  1333. but clean code always uses real whitespace to separate the comment
  1334. visually from surrounding code.
  1335. @node Identifiers
  1336. @section Identifiers
  1337. @cindex identifiers
  1338. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1339. as well as @samp{_}, that does not start with a digit. Most compilers
  1340. also allow @samp{$}. An identifier can be as long as you like; for
  1341. example,
  1342. @example
  1343. int anti_dis_establishment_arian_ism;
  1344. @end example
  1345. @cindex case of letters in identifiers
  1346. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1347. and @code{A} are two different identifiers.
  1348. @cindex keyword
  1349. @cindex reserved words
  1350. Identifiers in C are used as variable names, function names, typedef
  1351. names, enumeration constants, type tags, field names, and labels.
  1352. Certain identifiers in C are @dfn{keywords}, which means they have
  1353. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1354. meaning you cannot use them in any other way. For instance, you can't
  1355. define a variable or function named @code{return} or @code{if}.
  1356. You can also include other characters, even non-ASCII characters, in
  1357. identifiers by writing their Unicode character names, which start with
  1358. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1359. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1360. characters in identifiers, and when they are written in English, they
  1361. never need non-ASCII characters. @xref{English}.
  1362. Whitespace is required to separate two consecutive identifiers, or to
  1363. separate an identifier from a preceding or following numeric
  1364. constant.
  1365. @node Operators/Punctuation
  1366. @section Operators and Punctuation
  1367. @cindex operators
  1368. @cindex punctuation
  1369. Here we describe the lexical syntax of operators and punctuation in C.
  1370. The specific operators of C and their meanings are presented in
  1371. subsequent chapters.
  1372. Most operators in C consist of one or two characters that can't be
  1373. used in identifiers. The characters used for operators in C are
  1374. @samp{!~^&|*/%+-=<>,.?:}.
  1375. Some operators are a single character. For instance, @samp{-} is the
  1376. operator for negation (with one operand) and the operator for
  1377. subtraction (with two operands).
  1378. Some operators are two characters. For example, @samp{++} is the
  1379. increment operator. Recognition of multicharacter operators works by
  1380. grouping together as many consecutive characters as can constitute one
  1381. operator.
  1382. For instance, the character sequence @samp{++} is always interpreted
  1383. as the increment operator; therefore, if we want to write two
  1384. consecutive instances of the operator @samp{+}, we must separate them
  1385. with a space so that they do not combine as one token. Applying the
  1386. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1387. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1388. of a valid C program and the former could not (since @code{a++}
  1389. is not an lvalue and thus can't be the operand of @code{++}).
  1390. A few C operators are keywords rather than special characters. They
  1391. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1392. (@pxref{Type Alignment}).
  1393. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1394. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1395. @samp{@}}) begin and end a block at the statement level
  1396. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1397. for a variable with multiple elements or components (such as arrays or
  1398. structures).
  1399. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1400. @code{array[5]}.
  1401. Parentheses are used in expressions for explicit nesting of
  1402. expressions (@pxref{Basic Arithmetic}), around the parameter
  1403. declarations in a function declaration or definition, and around the
  1404. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1405. (@pxref{Function Calls}). Several kinds of statements also use
  1406. parentheses as part of their syntax---for instance, @code{if}
  1407. statements, @code{for} statements, @code{while} statements, and
  1408. @code{switch} statements. @xref{if Statement}, and following
  1409. sections.
  1410. Parentheses are also required around the operand of the operator
  1411. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1412. type rather than a value. @xref{Type Size}.
  1413. @node Line Continuation
  1414. @section Line Continuation
  1415. @cindex line continuation
  1416. @cindex continuation of lines
  1417. The sequence of a backslash and a newline is ignored absolutely
  1418. anywhere in a C program. This makes it possible to split a single
  1419. source line into multiple lines in the source file. GNU C tolerates
  1420. and ignores other whitespace between the backslash and the newline.
  1421. In particular, it always ignores a CR (carriage return) character
  1422. there, in case some text editor decided to end the line with the CRLF
  1423. sequence.
  1424. The main use of line continuation in C is for macro definitions that
  1425. would be inconveniently long for a single line (@pxref{Macros}).
  1426. It is possible to continue a line comment onto another line with
  1427. backslash-newline. You can put backslash-newline in the middle of an
  1428. identifier, even a keyword, or an operator. You can even split
  1429. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1430. backslash-newline. Here's an ugly example:
  1431. @example
  1432. @group
  1433. /\
  1434. *
  1435. */ fo\
  1436. o +\
  1437. = 1\
  1438. 0;
  1439. @end group
  1440. @end example
  1441. @noindent
  1442. That's equivalent to @samp{/* */ foo += 10;}.
  1443. Don't do those things in real programs, since they make code hard to
  1444. read.
  1445. @strong{Note:} For the sake of using certain tools on the source code, it is
  1446. wise to end every source file with a newline character which is not
  1447. preceded by a backslash, so that it really ends the last line.
  1448. @node Arithmetic
  1449. @chapter Arithmetic
  1450. @cindex arithmetic operators
  1451. @cindex operators, arithmetic
  1452. @c ??? Duplication with other sections -- get rid of that?
  1453. Arithmetic operators in C attempt to be as similar as possible to the
  1454. abstract arithmetic operations, but it is impossible to do this
  1455. perfectly. Numbers in a computer have a finite range of possible
  1456. values, and non-integer values have a limit on their possible
  1457. accuracy. Nonetheless, in most cases you will encounter no surprises
  1458. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1459. for multiplication.
  1460. Each C operator has a @dfn{precedence}, which is its rank in the
  1461. grammatical order of the various operators. The operators with the
  1462. highest precedence grab adjoining operands first; these expressions
  1463. then become operands for operators of lower precedence. We give some
  1464. information about precedence of operators in this chapter where we
  1465. describe the operators; for the full explanation, see @ref{Binary
  1466. Operator Grammar}.
  1467. The arithmetic operators always @dfn{promote} their operands before
  1468. operating on them. This means converting narrow integer data types to
  1469. a wider data type (@pxref{Operand Promotions}). If you are just
  1470. learning C, don't worry about this yet.
  1471. Given two operands that have different types, most arithmetic
  1472. operations convert them both to their @dfn{common type}. For
  1473. instance, if one is @code{int} and the other is @code{double}, the
  1474. common type is @code{double}. (That's because @code{double} can
  1475. represent all the values that an @code{int} can hold, but not vice
  1476. versa.) For the full details, see @ref{Common Type}.
  1477. @menu
  1478. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1479. and division.
  1480. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1481. * Integer Overflow:: When an integer value exceeds the range
  1482. of its type.
  1483. * Mixed Mode:: Calculating with both integer values
  1484. and floating-point values.
  1485. * Division and Remainder:: How integer division works.
  1486. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1487. * Shift Operations:: Shift integer bits left or right.
  1488. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1489. @end menu
  1490. @node Basic Arithmetic
  1491. @section Basic Arithmetic
  1492. @cindex addition operator
  1493. @cindex subtraction operator
  1494. @cindex multiplication operator
  1495. @cindex division operator
  1496. @cindex negation operator
  1497. @cindex operator, addition
  1498. @cindex operator, subtraction
  1499. @cindex operator, multiplication
  1500. @cindex operator, division
  1501. @cindex operator, negation
  1502. Basic arithmetic in C is done with the usual binary operators of
  1503. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1504. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1505. used to change the sign of a number. The unary @code{+} operator also
  1506. exists; it yields its operand unaltered.
  1507. @samp{/} is the division operator, but dividing integers may not give
  1508. the result you expect. Its value is an integer, which is not equal to
  1509. the mathematical quotient when that is a fraction. Use @samp{%} to
  1510. get the corresponding integer remainder when necessary.
  1511. @xref{Division and Remainder}. Floating point division yields value
  1512. as close as possible to the mathematical quotient.
  1513. These operators use algebraic syntax with the usual algebraic
  1514. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1515. and division are done before addition and subtraction, but you can use
  1516. parentheses to explicitly specify how the operators nest. They are
  1517. left-associative (@pxref{Associativity and Ordering}). Thus,
  1518. @example
  1519. -a + b - c + d * e / f
  1520. @end example
  1521. @noindent
  1522. is equivalent to
  1523. @example
  1524. (((-a) + b) - c) + ((d * e) / f)
  1525. @end example
  1526. @node Integer Arithmetic
  1527. @section Integer Arithmetic
  1528. @cindex integer arithmetic
  1529. Each of the basic arithmetic operations in C has two variants for
  1530. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1531. by the data types of their operands.
  1532. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1533. A signed type can hold a range of positive and negative numbers, with
  1534. zero near the middle of the range. An unsigned type can hold only
  1535. nonnegative numbers; its range starts with zero and runs upward.
  1536. The most basic integer types are @code{int}, which normally can hold
  1537. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1538. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1539. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1540. computers but not always on embedded controllers.) @xref{Integer
  1541. Types}, for full information about integer types.
  1542. When a basic arithmetic operation is given two signed operands, it
  1543. does signed arithmetic. Given two unsigned operands, it does
  1544. unsigned arithmetic.
  1545. If one operand is @code{unsigned int} and the other is @code{int}, the
  1546. operator treats them both as unsigned. More generally, the common
  1547. type of the operands determines whether the operation is signed or
  1548. not. @xref{Common Type}.
  1549. Printing the results of unsigned arithmetic with @code{printf} using
  1550. @samp{%d} can produce surprising results for values far away from
  1551. zero. Even though the rules above say that the computation was done
  1552. with unsigned arithmetic, the printed result may appear to be signed!
  1553. The explanation is that the bit pattern resulting from addition,
  1554. subtraction or multiplication is actually the same for signed and
  1555. unsigned operations. The difference is only in the data type of the
  1556. result, which affects the @emph{interpretation} of the result bit pattern,
  1557. and whether the arithmetic operation can overflow (see the next section).
  1558. But @samp{%d} doesn't know its argument's data type. It sees only the
  1559. value's bit pattern, and it is defined to interpret that as
  1560. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1561. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1562. libc, The GNU C Library Reference Manual}.
  1563. Arithmetic in C never operates directly on narrow integer types (those
  1564. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1565. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1566. @node Integer Overflow
  1567. @section Integer Overflow
  1568. @cindex integer overflow
  1569. @cindex overflow, integer
  1570. When the mathematical value of an arithmetic operation doesn't fit in
  1571. the range of the data type in use, that's called @dfn{overflow}.
  1572. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1573. Integer overflow happens only in arithmetic operations. Type conversion
  1574. operations, by definition, do not cause overflow, not even when the
  1575. result can't fit in its new type. @xref{Integer Conversion}.
  1576. Signed numbers use two's-complement representation, in which the most
  1577. negative number lacks a positive counterpart (@pxref{Integers in
  1578. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1579. overflow.
  1580. @menu
  1581. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1582. * Signed Overflow:: Overlow in signed integer arithmetic.
  1583. @end menu
  1584. @node Unsigned Overflow
  1585. @subsection Overflow with Unsigned Integers
  1586. Unsigned arithmetic in C ignores overflow; it produces the true result
  1587. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1588. in the data type. We say it ``truncates'' the true result to the
  1589. lowest @var{n} bits.
  1590. A true result that is negative, when taken modulo the @var{n}th power
  1591. of 2, yields a positive number. For instance,
  1592. @example
  1593. unsigned int x = 1;
  1594. unsigned int y;
  1595. y = -x;
  1596. @end example
  1597. @noindent
  1598. causes overflow because the negative number @minus{}1 can't be stored
  1599. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1600. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1601. is the largest value that the unsigned data type can store. For a
  1602. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1603. and Minimum Values}.
  1604. Adding that number to itself, as here,
  1605. @example
  1606. unsigned int z;
  1607. z = y + y;
  1608. @end example
  1609. @noindent
  1610. ought to yield 8,489,934,590; however, that is again too large to fit,
  1611. so overflow truncates the value to 4,294,967,294. If that were a
  1612. signed integer, it would mean @minus{}2, which (not by coincidence)
  1613. equals @minus{}1 + @minus{}1.
  1614. @node Signed Overflow
  1615. @subsection Overflow with Signed Integers
  1616. @cindex compiler options for integer overflow
  1617. @cindex integer overflow, compiler options
  1618. @cindex overflow, compiler options
  1619. For signed integers, the result of overflow in C is @emph{in
  1620. principle} undefined, meaning that anything whatsoever could happen.
  1621. Therefore, C compilers can do optimizations that treat the overflow
  1622. case with total unconcern. (Since the result of overflow is undefined
  1623. in principle, one cannot claim that these optimizations are
  1624. erroneous.)
  1625. @strong{Watch out:} These optimizations can do surprising things. For
  1626. instance,
  1627. @example
  1628. int i;
  1629. @r{@dots{}}
  1630. if (i < i + 1)
  1631. x = 5;
  1632. @end example
  1633. @noindent
  1634. could be optimized to do the assignment unconditionally, because the
  1635. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1636. GCC offers compiler options to control handling signed integer
  1637. overflow. These options operate per module; that is, each module
  1638. behaves according to the options it was compiled with.
  1639. These two options specify particular ways to handle signed integer
  1640. overflow, other than the default way:
  1641. @table @option
  1642. @item -fwrapv
  1643. Make signed integer operations well-defined, like unsigned integer
  1644. operations: they produce the @var{n} low-order bits of the true
  1645. result. The highest of those @var{n} bits is the sign bit of the
  1646. result. With @option{-fwrapv}, these out-of-range operations are not
  1647. considered overflow, so (strictly speaking) integer overflow never
  1648. happens.
  1649. The option @option{-fwrapv} enables some optimizations based on the
  1650. defined values of out-of-range results. In GCC 8, it disables
  1651. optimizations that are based on assuming signed integer operations
  1652. will not overflow.
  1653. @item -ftrapv
  1654. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1655. This terminates the program unless the program handles the signal.
  1656. @xref{Signals}.
  1657. @end table
  1658. One other option is useful for finding where overflow occurs:
  1659. @ignore
  1660. @item -fno-strict-overflow
  1661. Disable optimizations that are based on assuming signed integer
  1662. operations will not overflow.
  1663. @end ignore
  1664. @table @option
  1665. @item -fsanitize=signed-integer-overflow
  1666. Output a warning message at run time when signed integer overflow
  1667. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1668. This takes priority over @option{-ftrapv}.
  1669. @end table
  1670. @node Mixed Mode
  1671. @section Mixed-Mode Arithmetic
  1672. Mixing integers and floating-point numbers in a basic arithmetic
  1673. operation converts the integers automatically to floating point.
  1674. In most cases, this gives exactly the desired results.
  1675. But sometimes it matters precisely where the conversion occurs.
  1676. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1677. as an integer, then converts the sum to floating point for the
  1678. multiplication. If the addition gets an overflow, that is not
  1679. equivalent to converting both integers to floating point and then
  1680. adding them. You can get the latter result by explicitly converting
  1681. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1682. @xref{Explicit Type Conversion}.
  1683. @c Eggert's report
  1684. Adding or multiplying several values, including some integers and some
  1685. floating point, does the operations left to right. Thus, @code{3.0 +
  1686. i + j} converts @code{i} to floating point, then adds 3.0, then
  1687. converts @code{j} to floating point and adds that. You can specify a
  1688. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1689. and @code{j} first and then adds that result (converting to floating
  1690. point) to 3.0. In this respect, C differs from other languages, such
  1691. as Fortran.
  1692. @node Division and Remainder
  1693. @section Division and Remainder
  1694. @cindex remainder operator
  1695. @cindex modulus
  1696. @cindex operator, remainder
  1697. Division of integers in C rounds the result to an integer. The result
  1698. is always rounded towards zero.
  1699. @example
  1700. 16 / 3 @result{} 5
  1701. -16 / 3 @result{} -5
  1702. 16 / -3 @result{} -5
  1703. -16 / -3 @result{} 5
  1704. @end example
  1705. @noindent
  1706. To get the corresponding remainder, use the @samp{%} operator:
  1707. @example
  1708. 16 % 3 @result{} 1
  1709. -16 % 3 @result{} -1
  1710. 16 % -3 @result{} 1
  1711. -16 % -3 @result{} -1
  1712. @end example
  1713. @noindent
  1714. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1715. From the rounded quotient and the remainder, you can reconstruct
  1716. the dividend, like this:
  1717. @example
  1718. int
  1719. original_dividend (int divisor, int quotient, int remainder)
  1720. @{
  1721. return divisor * quotient + remainder;
  1722. @}
  1723. @end example
  1724. To do unrounded division, use floating point. If only one operand is
  1725. floating point, @samp{/} converts the other operand to floating
  1726. point.
  1727. @example
  1728. 16.0 / 3 @result{} 5.333333333333333
  1729. 16 / 3.0 @result{} 5.333333333333333
  1730. 16.0 / 3.0 @result{} 5.333333333333333
  1731. 16 / 3 @result{} 5
  1732. @end example
  1733. The remainder operator @samp{%} is not allowed for floating-point
  1734. operands, because it is not needed. The concept of remainder makes
  1735. sense for integers because the result of division of integers has to
  1736. be an integer. For floating point, the result of division is a
  1737. floating-point number, in other words a fraction, which will differ
  1738. from the exact result only by a very small amount.
  1739. There are functions in the standard C library to calculate remainders
  1740. from integral-values division of floating-point numbers.
  1741. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1742. Reference Manual}.
  1743. Integer division overflows in one specific case: dividing the smallest
  1744. negative value for the data type (@pxref{Maximum and Minimum Values})
  1745. by @minus{}1. That's because the correct result, which is the
  1746. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1747. in the same number of bits. On some computers now in use, this always
  1748. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1749. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1750. Division by zero leads to unpredictable results---depending on the
  1751. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1752. produce a numeric result.
  1753. @cindex division by zero
  1754. @cindex zero, division by
  1755. @strong{Watch out:} Make sure the program does not divide by zero. If
  1756. you can't prove that the divisor is not zero, test whether it is zero,
  1757. and skip the division if so.
  1758. @node Numeric Comparisons
  1759. @section Numeric Comparisons
  1760. @cindex numeric comparisons
  1761. @cindex comparisons
  1762. @cindex operators, comparison
  1763. @cindex equal operator
  1764. @cindex not-equal operator
  1765. @cindex less-than operator
  1766. @cindex greater-than operator
  1767. @cindex less-or-equal operator
  1768. @cindex greater-or-equal operator
  1769. @cindex operator, equal
  1770. @cindex operator, not-equal
  1771. @cindex operator, less-than
  1772. @cindex operator, greater-than
  1773. @cindex operator, less-or-equal
  1774. @cindex operator, greater-or-equal
  1775. @cindex truth value
  1776. There are two kinds of comparison operators: @dfn{equality} and
  1777. @dfn{ordering}. Equality comparisons test whether two expressions
  1778. have the same value. The result is a @dfn{truth value}: a number that
  1779. is 1 for ``true'' and 0 for ``false.''
  1780. @example
  1781. a == b /* @r{Test for equal.} */
  1782. a != b /* @r{Test for not equal.} */
  1783. @end example
  1784. The equality comparison is written @code{==} because plain @code{=}
  1785. is the assignment operator.
  1786. Ordering comparisons test which operand is greater or less. Their
  1787. results are truth values. These are the ordering comparisons of C:
  1788. @example
  1789. a < b /* @r{Test for less-than.} */
  1790. a > b /* @r{Test for greater-than.} */
  1791. a <= b /* @r{Test for less-than-or-equal.} */
  1792. a >= b /* @r{Test for greater-than-or-equal.} */
  1793. @end example
  1794. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1795. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1796. mathematics. However, if @code{a} and @code{b} are special floating
  1797. point values (not ordinary numbers), all three can be false.
  1798. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1799. @node Shift Operations
  1800. @section Shift Operations
  1801. @cindex shift operators
  1802. @cindex operators, shift
  1803. @cindex operators, shift
  1804. @cindex shift count
  1805. @dfn{Shifting} an integer means moving the bit values to the left or
  1806. right within the bits of the data type. Shifting is defined only for
  1807. integers. Here's the way to write it:
  1808. @example
  1809. /* @r{Left shift.} */
  1810. 5 << 2 @result{} 20
  1811. /* @r{Right shift.} */
  1812. 5 >> 2 @result{} 1
  1813. @end example
  1814. @noindent
  1815. The left operand is the value to be shifted, and the right operand
  1816. says how many bits to shift it (the @dfn{shift count}). The left
  1817. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1818. operates on a narrow integer type; it's always either @code{int} or
  1819. wider. The value of the shift operator has the same type as the
  1820. promoted left operand.
  1821. @menu
  1822. * Bits Shifted In:: How shifting makes new bits to shift in.
  1823. * Shift Caveats:: Caveats of shift operations.
  1824. * Shift Hacks:: Clever tricks with shift operations.
  1825. @end menu
  1826. @node Bits Shifted In
  1827. @subsection Shifting Makes New Bits
  1828. A shift operation shifts towards one end of the number and has to
  1829. generate new bits at the other end.
  1830. Shifting left one bit must generate a new least significant bit. It
  1831. always brings in zero there. It is equivalent to multiplying by the
  1832. appropriate power of 2. For example,
  1833. @example
  1834. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1835. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1836. @end example
  1837. The meaning of shifting right depends on whether the data type is
  1838. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1839. data type, it performs ``arithmetic shift,'' which keeps the number's
  1840. sign unchanged by duplicating the sign bit. For an unsigned data
  1841. type, it performs ``logical shift,'' which always shifts in zeros at
  1842. the most significant bit.
  1843. In both cases, shifting right one bit is division by two, rounding
  1844. towards negative infinity. For example,
  1845. @example
  1846. (unsigned) 19 >> 2 @result{} 4
  1847. (unsigned) 20 >> 2 @result{} 5
  1848. (unsigned) 21 >> 2 @result{} 5
  1849. @end example
  1850. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1851. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1852. zero.
  1853. The shift count must be zero or greater. Shifting by a negative
  1854. number of bits gives machine-dependent results.
  1855. @node Shift Caveats
  1856. @subsection Caveats for Shift Operations
  1857. @strong{Warning:} If the shift count is greater than or equal to the
  1858. width in bits of the first operand, the results are machine-dependent.
  1859. Logically speaking, the ``correct'' value would be either -1 (for
  1860. right shift of a negative number) or 0 (in all other cases), but what
  1861. it really generates is whatever the machine's shift instruction does in
  1862. that case. So unless you can prove that the second operand is not too
  1863. large, write code to check it at run time.
  1864. @strong{Warning:} Never rely on how the shift operators relate in
  1865. precedence to other arithmetic binary operators. Programmers don't
  1866. remember these precedences, and won't understand the code. Always use
  1867. parentheses to explicitly specify the nesting, like this:
  1868. @example
  1869. a + (b << 5) /* @r{Shift first, then add.} */
  1870. (a + b) << 5 /* @r{Add first, then shift.} */
  1871. @end example
  1872. Note: according to the C standard, shifting of signed values isn't
  1873. guaranteed to work properly when the value shifted is negative, or
  1874. becomes negative during the operation of shifting left. However, only
  1875. pedants have a reason to be concerned about this; only computers with
  1876. strange shift instructions could plausibly do this wrong. In GNU C,
  1877. the operation always works as expected,
  1878. @node Shift Hacks
  1879. @subsection Shift Hacks
  1880. You can use the shift operators for various useful hacks. For
  1881. example, given a date specified by day of the month @code{d}, month
  1882. @code{m}, and year @code{y}, you can store the entire date in a single
  1883. integer @code{date}:
  1884. @example
  1885. unsigned int d = 12;
  1886. unsigned int m = 6;
  1887. unsigned int y = 1983;
  1888. unsigned int date = ((y << 4) + m) << 5) + d;
  1889. @end example
  1890. @noindent
  1891. To extract the original day, month, and year out of
  1892. @code{date}, use a combination of shift and remainder.
  1893. @example
  1894. d = date % 32;
  1895. m = (date >> 5) % 16;
  1896. y = date >> 9;
  1897. @end example
  1898. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1899. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1900. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1901. multiplication, since negating a value is equivalent to multiplying it
  1902. by @minus{}1.
  1903. @node Bitwise Operations
  1904. @section Bitwise Operations
  1905. @cindex bitwise operators
  1906. @cindex operators, bitwise
  1907. @cindex negation, bitwise
  1908. @cindex conjunction, bitwise
  1909. @cindex disjunction, bitwise
  1910. Bitwise operators operate on integers, treating each bit independently.
  1911. They are not allowed for floating-point types.
  1912. The examples in this section use binary constants, starting with
  1913. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1914. of type @code{int}.
  1915. @table @code
  1916. @item ~@code{a}
  1917. Unary operator for bitwise negation; this changes each bit of
  1918. @code{a} from 1 to 0 or from 0 to 1.
  1919. @example
  1920. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1921. ~0 @result{} 0b11111111111111111111111111111111
  1922. ~0b11111111111111111111111111111111 @result{} 0
  1923. ~ (-1) @result{} 0
  1924. @end example
  1925. It is useful to remember that @code{~@var{x} + 1} equals
  1926. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1927. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1928. as @var{x}.
  1929. @item @code{a} & @code{b}
  1930. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1931. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1932. @example
  1933. 0b10101010 & 0b11001100 @result{} 0b10001000
  1934. @end example
  1935. @item @code{a} | @code{b}
  1936. Binary operator for bitwise ``or'' (``inclusive or'' or
  1937. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1938. either @code{a} or @code{b}.
  1939. @example
  1940. 0b10101010 | 0b11001100 @result{} 0b11101110
  1941. @end example
  1942. @item @code{a} ^ @code{b}
  1943. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1944. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1945. @example
  1946. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1947. @end example
  1948. @end table
  1949. To understand the effect of these operators on signed integers, keep
  1950. in mind that all modern computers use two's-complement representation
  1951. (@pxref{Integer Representations}) for negative integers. This means
  1952. that the highest bit of the number indicates the sign; it is 1 for a
  1953. negative number and 0 for a positive number. In a negative number,
  1954. the value in the other bits @emph{increases} as the number gets closer
  1955. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1956. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1957. @strong{Warning:} C defines a precedence ordering for the bitwise
  1958. binary operators, but you should never rely on it. You should
  1959. never rely on how bitwise binary operators relate in precedence to the
  1960. arithmetic and shift binary operators. Other programmers don't
  1961. remember this precedence ordering, so always use parentheses to
  1962. explicitly specify the nesting.
  1963. For example, suppose @code{offset} is an integer that specifies
  1964. the offset within shared memory of a table, except that its bottom few
  1965. bits (@code{LOWBITS} says how many) are special flags. Here's
  1966. how to get just that offset and add it to the base address.
  1967. @example
  1968. shared_mem_base + (offset & (-1 << LOWBITS))
  1969. @end example
  1970. Thanks to the outer set of parentheses, we don't need to know whether
  1971. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1972. set, we don't need to know whether @samp{&} has higher precedence than
  1973. @samp{<<}. But we can rely on all unary operators to have higher
  1974. precedence than any binary operator, so we don't need parentheses
  1975. around the left operand of @samp{<<}.
  1976. @node Assignment Expressions
  1977. @chapter Assignment Expressions
  1978. @cindex assignment expressions
  1979. @cindex operators, assignment
  1980. As a general concept in programming, an @dfn{assignment} is a
  1981. construct that stores a new value into a place where values can be
  1982. stored---for instance, in a variable. Such places are called
  1983. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1984. An assignment in C is an expression because it has a value; we call
  1985. it an @dfn{assignment expression}. A simple assignment looks like
  1986. @example
  1987. @var{lvalue} = @var{value-to-store}
  1988. @end example
  1989. @noindent
  1990. We say it assigns the value of the expression @var{value-to-store} to
  1991. the location @var{lvalue}, or that it stores @var{value-to-store}
  1992. there. You can think of the ``l'' in ``lvalue'' as standing for
  1993. ``left,'' since that's what you put on the left side of the assignment
  1994. operator.
  1995. However, that's not the only way to use an lvalue, and not all lvalues
  1996. can be assigned to. To use the lvalue in the left side of an
  1997. assignment, it has to be @dfn{modifiable}. In C, that means it was
  1998. not declared with the type qualifier @code{const} (@pxref{const}).
  1999. The value of the assignment expression is that of @var{lvalue} after
  2000. the new value is stored in it. This means you can use an assignment
  2001. inside other expressions. Assignment operators are right-associative
  2002. so that
  2003. @example
  2004. x = y = z = 0;
  2005. @end example
  2006. @noindent
  2007. is equivalent to
  2008. @example
  2009. x = (y = (z = 0));
  2010. @end example
  2011. This is the only useful way for them to associate;
  2012. the other way,
  2013. @example
  2014. ((x = y) = z) = 0;
  2015. @end example
  2016. @noindent
  2017. would be invalid since an assignment expression such as @code{x = y}
  2018. is not valid as an lvalue.
  2019. @strong{Warning:} Write parentheses around an assignment if you nest
  2020. it inside another expression, unless that is a conditional expression,
  2021. or comma-separated series, or another assignment.
  2022. @menu
  2023. * Simple Assignment:: The basics of storing a value.
  2024. * Lvalues:: Expressions into which a value can be stored.
  2025. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2026. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2027. an lvalue's contents.
  2028. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2029. * Assignment in Subexpressions:: How to avoid ambiguity.
  2030. * Write Assignments Separately:: Write assignments as separate statements.
  2031. @end menu
  2032. @node Simple Assignment
  2033. @section Simple Assignment
  2034. @cindex simple assignment
  2035. @cindex assignment, simple
  2036. A @dfn{simple assignment expression} computes the value of the right
  2037. operand and stores it into the lvalue on the left. Here is a simple
  2038. assignment expression that stores 5 in @code{i}:
  2039. @example
  2040. i = 5
  2041. @end example
  2042. @noindent
  2043. We say that this is an @dfn{assignment to} the variable @code{i} and
  2044. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2045. because it is an expression (so it has a value). Adding a semicolon
  2046. at the end would make it a statement (@pxref{Expression Statement}).
  2047. Here is another example of a simple assignment expression. Its
  2048. operands are not simple, but the kind of assignment done here is
  2049. simple assignment.
  2050. @example
  2051. x[foo ()] = y + 6
  2052. @end example
  2053. A simple assignment with two different numeric data types converts the
  2054. right operand value to the lvalue's type, if possible. It can convert
  2055. any numeric type to any other numeric type.
  2056. Simple assignment is also allowed on some non-numeric types: pointers
  2057. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2058. unions (@pxref{Unions}).
  2059. @strong{Warning:} Assignment is not allowed on arrays because
  2060. there are no array values in C; C variables can be arrays, but these
  2061. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2062. Arrays}.
  2063. @xref{Assignment Type Conversions}, for the complete rules about data
  2064. types used in assignments.
  2065. @node Lvalues
  2066. @section Lvalues
  2067. @cindex lvalues
  2068. An expression that identifies a memory space that holds a value is
  2069. called an @dfn{lvalue}, because it is a location that can hold a value.
  2070. The standard kinds of lvalues are:
  2071. @itemize @bullet
  2072. @item
  2073. A variable.
  2074. @item
  2075. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2076. unary @samp{*}.
  2077. @item
  2078. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2079. the structure value is an lvalue.
  2080. @item
  2081. A structure field reference using @samp{->}. This is always an lvalue
  2082. since @samp{->} implies pointer dereference.
  2083. @item
  2084. A union alternative reference (@pxref{Unions}), on the same conditions
  2085. as for structure fields.
  2086. @item
  2087. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2088. is an lvalue.
  2089. @end itemize
  2090. If an expression's outermost operation is any other operator, that
  2091. expression is not an lvalue. Thus, the variable @code{x} is an
  2092. lvalue, but @code{x + 0} is not, even though these two expressions
  2093. compute the same value (assuming @code{x} is a number).
  2094. An array can be an lvalue (the rules above determine whether it is
  2095. one), but using the array in an expression converts it automatically
  2096. to a pointer to the first element. The result of this conversion is
  2097. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2098. use @code{a} by itself as the left operand of an assignment. But you
  2099. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2100. lvalue since @code{a} is an lvalue.
  2101. @node Modifying Assignment
  2102. @section Modifying Assignment
  2103. @cindex modifying assignment
  2104. @cindex assignment, modifying
  2105. You can abbreviate the common construct
  2106. @example
  2107. @var{lvalue} = @var{lvalue} + @var{expression}
  2108. @end example
  2109. @noindent
  2110. as
  2111. @example
  2112. @var{lvalue} += @var{expression}
  2113. @end example
  2114. This is known as a @dfn{modifying assignment}. For instance,
  2115. @example
  2116. i = i + 5;
  2117. i += 5;
  2118. @end example
  2119. @noindent
  2120. shows two statements that are equivalent. The first uses
  2121. simple assignment; the second uses modifying assignment.
  2122. Modifying assignment works with any binary arithmetic operator. For
  2123. instance, you can subtract something from an lvalue like this,
  2124. @example
  2125. @var{lvalue} -= @var{expression}
  2126. @end example
  2127. @noindent
  2128. or multiply it by a certain amount like this,
  2129. @example
  2130. @var{lvalue} *= @var{expression}
  2131. @end example
  2132. @noindent
  2133. or shift it by a certain amount like this.
  2134. @example
  2135. @var{lvalue} <<= @var{expression}
  2136. @var{lvalue} >>= @var{expression}
  2137. @end example
  2138. In most cases, this feature adds no power to the language, but it
  2139. provides substantial convenience. Also, when @var{lvalue} contains
  2140. code that has side effects, the simple assignment performs those side
  2141. effects twice, while the modifying assignment performs them once. For
  2142. instance,
  2143. @example
  2144. x[foo ()] = x[foo ()] + 5;
  2145. @end example
  2146. @noindent
  2147. calls @code{foo} twice, and it could return different values each
  2148. time. If @code{foo ()} returns 1 the first time and 3 the second
  2149. time, then the effect could be to add @code{x[3]} and 5 and store the
  2150. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2151. result in @code{x[3]}. We don't know which of the two it will do,
  2152. because C does not specify which call to @code{foo} is computed first.
  2153. Such a statement is not well defined, and shouldn't be used.
  2154. By contrast,
  2155. @example
  2156. x[foo ()] += 5;
  2157. @end example
  2158. @noindent
  2159. is well defined: it calls @code{foo} only once to determine which
  2160. element of @code{x} to adjust, and it adjusts that element by adding 5
  2161. to it.
  2162. @node Increment/Decrement
  2163. @section Increment and Decrement Operators
  2164. @cindex increment operator
  2165. @cindex decrement operator
  2166. @cindex operator, increment
  2167. @cindex operator, decrement
  2168. @cindex preincrement expression
  2169. @cindex predecrement expression
  2170. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2171. @dfn{decrement} operators. When used on a numeric value, they add or
  2172. subtract 1. We don't consider them assignments, but they are
  2173. equivalent to assignments.
  2174. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2175. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2176. and the result becomes the expression's value. For instance,
  2177. @example
  2178. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2179. int
  2180. main (void)
  2181. @{
  2182. int i = 5;
  2183. printf ("%d\n", i);
  2184. printf ("%d\n", ++i);
  2185. printf ("%d\n", i);
  2186. return 0;
  2187. @}
  2188. @end example
  2189. @noindent
  2190. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2191. increments @code{i} from 5 to 6, and has the value 6, so the output
  2192. from @code{printf} on that line says @samp{6}.
  2193. Using @samp{--} instead, for predecrement,
  2194. @example
  2195. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2196. int
  2197. main (void)
  2198. @{
  2199. int i = 5;
  2200. printf ("%d\n", i);
  2201. printf ("%d\n", --i);
  2202. printf ("%d\n", i);
  2203. return 0;
  2204. @}
  2205. @end example
  2206. @noindent
  2207. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2208. again @samp{4}.
  2209. @node Postincrement/Postdecrement
  2210. @section Postincrement and Postdecrement
  2211. @cindex postincrement expression
  2212. @cindex postdecrement expression
  2213. @cindex operator, postincrement
  2214. @cindex operator, postdecrement
  2215. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2216. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2217. increments or decrement it. Thus, the value of @code{i++} is the same
  2218. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2219. little later.'' This is called @dfn{postincrement} or
  2220. @dfn{postdecrement}.
  2221. For example,
  2222. @example
  2223. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2224. int
  2225. main (void)
  2226. @{
  2227. int i = 5;
  2228. printf ("%d\n", i);
  2229. printf ("%d\n", i++);
  2230. printf ("%d\n", i);
  2231. return 0;
  2232. @}
  2233. @end example
  2234. @noindent
  2235. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2236. has the value 5, which is the value of @code{i} at the time,
  2237. but it increments @code{i} from 5 to 6 just a little later.
  2238. How much later is ``just a little later''? That is flexible. The
  2239. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2240. that means by the end of the statement. @xref{Sequence Points}.
  2241. If a unary operator precedes a postincrement or postincrement expression,
  2242. the increment nests inside:
  2243. @example
  2244. -a++ @r{is equivalent to} -(a++)
  2245. @end example
  2246. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2247. it can't be incremented.
  2248. @node Assignment in Subexpressions
  2249. @section Pitfall: Assignment in Subexpressions
  2250. @cindex assignment in subexpressions
  2251. @cindex subexpressions, assignment in
  2252. In C, the order of computing parts of an expression is not fixed.
  2253. Aside from a few special cases, the operations can be computed in any
  2254. order. If one part of the expression has an assignment to @code{x}
  2255. and another part of the expression uses @code{x}, the result is
  2256. unpredictable because that use might be computed before or after the
  2257. assignment.
  2258. Here's an example of ambiguous code:
  2259. @example
  2260. x = 20;
  2261. printf ("%d %d\n", x, x = 4);
  2262. @end example
  2263. @noindent
  2264. If the second argument, @code{x}, is computed before the third argument,
  2265. @code{x = 4}, the second argument's value will be 20. If they are
  2266. computed in the other order, the second argument's value will be 4.
  2267. Here's one way to make that code unambiguous:
  2268. @example
  2269. y = 20;
  2270. printf ("%d %d\n", y, x = 4);
  2271. @end example
  2272. Here's another way, with the other meaning:
  2273. @example
  2274. x = 4;
  2275. printf ("%d %d\n", x, x);
  2276. @end example
  2277. This issue applies to all kinds of assignments, and to the increment
  2278. and decrement operators, which are equivalent to assignments.
  2279. @xref{Order of Execution}, for more information about this.
  2280. However, it can be useful to write assignments inside an
  2281. @code{if}-condition or @code{while}-test along with logical operators.
  2282. @xref{Logicals and Assignments}.
  2283. @node Write Assignments Separately
  2284. @section Write Assignments in Separate Statements
  2285. It is often convenient to write an assignment inside an
  2286. @code{if}-condition, but that can reduce the readability of the
  2287. program. Here's an example of what to avoid:
  2288. @example
  2289. if (x = advance (x))
  2290. @r{@dots{}}
  2291. @end example
  2292. The idea here is to advance @code{x} and test if the value is nonzero.
  2293. However, readers might miss the fact that it uses @samp{=} and not
  2294. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2295. inside a condition is a common error, so GNU C can give warnings when
  2296. @samp{=} appears in a way that suggests it's an error.
  2297. It is much clearer to write the assignment as a separate statement, like this:
  2298. @example
  2299. x = advance (x);
  2300. if (x != 0)
  2301. @r{@dots{}}
  2302. @end example
  2303. @noindent
  2304. This makes it unmistakably clear that @code{x} is assigned a new value.
  2305. Another method is to use the comma operator (@pxref{Comma Operator}),
  2306. like this:
  2307. @example
  2308. if (x = advance (x), x != 0)
  2309. @r{@dots{}}
  2310. @end example
  2311. @noindent
  2312. However, putting the assignment in a separate statement is usually clearer
  2313. unless the assignment is very short, because it reduces nesting.
  2314. @node Execution Control Expressions
  2315. @chapter Execution Control Expressions
  2316. @cindex execution control expressions
  2317. @cindex expressions, execution control
  2318. This chapter describes the C operators that combine expressions to
  2319. control which of those expressions execute, or in which order.
  2320. @menu
  2321. * Logical Operators:: Logical conjunction, disjunction, negation.
  2322. * Logicals and Comparison:: Logical operators with comparison operators.
  2323. * Logicals and Assignments:: Assignments with logical operators.
  2324. * Conditional Expression:: An if/else construct inside expressions.
  2325. * Comma Operator:: Build a sequence of subexpressions.
  2326. @end menu
  2327. @node Logical Operators
  2328. @section Logical Operators
  2329. @cindex logical operators
  2330. @cindex operators, logical
  2331. @cindex conjunction operator
  2332. @cindex disjunction operator
  2333. @cindex negation operator, logical
  2334. The @dfn{logical operators} combine truth values, which are normally
  2335. represented in C as numbers. Any expression with a numeric value is a
  2336. valid truth value: zero means false, and any other value means true.
  2337. A pointer type is also meaningful as a truth value; a null pointer
  2338. (which is zero) means false, and a non-null pointer means true
  2339. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2340. or 0 and has type @code{int} (@pxref{Integer Types}).
  2341. The logical operators are used mainly in the condition of an @code{if}
  2342. statement, or in the end test in a @code{for} statement or
  2343. @code{while} statement (@pxref{Statements}). However, they are valid
  2344. in any context where an integer-valued expression is allowed.
  2345. @table @samp
  2346. @item ! @var{exp}
  2347. Unary operator for logical ``not.'' The value is 1 (true) if
  2348. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2349. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2350. function call, you should write parentheses around it.
  2351. @item @var{left} && @var{right}
  2352. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2353. @var{right}. If both of the operands are true, the @samp{&&} expression
  2354. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2355. gives the value 0 (false). If @var{left} yields a false value,
  2356. that determines the overall result, so @var{right} is not computed.
  2357. @item @var{left} || @var{right}
  2358. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2359. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2360. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2361. gives the value 0 (false). If @var{left} yields a true value,
  2362. that determines the overall result, so @var{right} is not computed.
  2363. @end table
  2364. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2365. and @samp{||}. When you use them together, always use parentheses to
  2366. specify explicitly how they nest, as shown here:
  2367. @example
  2368. if ((r != 0 && x % r == 0)
  2369. ||
  2370. (s != 0 && x % s == 0))
  2371. @end example
  2372. @node Logicals and Comparison
  2373. @section Logical Operators and Comparisons
  2374. The most common thing to use inside the logical operators is a
  2375. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2376. precedence than comparison operators and arithmetic operators, so we
  2377. can write expressions like this without parentheses and get the
  2378. nesting that is natural: two comparison operations that must both be
  2379. true.
  2380. @example
  2381. if (r != 0 && x % r == 0)
  2382. @end example
  2383. @noindent
  2384. This example also shows how it is useful that @samp{&&} guarantees to
  2385. skip the right operand if the left one turns out false. Because of
  2386. that, this code never tries to divide by zero.
  2387. This is equivalent:
  2388. @example
  2389. if (r && x % r == 0)
  2390. @end example
  2391. @noindent
  2392. A truth value is simply a number, so @code{r}
  2393. as a truth value tests whether it is nonzero.
  2394. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2395. So it is better style to write the explicit @code{!= 0}.
  2396. Here's another equivalent way to write it:
  2397. @example
  2398. if (!(r == 0) && x % r == 0)
  2399. @end example
  2400. @noindent
  2401. This illustrates the unary @samp{!} operator, and the need to
  2402. write parentheses around its operand.
  2403. @node Logicals and Assignments
  2404. @section Logical Operators and Assignments
  2405. There are cases where assignments nested inside the condition can
  2406. actually make a program @emph{easier} to read. Here is an example
  2407. using a hypothetical type @code{list} which represents a list; it
  2408. tests whether the list has at least two links, using hypothetical
  2409. functions, @code{nonempty} which is true of the argument is a nonempty
  2410. list, and @code{list_next} which advances from one list link to the
  2411. next. We assume that a list is never a null pointer, so that the
  2412. assignment expressions are always ``true.''
  2413. @example
  2414. if (nonempty (list)
  2415. && (temp1 = list_next (list))
  2416. && nonempty (temp1)
  2417. && (temp2 = list_next (temp1)))
  2418. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2419. @end example
  2420. @noindent
  2421. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2422. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2423. only natural place to put the assignments is among those calls.
  2424. It would be possible to rewrite this as several statements, but that
  2425. could make it much more cumbersome. On the other hand, when the test
  2426. is even more complex than this one, splitting it into multiple
  2427. statements might be necessary for clarity.
  2428. If an empty list is a null pointer, we can dispense with calling
  2429. @code{nonempty}:
  2430. @example
  2431. if ((temp1 = list_next (list))
  2432. && (temp2 = list_next (temp1)))
  2433. @r{@dots{}}
  2434. @end example
  2435. @node Conditional Expression
  2436. @section Conditional Expression
  2437. @cindex conditional expression
  2438. @cindex expression, conditional
  2439. C has a conditional expression that selects one of two expressions
  2440. to compute and get the value from. It looks like this:
  2441. @example
  2442. @var{condition} ? @var{iftrue} : @var{iffalse}
  2443. @end example
  2444. @menu
  2445. * Conditional Rules:: Rules for the conditional operator.
  2446. * Conditional Branches:: About the two branches in a conditional.
  2447. @end menu
  2448. @node Conditional Rules
  2449. @subsection Rules for Conditional Operator
  2450. The first operand, @var{condition}, should be a value that can be
  2451. compared with zero---a number or a pointer. If it is true (nonzero),
  2452. then the conditional expression computes @var{iftrue} and its value
  2453. becomes the value of the conditional expression. Otherwise the
  2454. conditional expression computes @var{iffalse} and its value becomes
  2455. the value of the conditional expression. The conditional expression
  2456. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2457. of them.
  2458. Here's an example: the absolute value of a number @code{x}
  2459. can be written as @code{(x >= 0 ? x : -x)}.
  2460. @strong{Warning:} The conditional expression operators have rather low
  2461. syntactic precedence. Except when the conditional expression is used
  2462. as an argument in a function call, write parentheses around it. For
  2463. clarity, always write parentheses around it if it extends across more
  2464. than one line.
  2465. Assignment operators and the comma operator (@pxref{Comma Operator})
  2466. have lower precedence than conditional expression operators, so write
  2467. parentheses around those when they appear inside a conditional
  2468. expression. @xref{Order of Execution}.
  2469. @node Conditional Branches
  2470. @subsection Conditional Operator Branches
  2471. @cindex branches of conditional expression
  2472. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2473. conditional.
  2474. The two branches should normally have the same type, but a few
  2475. exceptions are allowed. If they are both numeric types, the
  2476. conditional converts both to their common type (@pxref{Common Type}).
  2477. With pointers (@pxref{Pointers}), the two values can be pointers to
  2478. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2479. result type is a similar pointer whose target type combines all the
  2480. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2481. If one branch has type @code{void *} and the other is a pointer to an
  2482. object (not to a function), the conditional converts the @code{void *}
  2483. branch to the type of the other.
  2484. If one branch is an integer constant with value zero and the other is
  2485. a pointer, the conditional converts zero to the pointer's type.
  2486. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2487. that case, if @var{condition} is nonzero, its value becomes the value of
  2488. the conditional expression, after conversion to the common type.
  2489. Thus,
  2490. @example
  2491. x ? : y
  2492. @end example
  2493. @noindent
  2494. has the value of @code{x} if that is nonzero; otherwise, the value of
  2495. @code{y}.
  2496. @cindex side effect in ?:
  2497. @cindex ?: side effect
  2498. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2499. In that case, writing that expression twice would carry out the side
  2500. effects twice, but writing it once does them just once. For example,
  2501. if we suppose that the function @code{next_element} advances a pointer
  2502. variable to point to the next element in a list and returns the new
  2503. pointer,
  2504. @example
  2505. next_element () ? : default_pointer
  2506. @end example
  2507. @noindent
  2508. is a way to advance the pointer and use its new value if it isn't
  2509. null, but use @code{default_pointer} if that is null. We must not do
  2510. it this way,
  2511. @example
  2512. next_element () ? next_element () : default_pointer
  2513. @end example
  2514. @noindent
  2515. because it would advance the pointer a second time.
  2516. @node Comma Operator
  2517. @section Comma Operator
  2518. @cindex comma operator
  2519. @cindex operator, comma
  2520. The comma operator stands for sequential execution of expressions.
  2521. The value of the comma expression comes from the last expression in
  2522. the sequence; the previous expressions are computed only for their
  2523. side effects. It looks like this:
  2524. @example
  2525. @var{exp1}, @var{exp2} @r{@dots{}}
  2526. @end example
  2527. @noindent
  2528. You can bundle any number of expressions together this way, by putting
  2529. commas between them.
  2530. @menu
  2531. * Uses of Comma:: When to use the comma operator.
  2532. * Clean Comma:: Clean use of the comma operator.
  2533. * Avoid Comma:: When to not use the comma operator.
  2534. @end menu
  2535. @node Uses of Comma
  2536. @subsection The Uses of the Comma Operator
  2537. With commas, you can put several expressions into a place that
  2538. requires just one expression---for example, in the header of a
  2539. @code{for} statement. This statement
  2540. @example
  2541. for (i = 0, j = 10, k = 20; i < n; i++)
  2542. @end example
  2543. @noindent
  2544. contains three assignment expressions, to initialize @code{i}, @code{j}
  2545. and @code{k}. The syntax of @code{for} requires just one expression
  2546. for initialization; to include three assignments, we use commas to
  2547. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2548. 20}. This technique is also useful in the loop-advance expression,
  2549. the last of the three inside the @code{for} parentheses.
  2550. In the @code{for} statement and the @code{while} statement
  2551. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2552. effect before the loop-exit test. For example,
  2553. @example
  2554. while (printf ("At the test, x = %d\n", x), x != 0)
  2555. @end example
  2556. @node Clean Comma
  2557. @subsection Clean Use of the Comma Operator
  2558. Always write parentheses around a series of comma operators, except
  2559. when it is at top level in an expression statement, or within the
  2560. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2561. statement (@pxref{Statements}). For instance, in
  2562. @example
  2563. for (i = 0, j = 10, k = 20; i < n; i++)
  2564. @end example
  2565. @noindent
  2566. the commas between the assignments are clear because they are between
  2567. a parenthesis and a semicolon.
  2568. The arguments in a function call are also separated by commas, but that is
  2569. not an instance of the comma operator. Note the difference between
  2570. @example
  2571. foo (4, 5, 6)
  2572. @end example
  2573. @noindent
  2574. which passes three arguments to @code{foo} and
  2575. @example
  2576. foo ((4, 5, 6))
  2577. @end example
  2578. @noindent
  2579. which uses the comma operator and passes just one argument
  2580. (with value 6).
  2581. @strong{Warning:} don't use the comma operator around an argument
  2582. of a function unless it helps understand the code. When you do so,
  2583. don't put part of another argument on the same line. Instead, add a
  2584. line break to make the parentheses around the comma operator easier to
  2585. see, like this.
  2586. @example
  2587. foo ((mumble (x, y), frob (z)),
  2588. *p)
  2589. @end example
  2590. @node Avoid Comma
  2591. @subsection When Not to Use the Comma Operator
  2592. You can use a comma in any subexpression, but in most cases it only
  2593. makes the code confusing, and it is clearer to raise all but the last
  2594. of the comma-separated expressions to a higher level. Thus, instead
  2595. of this:
  2596. @example
  2597. x = (y += 4, 8);
  2598. @end example
  2599. @noindent
  2600. it is much clearer to write this:
  2601. @example
  2602. y += 4, x = 8;
  2603. @end example
  2604. @noindent
  2605. or this:
  2606. @example
  2607. y += 4;
  2608. x = 8;
  2609. @end example
  2610. Use commas only in the cases where there is no clearer alternative
  2611. involving multiple statements.
  2612. By contrast, don't hesitate to use commas in the expansion in a macro
  2613. definition. The trade-offs of code clarity are different in that
  2614. case, because the @emph{use} of the macro may improve overall clarity
  2615. so much that the ugliness of the macro's @emph{definition} is a small
  2616. price to pay. @xref{Macros}.
  2617. @node Binary Operator Grammar
  2618. @chapter Binary Operator Grammar
  2619. @cindex binary operator grammar
  2620. @cindex grammar, binary operator
  2621. @cindex operator precedence
  2622. @cindex precedence, operator
  2623. @cindex left-associative
  2624. @dfn{Binary operators} are those that take two operands, one
  2625. on the left and one on the right.
  2626. All the binary operators in C are syntactically left-associative.
  2627. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2628. @var{op} b) @var{op} c}}. However, you should only write repeated
  2629. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2630. @samp{/}, because those cases are clear from algebra. So it is ok to
  2631. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2632. c} or @code{a % b % c}.
  2633. Each C operator has a @dfn{precedence}, which is its rank in the
  2634. grammatical order of the various operators. The operators with the
  2635. highest precedence grab adjoining operands first; these expressions
  2636. then become operands for operators of lower precedence.
  2637. The precedence order of operators in C is fully specified, so any
  2638. combination of operations leads to a well-defined nesting. We state
  2639. only part of the full precedence ordering here because it is bad
  2640. practice for C code to depend on the other cases. For cases not
  2641. specified in this chapter, always use parentheses to make the nesting
  2642. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2643. remembering anything about the C precedence order beyond what's stated
  2644. here. I studied the full precedence table to write the parser, and
  2645. promptly forgot it again. If you need to look up the full precedence order
  2646. to understand some C code, fix the code with parentheses so nobody else
  2647. needs to do that.}
  2648. You can depend on this subsequence of the precedence ordering
  2649. (stated from highest precedence to lowest):
  2650. @enumerate
  2651. @item
  2652. Component access (@samp{.} and @samp{->}).
  2653. @item
  2654. Unary prefix operators.
  2655. @item
  2656. Unary postfix operators.
  2657. @item
  2658. Multiplication, division, and remainder (they have the same precedence).
  2659. @item
  2660. Addition and subtraction (they have the same precedence).
  2661. @item
  2662. Comparisons---but watch out!
  2663. @item
  2664. Logical operators @samp{&&} and @samp{||}---but watch out!
  2665. @item
  2666. Conditional expression with @samp{?} and @samp{:}.
  2667. @item
  2668. Assignments.
  2669. @item
  2670. Sequential execution (the comma operator, @samp{,}).
  2671. @end enumerate
  2672. Two of the lines in the above list say ``but watch out!'' That means
  2673. that the line covers operators with subtly different precedence.
  2674. Never depend on the grammar of C to decide how two comparisons nest;
  2675. instead, always use parentheses to specify their nesting.
  2676. You can let several @samp{&&} operators associate, or several
  2677. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2678. and @samp{||} nest with each other. @xref{Logical Operators}.
  2679. There is one other precedence ordering that code can depend on:
  2680. @enumerate
  2681. @item
  2682. Unary postfix operators.
  2683. @item
  2684. Bitwise and shift operators---but watch out!
  2685. @item
  2686. Conditional expression with @samp{?} and @samp{:}.
  2687. @end enumerate
  2688. The caveat for bitwise and shift operators is like that for logical
  2689. operators: you can let multiple uses of one bitwise operator
  2690. associate, but always use parentheses to control nesting of dissimilar
  2691. operators.
  2692. These lists do not specify any precedence ordering between the bitwise
  2693. and shift operators of the second list and the binary operators above
  2694. conditional expressions in the first list. When they come together,
  2695. parenthesize them. @xref{Bitwise Operations}.
  2696. @node Order of Execution
  2697. @chapter Order of Execution
  2698. @cindex order of execution
  2699. The order of execution of a C program is not always obvious, and not
  2700. necessarily predictable. This chapter describes what you can count on.
  2701. @menu
  2702. * Reordering of Operands:: Operations in C are not necessarily computed
  2703. in the order they are written.
  2704. * Associativity and Ordering:: Some associative operations are performed
  2705. in a particular order; others are not.
  2706. * Sequence Points:: Some guarantees about the order of operations.
  2707. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2708. * Ordering of Operands:: Evaluation order of operands
  2709. and function arguments.
  2710. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2711. only if it has no impact on program results.
  2712. @end menu
  2713. @node Reordering of Operands
  2714. @section Reordering of Operands
  2715. @cindex ordering of operands
  2716. @cindex reordering of operands
  2717. @cindex operand execution ordering
  2718. The C language does not necessarily carry out operations within an
  2719. expression in the order they appear in the code. For instance, in
  2720. this expression,
  2721. @example
  2722. foo () + bar ()
  2723. @end example
  2724. @noindent
  2725. @code{foo} might be called first or @code{bar} might be called first.
  2726. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2727. results can be unpredictable.
  2728. The unpredictable order of computation of subexpressions also makes a
  2729. difference when one of them contains an assignment. We already saw
  2730. this example of bad code,
  2731. @example
  2732. x = 20;
  2733. printf ("%d %d\n", x, x = 4);
  2734. @end example
  2735. @noindent
  2736. in which the second argument, @code{x}, has a different value
  2737. depending on whether it is computed before or after the assignment in
  2738. the third argument.
  2739. @node Associativity and Ordering
  2740. @section Associativity and Ordering
  2741. @cindex associativity and ordering
  2742. An associative binary operator, such as @code{+}, when used repeatedly
  2743. can combine any number of operands. The operands' values may be
  2744. computed in any order.
  2745. If the values are integers and overflow can be ignored, they may be
  2746. combined in any order. Thus, given four functions that return
  2747. @code{unsigned int}, calling them and adding their results as here
  2748. @example
  2749. (foo () + bar ()) + (baz () + quux ())
  2750. @end example
  2751. @noindent
  2752. may add up the results in any order.
  2753. By contrast, arithmetic on signed integers, with overflow significant,
  2754. is not really associative (@pxref{Integer Overflow}). Thus, the
  2755. additions must be done in the order specified, obeying parentheses and
  2756. left-association. That means computing @code{(foo () + bar ())} and
  2757. @code{(baz () + quux ())} first (in either order), then adding the
  2758. two.
  2759. The same applies to arithmetic on floating-point values, since that
  2760. too is not really associative. However, the GCC option
  2761. @option{-funsafe-math-optimizations} allows the compiler to change the
  2762. order of calculation when an associative operation (associative in
  2763. exact mathematics) combines several operands. The option takes effect
  2764. when compiling a module (@pxref{Compilation}). Changing the order
  2765. of association can enable the program to pipeline the floating point
  2766. operations.
  2767. In all these cases, the four function calls can be done in any order.
  2768. There is no right or wrong about that.
  2769. @node Sequence Points
  2770. @section Sequence Points
  2771. @cindex sequence points
  2772. @cindex full expression
  2773. There are some points in the code where C makes limited guarantees
  2774. about the order of operations. These are called @dfn{sequence
  2775. points}. Here is where they occur:
  2776. @itemize @bullet
  2777. @item
  2778. At the end of a @dfn{full expression}; that is to say, an expression
  2779. that is not part of a larger expression. All side effects specified
  2780. by that expression are carried out before execution moves
  2781. on to subsequent code.
  2782. @item
  2783. At the end of the first operand of certain operators: @samp{,},
  2784. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2785. that expression are carried out before any execution of the
  2786. next operand.
  2787. The commas that separate arguments in a function call are @emph{not}
  2788. comma operators, and they do not create sequence points. The rule
  2789. for function arguments and the rule for operands are different
  2790. (@pxref{Ordering of Operands}).
  2791. @item
  2792. Just before calling a function. All side effects specified by the
  2793. argument expressions are carried out before calling the function.
  2794. If the function to be called is not constant---that is, if it is
  2795. computed by an expression---all side effects in that expression are
  2796. carried out before calling the function.
  2797. @end itemize
  2798. The ordering imposed by a sequence point applies locally to a limited
  2799. range of code, as stated above in each case. For instance, the
  2800. ordering imposed by the comma operator does not apply to code outside
  2801. that comma operator. Thus, in this code,
  2802. @example
  2803. (x = 5, foo (x)) + x * x
  2804. @end example
  2805. @noindent
  2806. the sequence point of the comma operator orders @code{x = 5} before
  2807. @code{foo (x)}, but @code{x * x} could be computed before or after
  2808. them.
  2809. @node Postincrement and Ordering
  2810. @section Postincrement and Ordering
  2811. @cindex postincrement and ordering
  2812. @cindex ordering and postincrement
  2813. Ordering requirements are loose with the postincrement and
  2814. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2815. specify side effects to happen ``a little later.'' They must happen
  2816. before the next sequence point, but that still leaves room for various
  2817. meanings. In this expression,
  2818. @example
  2819. z = x++ - foo ()
  2820. @end example
  2821. @noindent
  2822. it's unpredictable whether @code{x} gets incremented before or after
  2823. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2824. it might see the old value or it might see the incremented value.
  2825. In this perverse expression,
  2826. @example
  2827. x = x++
  2828. @end example
  2829. @noindent
  2830. @code{x} will certainly be incremented but the incremented value may
  2831. not stick. If the incrementation of @code{x} happens after the
  2832. assignment to @code{x}, the incremented value will remain in place.
  2833. But if the incrementation happens first, the assignment will overwrite
  2834. that with the not-yet-incremented value, so the expression as a whole
  2835. will leave @code{x} unchanged.
  2836. @node Ordering of Operands
  2837. @section Ordering of Operands
  2838. @cindex ordering of operands
  2839. @cindex operand ordering
  2840. Operands and arguments can be computed in any order, but there are limits to
  2841. this intermixing in GNU C:
  2842. @itemize @bullet
  2843. @item
  2844. The operands of a binary arithmetic operator can be computed in either
  2845. order, but they can't be intermixed: one of them has to come first,
  2846. followed by the other. Any side effects in the operand that's computed
  2847. first are executed before the other operand is computed.
  2848. @item
  2849. That applies to assignment operators too, except that in simple assignment
  2850. the previous value of the left operand is unused.
  2851. @item
  2852. The arguments in a function call can be computed in any order, but
  2853. they can't be intermixed. Thus, one argument is fully computed, then
  2854. another, and so on until they are all done. Any side effects in one argument
  2855. are executed before computation of another argument begins.
  2856. @end itemize
  2857. These rules don't cover side effects caused by postincrement and
  2858. postdecrement operators---those can be deferred up to the next
  2859. sequence point.
  2860. If you want to get pedantic, the fact is that GCC can reorder the
  2861. computations in many other ways provided that doesn't alter the result
  2862. of running the program. However, because they don't alter the result
  2863. of running the program, they are negligible, unless you are concerned
  2864. with the values in certain variables at various times as seen by other
  2865. processes. In those cases, you can use @code{volatile} to prevent
  2866. optimizations that would make them behave strangely. @xref{volatile}.
  2867. @node Optimization and Ordering
  2868. @section Optimization and Ordering
  2869. @cindex optimization and ordering
  2870. @cindex ordering and optimization
  2871. Sequence points limit the compiler's freedom to reorder operations
  2872. arbitrarily, but optimizations can still reorder them if the compiler
  2873. concludes that this won't alter the results. Thus, in this code,
  2874. @example
  2875. x++;
  2876. y = z;
  2877. x++;
  2878. @end example
  2879. @noindent
  2880. there is a sequence point after each statement, so the code is
  2881. supposed to increment @code{x} once before the assignment to @code{y}
  2882. and once after. However, incrementing @code{x} has no effect on
  2883. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2884. the code could be optimized into this:
  2885. @example
  2886. y = z;
  2887. x += 2;
  2888. @end example
  2889. Normally that has no effect except to make the program faster. But
  2890. there are special situations where it can cause trouble due to things
  2891. that the compiler cannot know about, such as shared memory. To limit
  2892. optimization in those places, use the @code{volatile} type qualifier
  2893. (@pxref{volatile}).
  2894. @node Primitive Types
  2895. @chapter Primitive Data Types
  2896. @cindex primitive types
  2897. @cindex types, primitive
  2898. This chapter describes all the primitive data types of C---that is,
  2899. all the data types that aren't built up from other types. They
  2900. include the types @code{int} and @code{double} that we've already covered.
  2901. @menu
  2902. * Integer Types:: Description of integer types.
  2903. * Floating-Point Data Types:: Description of floating-point types.
  2904. * Complex Data Types:: Description of complex number types.
  2905. * The Void Type:: A type indicating no value at all.
  2906. * Other Data Types:: A brief summary of other types.
  2907. * Type Designators:: Referring to a data type abstractly.
  2908. @end menu
  2909. These types are all made up of bytes (@pxref{Storage}).
  2910. @node Integer Types
  2911. @section Integer Data Types
  2912. @cindex integer types
  2913. @cindex types, integer
  2914. Here we describe all the integer types and their basic
  2915. characteristics. @xref{Integers in Depth}, for more information about
  2916. the bit-level integer data representations and arithmetic.
  2917. @menu
  2918. * Basic Integers:: Overview of the various kinds of integers.
  2919. * Signed and Unsigned Types:: Integers can either hold both negative and
  2920. non-negative values, or only non-negative.
  2921. * Narrow Integers:: When to use smaller integer types.
  2922. * Integer Conversion:: Casting a value from one integer type
  2923. to another.
  2924. * Boolean Type:: An integer type for boolean values.
  2925. * Integer Variations:: Sizes of integer types can vary
  2926. across platforms.
  2927. @end menu
  2928. @node Basic Integers
  2929. @subsection Basic Integers
  2930. @findex char
  2931. @findex int
  2932. @findex short int
  2933. @findex long int
  2934. @findex long long int
  2935. Integer data types in C can be signed or unsigned. An unsigned type
  2936. can represent only positive numbers and zero. A signed type can
  2937. represent both positive and negative numbers, in a range spread almost
  2938. equally on both sides of zero.
  2939. Aside from signedness, the integer data types vary in size: how many
  2940. bytes long they are. The size determines how many different integer
  2941. values the type can hold.
  2942. Here's a list of the signed integer data types, with the sizes they
  2943. have on most computers. Each has a corresponding unsigned type; see
  2944. @ref{Signed and Unsigned Types}.
  2945. @table @code
  2946. @item signed char
  2947. One byte (8 bits). This integer type is used mainly for integers that
  2948. represent characters, as part of arrays or other data structures.
  2949. @item short
  2950. @itemx short int
  2951. Two bytes (16 bits).
  2952. @item int
  2953. Four bytes (32 bits).
  2954. @item long
  2955. @itemx long int
  2956. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2957. platform. Typically it is 32 bits on 32-bit computers
  2958. and 64 bits on 64-bit computers, but there are exceptions.
  2959. @item long long
  2960. @itemx long long int
  2961. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2962. incorporated into standard C as of ISO C99.
  2963. @end table
  2964. You can omit @code{int} when you use @code{long} or @code{short}.
  2965. This is harmless and customary.
  2966. @node Signed and Unsigned Types
  2967. @subsection Signed and Unsigned Types
  2968. @cindex signed types
  2969. @cindex unsigned types
  2970. @cindex types, signed
  2971. @cindex types, unsigned
  2972. @findex signed
  2973. @findex unsigned
  2974. An unsigned integer type can represent only positive numbers and zero.
  2975. A signed type can represent both positive and negative number, in a
  2976. range spread almost equally on both sides of zero. For instance,
  2977. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2978. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2979. these types holds 256 different possible values, since they are both 8
  2980. bits wide.
  2981. Write @code{signed} or @code{unsigned} before the type keyword to
  2982. specify a signed or an unsigned type. However, the integer types
  2983. other than @code{char} are signed by default; with them, @code{signed}
  2984. is a no-op.
  2985. Plain @code{char} may be signed or unsigned; this depends on the
  2986. compiler, the machine in use, and its operating system.
  2987. In many programs, it makes no difference whether @code{char} is
  2988. signed. When it does matter, don't leave it to chance; write
  2989. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2990. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2991. Arctic Char. When my meal arrived, I noted that the chef had not
  2992. signed it. So I complained, ``This char is unsigned---I wanted a
  2993. signed char!'' Or rather, I would have said this if I had thought of
  2994. it fast enough.}
  2995. @node Narrow Integers
  2996. @subsection Narrow Integers
  2997. The types that are narrower than @code{int} are rarely used for
  2998. ordinary variables---we declare them @code{int} instead. This is
  2999. because C converts those narrower types to @code{int} for any
  3000. arithmetic. There is literally no reason to declare a local variable
  3001. @code{char}, for instance.
  3002. In particular, if the value is really a character, you should declare
  3003. the variable @code{int}. Not @code{char}! Using that narrow type can
  3004. force the compiler to truncate values for conversion, which is a
  3005. waste. Furthermore, some functions return either a character value,
  3006. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3007. values distinct.
  3008. The narrow integer types are useful as parts of other objects, such as
  3009. arrays and structures. Compare these array declarations, whose sizes
  3010. on 32-bit processors are shown:
  3011. @example
  3012. signed char ac[1000]; /* @r{1000 bytes} */
  3013. short as[1000]; /* @r{2000 bytes} */
  3014. int ai[1000]; /* @r{4000 bytes} */
  3015. long long all[1000]; /* @r{8000 bytes} */
  3016. @end example
  3017. In addition, character strings must be made up of @code{char}s,
  3018. because that's what all the standard library string functions expect.
  3019. Thus, array @code{ac} could be used as a character string, but the
  3020. others could not be.
  3021. @node Integer Conversion
  3022. @subsection Conversion among Integer Types
  3023. C converts between integer types implicitly in many situations. It
  3024. converts the narrow integer types, @code{char} and @code{short}, to
  3025. @code{int} whenever they are used in arithmetic. Assigning a new
  3026. value to an integer variable (or other lvalue) converts the value to
  3027. the variable's type.
  3028. You can also convert one integer type to another explicitly with a
  3029. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3030. The process of conversion to a wider type is straightforward: the
  3031. value is unchanged. The only exception is when converting a negative
  3032. value (in a signed type, obviously) to a wider unsigned type. In that
  3033. case, the result is a positive value with the same bits
  3034. (@pxref{Integers in Depth}).
  3035. @cindex truncation
  3036. Converting to a narrower type, also called @dfn{truncation}, involves
  3037. discarding some of the value's bits. This is not considered overflow
  3038. (@pxref{Integer Overflow}) because loss of significant bits is a
  3039. normal consequence of truncation. Likewise for conversion between
  3040. signed and unsigned types of the same width.
  3041. More information about conversion for assignment is in
  3042. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3043. see @ref{Argument Promotions}.
  3044. @node Boolean Type
  3045. @subsection Boolean Type
  3046. @cindex boolean type
  3047. @cindex type, boolean
  3048. @findex bool
  3049. The unsigned integer type @code{bool} holds truth values: its possible
  3050. values are 0 and 1. Converting any nonzero value to @code{bool}
  3051. results in 1. For example:
  3052. @example
  3053. bool a = 0;
  3054. bool b = 1;
  3055. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3056. @end example
  3057. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3058. the header file @file{stdbool.h}.
  3059. @node Integer Variations
  3060. @subsection Integer Variations
  3061. The integer types of C have standard @emph{names}, but what they
  3062. @emph{mean} varies depending on the kind of platform in use:
  3063. which kind of computer, which operating system, and which compiler.
  3064. It may even depend on the compiler options used.
  3065. Plain @code{char} may be signed or unsigned; this depends on the
  3066. platform, too. Even for GNU C, there is no general rule.
  3067. In theory, all of the integer types' sizes can vary. @code{char} is
  3068. always considered one ``byte'' for C, but it is not necessarily an
  3069. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3070. specifies only that none of these types is narrower than the ones
  3071. above it in the list in @ref{Basic Integers}, and that @code{short}
  3072. has at least 16 bits.
  3073. It is possible that in the future GNU C will support platforms where
  3074. @code{int} is 64 bits long. In practice, however, on today's real
  3075. computers, there is little variation; you can rely on the table
  3076. given previously (@pxref{Basic Integers}).
  3077. To be completely sure of the size of an integer type,
  3078. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3079. Their corresponding unsigned types add @samp{u} at the front.
  3080. To define these, include the header file @file{stdint.h}.
  3081. The GNU C Compiler compiles for some embedded controllers that use two
  3082. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3083. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3084. 32 bits. These processors can't support an ordinary operating system
  3085. (they may have their own specialized operating systems), and most C
  3086. programs do not try to support them.
  3087. @node Floating-Point Data Types
  3088. @section Floating-Point Data Types
  3089. @cindex floating-point types
  3090. @cindex types, floating-point
  3091. @findex double
  3092. @findex float
  3093. @findex long double
  3094. @dfn{Floating point} is the binary analogue of scientific notation:
  3095. internally it represents a number as a fraction and a binary exponent; the
  3096. value is that fraction multiplied by the specified power of 2.
  3097. For instance, to represent 6, the fraction would be 0.75 and the
  3098. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3099. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3100. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3101. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3102. -1 as the exponent.
  3103. These binary exponents are used by machine instructions. You can
  3104. write a floating-point constant this way if you wish, using
  3105. hexadecimal; but normally we write floating-point numbers in decimal.
  3106. @xref{Floating Constants}.
  3107. C has three floating-point data types:
  3108. @table @code
  3109. @item double
  3110. ``Double-precision'' floating point, which uses 64 bits. This is the
  3111. normal floating-point type, and modern computers normally do
  3112. their floating-point computations in this type, or some wider type.
  3113. Except when there is a special reason to do otherwise, this is the
  3114. type to use for floating-point values.
  3115. @item float
  3116. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3117. for floating-point values stored in structures and arrays, to save
  3118. space when the full precision of @code{double} is not needed. In
  3119. addition, single-precision arithmetic is faster on some computers, and
  3120. occasionally that is useful. But not often---most programs don't use
  3121. the type @code{float}.
  3122. C would be cleaner if @code{float} were the name of the type we
  3123. use for most floating-point values; however, for historical reasons,
  3124. that's not so.
  3125. @item long double
  3126. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3127. precision, depending on the machine in use. On some machines, which
  3128. have no floating-point format wider than @code{double}, this is
  3129. equivalent to @code{double}.
  3130. @end table
  3131. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3132. Point in Depth}, for more information.
  3133. @node Complex Data Types
  3134. @section Complex Data Types
  3135. @cindex complex numbers
  3136. @cindex types, complex
  3137. @cindex @code{_Complex} keyword
  3138. @cindex @code{__complex__} keyword
  3139. @findex _Complex
  3140. @findex __complex__
  3141. Complex numbers can include both a real part and an imaginary part.
  3142. The numeric constants covered above have real-numbered values. An
  3143. imaginary-valued constant is an ordinary real-valued constant followed
  3144. by @samp{i}.
  3145. To declare numeric variables as complex, use the @code{_Complex}
  3146. keyword.@footnote{For compatibility with older versions of GNU C, the
  3147. keyword @code{__complex__} is also allowed. Going forward, however,
  3148. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3149. standard C complex data types are floating point,
  3150. @example
  3151. _Complex float foo;
  3152. _Complex double bar;
  3153. _Complex long double quux;
  3154. @end example
  3155. @noindent
  3156. but GNU C supports integer complex types as well.
  3157. Since @code{_Complex} is a keyword just like @code{float} and
  3158. @code{double} and @code{long}, the keywords can appear in any order,
  3159. but the order shown above seems most logical.
  3160. GNU C supports constants for complex values; for instance, @code{4.0 +
  3161. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3162. @xref{Imaginary Constants}.
  3163. To pull the real and imaginary parts of the number back out, GNU C
  3164. provides the keywords @code{__real__} and @code{__imag__}:
  3165. @example
  3166. _Complex double foo = 4.0 + 3.0i;
  3167. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3168. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3169. @end example
  3170. @noindent
  3171. Standard C does not include these keywords, and instead relies on
  3172. functions defined in @code{complex.h} for accessing the real and
  3173. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3174. @code{creall} extract the real part of a float, double, or long double
  3175. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3176. @code{cimagl} extract the imaginary part.
  3177. @cindex complex conjugation
  3178. GNU C also defines @samp{~} as an operator for complex conjugation,
  3179. which means negating the imaginary part of a complex number:
  3180. @example
  3181. _Complex double foo = 4.0 + 3.0i;
  3182. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3183. @end example
  3184. @noindent
  3185. For standard C compatibility, you can use the appropriate library
  3186. function: @code{conjf}, @code{conj}, or @code{confl}.
  3187. @node The Void Type
  3188. @section The Void Type
  3189. @cindex void type
  3190. @cindex type, void
  3191. @findex void
  3192. The data type @code{void} is a dummy---it allows no operations. It
  3193. really means ``no value at all.'' When a function is meant to return
  3194. no value, we write @code{void} for its return type. Then
  3195. @code{return} statements in that function should not specify a value
  3196. (@pxref{return Statement}). Here's an example:
  3197. @example
  3198. void
  3199. print_if_positive (double x, double y)
  3200. @{
  3201. if (x <= 0)
  3202. return;
  3203. if (y <= 0)
  3204. return;
  3205. printf ("Next point is (%f,%f)\n", x, y);
  3206. @}
  3207. @end example
  3208. A @code{void}-returning function is comparable to what some other languages
  3209. call a ``procedure'' instead of a ``function.''
  3210. @c ??? Already presented
  3211. @c @samp{%f} in an output template specifies to format a @code{double} value
  3212. @c as a decimal number, using a decimal point if needed.
  3213. @node Other Data Types
  3214. @section Other Data Types
  3215. Beyond the primitive types, C provides several ways to construct new
  3216. data types. For instance, you can define @dfn{pointers}, values that
  3217. represent the addresses of other data (@pxref{Pointers}). You can
  3218. define @dfn{structures}, as in many other languages
  3219. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3220. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3221. are collections of named integer codes (@pxref{Enumeration Types}).
  3222. @dfn{Array types} in C are used for allocating space for objects,
  3223. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3224. @node Type Designators
  3225. @section Type Designators
  3226. @cindex type designator
  3227. Some C constructs require a way to designate a specific data type
  3228. independent of any particular variable or expression which has that
  3229. type. The way to do this is with a @dfn{type designator}. The
  3230. constucts that need one include casts (@pxref{Explicit Type
  3231. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3232. We also use type designators to talk about the type of a value in C,
  3233. so you will see many type designators in this manual. When we say,
  3234. ``The value has type @code{int},'' @code{int} is a type designator.
  3235. To make the designator for any type, imagine a variable declaration
  3236. for a variable of that type and delete the variable name and the final
  3237. semicolon.
  3238. For example, to designate the type of full-word integers, we start
  3239. with the declaration for a variable @code{foo} with that type,
  3240. which is this:
  3241. @example
  3242. int foo;
  3243. @end example
  3244. @noindent
  3245. Then we delete the variable name @code{foo} and the semicolon, leaving
  3246. @code{int}---exactly the keyword used in such a declaration.
  3247. Therefore, the type designator for this type is @code{int}.
  3248. What about long unsigned integers? From the declaration
  3249. @example
  3250. unsigned long int foo;
  3251. @end example
  3252. @noindent
  3253. we determine that the designator is @code{unsigned long int}.
  3254. Following this procedure, the designator for any primitive type is
  3255. simply the set of keywords which specifies that type in a declaration.
  3256. The same is true for compound types such as structures, unions, and
  3257. enumerations.
  3258. Designators for pointer types do follow the rule of deleting the
  3259. variable name and semicolon, but the result is not so simple.
  3260. @xref{Pointer Type Designators}, as part of the chapter about
  3261. pointers. @xref{Array Type Designators}), for designators for array
  3262. types.
  3263. To understand what type a designator stands for, imagine a variable
  3264. name inserted into the right place in the designator to make a valid
  3265. declaration. What type would that variable be declared as? That is the
  3266. type the designator designates.
  3267. @node Constants
  3268. @chapter Constants
  3269. @cindex constants
  3270. A @dfn{constant} is an expression that stands for a specific value by
  3271. explicitly representing the desired value. C allows constants for
  3272. numbers, characters, and strings. We have already seen numeric and
  3273. string constants in the examples.
  3274. @menu
  3275. * Integer Constants:: Literal integer values.
  3276. * Integer Const Type:: Types of literal integer values.
  3277. * Floating Constants:: Literal floating-point values.
  3278. * Imaginary Constants:: Literal imaginary number values.
  3279. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3280. * Character Constants:: Literal character values.
  3281. * String Constants:: Literal string values.
  3282. * UTF-8 String Constants:: Literal UTF-8 string values.
  3283. * Unicode Character Codes:: Unicode characters represented
  3284. in either UTF-16 or UTF-32.
  3285. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3286. * Wide String Constants:: Literal string values made up of
  3287. 16- or 32-bit characters.
  3288. @end menu
  3289. @node Integer Constants
  3290. @section Integer Constants
  3291. @cindex integer constants
  3292. @cindex constants, integer
  3293. An integer constant consists of a number to specify the value,
  3294. followed optionally by suffix letters to specify the data type.
  3295. The simplest integer constants are numbers written in base 10
  3296. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3297. constant cannot start with the character @samp{0} (zero) because
  3298. that makes the constant octal.
  3299. You can get the effect of a negative integer constant by putting a
  3300. minus sign at the beginning. Grammatically speaking, that is an
  3301. arithmetic expression rather than a constant, but it behaves just like
  3302. a true constant.
  3303. Integer constants can also be written in octal (base 8), hexadecimal
  3304. (base 16), or binary (base 2). An octal constant starts with the
  3305. character @samp{0} (zero), followed by any number of octal digits
  3306. (@samp{0} to @samp{7}):
  3307. @example
  3308. 0 // @r{zero}
  3309. 077 // @r{63}
  3310. 0403 // @r{259}
  3311. @end example
  3312. @noindent
  3313. Pedantically speaking, the constant @code{0} is an octal constant, but
  3314. we can think of it as decimal; it has the same value either way.
  3315. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3316. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3317. through @samp{f} in upper or lower case):
  3318. @example
  3319. 0xff // @r{255}
  3320. 0XA0 // @r{160}
  3321. 0xffFF // @r{65535}
  3322. @end example
  3323. @cindex binary integer constants
  3324. A binary constant starts with @samp{0b} (upper or lower case) followed
  3325. by bits (each represented by the characters @samp{0} or @samp{1}):
  3326. @example
  3327. 0b101 // @r{5}
  3328. @end example
  3329. Binary constants are a GNU C extension, not part of the C standard.
  3330. Sometimes a space is needed after an integer constant to avoid
  3331. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3332. @node Integer Const Type
  3333. @section Integer Constant Data Types
  3334. @cindex integer constant data types
  3335. @cindex constant data types, integer
  3336. @cindex types of integer constants
  3337. The type of an integer constant is normally @code{int}, if the value
  3338. fits in that type, but here are the complete rules. The type
  3339. of an integer constant is the first one in this sequence that can
  3340. properly represent the value,
  3341. @enumerate
  3342. @item
  3343. @code{int}
  3344. @item
  3345. @code{unsigned int}
  3346. @item
  3347. @code{long int}
  3348. @item
  3349. @code{unsigned long int}
  3350. @item
  3351. @code{long long int}
  3352. @item
  3353. @code{unsigned long long int}
  3354. @end enumerate
  3355. @noindent
  3356. and that isn't excluded by the following rules.
  3357. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3358. first two types (non-@code{long}).
  3359. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3360. first four types (non-@code{long long}).
  3361. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3362. the signed types.
  3363. Otherwise, if the constant is decimal, that excludes the unsigned
  3364. types.
  3365. @c ### This said @code{unsigned int} is excluded.
  3366. @c ### See 17 April 2016
  3367. Here are some examples of the suffixes.
  3368. @example
  3369. 3000000000u // @r{three billion as @code{unsigned int}.}
  3370. 0LL // @r{zero as a @code{long long int}.}
  3371. 0403l // @r{259 as a @code{long int}.}
  3372. @end example
  3373. Suffixes in integer constants are rarely used. When the precise type
  3374. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3375. Type Conversion}).
  3376. @xref{Integer Types}.
  3377. @node Floating Constants
  3378. @section Floating-Point Constants
  3379. @cindex floating-point constants
  3380. @cindex constants, floating-point
  3381. A floating-point constant must have either a decimal point, an
  3382. exponent-of-ten, or both; they distinguish it from an integer
  3383. constant.
  3384. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3385. value follows. It is always written as a decimal number; it can
  3386. optionally start with a sign. The exponent @var{n} means to multiply
  3387. the constant's value by ten to the @var{n}th power.
  3388. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3389. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3390. writing a floating-point number whose value is 1500. They are all
  3391. equivalent.
  3392. Here are more examples with decimal points:
  3393. @example
  3394. 1.0
  3395. 1000.
  3396. 3.14159
  3397. .05
  3398. .0005
  3399. @end example
  3400. For each of them, here are some equivalent constants written with
  3401. exponents:
  3402. @example
  3403. 1e0, 1.0000e0
  3404. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3405. 3.14159e0
  3406. 5e-2, .0005e+2, 5E-2, .0005E2
  3407. .05e-2
  3408. @end example
  3409. A floating-point constant normally has type @code{double}. You can
  3410. force it to type @code{float} by adding @samp{f} or @samp{F}
  3411. at the end. For example,
  3412. @example
  3413. 3.14159f
  3414. 3.14159e0f
  3415. 1000.f
  3416. 100E1F
  3417. .0005f
  3418. .05e-2f
  3419. @end example
  3420. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3421. to type @code{long double}.
  3422. You can use exponents in hexadecimal floating constants, but since
  3423. @samp{e} would be interpreted as a hexadecimal digit, the character
  3424. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3425. The exponent in a hexadecimal floating constant is a possibly-signed
  3426. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3427. multiply into the number.
  3428. Here are some examples:
  3429. @example
  3430. @group
  3431. 0xAp2 // @r{40 in decimal}
  3432. 0xAp-1 // @r{5 in decimal}
  3433. 0x2.0Bp4 // @r{16.75 decimal}
  3434. 0xE.2p3 // @r{121 decimal}
  3435. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3436. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3437. 0x100p-8 // @r{1}
  3438. 0x10p-4 // @r{1}
  3439. 0x1p+4 // @r{16}
  3440. 0x1p+8 // @r{256}
  3441. @end group
  3442. @end example
  3443. @xref{Floating-Point Data Types}.
  3444. @node Imaginary Constants
  3445. @section Imaginary Constants
  3446. @cindex imaginary constants
  3447. @cindex complex constants
  3448. @cindex constants, imaginary
  3449. A complex number consists of a real part plus an imaginary part.
  3450. (Either or both parts may be zero.) This section explains how to
  3451. write numeric constants with imaginary values. By adding these to
  3452. ordinary real-valued numeric constants, we can make constants with
  3453. complex values.
  3454. The simple way to write an imaginary-number constant is to attach the
  3455. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3456. floating-point constant. For example, @code{2.5fi} has type
  3457. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3458. The four alternative suffix letters are all equivalent.
  3459. @cindex _Complex_I
  3460. The other way to write an imaginary constant is to multiply a real
  3461. constant by @code{_Complex_I}, which represents the imaginary number
  3462. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3463. this clunky way is needed.
  3464. To write a complex constant with a nonzero real part and a nonzero
  3465. imaginary part, write the two separately and add them, like this:
  3466. @example
  3467. 4.0 + 3.0i
  3468. @end example
  3469. @noindent
  3470. That gives the value 4 + 3i, with type @code{_Complex double}.
  3471. Such a sum can include multiple real constants, or none. Likewise, it
  3472. can include multiple imaginary constants, or none. For example:
  3473. @example
  3474. _Complex double foo, bar, quux;
  3475. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3476. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3477. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3478. @end example
  3479. @xref{Complex Data Types}.
  3480. @node Invalid Numbers
  3481. @section Invalid Numbers
  3482. Some number-like constructs which are not really valid as numeric
  3483. constants are treated as numbers in preprocessing directives. If
  3484. these constructs appear outside of preprocessing, they are erroneous.
  3485. @xref{Preprocessing Tokens}.
  3486. Sometimes we need to insert spaces to separate tokens so that they
  3487. won't be combined into a single number-like construct. For example,
  3488. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3489. constant, so it is a syntax error. If what we want is the three
  3490. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3491. @node Character Constants
  3492. @section Character Constants
  3493. @cindex character constants
  3494. @cindex constants, character
  3495. @cindex escape sequence
  3496. A @dfn{character constant} is written with single quotes, as in
  3497. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3498. character that the constant should represent. The constant has type
  3499. @code{int}, and its value is the character code of that character.
  3500. For instance, @code{'a'} represents the character code for the letter
  3501. @samp{a}: 97, that is.
  3502. To put the @samp{'} character (single quote) in the character
  3503. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3504. constant looks like @code{'\''}. This sort of sequence, starting with
  3505. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3506. here functions as a kind of @dfn{escape character}.
  3507. To put the @samp{\} character (backslash) in the character constant,
  3508. quote it likewise with @samp{\} (another backslash). This character
  3509. constant looks like @code{'\\'}.
  3510. @cindex bell character
  3511. @cindex @samp{\a}
  3512. @cindex backspace
  3513. @cindex @samp{\b}
  3514. @cindex tab (ASCII character)
  3515. @cindex @samp{\t}
  3516. @cindex vertical tab
  3517. @cindex @samp{\v}
  3518. @cindex formfeed
  3519. @cindex @samp{\f}
  3520. @cindex newline
  3521. @cindex @samp{\n}
  3522. @cindex return (ASCII character)
  3523. @cindex @samp{\r}
  3524. @cindex escape (ASCII character)
  3525. @cindex @samp{\e}
  3526. Here are all the escape sequences that represent specific
  3527. characters in a character constant. The numeric values shown are
  3528. the corresponding ASCII character codes, as decimal numbers.
  3529. @example
  3530. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3531. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3532. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3533. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3534. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3535. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3536. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3537. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3538. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3539. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3540. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3541. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3542. @end example
  3543. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3544. You can also write octal and hex character codes as
  3545. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3546. option here, so octal codes do not need to start with @samp{0}.
  3547. The character constant's value has type @code{int}. However, the
  3548. character code is treated initially as a @code{char} value, which is
  3549. then converted to @code{int}. If the character code is greater than
  3550. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3551. on a platform where the type @code{char} is 8 bits long and signed.
  3552. @node String Constants
  3553. @section String Constants
  3554. @cindex string constants
  3555. @cindex constants, string
  3556. A @dfn{string constant} represents a series of characters. It starts
  3557. with @samp{"} and ends with @samp{"}; in between are the contents of
  3558. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3559. newline in the contents works in string constants as in character
  3560. constants. In a string constant, @samp{'} does not need to be quoted.
  3561. A string constant defines an array of characters which contains the
  3562. specified characters followed by the null character (code 0). Using
  3563. the string constant is equivalent to using the name of an array with
  3564. those contents. In simple cases, the length in bytes of the string
  3565. constant is one greater than the number of characters written in it.
  3566. As with any array in C, using the string constant in an expression
  3567. converts the array to a pointer (@pxref{Pointers}) to the array's
  3568. first element (@pxref{Accessing Array Elements}). This pointer will
  3569. have type @code{char *} because it points to an element of type
  3570. @code{char}. @code{char *} is an example of a type designator for a
  3571. pointer type (@pxref{Pointer Type Designators}). That type is used
  3572. for strings generally, not just the strings expressed as constants
  3573. in a program.
  3574. Thus, the string constant @code{"Foo!"} is almost
  3575. equivalent to declaring an array like this
  3576. @example
  3577. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3578. @end example
  3579. @noindent
  3580. and then using @code{string_array_1} in the program. There
  3581. are two differences, however:
  3582. @itemize @bullet
  3583. @item
  3584. The string constant doesn't define a name for the array.
  3585. @item
  3586. The string constant is probably stored in a read-only area of memory.
  3587. @end itemize
  3588. Newlines are not allowed in the text of a string constant. The motive
  3589. for this prohibition is to catch the error of omitting the closing
  3590. @samp{"}. To put a newline in a constant string, write it as
  3591. @samp{\n} in the string constant.
  3592. A real null character in the source code inside a string constant
  3593. causes a warning. To put a null character in the middle of a string
  3594. constant, write @samp{\0} or @samp{\000}.
  3595. Consecutive string constants are effectively concatenated. Thus,
  3596. @example
  3597. "Fo" "o!" @r{is equivalent to} "Foo!"
  3598. @end example
  3599. This is useful for writing a string containing multiple lines,
  3600. like this:
  3601. @example
  3602. "This message is so long that it needs more than\n"
  3603. "a single line of text. C does not allow a newline\n"
  3604. "to represent itself in a string constant, so we have to\n"
  3605. "write \\n to put it in the string. For readability of\n"
  3606. "the source code, it is advisable to put line breaks in\n"
  3607. "the source where they occur in the contents of the\n"
  3608. "constant.\n"
  3609. @end example
  3610. The sequence of a backslash and a newline is ignored anywhere
  3611. in a C program, and that includes inside a string constant.
  3612. Thus, you can write multi-line string constants this way:
  3613. @example
  3614. "This is another way to put newlines in a string constant\n\
  3615. and break the line after them in the source code."
  3616. @end example
  3617. @noindent
  3618. However, concatenation is the recommended way to do this.
  3619. You can also write perverse string constants like this,
  3620. @example
  3621. "Fo\
  3622. o!"
  3623. @end example
  3624. @noindent
  3625. but don't do that---write it like this instead:
  3626. @example
  3627. "Foo!"
  3628. @end example
  3629. Be careful to avoid passing a string constant to a function that
  3630. modifies the string it receives. The memory where the string constant
  3631. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3632. signal that normally terminates the function (@pxref{Signals}. Even
  3633. worse, the memory may not be read-only. Then the function might
  3634. modify the string constant, thus spoiling the contents of other string
  3635. constants that are supposed to contain the same value and are unified
  3636. by the compiler.
  3637. @node UTF-8 String Constants
  3638. @section UTF-8 String Constants
  3639. @cindex UTF-8 String Constants
  3640. Writing @samp{u8} immediately before a string constant, with no
  3641. intervening space, means to represent that string in UTF-8 encoding as
  3642. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3643. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3644. as multibyte sequences. Here is an example of a UTF-8 constant:
  3645. @example
  3646. u8"A cónstàñt"
  3647. @end example
  3648. This constant occupies 13 bytes plus the terminating null,
  3649. because each of the accented letters is a two-byte sequence.
  3650. Concatenating an ordinary string with a UTF-8 string conceptually
  3651. produces another UTF-8 string. However, if the ordinary string
  3652. contains character codes 128 and up, the results cannot be relied on.
  3653. @node Unicode Character Codes
  3654. @section Unicode Character Codes
  3655. @cindex Unicode character codes
  3656. @cindex universal character names
  3657. You can specify Unicode characters, for individual character constants
  3658. or as part of string constants (@pxref{String Constants}), using
  3659. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3660. hexadecimal Unicode character code. If the code value is too big for
  3661. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3662. Unicode character code. (These codes are called @dfn{universal
  3663. character names}.) For example,
  3664. @example
  3665. \u6C34 /* @r{16-bit code (UTF-16)} */
  3666. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3667. @end example
  3668. @noindent
  3669. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3670. Constants}). For instance,
  3671. @example
  3672. u8"fóó \u6C34 \U0010ABCD"
  3673. @end example
  3674. You can also use them in wide character constants (@pxref{Wide
  3675. Character Constants}), like this:
  3676. @example
  3677. u'\u6C34' /* @r{16-bit code} */
  3678. U'\U0010ABCD' /* @r{32-bit code} */
  3679. @end example
  3680. @noindent
  3681. and in wide string constants (@pxref{Wide String Constants}), like
  3682. this:
  3683. @example
  3684. u"\u6C34\u6C33" /* @r{16-bit code} */
  3685. U"\U0010ABCD" /* @r{32-bit code} */
  3686. @end example
  3687. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3688. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3689. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3690. actually ASCII control characters, and you can specify them with other
  3691. escape sequences (@pxref{Character Constants}).
  3692. @node Wide Character Constants
  3693. @section Wide Character Constants
  3694. @cindex wide character constants
  3695. @cindex constants, wide character
  3696. A @dfn{wide character constant} represents characters with more than 8
  3697. bits of character code. This is an obscure feature that we need to
  3698. document but that you probably won't ever use. If you're just
  3699. learning C, you may as well skip this section.
  3700. The original C wide character constant looks like @samp{L} (upper
  3701. case!) followed immediately by an ordinary character constant (with no
  3702. intervening space). Its data type is @code{wchar_t}, which is an
  3703. alias defined in @file{stddef.h} for one of the standard integer
  3704. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3705. it is 16 bits, these character constants use the UTF-16 form of
  3706. Unicode; if 32 bits, UTF-32.
  3707. There are also Unicode wide character constants which explicitly
  3708. specify the width. These constants start with @samp{u} or @samp{U}
  3709. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3710. character constant, and @samp{U} a 32-bit Unicode wide character
  3711. constant. Their types are, respectively, @code{char16_t} and
  3712. @w{@code{char32_t}}; they are declared in the header file
  3713. @file{uchar.h}. These character constants are valid even if
  3714. @file{uchar.h} is not included, but some uses of them may be
  3715. inconvenient without including it to declare those type names.
  3716. The character represented in a wide character constant can be an
  3717. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3718. are all valid, and they are all equal to @code{'a'}.
  3719. In all three kinds of wide character constants, you can write a
  3720. non-ASCII Unicode character in the constant itself; the constant's
  3721. value is the character's Unicode character code. Or you can specify
  3722. the Unicode character with an escape sequence (@pxref{Unicode
  3723. Character Codes}).
  3724. @node Wide String Constants
  3725. @section Wide String Constants
  3726. @cindex wide string constants
  3727. @cindex constants, wide string
  3728. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3729. characters. They are rarely used; if you're just
  3730. learning C, you may as well skip this section.
  3731. There are three kinds of wide string constants, which differ in the
  3732. data type used for each character in the string. Each wide string
  3733. constant is equivalent to an array of integers, but the data type of
  3734. those integers depends on the kind of wide string. Using the constant
  3735. in an expression will convert the array to a pointer to its first
  3736. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3737. For each kind of wide string constant, we state here what type that
  3738. pointer will be.
  3739. @table @code
  3740. @item char16_t
  3741. This is a 16-bit Unicode wide string constant: each element is a
  3742. 16-bit Unicode character code with type @code{char16_t}, so the string
  3743. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3744. @pxref{Pointer Type Designators}.) The constant is written as
  3745. @samp{u} (which must be lower case) followed (with no intervening
  3746. space) by a string constant with the usual syntax.
  3747. @item char32_t
  3748. This is a 32-bit Unicode wide string constant: each element is a
  3749. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3750. It's written as @samp{U} (which must be upper case) followed (with no
  3751. intervening space) by a string constant with the usual syntax.
  3752. @item wchar_t
  3753. This is the original kind of wide string constant. It's written as
  3754. @samp{L} (which must be upper case) followed (with no intervening
  3755. space) by a string constant with the usual syntax, and the string has
  3756. type @code{wchar_t@ *}.
  3757. The width of the data type @code{wchar_t} depends on the target
  3758. platform, which makes this kind of wide string somewhat less useful
  3759. than the newer kinds.
  3760. @end table
  3761. @code{char16_t} and @code{char32_t} are declared in the header file
  3762. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3763. Consecutive wide string constants of the same kind concatenate, just
  3764. like ordinary string constants. A wide string constant concatenated
  3765. with an ordinary string constant results in a wide string constant.
  3766. You can't concatenate two wide string constants of different kinds.
  3767. You also can't concatenate a wide string constant (of any kind) with a
  3768. UTF-8 string constant.
  3769. @node Type Size
  3770. @chapter Type Size
  3771. @cindex type size
  3772. @cindex size of type
  3773. @findex sizeof
  3774. Each data type has a @dfn{size}, which is the number of bytes
  3775. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3776. a C program, use @code{sizeof}. There are two ways to use it:
  3777. @table @code
  3778. @item sizeof @var{expression}
  3779. This gives the size of @var{expression}, based on its data type. It
  3780. does not calculate the value of @var{expression}, only its size, so if
  3781. @var{expression} includes side effects or function calls, they do not
  3782. happen. Therefore, @code{sizeof} is always a compile-time operation
  3783. that has zero run-time cost.
  3784. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3785. operand of @code{sizeof}.
  3786. For example,
  3787. @example
  3788. double a;
  3789. i = sizeof a + 10;
  3790. @end example
  3791. @noindent
  3792. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3793. Here's how to determine the number of elements in an array
  3794. @code{array}:
  3795. @example
  3796. (sizeof array / sizeof array[0])
  3797. @end example
  3798. @noindent
  3799. The expression @code{sizeof array} gives the size of the array, not
  3800. the size of a pointer to an element. However, if @var{expression} is
  3801. a function parameter that was declared as an array, that
  3802. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3803. the result is the size of that pointer.
  3804. @item sizeof (@var{type})
  3805. This gives the size of @var{type}.
  3806. For example,
  3807. @example
  3808. i = sizeof (double) + 10;
  3809. @end example
  3810. @noindent
  3811. is equivalent to the previous example.
  3812. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3813. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3814. C, which makes adding an integer to a function pointer work as desired
  3815. (@pxref{Pointer Arithmetic}).
  3816. @end table
  3817. @strong{Warning}: When you use @code{sizeof} with a type
  3818. instead of an expression, you must write parentheses around the type.
  3819. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3820. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3821. the cast expression to avoid an ambiguity in the grammar of C@.
  3822. Specifically,
  3823. @example
  3824. sizeof (int) -x
  3825. @end example
  3826. @noindent
  3827. parses as
  3828. @example
  3829. (sizeof (int)) - x
  3830. @end example
  3831. @noindent
  3832. If what you want is
  3833. @example
  3834. sizeof ((int) -x)
  3835. @end example
  3836. @noindent
  3837. you must write it that way, with parentheses.
  3838. The data type of the value of the @code{sizeof} operator is always one
  3839. of the unsigned integer types; which one of those types depends on the
  3840. machine. The header file @code{stddef.h} defines the typedef name
  3841. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3842. Names}.
  3843. @node Pointers
  3844. @chapter Pointers
  3845. @cindex pointers
  3846. Among high-level languages, C is rather low level, close to the
  3847. machine. This is mainly because it has explicit @dfn{pointers}. A
  3848. pointer value is the numeric address of data in memory. The type of
  3849. data to be found at that address is specified by the data type of the
  3850. pointer itself. The unary operator @samp{*} gets the data that a
  3851. pointer points to---this is called @dfn{dereferencing the pointer}.
  3852. C also allows pointers to functions, but since there are some
  3853. differences in how they work, we treat them later. @xref{Function
  3854. Pointers}.
  3855. @menu
  3856. * Address of Data:: Using the ``address-of'' operator.
  3857. * Pointer Types:: For each type, there is a pointer type.
  3858. * Pointer Declarations:: Declaring variables with pointer types.
  3859. * Pointer Type Designators:: Designators for pointer types.
  3860. * Pointer Dereference:: Accessing what a pointer points at.
  3861. * Null Pointers:: Pointers which do not point to any object.
  3862. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3863. * Void Pointers:: Totally generic pointers, can cast to any.
  3864. * Pointer Comparison:: Comparing memory address values.
  3865. * Pointer Arithmetic:: Computing memory address values.
  3866. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3867. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3868. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3869. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3870. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3871. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3872. @end menu
  3873. @node Address of Data
  3874. @section Address of Data
  3875. @cindex address-of operator
  3876. The most basic way to make a pointer is with the ``address-of''
  3877. operator, @samp{&}. Let's suppose we have these variables available:
  3878. @example
  3879. int i;
  3880. double a[5];
  3881. @end example
  3882. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3883. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3884. address of the element 3 of @code{a}. (It is actually the fourth
  3885. element in the array, since the first element has index 0.)
  3886. The address-of operator is unusual because it operates on a place to
  3887. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3888. stored there. (The left argument of a simple assignment is unusual in
  3889. the same way.) You can use it on any lvalue except a bit field
  3890. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3891. Constructors}).
  3892. @node Pointer Types
  3893. @section Pointer Types
  3894. For each data type @var{t}, there is a type for pointers to type
  3895. @var{t}. For these variables,
  3896. @example
  3897. int i;
  3898. double a[5];
  3899. @end example
  3900. @itemize @bullet
  3901. @item
  3902. @code{i} has type @code{int}; we say
  3903. @code{&i} is a ``pointer to @code{int}.''
  3904. @item
  3905. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3906. arrays of five @code{double}s.''
  3907. @item
  3908. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3909. to @code{double}.''
  3910. @end itemize
  3911. @node Pointer Declarations
  3912. @section Pointer-Variable Declarations
  3913. The way to declare that a variable @code{foo} points to type @var{t} is
  3914. @example
  3915. @var{t} *foo;
  3916. @end example
  3917. To remember this syntax, think ``if you dereference @code{foo}, using
  3918. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3919. points to type @var{t}.''
  3920. Thus, we can declare variables that hold pointers to these three
  3921. types, like this:
  3922. @example
  3923. int *ptri; /* @r{Pointer to @code{int}.} */
  3924. double *ptrd; /* @r{Pointer to @code{double}.} */
  3925. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3926. @end example
  3927. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3928. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3929. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3930. @code{double}.'' The parentheses express the point that you would
  3931. dereference it first, then subscript it.
  3932. Contrast the last one with this:
  3933. @example
  3934. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3935. @end example
  3936. @noindent
  3937. Because @samp{*} has higher syntactic precedence than subscripting,
  3938. you would subscript @code{aptrd} then dereference it. Therefore, it
  3939. declares an array of pointers, not a pointer.
  3940. @node Pointer Type Designators
  3941. @section Pointer-Type Designators
  3942. Every type in C has a designator; you make it by deleting the variable
  3943. name and the semicolon from a declaration (@pxref{Type
  3944. Designators}). Here are the designators for the pointer
  3945. types of the example declarations in the previous section:
  3946. @example
  3947. int * /* @r{Pointer to @code{int}.} */
  3948. double * /* @r{Pointer to @code{double}.} */
  3949. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3950. @end example
  3951. Remember, to understand what type a designator stands for, imagine the
  3952. variable name that would be in the declaration, and figure out what
  3953. type it would declare that variable with. @code{double (*)[5]} can
  3954. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3955. which, when dereferenced, gives an array of 5 @code{double}s.
  3956. @node Pointer Dereference
  3957. @section Dereferencing Pointers
  3958. @cindex dereferencing pointers
  3959. @cindex pointer dereferencing
  3960. The main use of a pointer value is to @dfn{dereference it} (access the
  3961. data it points at) with the unary @samp{*} operator. For instance,
  3962. @code{*&i} is the value at @code{i}'s address---which is just
  3963. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3964. valid.
  3965. A pointer-dereference expression whose type is data (not a function)
  3966. is an lvalue.
  3967. Pointers become really useful when we store them somewhere and use
  3968. them later. Here's a simple example to illustrate the practice:
  3969. @example
  3970. @{
  3971. int i;
  3972. int *ptr;
  3973. ptr = &i;
  3974. i = 5;
  3975. @r{@dots{}}
  3976. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3977. @}
  3978. @end example
  3979. This shows how to declare the variable @code{ptr} as type
  3980. @code{int *} (pointer to @code{int}), store a pointer value into it
  3981. (pointing at @code{i}), and use it later to get the value of the
  3982. object it points at (the value in @code{i}).
  3983. If anyone can provide a useful example which is this basic,
  3984. I would be grateful.
  3985. @node Null Pointers
  3986. @section Null Pointers
  3987. @cindex null pointers
  3988. @cindex pointers, null
  3989. @c ???stdio loads sttddef
  3990. A pointer value can be @dfn{null}, which means it does not point to
  3991. any object. The cleanest way to get a null pointer is by writing
  3992. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3993. also do it by casting 0 to the desired pointer type, as in
  3994. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  3995. @xref{Explicit Type Conversion}.)
  3996. You can store a null pointer in any lvalue whose data type
  3997. is a pointer type:
  3998. @example
  3999. char *foo;
  4000. foo = NULL;
  4001. @end example
  4002. These two, if consecutive, can be combined into a declaration with
  4003. initializer,
  4004. @example
  4005. char *foo = NULL;
  4006. @end example
  4007. You can also explicitly cast @code{NULL} to the specific pointer type
  4008. you want---it makes no difference.
  4009. @example
  4010. char *foo;
  4011. foo = (char *) NULL;
  4012. @end example
  4013. To test whether a pointer is null, compare it with zero or
  4014. @code{NULL}, as shown here:
  4015. @example
  4016. if (p != NULL)
  4017. /* @r{@code{p} is not null.} */
  4018. operate (p);
  4019. @end example
  4020. Since testing a pointer for not being null is basic and frequent, all
  4021. but beginners in C will understand the conditional without need for
  4022. @code{!= NULL}:
  4023. @example
  4024. if (p)
  4025. /* @r{@code{p} is not null.} */
  4026. operate (p);
  4027. @end example
  4028. @node Invalid Dereference
  4029. @section Dereferencing Null or Invalid Pointers
  4030. Trying to dereference a null pointer is an error. On most platforms,
  4031. it generally causes a signal, usually @code{SIGSEGV}
  4032. (@pxref{Signals}).
  4033. @example
  4034. char *foo = NULL;
  4035. c = *foo; /* @r{This causes a signal and terminates.} */
  4036. @end example
  4037. @noindent
  4038. Likewise a pointer that has the wrong alignment for the target data type
  4039. (on most types of computer), or points to a part of memory that has
  4040. not been allocated in the process's address space.
  4041. The signal terminates the program, unless the program has arranged to
  4042. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4043. The GNU C Library Reference Manual}).
  4044. However, the signal might not happen if the dereference is optimized
  4045. away. In the example above, if you don't subsequently use the value
  4046. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4047. can prevent such optimization using the @code{volatile} qualifier, as
  4048. shown here:
  4049. @example
  4050. volatile char *p;
  4051. volatile char c;
  4052. c = *p;
  4053. @end example
  4054. You can use this to test whether @code{p} points to unallocated
  4055. memory. Set up a signal handler first, so the signal won't terminate
  4056. the program.
  4057. @node Void Pointers
  4058. @section Void Pointers
  4059. @cindex void pointers
  4060. @cindex pointers, void
  4061. The peculiar type @code{void *}, a pointer whose target type is
  4062. @code{void}, is used often in C@. It represents a pointer to
  4063. we-don't-say-what. Thus,
  4064. @example
  4065. void *numbered_slot_pointer (int);
  4066. @end example
  4067. @noindent
  4068. declares a function @code{numbered_slot_pointer} that takes an
  4069. integer parameter and returns a pointer, but we don't say what type of
  4070. data it points to.
  4071. With type @code{void *}, you can pass the pointer around and test
  4072. whether it is null. However, dereferencing it gives a @code{void}
  4073. value that can't be used (@pxref{The Void Type}). To dereference the
  4074. pointer, first convert it to some other pointer type.
  4075. Assignments convert @code{void *} automatically to any other pointer
  4076. type, if the left operand has a pointer type; for instance,
  4077. @example
  4078. @{
  4079. int *p;
  4080. /* @r{Converts return value to @code{int *}.} */
  4081. p = numbered_slot_pointer (5);
  4082. @r{@dots{}}
  4083. @}
  4084. @end example
  4085. Passing an argument of type @code{void *} for a parameter that has a
  4086. pointer type also converts. For example, supposing the function
  4087. @code{hack} is declared to require type @code{float *} for its
  4088. argument, this will convert the null pointer to that type.
  4089. @example
  4090. /* @r{Declare @code{hack} that way.}
  4091. @r{We assume it is defined somewhere else.} */
  4092. void hack (float *);
  4093. @dots{}
  4094. /* @r{Now call @code{hack}.} */
  4095. @{
  4096. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4097. @r{to @code{float *} to pass it to @code{hack}.} */
  4098. hack (numbered_slot_pointer (5));
  4099. @r{@dots{}}
  4100. @}
  4101. @end example
  4102. You can also convert to another pointer type with an explicit cast
  4103. (@pxref{Explicit Type Conversion}), like this:
  4104. @example
  4105. (int *) numbered_slot_pointer (5)
  4106. @end example
  4107. Here is an example which decides at run time which pointer
  4108. type to convert to:
  4109. @example
  4110. void
  4111. extract_int_or_double (void *ptr, bool its_an_int)
  4112. @{
  4113. if (its_an_int)
  4114. handle_an_int (*(int *)ptr);
  4115. else
  4116. handle_a_double (*(double *)ptr);
  4117. @}
  4118. @end example
  4119. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4120. to type @code{int *}, then dereference it.
  4121. @node Pointer Comparison
  4122. @section Pointer Comparison
  4123. @cindex pointer comparison
  4124. @cindex comparison, pointer
  4125. Two pointer values are equal if they point to the same location, or if
  4126. they are both null. You can test for this with @code{==} and
  4127. @code{!=}. Here's a trivial example:
  4128. @example
  4129. @{
  4130. int i;
  4131. int *p, *q;
  4132. p = &i;
  4133. q = &i;
  4134. if (p == q)
  4135. printf ("This will be printed.\n");
  4136. if (p != q)
  4137. printf ("This won't be printed.\n");
  4138. @}
  4139. @end example
  4140. Ordering comparisons such as @code{>} and @code{>=} operate on
  4141. pointers by converting them to unsigned integers. The C standard says
  4142. the two pointers must point within the same object in memory, but on
  4143. GNU/Linux systems these operations simply compare the numeric values
  4144. of the pointers.
  4145. The pointer values to be compared should in principle have the same type, but
  4146. they are allowed to differ in limited cases. First of all, if the two
  4147. pointers' target types are nearly compatible (@pxref{Compatible
  4148. Types}), the comparison is allowed.
  4149. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4150. the other is another pointer type, the comparison operator converts
  4151. the @code{void *} pointer to the other type so as to compare them.
  4152. (In standard C, this is not allowed if the other type is a function
  4153. pointer type, but that works in GNU C@.)
  4154. Comparison operators also allow comparing the integer 0 with a pointer
  4155. value. Thus works by converting 0 to a null pointer of the same type
  4156. as the other operand.
  4157. @node Pointer Arithmetic
  4158. @section Pointer Arithmetic
  4159. @cindex pointer arithmetic
  4160. @cindex arithmetic, pointer
  4161. Adding an integer (positive or negative) to a pointer is valid in C@.
  4162. It assumes that the pointer points to an element in an array, and
  4163. advances or retracts the pointer across as many array elements as the
  4164. integer specifies. Here is an example, in which adding a positive
  4165. integer advances the pointer to a later element in the same array.
  4166. @example
  4167. void
  4168. incrementing_pointers ()
  4169. @{
  4170. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4171. int elt0, elt1, elt4;
  4172. int *p = &array[0];
  4173. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4174. elt0 = *p;
  4175. ++p;
  4176. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4177. elt1 = *p;
  4178. p += 3;
  4179. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4180. elt4 = *p;
  4181. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4182. elt0, elt1, elt4);
  4183. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4184. @}
  4185. @end example
  4186. Here's an example where adding a negative integer retracts the pointer
  4187. to an earlier element in the same array.
  4188. @example
  4189. void
  4190. decrementing_pointers ()
  4191. @{
  4192. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4193. int elt0, elt3, elt4;
  4194. int *p = &array[4];
  4195. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4196. elt4 = *p;
  4197. --p;
  4198. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4199. elt3 = *p;
  4200. p -= 3;
  4201. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4202. elt0 = *p;
  4203. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4204. elt0, elt3, elt4);
  4205. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4206. @}
  4207. @end example
  4208. If one pointer value was made by adding an integer to another
  4209. pointer value, it should be possible to subtract the pointer values
  4210. and recover that integer. That works too in C@.
  4211. @example
  4212. void
  4213. subtract_pointers ()
  4214. @{
  4215. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4216. int *p0, *p3, *p4;
  4217. int *p = &array[4];
  4218. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4219. p4 = p;
  4220. --p;
  4221. /* @r{Now @code{p} points at element 3. Save the value.} */
  4222. p3 = p;
  4223. p -= 3;
  4224. /* @r{Now @code{p} points at element 0. Save the value.} */
  4225. p0 = p;
  4226. printf ("%d, %d, %d, %d\n",
  4227. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4228. /* @r{Prints 4, 0, 3, -3.} */
  4229. @}
  4230. @end example
  4231. The addition operation does not know where arrays are. All it does is
  4232. add the integer (multiplied by object size) to the value of the
  4233. pointer. When the initial pointer and the result point into a single
  4234. array, the result is well-defined.
  4235. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4236. into different memory objects.
  4237. The difference between two pointers has type @code{int}, or
  4238. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4239. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4240. file @file{stddef.h}.
  4241. This definition of pointer subtraction is consistent with
  4242. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4243. @code{p3}, as in ordinary algebra.
  4244. In standard C, addition and subtraction are not allowed on @code{void
  4245. *}, since the target type's size is not defined in that case.
  4246. Likewise, they are not allowed on pointers to function types.
  4247. However, these operations work in GNU C, and the ``size of the target
  4248. type'' is taken as 1.
  4249. @node Pointers and Arrays
  4250. @section Pointers and Arrays
  4251. @cindex pointers and arrays
  4252. @cindex arrays and pointers
  4253. The clean way to refer to an array element is
  4254. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4255. same job is to get the address of that element as a pointer, then
  4256. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4257. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4258. pointer to element zero, then increments it with @code{+} to point to
  4259. the desired element, then gets the value from there.
  4260. That pointer-arithmetic construct is the @emph{definition} of square
  4261. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4262. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4263. symmetrically, so one must be a pointer and the other an integer; it
  4264. does not matter which comes first.
  4265. Since indexing with square brackets is defined in terms of addition
  4266. and dereference, that too is symmetrical. Thus, you can write
  4267. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4268. would be foolish to write @code{3[array]}, since it has no advantage
  4269. and could confuse people who read the code.
  4270. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4271. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4272. instead. Why is this valid? The name of the array, when used by
  4273. itself as an expression (other than in @code{sizeof}), stands for a
  4274. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4275. converts @code{array} implicitly to @code{&array[0]}, and the result
  4276. is a pointer to element 3, equivalent to @code{&array[3]}.
  4277. Since square brackets are defined in terms of such addition,
  4278. @code{array[3]} first converts @code{array} to a pointer. That's why
  4279. it works to use an array directly in that construct.
  4280. @node Pointer Arithmetic Low Level
  4281. @section Pointer Arithmetic at Low Level
  4282. @cindex pointer arithmetic, low level
  4283. @cindex low level pointer arithmetic
  4284. The behavior of pointer arithmetic is theoretically defined only when
  4285. the pointer values all point within one object allocated in memory.
  4286. But the addition and subtraction operators can't tell whether the
  4287. pointer values are all within one object. They don't know where
  4288. objects start and end. So what do they really do?
  4289. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4290. address, which is in fact an integer---call it @var{pint}. It treats
  4291. @var{i} as a number of elements of the type that @var{p} points to.
  4292. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4293. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4294. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4295. If the starting pointer value @var{p} and the result do not point at
  4296. parts of the same object, the operation is not officially legitimate,
  4297. and C code is not ``supposed'' to do it. But you can do it anyway,
  4298. and it gives precisely the results described by the procedure above.
  4299. In some special situations it can do something useful, but non-wizards
  4300. should avoid it.
  4301. Here's a function to offset a pointer value @emph{as if} it pointed to
  4302. an object of any given size, by explicitly performing that calculation:
  4303. @example
  4304. #include <stdint.h>
  4305. void *
  4306. ptr_add (void *p, int i, int objsize)
  4307. @{
  4308. intptr_t p_address = (long) p;
  4309. intptr_t totalsize = i * objsize;
  4310. intptr_t new_address = p_address + totalsize;
  4311. return (void *) new_address;
  4312. @}
  4313. @end example
  4314. @noindent
  4315. @cindex @code{intptr_t}
  4316. This does the same job as @code{@var{p} + @var{i}} with the proper
  4317. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4318. defined in the header file @file{stdint.h}. (In practice, @code{long
  4319. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4320. @node Pointer Increment/Decrement
  4321. @section Pointer Increment and Decrement
  4322. @cindex pointer increment and decrement
  4323. @cindex incrementing pointers
  4324. @cindex decrementing pointers
  4325. The @samp{++} operator adds 1 to a variable. We have seen it for
  4326. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4327. For instance, suppose we have a series of positive integers,
  4328. terminated by a zero, and we want to add them all up.
  4329. @example
  4330. int
  4331. sum_array_till_0 (int *p)
  4332. @{
  4333. int sum = 0;
  4334. for (;;)
  4335. @{
  4336. /* @r{Fetch the next integer.} */
  4337. int next = *p++;
  4338. /* @r{Exit the loop if it's 0.} */
  4339. if (next == 0)
  4340. break;
  4341. /* @r{Add it into running total.} */
  4342. sum += next;
  4343. @}
  4344. return sum;
  4345. @}
  4346. @end example
  4347. @noindent
  4348. The statement @samp{break;} will be explained further on (@pxref{break
  4349. Statement}). Used in this way, it immediately exits the surrounding
  4350. @code{for} statement.
  4351. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4352. takes precedence over a prefix operator. Therefore, it dereferences
  4353. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4354. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4355. pointer, adding 1 to it advances it by the width of the datum it
  4356. points to---in this case, one @code{int}. Therefore, each iteration
  4357. of the loop picks up the next integer from the series and puts it into
  4358. @code{next}.
  4359. This @code{for}-loop has no initialization expression since @code{p}
  4360. and @code{sum} are already initialized, it has no end-test since the
  4361. @samp{break;} statement will exit it, and needs no expression to
  4362. advance it since that's done within the loop by incrementing @code{p}
  4363. and @code{sum}. Thus, those three expressions after @code{for} are
  4364. left empty.
  4365. Another way to write this function is by keeping the parameter value unchanged
  4366. and using indexing to access the integers in the table.
  4367. @example
  4368. int
  4369. sum_array_till_0_indexing (int *p)
  4370. @{
  4371. int i;
  4372. int sum = 0;
  4373. for (i = 0; ; i++)
  4374. @{
  4375. /* @r{Fetch the next integer.} */
  4376. int next = p[i];
  4377. /* @r{Exit the loop if it's 0.} */
  4378. if (next == 0)
  4379. break;
  4380. /* @r{Add it into running total.} */
  4381. sum += next;
  4382. @}
  4383. return sum;
  4384. @}
  4385. @end example
  4386. In this program, instead of advancing @code{p}, we advance @code{i}
  4387. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4388. i)}.) Either way, it uses the same address to get the next integer.
  4389. It makes no difference in this program whether we write @code{i++} or
  4390. @code{++i}, because the value is not used. All that matters is the
  4391. effect, to increment @code{i}.
  4392. The @samp{--} operator also works on pointers; it can be used
  4393. to scan backwards through an array, like this:
  4394. @example
  4395. int
  4396. after_last_nonzero (int *p, int len)
  4397. @{
  4398. /* @r{Set up @code{q} to point just after the last array element.} */
  4399. int *q = p + len;
  4400. while (q != p)
  4401. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4402. if (*--q != 0)
  4403. /* @r{Return the index of the element after that nonzero.} */
  4404. return q - p + 1;
  4405. return 0;
  4406. @}
  4407. @end example
  4408. That function returns the length of the nonzero part of the
  4409. array specified by its arguments; that is, the index of the
  4410. first zero of the run of zeros at the end.
  4411. @node Pointer Arithmetic Drawbacks
  4412. @section Drawbacks of Pointer Arithmetic
  4413. @cindex drawbacks of pointer arithmetic
  4414. @cindex pointer arithmetic, drawbacks
  4415. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4416. major security flaw in the C language. Theoretically, it is only
  4417. valid to adjust a pointer within one object allocated as a unit in
  4418. memory. However, if you unintentionally adjust a pointer across the
  4419. bounds of the object and into some other object, the system has no way
  4420. to detect this error.
  4421. A bug which does that can easily result in clobbering part of another
  4422. object. For example, with @code{array[-1]} you can read or write the
  4423. nonexistent element before the beginning of an array---probably part
  4424. of some other data.
  4425. Combining pointer arithmetic with casts between pointer types, you can
  4426. create a pointer that fails to be properly aligned for its type. For
  4427. example,
  4428. @example
  4429. int a[2];
  4430. char *pa = (char *)a;
  4431. int *p = (int *)(pa + 1);
  4432. @end example
  4433. @noindent
  4434. gives @code{p} a value pointing to an ``integer'' that includes part
  4435. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4436. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4437. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4438. ``works,'' it may be quite slow. It can also cause aliasing
  4439. confusions (@pxref{Aliasing}).
  4440. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4441. unless it is really necessary.
  4442. @node Pointer-Integer Conversion
  4443. @section Pointer-Integer Conversion
  4444. @cindex pointer-integer conversion
  4445. @cindex conversion between pointers and integers
  4446. @cindex @code{uintptr_t}
  4447. On modern computers, an address is simply a number. It occupies the
  4448. same space as some size of integer. In C, you can convert a pointer
  4449. to the appropriate integer types and vice versa, without losing
  4450. information. The appropriate integer types are @code{uintptr_t} (an
  4451. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4452. in @file{stdint.h}.
  4453. For instance,
  4454. @example
  4455. #include <stdint.h>
  4456. #include <stdio.h>
  4457. void
  4458. print_pointer (void *ptr)
  4459. @{
  4460. uintptr_t converted = (uintptr_t) ptr;
  4461. printf ("Pointer value is 0x%x\n",
  4462. (unsigned int) converted);
  4463. @}
  4464. @end example
  4465. @noindent
  4466. The specification @samp{%x} in the template (the first argument) for
  4467. @code{printf} means to represent this argument using hexadecimal
  4468. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4469. printing treats the number as unsigned, but it won't actually matter:
  4470. all @code{printf} gets to see is the series of bits in the number.
  4471. @strong{Warning:} Converting pointers to integers is risky---don't do
  4472. it unless it is really necessary.
  4473. @node Printing Pointers
  4474. @section Printing Pointers
  4475. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4476. For example:
  4477. @example
  4478. void
  4479. print_pointer (void *ptr)
  4480. @{
  4481. printf ("Pointer value is %p\n", ptr);
  4482. @}
  4483. @end example
  4484. The specification @samp{%p} works with any pointer type. It prints
  4485. @samp{0x} followed by the address in hexadecimal, printed as the
  4486. appropriate unsigned integer type.
  4487. @node Structures
  4488. @chapter Structures
  4489. @cindex structures
  4490. @findex struct
  4491. @cindex fields in structures
  4492. A @dfn{structure} is a user-defined data type that holds various
  4493. @dfn{fields} of data. Each field has a name and a data type specified
  4494. in the structure's definition.
  4495. Here we define a structure suitable for storing a linked list of
  4496. integers. Each list item will hold one integer, plus a pointer
  4497. to the next item.
  4498. @example
  4499. struct intlistlink
  4500. @{
  4501. int datum;
  4502. struct intlistlink *next;
  4503. @};
  4504. @end example
  4505. The structure definition has a @dfn{type tag} so that the code can
  4506. refer to this structure. The type tag here is @code{intlistlink}.
  4507. The definition refers recursively to the same structure through that
  4508. tag.
  4509. You can define a structure without a type tag, but then you can't
  4510. refer to it again. That is useful only in some special contexts, such
  4511. as inside a @code{typedef} or a @code{union}.
  4512. The contents of the structure are specified by the @dfn{field
  4513. declarations} inside the braces. Each field in the structure needs a
  4514. declaration there. The fields in one structure definition must have
  4515. distinct names, but these names do not conflict with any other names
  4516. in the program.
  4517. A field declaration looks just like a variable declaration. You can
  4518. combine field declarations with the same beginning, just as you can
  4519. combine variable declarations.
  4520. This structure has two fields. One, named @code{datum}, has type
  4521. @code{int} and will hold one integer in the list. The other, named
  4522. @code{next}, is a pointer to another @code{struct intlistlink}
  4523. which would be the rest of the list. In the last list item, it would
  4524. be @code{NULL}.
  4525. This structure definition is recursive, since the type of the
  4526. @code{next} field refers to the structure type. Such recursion is not
  4527. a problem; in fact, you can use the type @code{struct intlistlink *}
  4528. before the definition of the type @code{struct intlistlink} itself.
  4529. That works because pointers to all kinds of structures really look the
  4530. same at the machine level.
  4531. After defining the structure, you can declare a variable of type
  4532. @code{struct intlistlink} like this:
  4533. @example
  4534. struct intlistlink foo;
  4535. @end example
  4536. The structure definition itself can serve as the beginning of a
  4537. variable declaration, so you can declare variables immediately after,
  4538. like this:
  4539. @example
  4540. struct intlistlink
  4541. @{
  4542. int datum;
  4543. struct intlistlink *next;
  4544. @} foo;
  4545. @end example
  4546. @noindent
  4547. But that is ugly. It is almost always clearer to separate the
  4548. definition of the structure from its uses.
  4549. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4550. the scope of the structure type name to that block. That means the
  4551. structure type is recognized only within that block. Declaring it in
  4552. a function parameter list, as here,
  4553. @example
  4554. int f (struct foo @{int a, b@} parm);
  4555. @end example
  4556. @noindent
  4557. (assuming that @code{struct foo} is not already defined) limits the
  4558. scope of the structure type @code{struct foo} to that parameter list;
  4559. that is basically useless, so it triggers a warning.
  4560. Standard C requires at least one field in a structure.
  4561. GNU C does not require this.
  4562. @menu
  4563. * Referencing Fields:: Accessing field values in a structure object.
  4564. * Dynamic Memory Allocation:: Allocating space for objects
  4565. while the program is running.
  4566. * Field Offset:: Memory layout of fields within a structure.
  4567. * Structure Layout:: Planning the memory layout of fields.
  4568. * Packed Structures:: Packing structure fields as close as possible.
  4569. * Bit Fields:: Dividing integer fields
  4570. into fields with fewer bits.
  4571. * Bit Field Packing:: How bit fields pack together in integers.
  4572. * const Fields:: Making structure fields immutable.
  4573. * Zero Length:: Zero-length array as a variable-length object.
  4574. * Flexible Array Fields:: Another approach to variable-length objects.
  4575. * Overlaying Structures:: Casting one structure type
  4576. over an object of another structure type.
  4577. * Structure Assignment:: Assigning values to structure objects.
  4578. * Unions:: Viewing the same object in different types.
  4579. * Packing With Unions:: Using a union type to pack various types into
  4580. the same memory space.
  4581. * Cast to Union:: Casting a value one of the union's alternative
  4582. types to the type of the union itself.
  4583. * Structure Constructors:: Building new structure objects.
  4584. * Unnamed Types as Fields:: Fields' types do not always need names.
  4585. * Incomplete Types:: Types which have not been fully defined.
  4586. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4587. * Type Tags:: Scope of structure and union type tags.
  4588. @end menu
  4589. @node Referencing Fields
  4590. @section Referencing Structure Fields
  4591. @cindex referencing structure fields
  4592. @cindex structure fields, referencing
  4593. To make a structure useful, there has to be a way to examine and store
  4594. its fields. The @samp{.} (period) operator does that; its use looks
  4595. like @code{@var{object}.@var{field}}.
  4596. Given this structure and variable,
  4597. @example
  4598. struct intlistlink
  4599. @{
  4600. int datum;
  4601. struct intlistlink *next;
  4602. @};
  4603. struct intlistlink foo;
  4604. @end example
  4605. @noindent
  4606. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4607. fields in the value of @code{foo}. These fields are lvalues, so you
  4608. can store values into them, and read the values out again.
  4609. Most often, structures are dynamically allocated (see the next
  4610. section), and we refer to the objects via pointers.
  4611. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4612. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4613. contains this declaration:
  4614. @example
  4615. struct intlistlink *ptr;
  4616. @end example
  4617. @noindent
  4618. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4619. to the two fields in the object that @code{ptr} points to.
  4620. If a unary operator precedes an expression using @samp{->},
  4621. the @samp{->} nests inside:
  4622. @example
  4623. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4624. @end example
  4625. You can intermix @samp{->} and @samp{.} without parentheses,
  4626. as shown here:
  4627. @example
  4628. struct @{ double d; struct intlistlink l; @} foo;
  4629. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4630. @end example
  4631. @node Dynamic Memory Allocation
  4632. @section Dynamic Memory Allocation
  4633. @cindex dynamic memory allocation
  4634. @cindex memory allocation, dynamic
  4635. @cindex allocating memory dynamically
  4636. To allocate an object dynamically, call the library function
  4637. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4638. Reference Manual}). Here is how to allocate an object of type
  4639. @code{struct intlistlink}. To make this code work, include the file
  4640. @file{stdlib.h}, like this:
  4641. @example
  4642. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4643. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4644. @dots{}
  4645. struct intlistlink *
  4646. alloc_intlistlink ()
  4647. @{
  4648. struct intlistlink *p;
  4649. p = malloc (sizeof (struct intlistlink));
  4650. if (p == NULL)
  4651. fatal ("Ran out of storage");
  4652. /* @r{Initialize the contents.} */
  4653. p->datum = 0;
  4654. p->next = NULL;
  4655. return p;
  4656. @}
  4657. @end example
  4658. @noindent
  4659. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4660. will automatically convert it to type @code{struct intlistlink *}.
  4661. The return value of @code{malloc} is always sufficiently aligned
  4662. (@pxref{Type Alignment}) that it is valid for any data type.
  4663. The test for @code{p == NULL} is necessary because @code{malloc}
  4664. returns a null pointer if it cannot get any storage. We assume that
  4665. the program defines the function @code{fatal} to report a fatal error
  4666. to the user.
  4667. Here's how to add one more integer to the front of such a list:
  4668. @example
  4669. struct intlistlink *my_list = NULL;
  4670. void
  4671. add_to_mylist (int my_int)
  4672. @{
  4673. struct intlistlink *p = alloc_intlistlink ();
  4674. p->datum = my_int;
  4675. p->next = mylist;
  4676. mylist = p;
  4677. @}
  4678. @end example
  4679. The way to free the objects is by calling @code{free}. Here's
  4680. a function to free all the links in one of these lists:
  4681. @example
  4682. void
  4683. free_intlist (struct intlistlink *p)
  4684. @{
  4685. while (p)
  4686. @{
  4687. struct intlistlink *q = p;
  4688. p = p->next;
  4689. free (q);
  4690. @}
  4691. @}
  4692. @end example
  4693. We must extract the @code{next} pointer from the object before freeing
  4694. it, because @code{free} can clobber the data that was in the object.
  4695. For the same reason, the program must not use the list any more after
  4696. freeing its elements. To make sure it won't, it is best to clear out
  4697. the variable where the list was stored, like this:
  4698. @example
  4699. free_intlist (mylist);
  4700. mylist = NULL;
  4701. @end example
  4702. @node Field Offset
  4703. @section Field Offset
  4704. @cindex field offset
  4705. @cindex structure field offset
  4706. @cindex offset of structure fields
  4707. To determine the offset of a given field @var{field} in a structure
  4708. type @var{type}, use the macro @code{offsetof}, which is defined in
  4709. the file @file{stddef.h}. It is used like this:
  4710. @example
  4711. offsetof (@var{type}, @var{field})
  4712. @end example
  4713. Here is an example:
  4714. @example
  4715. struct foo
  4716. @{
  4717. int element;
  4718. struct foo *next;
  4719. @};
  4720. offsetof (struct foo, next)
  4721. /* @r{On most machines that is 4. It may be 8.} */
  4722. @end example
  4723. @node Structure Layout
  4724. @section Structure Layout
  4725. @cindex structure layout
  4726. @cindex layout of structures
  4727. The rest of this chapter covers advanced topics about structures. If
  4728. you are just learning C, you can skip it.
  4729. The precise layout of a @code{struct} type is crucial when using it to
  4730. overlay hardware registers, to access data structures in shared
  4731. memory, or to assemble and disassemble packets for network
  4732. communication. It is also important for avoiding memory waste when
  4733. the program makes many objects of that type. However, the layout
  4734. depends on the target platform. Each platform has conventions for
  4735. structure layout, which compilers need to follow.
  4736. Here are the conventions used on most platforms.
  4737. The structure's fields appear in the structure layout in the order
  4738. they are declared. When possible, consecutive fields occupy
  4739. consecutive bytes within the structure. However, if a field's type
  4740. demands more alignment than it would get that way, C gives it the
  4741. alignment it requires by leaving a gap after the previous field.
  4742. Once all the fields have been laid out, it is possible to determine
  4743. the structure's alignment and size. The structure's alignment is the
  4744. maximum alignment of any of the fields in it. Then the structure's
  4745. size is rounded up to a multiple of its alignment. That may require
  4746. leaving a gap at the end of the structure.
  4747. Here are some examples, where we assume that @code{char} has size and
  4748. alignment 1 (always true), and @code{int} has size and alignment 4
  4749. (true on most kinds of computers):
  4750. @example
  4751. struct foo
  4752. @{
  4753. char a, b;
  4754. int c;
  4755. @};
  4756. @end example
  4757. @noindent
  4758. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4759. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4760. There is a gap of 2 bytes before @code{c}.
  4761. Contrast that with this structure:
  4762. @example
  4763. struct foo
  4764. @{
  4765. char a;
  4766. int c;
  4767. char b;
  4768. @};
  4769. @end example
  4770. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4771. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4772. gaps: three bytes before @code{c}, and three bytes at the end.
  4773. These two structures have the same contents at the C level, but one
  4774. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4775. fields. A reliable way to avoid this sort of wastage is to order the
  4776. fields by size, biggest fields first.
  4777. @node Packed Structures
  4778. @section Packed Structures
  4779. @cindex packed structures
  4780. @cindex @code{__attribute__((packed))}
  4781. In GNU C you can force a structure to be laid out with no gaps by
  4782. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4783. end of the structure type declaration). Here's an example:
  4784. @example
  4785. struct __attribute__((packed)) foo
  4786. @{
  4787. char a;
  4788. int c;
  4789. char b;
  4790. @};
  4791. @end example
  4792. Without @code{__attribute__((packed))}, this structure occupies 12
  4793. bytes (as described in the previous section), assuming 4-byte
  4794. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4795. only 6 bytes long---the sum of the lengths of its fields.
  4796. Use of @code{__attribute__((packed))} often results in fields that
  4797. don't have the normal alignment for their types. Taking the address
  4798. of such a field can result in an invalid pointer because of its
  4799. improper alignment. Dereferencing such a pointer can cause a
  4800. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4801. unaligned pointers.
  4802. @xref{Attributes}.
  4803. @node Bit Fields
  4804. @section Bit Fields
  4805. @cindex bit fields
  4806. A structure field declaration with an integer type can specify the
  4807. number of bits the field should occupy. We call that a @dfn{bit
  4808. field}. These are useful because consecutive bit fields are packed
  4809. into a larger storage unit. For instance,
  4810. @example
  4811. unsigned char opcode: 4;
  4812. @end example
  4813. @noindent
  4814. specifies that this field takes just 4 bits.
  4815. Since it is unsigned, its possible values range
  4816. from 0 to 15. A signed field with 4 bits, such as this,
  4817. @example
  4818. signed char small: 4;
  4819. @end example
  4820. @noindent
  4821. can hold values from -8 to 7.
  4822. You can subdivide a single byte into those two parts by writing
  4823. @example
  4824. unsigned char opcode: 4;
  4825. signed char small: 4;
  4826. @end example
  4827. @noindent
  4828. in the structure. With bit fields, these two numbers fit into
  4829. a single @code{char}.
  4830. Here's how to declare a one-bit field that can hold either 0 or 1:
  4831. @example
  4832. unsigned char special_flag: 1;
  4833. @end example
  4834. You can also use the @code{bool} type for bit fields:
  4835. @example
  4836. bool special_flag: 1;
  4837. @end example
  4838. Except when using @code{bool} (which is always unsigned,
  4839. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4840. for a bit field. There is a default, if that's not specified: the bit
  4841. field is signed if plain @code{char} is signed, except that the option
  4842. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4843. is cleaner not to depend on this default.
  4844. Bit fields are special in that you cannot take their address with
  4845. @samp{&}. They are not stored with the size and alignment appropriate
  4846. for the specified type, so they cannot be addressed through pointers
  4847. to that type.
  4848. @node Bit Field Packing
  4849. @section Bit Field Packing
  4850. Programs to communicate with low-level hardware interfaces need to
  4851. define bit fields laid out to match the hardware data. This section
  4852. explains how to do that.
  4853. Consecutive bit fields are packed together, but each bit field must
  4854. fit within a single object of its specified type. In this example,
  4855. @example
  4856. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4857. @end example
  4858. @noindent
  4859. all five fields fit consecutively into one two-byte @code{short}.
  4860. They need 15 bits, and one @code{short} provides 16. By contrast,
  4861. @example
  4862. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4863. @end example
  4864. @noindent
  4865. needs three bytes. It fits @code{a} and @code{b} into one
  4866. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4867. add up to 9 bits). So @code{c} and @code{d} go into a second
  4868. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4869. Then @code{e} needs a third @code{char}. By contrast,
  4870. @example
  4871. unsigned char a : 3, b : 3;
  4872. unsigned int c : 3;
  4873. unsigned char d : 3, e : 3;
  4874. @end example
  4875. @noindent
  4876. needs only two bytes: the type @code{unsigned int}
  4877. allows @code{c} to straddle bytes that are in the same word.
  4878. You can leave a gap of a specified number of bits by defining a
  4879. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4880. It is allocated space in the structure just as a named bit field would
  4881. be allocated.
  4882. You can force the following bit field to advance to the following
  4883. aligned memory object with @code{@var{type} : 0;}.
  4884. Both of these constructs can syntactically share @var{type} with
  4885. ordinary bit fields. This example illustrates both:
  4886. @example
  4887. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4888. @end example
  4889. @noindent
  4890. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4891. between them. Then @code{: 0} advances to the next @code{int},
  4892. so @code{c} and @code{d} fit into that one.
  4893. These rules for packing bit fields apply to most target platforms,
  4894. including all the usual real computers. A few embedded controllers
  4895. have special layout rules.
  4896. @node const Fields
  4897. @section @code{const} Fields
  4898. @cindex const fields
  4899. @cindex structure fields, constant
  4900. @c ??? Is this a C standard feature?
  4901. A structure field declared @code{const} cannot be assigned to
  4902. (@pxref{const}). For instance, let's define this modified version of
  4903. @code{struct intlistlink}:
  4904. @example
  4905. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4906. @{
  4907. const int datum;
  4908. struct intlistlink *next;
  4909. @};
  4910. @end example
  4911. This structure can be used to prevent part of the code from modifying
  4912. the @code{datum} field:
  4913. @example
  4914. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4915. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4916. struct intlistlink_ro *q
  4917. = (struct intlistlink_ro *) p;
  4918. q->datum = 5; /* @r{Error!} */
  4919. p->datum = 5; /* @r{Valid since @code{*p} is}
  4920. @r{not a @code{struct intlistlink_ro}.} */
  4921. @end example
  4922. A @code{const} field can get a value in two ways: by initialization of
  4923. the whole structure, and by making a pointer-to-structure point to an object
  4924. in which that field already has a value.
  4925. Any @code{const} field in a structure type makes assignment impossible
  4926. for structures of that type (@pxref{Structure Assignment}). That is
  4927. because structure assignment works by assigning the structure's
  4928. fields, one by one.
  4929. @node Zero Length
  4930. @section Arrays of Length Zero
  4931. @cindex array of length zero
  4932. @cindex zero-length arrays
  4933. @cindex length-zero arrays
  4934. GNU C allows zero-length arrays. They are useful as the last element
  4935. of a structure that is really a header for a variable-length object.
  4936. Here's an example, where we construct a variable-size structure
  4937. to hold a line which is @code{this_length} characters long:
  4938. @example
  4939. struct line @{
  4940. int length;
  4941. char contents[0];
  4942. @};
  4943. struct line *thisline
  4944. = ((struct line *)
  4945. malloc (sizeof (struct line)
  4946. + this_length));
  4947. thisline->length = this_length;
  4948. @end example
  4949. In ISO C90, we would have to give @code{contents} a length of 1, which
  4950. means either wasting space or complicating the argument to @code{malloc}.
  4951. @node Flexible Array Fields
  4952. @section Flexible Array Fields
  4953. @cindex flexible array fields
  4954. @cindex array fields, flexible
  4955. The C99 standard adopted a more complex equivalent of zero-length
  4956. array fields. It's called a @dfn{flexible array}, and it's indicated
  4957. by omitting the length, like this:
  4958. @example
  4959. struct line
  4960. @{
  4961. int length;
  4962. char contents[];
  4963. @};
  4964. @end example
  4965. The flexible array has to be the last field in the structure, and there
  4966. must be other fields before it.
  4967. Under the C standard, a structure with a flexible array can't be part
  4968. of another structure, and can't be an element of an array.
  4969. GNU C allows static initialization of flexible array fields. The effect
  4970. is to ``make the array long enough'' for the initializer.
  4971. @example
  4972. struct f1 @{ int x; int y[]; @} f1
  4973. = @{ 1, @{ 2, 3, 4 @} @};
  4974. @end example
  4975. @noindent
  4976. This defines a structure variable named @code{f1}
  4977. whose type is @code{struct f1}. In C, a variable name or function name
  4978. never conflicts with a structure type tag.
  4979. Omitting the flexible array field's size lets the initializer
  4980. determine it. This is allowed only when the flexible array is defined
  4981. in the outermost structure and you declare a variable of that
  4982. structure type. For example:
  4983. @example
  4984. struct foo @{ int x; int y[]; @};
  4985. struct bar @{ struct foo z; @};
  4986. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4987. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4988. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4989. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4990. @end example
  4991. @node Overlaying Structures
  4992. @section Overlaying Different Structures
  4993. @cindex overlaying structures
  4994. @cindex structures, overlaying
  4995. Be careful about using different structure types to refer to the same
  4996. memory within one function, because GNU C can optimize code assuming
  4997. it never does that. @xref{Aliasing}. Here's an example of the kind of
  4998. aliasing that can cause the problem:
  4999. @example
  5000. struct a @{ int size; char *data; @};
  5001. struct b @{ int size; char *data; @};
  5002. struct a foo;
  5003. struct b *q = (struct b *) &foo;
  5004. @end example
  5005. Here @code{q} points to the same memory that the variable @code{foo}
  5006. occupies, but they have two different types. The two types
  5007. @code{struct a} and @code{struct b} are defined alike, but they are
  5008. not the same type. Interspersing references using the two types,
  5009. like this,
  5010. @example
  5011. p->size = 0;
  5012. q->size = 1;
  5013. x = p->size;
  5014. @end example
  5015. @noindent
  5016. allows GNU C to assume that @code{p->size} is still zero when it is
  5017. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5018. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5019. Other compilers might also do this optimization. The ISO C standard
  5020. considers such code erroneous, precisely so that this optimization
  5021. will be valid.
  5022. @node Structure Assignment
  5023. @section Structure Assignment
  5024. @cindex structure assignment
  5025. @cindex assigning structures
  5026. Assignment operating on a structure type copies the structure. The
  5027. left and right operands must have the same type. Here is an example:
  5028. @example
  5029. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5030. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5031. @r{@dots{}}
  5032. struct point @{ double x, y; @};
  5033. struct point *
  5034. copy_point (struct point point)
  5035. @{
  5036. struct point *p
  5037. = (struct point *) malloc (sizeof (struct point));
  5038. if (p == NULL)
  5039. fatal ("Out of memory");
  5040. *p = point;
  5041. return p;
  5042. @}
  5043. @end example
  5044. Notionally, assignment on a structure type works by copying each of
  5045. the fields. Thus, if any of the fields has the @code{const}
  5046. qualifier, that structure type does not allow assignment:
  5047. @example
  5048. struct point @{ const double x, y; @};
  5049. struct point a, b;
  5050. a = b; /* @r{Error!} */
  5051. @end example
  5052. @xref{Assignment Expressions}.
  5053. @node Unions
  5054. @section Unions
  5055. @cindex unions
  5056. @findex union
  5057. A @dfn{union type} defines alternative ways of looking at the same
  5058. piece of memory. Each alternative view is defined with a data type,
  5059. and identified by a name. A union definition looks like this:
  5060. @example
  5061. union @var{name}
  5062. @{
  5063. @var{alternative declarations}@r{@dots{}}
  5064. @};
  5065. @end example
  5066. Each alternative declaration looks like a structure field declaration,
  5067. except that it can't be a bit field. For instance,
  5068. @example
  5069. union number
  5070. @{
  5071. long int integer;
  5072. double float;
  5073. @}
  5074. @end example
  5075. @noindent
  5076. lets you store either an integer (type @code{long int}) or a floating
  5077. point number (type @code{double}) in the same place in memory. The
  5078. length and alignment of the union type are the maximum of all the
  5079. alternatives---they do not have to be the same. In this union
  5080. example, @code{double} probably takes more space than @code{long int},
  5081. but that doesn't cause a problem in programs that use the union in the
  5082. normal way.
  5083. The members don't have to be different in data type. Sometimes
  5084. each member pertains to a way the data will be used. For instance,
  5085. @example
  5086. union datum
  5087. @{
  5088. double latitude;
  5089. double longitude;
  5090. double height;
  5091. double weight;
  5092. int continent;
  5093. @}
  5094. @end example
  5095. This union holds one of several kinds of data; most kinds are floating
  5096. points, but the value can also be a code for a continent which is an
  5097. integer. You @emph{could} use one member of type @code{double} to
  5098. access all the values which have that type, but the different member
  5099. names will make the program clearer.
  5100. The alignment of a union type is the maximum of the alignments of the
  5101. alternatives. The size of the union type is the maximum of the sizes
  5102. of the alternatives, rounded up to a multiple of the alignment
  5103. (because every type's size must be a multiple of its alignment).
  5104. All the union alternatives start at the address of the union itself.
  5105. If an alternative is shorter than the union as a whole, it occupies
  5106. the first part of the union's storage, leaving the last part unused
  5107. @emph{for that alternative}.
  5108. @strong{Warning:} if the code stores data using one union alternative
  5109. and accesses it with another, the results depend on the kind of
  5110. computer in use. Only wizards should try to do this. However, when
  5111. you need to do this, a union is a clean way to do it.
  5112. Assignment works on any union type by copying the entire value.
  5113. @node Packing With Unions
  5114. @section Packing With Unions
  5115. Sometimes we design a union with the intention of packing various
  5116. kinds of objects into a certain amount of memory space. For example.
  5117. @example
  5118. union bytes8
  5119. @{
  5120. long long big_int_elt;
  5121. double double_elt;
  5122. struct @{ int first, second; @} two_ints;
  5123. struct @{ void *first, *second; @} two_ptrs;
  5124. @};
  5125. union bytes8 *p;
  5126. @end example
  5127. This union makes it possible to look at 8 bytes of data that @code{p}
  5128. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5129. single floating-point number (@code{p->double_elt}), as a pair of
  5130. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5131. as a pair of pointers (@code{p->two_ptrs.first} and
  5132. @code{p->two_ptrs.second}).
  5133. To pack storage with such a union makes assumptions about the sizes of
  5134. all the types involved. This particular union was written expecting a
  5135. pointer to have the same size as @code{int}. On a machine where one
  5136. pointer takes 8 bytes, the code using this union probably won't work
  5137. as expected. The union, as such, will function correctly---if you
  5138. store two values through @code{two_ints} and extract them through
  5139. @code{two_ints}, you will get the same integers back---but the part of
  5140. the program that expects the union to be 8 bytes long could
  5141. malfunction, or at least use too much space.
  5142. The above example shows one case where a @code{struct} type with no
  5143. tag can be useful. Another way to get effectively the same result
  5144. is with arrays as members of the union:
  5145. @example
  5146. union eight_bytes
  5147. @{
  5148. long long big_int_elt;
  5149. double double_elt;
  5150. int two_ints[2];
  5151. void *two_ptrs[2];
  5152. @};
  5153. @end example
  5154. @node Cast to Union
  5155. @section Cast to a Union Type
  5156. @cindex cast to a union
  5157. @cindex union, casting to a
  5158. In GNU C, you can explicitly cast any of the alternative types to the
  5159. union type; for instance,
  5160. @example
  5161. (union eight_bytes) (long long) 5
  5162. @end example
  5163. @noindent
  5164. makes a value of type @code{union eight_bytes} which gets its contents
  5165. through the alternative named @code{big_int_elt}.
  5166. The value being cast must exactly match the type of the alternative,
  5167. so this is not valid:
  5168. @example
  5169. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5170. @end example
  5171. A cast to union type looks like any other cast, except that the type
  5172. specified is a union type. You can specify the type either with
  5173. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5174. Typedef Names}).
  5175. Using the cast as the right-hand side of an assignment to a variable of
  5176. union type is equivalent to storing in an alternative of the union:
  5177. @example
  5178. union foo u;
  5179. u = (union foo) x @r{means} u.i = x
  5180. u = (union foo) y @r{means} u.d = y
  5181. @end example
  5182. You can also use the union cast as a function argument:
  5183. @example
  5184. void hack (union foo);
  5185. @r{@dots{}}
  5186. hack ((union foo) x);
  5187. @end example
  5188. @node Structure Constructors
  5189. @section Structure Constructors
  5190. @cindex structure constructors
  5191. @cindex constructors, structure
  5192. You can construct a structure value by writing its type in
  5193. parentheses, followed by an initializer that would be valid in a
  5194. declaration for that type. For instance, given this declaration,
  5195. @example
  5196. struct foo @{int a; char b[2];@} structure;
  5197. @end example
  5198. @noindent
  5199. you can create a @code{struct foo} value as follows:
  5200. @example
  5201. ((struct foo) @{x + y, 'a', 0@})
  5202. @end example
  5203. @noindent
  5204. This specifies @code{x + y} for field @code{a},
  5205. the character @samp{a} for field @code{b}'s element 0,
  5206. and the null character for field @code{b}'s element 1.
  5207. The parentheses around that constructor are to necessary, but we
  5208. recommend writing them to make the nesting of the containing
  5209. expression clearer.
  5210. You can also show the nesting of the two by writing it like
  5211. this:
  5212. @example
  5213. ((struct foo) @{x + y, @{'a', 0@} @})
  5214. @end example
  5215. Each of those is equivalent to writing the following statement
  5216. expression (@pxref{Statement Exprs}):
  5217. @example
  5218. (@{
  5219. struct foo temp = @{x + y, 'a', 0@};
  5220. temp;
  5221. @})
  5222. @end example
  5223. You can also create a union value this way, but it is not especially
  5224. useful since that is equivalent to doing a cast:
  5225. @example
  5226. ((union whosis) @{@var{value}@})
  5227. @r{is equivalent to}
  5228. ((union whosis) (@var{value}))
  5229. @end example
  5230. @node Unnamed Types as Fields
  5231. @section Unnamed Types as Fields
  5232. @cindex unnamed structures
  5233. @cindex unnamed unions
  5234. @cindex structures, unnamed
  5235. @cindex unions, unnamed
  5236. A structure or a union can contain, as fields,
  5237. unnamed structures and unions. Here's an example:
  5238. @example
  5239. struct
  5240. @{
  5241. int a;
  5242. union
  5243. @{
  5244. int b;
  5245. float c;
  5246. @};
  5247. int d;
  5248. @} foo;
  5249. @end example
  5250. @noindent
  5251. You can access the fields of the unnamed union within @code{foo} as if they
  5252. were individual fields at the same level as the union definition:
  5253. @example
  5254. foo.a = 42;
  5255. foo.b = 47;
  5256. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5257. foo.d = 314;
  5258. @end example
  5259. Avoid using field names that could cause ambiguity. For example, with
  5260. this definition:
  5261. @example
  5262. struct
  5263. @{
  5264. int a;
  5265. struct
  5266. @{
  5267. int a;
  5268. float b;
  5269. @};
  5270. @} foo;
  5271. @end example
  5272. @noindent
  5273. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5274. an error when a definition is ambiguous in this way.
  5275. @node Incomplete Types
  5276. @section Incomplete Types
  5277. @cindex incomplete types
  5278. @cindex types, incomplete
  5279. A type that has not been fully defined is called an @dfn{incomplete
  5280. type}. Structure and union types are incomplete when the code makes a
  5281. forward reference, such as @code{struct foo}, before defining the
  5282. type. An array type is incomplete when its length is unspecified.
  5283. You can't use an incomplete type to declare a variable or field, or
  5284. use it for a function parameter or return type. The operators
  5285. @code{sizeof} and @code{_Alignof} give errors when used on an
  5286. incomplete type.
  5287. However, you can define a pointer to an incomplete type, and declare a
  5288. variable or field with such a pointer type. In general, you can do
  5289. everything with such pointers except dereference them. For example:
  5290. @example
  5291. extern void bar (struct mysterious_value *);
  5292. void
  5293. foo (struct mysterious_value *arg)
  5294. @{
  5295. bar (arg);
  5296. @}
  5297. @r{@dots{}}
  5298. @{
  5299. struct mysterious_value *p, **q;
  5300. p = *q;
  5301. foo (p);
  5302. @}
  5303. @end example
  5304. @noindent
  5305. These examples are valid because the code doesn't try to understand
  5306. what @code{p} points to; it just passes the pointer around.
  5307. (Presumably @code{bar} is defined in some other file that really does
  5308. have a definition for @code{struct mysterious_value}.) However,
  5309. dereferencing the pointer would get an error; that requires a
  5310. definition for the structure type.
  5311. @node Intertwined Incomplete Types
  5312. @section Intertwined Incomplete Types
  5313. When several structure types contain pointers to each other, you can
  5314. define the types in any order because pointers to types that come
  5315. later are incomplete types. Thus,
  5316. Here is an example.
  5317. @example
  5318. /* @r{An employee record points to a group.} */
  5319. struct employee
  5320. @{
  5321. char *name;
  5322. @r{@dots{}}
  5323. struct group *group; /* @r{incomplete type.} */
  5324. @r{@dots{}}
  5325. @};
  5326. /* @r{An employee list points to employees.} */
  5327. struct employee_list
  5328. @{
  5329. struct employee *this_one;
  5330. struct employee_list *next; /* @r{incomplete type.} */
  5331. @r{@dots{}}
  5332. @};
  5333. /* @r{A group points to one employee_list.} */
  5334. struct group
  5335. @{
  5336. char *name;
  5337. @r{@dots{}}
  5338. struct employee_list *employees;
  5339. @r{@dots{}}
  5340. @};
  5341. @end example
  5342. @node Type Tags
  5343. @section Type Tags
  5344. @cindex type tags
  5345. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5346. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5347. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5348. name or function name; the type tags have a separate @dfn{name space}.
  5349. Thus, there is no name conflict in this code:
  5350. @example
  5351. struct pair @{ int a, b; @};
  5352. int pair = 1;
  5353. @end example
  5354. @noindent
  5355. nor in this one:
  5356. @example
  5357. struct pair @{ int a, b; @} pair;
  5358. @end example
  5359. @noindent
  5360. where @code{pair} is both a structure type tag and a variable name.
  5361. However, @code{struct}, @code{union}, and @code{enum} share the same
  5362. name space of tags, so this is a conflict:
  5363. @example
  5364. struct pair @{ int a, b; @};
  5365. enum pair @{ c, d @};
  5366. @end example
  5367. @noindent
  5368. and so is this:
  5369. @example
  5370. struct pair @{ int a, b; @};
  5371. struct pair @{ int c, d; @};
  5372. @end example
  5373. When the code defines a type tag inside a block, the tag's scope is
  5374. limited to that block (as for local variables). Two definitions for
  5375. one type tag do not conflict if they are in different scopes; rather,
  5376. each is valid in its scope. For example,
  5377. @example
  5378. struct pair @{ int a, b; @};
  5379. void
  5380. pair_up_doubles (int len, double array[])
  5381. @{
  5382. struct pair @{ double a, b; @};
  5383. @r{@dots{}}
  5384. @}
  5385. @end example
  5386. @noindent
  5387. has two definitions for @code{struct pair} which do not conflict. The
  5388. one inside the function applies only within the definition of
  5389. @code{pair_up_doubles}. Within its scope, that definition
  5390. @dfn{shadows} the outer definition.
  5391. If @code{struct pair} appears inside the function body, before the
  5392. inner definition, it refers to the outer definition---the only one
  5393. that has been seen at that point. Thus, in this code,
  5394. @example
  5395. struct pair @{ int a, b; @};
  5396. void
  5397. pair_up_doubles (int len, double array[])
  5398. @{
  5399. struct two_pairs @{ struct pair *p, *q; @};
  5400. struct pair @{ double a, b; @};
  5401. @r{@dots{}}
  5402. @}
  5403. @end example
  5404. @noindent
  5405. the structure @code{two_pairs} has pointers to the outer definition of
  5406. @code{struct pair}, which is probably not desirable.
  5407. To prevent that, you can write @code{struct pair;} inside the function
  5408. body as a variable declaration with no variables. This is a
  5409. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5410. type tag local to the current block, with the details of the type to
  5411. come later. Here's an example:
  5412. @example
  5413. void
  5414. pair_up_doubles (int len, double array[])
  5415. @{
  5416. /* @r{Forward declaration for @code{pair}.} */
  5417. struct pair;
  5418. struct two_pairs @{ struct pair *p, *q; @};
  5419. /* @r{Give the details.} */
  5420. struct pair @{ double a, b; @};
  5421. @r{@dots{}}
  5422. @}
  5423. @end example
  5424. However, the cleanest practice is to avoid shadowing type tags.
  5425. @node Arrays
  5426. @chapter Arrays
  5427. @cindex array
  5428. @cindex elements of arrays
  5429. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5430. all of the same data type. Each element is identified by its numeric
  5431. @var{index} within the array.
  5432. We presented arrays of numbers in the sample programs early in this
  5433. manual (@pxref{Array Example}). However, arrays can have elements of
  5434. any data type, including pointers, structures, unions, and other
  5435. arrays.
  5436. If you know another programming language, you may suppose that you know all
  5437. about arrays, but C arrays have special quirks, so in this chapter we
  5438. collect all the information about arrays in C@.
  5439. The elements of a C array are allocated consecutively in memory,
  5440. with no gaps between them. Each element is aligned as required
  5441. for its data type (@pxref{Type Alignment}).
  5442. @menu
  5443. * Accessing Array Elements:: How to access individual elements of an array.
  5444. * Declaring an Array:: How to name and reserve space for a new array.
  5445. * Strings:: A string in C is a special case of array.
  5446. * Array Type Designators:: Referring to a specific array type.
  5447. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5448. * Limitations of C Arrays:: Arrays are not first-class objects.
  5449. * Multidimensional Arrays:: Arrays of arrays.
  5450. * Constructing Array Values:: Assigning values to an entire array at once.
  5451. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5452. @end menu
  5453. @node Accessing Array Elements
  5454. @section Accessing Array Elements
  5455. @cindex accessing array elements
  5456. @cindex array elements, accessing
  5457. If the variable @code{a} is an array, the @var{n}th element of
  5458. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5459. an element's value or to assign to it:
  5460. @example
  5461. x = a[5];
  5462. a[6] = 1;
  5463. @end example
  5464. @noindent
  5465. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5466. lvalue.
  5467. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5468. valid index is one less than the number of elements.
  5469. The C language does not check whether array indices are in bounds, so
  5470. if the code uses an out-of-range index, it will access memory outside the
  5471. array.
  5472. @strong{Warning:} Using only valid index values in C is the
  5473. programmer's responsibility.
  5474. Array indexing in C is not a primitive operation: it is defined in
  5475. terms of pointer arithmetic and dereferencing. Now that we know
  5476. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5477. its job.
  5478. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5479. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5480. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5481. When an expression with array type (such as @code{a}) appears as part
  5482. of a larger C expression, it is converted automatically to a pointer
  5483. to element zero of that array. For instance, @code{a} in an
  5484. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5485. computed as @code{*(&a[0]+i)}.
  5486. Now we can analyze how that expression gives us the desired element of
  5487. the array. It makes a pointer to element 0 of @code{a}, advances it
  5488. by the value of @code{i}, and dereferences that pointer.
  5489. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5490. @node Declaring an Array
  5491. @section Declaring an Array
  5492. @cindex declaring an array
  5493. @cindex array, declaring
  5494. To make an array declaration, write @code{[@var{length}]} after the
  5495. name being declared. This construct is valid in the declaration of a
  5496. variable, a function parameter, a function value type (the value can't
  5497. be an array, but it can be a pointer to one), a structure field, or a
  5498. union alternative.
  5499. The surrounding declaration specifies the element type of the array;
  5500. that can be any type of data, but not @code{void} or a function type.
  5501. For instance,
  5502. @example
  5503. double a[5];
  5504. @end example
  5505. @noindent
  5506. declares @code{a} as an array of 5 @code{double}s.
  5507. @example
  5508. struct foo bstruct[length];
  5509. @end example
  5510. @noindent
  5511. declares @code{bstruct} as an array of @code{length} objects of type
  5512. @code{struct foo}. A variable array size like this is allowed when
  5513. the array is not file-scope.
  5514. Other declaration constructs can nest within the array declaration
  5515. construct. For instance:
  5516. @example
  5517. struct foo *b[length];
  5518. @end example
  5519. @noindent
  5520. declares @code{b} as an array of @code{length} pointers to
  5521. @code{struct foo}. This shows that the length need not be a constant
  5522. (@pxref{Arrays of Variable Length}).
  5523. @example
  5524. double (*c)[5];
  5525. @end example
  5526. @noindent
  5527. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5528. @example
  5529. char *(*f (int))[5];
  5530. @end example
  5531. @noindent
  5532. declares @code{f} as a function taking an @code{int} argument and
  5533. returning a pointer to an array of 5 strings (pointers to
  5534. @code{char}s).
  5535. @example
  5536. double aa[5][10];
  5537. @end example
  5538. @noindent
  5539. declares @code{aa} as an array of 5 elements, each of which is an
  5540. array of 10 @code{double}s. This shows how to declare a
  5541. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5542. All these declarations specify the array's length, which is needed in
  5543. these cases in order to allocate storage for the array.
  5544. @node Strings
  5545. @section Strings
  5546. @cindex string
  5547. A string in C is a sequence of elements of type @code{char},
  5548. terminated with the null character, the character with code zero.
  5549. Programs often need to use strings with specific, fixed contents. To
  5550. write one in a C program, use a @dfn{string constant} such as
  5551. @code{"Take me to your leader!"}. The data type of a string constant
  5552. is @code{char *}. For the full syntactic details of writing string
  5553. constants, @ref{String Constants}.
  5554. To declare a place to store a non-constant string, declare an array of
  5555. @code{char}. Keep in mind that it must include one extra @code{char}
  5556. for the terminating null. For instance,
  5557. @example
  5558. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5559. @end example
  5560. @noindent
  5561. declares an array named @samp{text} with six elements---five letters
  5562. and the terminating null character. An equivalent way to get the same
  5563. result is this,
  5564. @example
  5565. char text[] = "Hello";
  5566. @end example
  5567. @noindent
  5568. which copies the elements of the string constant, including @emph{its}
  5569. terminating null character.
  5570. @example
  5571. char message[200];
  5572. @end example
  5573. @noindent
  5574. declares an array long enough to hold a string of 199 ASCII characters
  5575. plus the terminating null character.
  5576. When you store a string into @code{message} be sure to check or prove
  5577. that the length does not exceed its size. For example,
  5578. @example
  5579. void
  5580. set_message (char *text)
  5581. @{
  5582. int i;
  5583. for (i = 0; i < sizeof (message); i++)
  5584. @{
  5585. message[i] = text[i];
  5586. if (text[i] == 0)
  5587. return;
  5588. @}
  5589. fatal_error ("Message is too long for `message');
  5590. @}
  5591. @end example
  5592. It's easy to do this with the standard library function
  5593. @code{strncpy}, which fills out the whole destination array (up to a
  5594. specified length) with null characters. Thus, if the last character
  5595. of the destination is not null, the string did not fit. Many system
  5596. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5597. to run faster than an explicit @code{for}-loop.
  5598. Here's what the code looks like:
  5599. @example
  5600. void
  5601. set_message (char *text)
  5602. @{
  5603. strncpy (message, text, sizeof (message));
  5604. if (message[sizeof (message) - 1] != 0)
  5605. fatal_error ("Message is too long for `message');
  5606. @}
  5607. @end example
  5608. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5609. Library Reference Manual}, for more information about the standard
  5610. library functions for operating on strings.
  5611. You can avoid putting a fixed length limit on strings you construct or
  5612. operate on by allocating the space for them dynamically.
  5613. @xref{Dynamic Memory Allocation}.
  5614. @node Array Type Designators
  5615. @section Array Type Designators
  5616. Every C type has a type designator, which you make by deleting the
  5617. variable name and the semicolon from a declaration (@pxref{Type
  5618. Designators}). The designators for array types follow this rule, but
  5619. they may appear surprising.
  5620. @example
  5621. @r{type} int a[5]; @r{designator} int [5]
  5622. @r{type} double a[5][3]; @r{designator} double [5][3]
  5623. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5624. @end example
  5625. @node Incomplete Array Types
  5626. @section Incomplete Array Types
  5627. @cindex incomplete array types
  5628. @cindex array types, incomplete
  5629. An array is equivalent, for most purposes, to a pointer to its zeroth
  5630. element. When that is true, the length of the array is irrelevant.
  5631. The length needs to be known only for allocating space for the array, or
  5632. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5633. contexts C allows
  5634. @itemize @bullet
  5635. @item
  5636. An @code{extern} declaration says how to refer to a variable allocated
  5637. elsewhere. It does not need to allocate space for the variable,
  5638. so if it is an array, you can omit the length. For example,
  5639. @example
  5640. extern int foo[];
  5641. @end example
  5642. @item
  5643. When declaring a function parameter as an array, the argument value
  5644. passed to the function is really a pointer to the array's zeroth
  5645. element. This value does not say how long the array really is, there
  5646. is no need to declare it. For example,
  5647. @example
  5648. int
  5649. func (int foo[])
  5650. @end example
  5651. @end itemize
  5652. These declarations are examples of @dfn{incomplete} array types, types
  5653. that are not fully specified. The incompleteness makes no difference
  5654. for accessing elements of the array, but it matters for some other
  5655. things. For instance, @code{sizeof} is not allowed on an incomplete
  5656. type.
  5657. With multidimensional arrays, only the first dimension can be omitted:
  5658. @example
  5659. extern struct chesspiece *funnyboard foo[][8];
  5660. @end example
  5661. In other words, the code doesn't have to say how many rows there are,
  5662. but it must state how big each row is.
  5663. @node Limitations of C Arrays
  5664. @section Limitations of C Arrays
  5665. @cindex limitations of C arrays
  5666. @cindex first-class object
  5667. Arrays have quirks in C because they are not ``first-class objects'':
  5668. there is no way in C to operate on an array as a unit.
  5669. The other composite objects in C, structures and unions, are
  5670. first-class objects: a C program can copy a structure or union value
  5671. in an assignment, or pass one as an argument to a function, or make a
  5672. function return one. You can't do those things with an array in C@.
  5673. That is because a value you can operate on never has an array type.
  5674. An expression in C can have an array type, but that doesn't produce
  5675. the array as a value. Instead it is converted automatically to a
  5676. pointer to the array's element at index zero. The code can operate
  5677. on the pointer, and through that on individual elements of the array,
  5678. but it can't get and operate on the array as a unit.
  5679. There are three exceptions to this conversion rule, but none of them
  5680. offers a way to operate on the array as a whole.
  5681. First, @samp{&} applied to an expression with array type gives you the
  5682. address of the array, as an array type. However, you can't operate on the
  5683. whole array that way---if you apply @samp{*} to get the array back,
  5684. that expression converts, as usual, to a pointer to its zeroth
  5685. element.
  5686. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5687. @code{typeof} do not convert the array to a pointer; they leave it as
  5688. an array. But they don't operate on the array's data---they only give
  5689. information about its type.
  5690. Third, a string constant used as an initializer for an array is not
  5691. converted to a pointer---rather, the declaration copies the
  5692. @emph{contents} of that string in that one special case.
  5693. You @emph{can} copy the contents of an array, just not with an
  5694. assignment operator. You can do it by calling the library function
  5695. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5696. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5697. when a structure contains just an array, you can copy that structure.
  5698. An array itself is an lvalue if it is a declared variable, or part of
  5699. a structure or union that is an lvalue. When you construct an array
  5700. from elements (@pxref{Constructing Array Values}), that array is not
  5701. an lvalue.
  5702. @node Multidimensional Arrays
  5703. @section Multidimensional Arrays
  5704. @cindex multidimensional arrays
  5705. @cindex array, multidimensional
  5706. Strictly speaking, all arrays in C are unidimensional. However, you
  5707. can create an array of arrays, which is more or less equivalent to a
  5708. multidimensional array. For example,
  5709. @example
  5710. struct chesspiece *board[8][8];
  5711. @end example
  5712. @noindent
  5713. declares an array of 8 arrays of 8 pointers to @code{struct
  5714. chesspiece}. This data type could represent the state of a chess
  5715. game. To access one square's contents requires two array index
  5716. operations, one for each dimension. For instance, you can write
  5717. @code{board[row][column]}, assuming @code{row} and @code{column}
  5718. are variables with integer values in the proper range.
  5719. How does C understand @code{board[row][column]}? First of all,
  5720. @code{board} is converted automatically to a pointer to the zeroth
  5721. element (at index zero) of @code{board}. Adding @code{row} to that
  5722. makes it point to the desired element. Thus, @code{board[row]}'s
  5723. value is an element of @code{board}---an array of 8 pointers.
  5724. However, as an expression with array type, it is converted
  5725. automatically to a pointer to the array's zeroth element. The second
  5726. array index operation, @code{[column]}, accesses the chosen element
  5727. from that array.
  5728. As this shows, pointer-to-array types are meaningful in C@.
  5729. You can declare a variable that points to a row in a chess board
  5730. like this:
  5731. @example
  5732. struct chesspiece *(*rowptr)[8];
  5733. @end example
  5734. @noindent
  5735. This points to an array of 8 pointers to @code{struct chesspiece}.
  5736. You can assign to it as follows:
  5737. @example
  5738. rowptr = &board[5];
  5739. @end example
  5740. The dimensions don't have to be equal in length. Here we declare
  5741. @code{statepop} as an array to hold the population of each state in
  5742. the United States for each year since 1900:
  5743. @example
  5744. #define NSTATES 50
  5745. @{
  5746. int nyears = current_year - 1900 + 1;
  5747. int statepop[NSTATES][nyears];
  5748. @r{@dots{}}
  5749. @}
  5750. @end example
  5751. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5752. each indexed by the year (counting from 1900). Thus, to get the
  5753. element for a particular state and year, we must subscript it first
  5754. by the number that indicates the state, and second by the index for
  5755. the year:
  5756. @example
  5757. statepop[state][year - 1900]
  5758. @end example
  5759. @cindex array, layout in memory
  5760. The subarrays within the multidimensional array are allocated
  5761. consecutively in memory, and within each subarray, its elements are
  5762. allocated consecutively in memory. The most efficient way to process
  5763. all the elements in the array is to scan the last subscript in the
  5764. innermost loop. This means consecutive accesses go to consecutive
  5765. memory locations, which optimizes use of the processor's memory cache.
  5766. For example:
  5767. @example
  5768. int total = 0;
  5769. float average;
  5770. for (int state = 0; state < NSTATES, ++state)
  5771. @{
  5772. for (int year = 0; year < nyears; ++year)
  5773. @{
  5774. total += statepop[state][year];
  5775. @}
  5776. @}
  5777. average = total / nyears;
  5778. @end example
  5779. C's layout for multidimensional arrays is different from Fortran's
  5780. layout. In Fortran, a multidimensional array is not an array of
  5781. arrays; rather, multidimensional arrays are a primitive feature, and
  5782. it is the first index that varies most rapidly between consecutive
  5783. memory locations. Thus, the memory layout of a 50x114 array in C
  5784. matches that of a 114x50 array in Fortran.
  5785. @node Constructing Array Values
  5786. @section Constructing Array Values
  5787. @cindex constructing array values
  5788. @cindex array values, constructing
  5789. You can construct an array from elements by writing them inside
  5790. braces, and preceding all that with the array type's designator in
  5791. parentheses. There is no need to specify the array length, since the
  5792. number of elements determines that. The constructor looks like this:
  5793. @example
  5794. (@var{elttype}[]) @{ @var{elements} @};
  5795. @end example
  5796. Here is an example, which constructs an array of string pointers:
  5797. @example
  5798. (char *[]) @{ "x", "y", "z" @};
  5799. @end example
  5800. That's equivalent in effect to declaring an array with the same
  5801. initializer, like this:
  5802. @example
  5803. char *array[] = @{ "x", "y", "z" @};
  5804. @end example
  5805. and then using the array.
  5806. If all the elements are simple constant expressions, or made up of
  5807. such, then the compound literal can be coerced to a pointer to its
  5808. zeroth element and used to initialize a file-scope variable
  5809. (@pxref{File-Scope Variables}), as shown here:
  5810. @example
  5811. char **foo = (char *[]) @{ "x", "y", "z" @};
  5812. @end example
  5813. @noindent
  5814. The data type of @code{foo} is @code{char **}, which is a pointer
  5815. type, not an array type. The declaration is equivalent to defining
  5816. and then using an array-type variable:
  5817. @example
  5818. char *nameless_array[] = @{ "x", "y", "z" @};
  5819. char **foo = &nameless_array[0];
  5820. @end example
  5821. @node Arrays of Variable Length
  5822. @section Arrays of Variable Length
  5823. @cindex array of variable length
  5824. @cindex variable-length arrays
  5825. In GNU C, you can declare variable-length arrays like any other
  5826. arrays, but with a length that is not a constant expression. The
  5827. storage is allocated at the point of declaration and deallocated when
  5828. the block scope containing the declaration exits. For example:
  5829. @example
  5830. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5831. #include <string.h> /* @r{Declares @code{str}.} */
  5832. FILE *
  5833. concat_fopen (char *s1, char *s2, char *mode)
  5834. @{
  5835. char str[strlen (s1) + strlen (s2) + 1];
  5836. strcpy (str, s1);
  5837. strcat (str, s2);
  5838. return fopen (str, mode);
  5839. @}
  5840. @end example
  5841. @noindent
  5842. (This uses some standard library functions; see @ref{String and Array
  5843. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5844. The length of an array is computed once when the storage is allocated
  5845. and is remembered for the scope of the array in case it is used in
  5846. @code{sizeof}.
  5847. @strong{Warning:} don't allocate a variable-length array if the size
  5848. might be very large (more than 100,000), or in a recursive function,
  5849. because that is likely to cause stack overflow. Allocate the array
  5850. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5851. Jumping or breaking out of the scope of the array name deallocates the
  5852. storage. Jumping into the scope is not allowed; that gives an error
  5853. message.
  5854. You can also use variable-length arrays as arguments to functions:
  5855. @example
  5856. struct entry
  5857. tester (int len, char data[len][len])
  5858. @{
  5859. @r{@dots{}}
  5860. @}
  5861. @end example
  5862. As usual, a function argument declared with an array type
  5863. is really a pointer to an array that already exists.
  5864. Calling the function does not allocate the array, so there's no
  5865. particular danger of stack overflow in using this construct.
  5866. To pass the array first and the length afterward, use a forward
  5867. declaration in the function's parameter list (another GNU extension).
  5868. For example,
  5869. @example
  5870. struct entry
  5871. tester (int len; char data[len][len], int len)
  5872. @{
  5873. @r{@dots{}}
  5874. @}
  5875. @end example
  5876. The @code{int len} before the semicolon is a @dfn{parameter forward
  5877. declaration}, and it serves the purpose of making the name @code{len}
  5878. known when the declaration of @code{data} is parsed.
  5879. You can write any number of such parameter forward declarations in the
  5880. parameter list. They can be separated by commas or semicolons, but
  5881. the last one must end with a semicolon, which is followed by the
  5882. ``real'' parameter declarations. Each forward declaration must match
  5883. a ``real'' declaration in parameter name and data type. ISO C11 does
  5884. not support parameter forward declarations.
  5885. @node Enumeration Types
  5886. @chapter Enumeration Types
  5887. @cindex enumeration types
  5888. @cindex types, enumeration
  5889. @cindex enumerator
  5890. An @dfn{enumeration type} represents a limited set of integer values,
  5891. each with a name. It is effectively equivalent to a primitive integer
  5892. type.
  5893. Suppose we have a list of possible emotional states to store in an
  5894. integer variable. We can give names to these alternative values with
  5895. an enumeration:
  5896. @example
  5897. enum emotion_state @{ neutral, happy, sad, worried,
  5898. calm, nervous @};
  5899. @end example
  5900. @noindent
  5901. (Never mind that this is a simplistic way to classify emotional states;
  5902. it's just a code example.)
  5903. The names inside the enumeration are called @dfn{enumerators}. The
  5904. enumeration type defines them as constants, and their values are
  5905. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5906. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5907. the enumerators explicitly like this:
  5908. @example
  5909. enum emotion_state @{ neutral = 2, happy = 5,
  5910. sad = 20, worried = 10,
  5911. calm = -5, nervous = -300 @};
  5912. @end example
  5913. Each enumerator which does not specify a value gets value zero
  5914. (if it is at the beginning) or the next consecutive integer.
  5915. @example
  5916. /* @r{@code{neutral} is 0 by default,}
  5917. @r{and @code{worried} is 21 by default.} */
  5918. enum emotion_state @{ neutral,
  5919. happy = 5, sad = 20, worried,
  5920. calm = -5, nervous = -300 @};
  5921. @end example
  5922. If an enumerator is obsolete, you can specify that using it should
  5923. cause a warning, by including an attribute in the enumerator's
  5924. declaration. Here is how @code{happy} would look with this
  5925. attribute:
  5926. @example
  5927. happy __attribute__
  5928. ((deprecated
  5929. ("impossible under plutocratic rule")))
  5930. = 5,
  5931. @end example
  5932. @xref{Attributes}.
  5933. You can declare variables with the enumeration type:
  5934. @example
  5935. enum emotion_state feelings_now;
  5936. @end example
  5937. In the C code itself, this is equivalent to declaring the variable
  5938. @code{int}. (If all the enumeration values are positive, it is
  5939. equivalent to @code{unsigned int}.) However, declaring it with the
  5940. enumeration type has an advantage in debugging, because GDB knows it
  5941. should display the current value of the variable using the
  5942. corresponding name. If the variable's type is @code{int}, GDB can
  5943. only show the value as a number.
  5944. The identifier that follows @code{enum} is called a @dfn{type tag}
  5945. since it distinguishes different enumeration types. Type tags are in
  5946. a separate name space and belong to scopes like most other names in C@.
  5947. @xref{Type Tags}, for explanation.
  5948. You can predeclare an @code{enum} type tag like a structure or union
  5949. type tag, like this:
  5950. @example
  5951. enum foo;
  5952. @end example
  5953. @noindent
  5954. The @code{enum} type is incomplete until you finish defining it.
  5955. You can optionally include a trailing comma at the end of a list of
  5956. enumeration values:
  5957. @example
  5958. enum emotion_state @{ neutral, happy, sad, worried,
  5959. calm, nervous, @};
  5960. @end example
  5961. @noindent
  5962. This is useful in some macro definitions, since it enables you to
  5963. assemble the list of enumerators without knowing which one is last.
  5964. The extra comma does not change the meaning of the enumeration in any
  5965. way.
  5966. @node Defining Typedef Names
  5967. @chapter Defining Typedef Names
  5968. @cindex typedef names
  5969. @findex typedef
  5970. You can define a data type keyword as an alias for any type, and then
  5971. use the alias syntactically like a built-in type keyword such as
  5972. @code{int}. You do this using @code{typedef}, so these aliases are
  5973. also called @dfn{typedef names}.
  5974. @code{typedef} is followed by text that looks just like a variable
  5975. declaration, but instead of declaring variables it defines data type
  5976. keywords.
  5977. Here's how to define @code{fooptr} as a typedef alias for the type
  5978. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5979. with that type:
  5980. @example
  5981. typedef struct foo *fooptr;
  5982. fooptr x, y;
  5983. @end example
  5984. @noindent
  5985. That declaration is equivalent to the following one:
  5986. @example
  5987. struct foo *x, *y;
  5988. @end example
  5989. You can define a typedef alias for any type. For instance, this makes
  5990. @code{frobcount} an alias for type @code{int}:
  5991. @example
  5992. typedef int frobcount;
  5993. @end example
  5994. @noindent
  5995. This doesn't define a new type distinct from @code{int}. Rather,
  5996. @code{frobcount} is another name for the type @code{int}. Once the
  5997. variable is declared, it makes no difference which name the
  5998. declaration used.
  5999. There is a syntactic difference, however, between @code{frobcount} and
  6000. @code{int}: A typedef name cannot be used with
  6001. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6002. to specify the type all by itself. So you can't write this:
  6003. @example
  6004. unsigned frobcount f1; /* @r{Error!} */
  6005. @end example
  6006. But you can write this:
  6007. @example
  6008. typedef unsigned int unsigned_frobcount;
  6009. unsigned_frobcount f1;
  6010. @end example
  6011. In other words, a typedef name is not an alias for @emph{a keyword}
  6012. such as @code{int}. It stands for a @emph{type}, and that could be
  6013. the type @code{int}.
  6014. Typedef names are in the same namespace as functions and variables, so
  6015. you can't use the same name for a typedef and a function, or a typedef
  6016. and a variable. When a typedef is declared inside a code block, it is
  6017. in scope only in that block.
  6018. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6019. because many of these have standard meanings.
  6020. You can redefine a typedef name to the exact same type as its first
  6021. definition, but you cannot redefine a typedef name to a
  6022. different type, even if the two types are compatible. For example, this
  6023. is valid:
  6024. @example
  6025. typedef int frobcount;
  6026. typedef int frotzcount;
  6027. typedef frotzcount frobcount;
  6028. typedef frobcount frotzcount;
  6029. @end example
  6030. @noindent
  6031. because each typedef name is always defined with the same type
  6032. (@code{int}), but this is not valid:
  6033. @example
  6034. enum foo @{f1, f2, f3@};
  6035. typedef enum foo frobcount;
  6036. typedef int frobcount;
  6037. @end example
  6038. @noindent
  6039. Even though the type @code{enum foo} is compatible with @code{int},
  6040. they are not the @emph{same} type.
  6041. @node Statements
  6042. @chapter Statements
  6043. @cindex statements
  6044. A @dfn{statement} specifies computations to be done for effect; it
  6045. does not produce a value, as an expression would. In general a
  6046. statement ends with a semicolon (@samp{;}), but blocks (which are
  6047. statements, more or less) are an exception to that rule.
  6048. @ifnottex
  6049. @xref{Blocks}.
  6050. @end ifnottex
  6051. The places to use statements are inside a block, and inside a
  6052. complex statement. A @dfn{complex statement} contains one or two
  6053. components that are nested statements. Each such component must
  6054. consist of one and only one statement. The way to put multiple
  6055. statements in such a component is to group them into a @dfn{block}
  6056. (@pxref{Blocks}), which counts as one statement.
  6057. The following sections describe the various kinds of statement.
  6058. @menu
  6059. * Expression Statement:: Evaluate an expression, as a statement,
  6060. usually done for a side effect.
  6061. * if Statement:: Basic conditional execution.
  6062. * if-else Statement:: Multiple branches for conditional execution.
  6063. * Blocks:: Grouping multiple statements together.
  6064. * return Statement:: Return a value from a function.
  6065. * Loop Statements:: Repeatedly executing a statement or block.
  6066. * switch Statement:: Multi-way conditional choices.
  6067. * switch Example:: A plausible example of using @code{switch}.
  6068. * Duffs Device:: A special way to use @code{switch}.
  6069. * Case Ranges:: Ranges of values for @code{switch} cases.
  6070. * Null Statement:: A statement that does nothing.
  6071. * goto Statement:: Jump to another point in the source code,
  6072. identified by a label.
  6073. * Local Labels:: Labels with limited scope.
  6074. * Labels as Values:: Getting the address of a label.
  6075. * Statement Exprs:: A series of statements used as an expression.
  6076. @end menu
  6077. @node Expression Statement
  6078. @section Expression Statement
  6079. @cindex expression statement
  6080. @cindex statement, expression
  6081. The most common kind of statement in C is an @dfn{expression statement}.
  6082. It consists of an expression followed by a
  6083. semicolon. The expression's value is discarded, so the expressions
  6084. that are useful are those that have side effects: assignment
  6085. expressions, increment and decrement expressions, and function calls.
  6086. Here are examples of expression statements:
  6087. @smallexample
  6088. x = 5; /* @r{Assignment expression.} */
  6089. p++; /* @r{Increment expression.} */
  6090. printf ("Done\n"); /* @r{Function call expression.} */
  6091. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6092. x + y; /* @r{Useless statement without effect.} */
  6093. @end smallexample
  6094. In very unusual circumstances we use an expression statement
  6095. whose purpose is to get a fault if an address is invalid:
  6096. @smallexample
  6097. volatile char *p;
  6098. @r{@dots{}}
  6099. *p; /* @r{Cause signal if @code{p} is null.} */
  6100. @end smallexample
  6101. If the target of @code{p} is not declared @code{volatile}, the
  6102. compiler might optimize away the memory access, since it knows that
  6103. the value isn't really used. @xref{volatile}.
  6104. @node if Statement
  6105. @section @code{if} Statement
  6106. @cindex @code{if} statement
  6107. @cindex statement, @code{if}
  6108. @findex if
  6109. An @code{if} statement computes an expression to decide
  6110. whether to execute the following statement or not.
  6111. It looks like this:
  6112. @example
  6113. if (@var{condition})
  6114. @var{execute-if-true}
  6115. @end example
  6116. The first thing this does is compute the value of @var{condition}. If
  6117. that is true (nonzero), then it executes the statement
  6118. @var{execute-if-true}. If the value of @var{condition} is false
  6119. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6120. nothing.
  6121. This is a @dfn{complex statement} because it contains a component
  6122. @var{if-true-substatement} that is a nested statement. It must be one
  6123. and only one statement. The way to put multiple statements there is
  6124. to group them into a @dfn{block} (@pxref{Blocks}).
  6125. @node if-else Statement
  6126. @section @code{if-else} Statement
  6127. @cindex @code{if}@dots{}@code{else} statement
  6128. @cindex statement, @code{if}@dots{}@code{else}
  6129. @findex else
  6130. An @code{if}-@code{else} statement computes an expression to decide
  6131. which of two nested statements to execute.
  6132. It looks like this:
  6133. @example
  6134. if (@var{condition})
  6135. @var{if-true-substatement}
  6136. else
  6137. @var{if-false-substatement}
  6138. @end example
  6139. The first thing this does is compute the value of @var{condition}. If
  6140. that is true (nonzero), then it executes the statement
  6141. @var{if-true-substatement}. If the value of @var{condition} is false
  6142. (zero), then it executes the statement @var{if-false-substatement} instead.
  6143. This is a @dfn{complex statement} because it contains components
  6144. @var{if-true-substatement} and @var{if-else-substatement} that are
  6145. nested statements. Each must be one and only one statement. The way
  6146. to put multiple statements in such a component is to group them into a
  6147. @dfn{block} (@pxref{Blocks}).
  6148. @node Blocks
  6149. @section Blocks
  6150. @cindex block
  6151. @cindex compound statement
  6152. A @dfn{block} is a construct that contains multiple statements of any
  6153. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6154. series of statements and declarations in between. Another name for
  6155. blocks is @dfn{compound statements}.
  6156. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6157. normal statement---it does not end with a semicolon. But you can
  6158. @emph{use} it like a statement; anywhere that a statement is required
  6159. or allowed, you can write a block and consider that block a statement.
  6160. So far it seems that a block is a kind of statement with an unusual
  6161. syntax. But that is not entirely true: a function body is also a
  6162. block, and that block is definitely not a statement. The text after a
  6163. function header is not treated as a statement; only a function body is
  6164. allowed there, and nothing else would be meaningful there.
  6165. In a formal grammar we would have to choose---either a block is a kind
  6166. of statement or it is not. But this manual is meant for humans, not
  6167. for parser generators. The clearest answer for humans is, ``a block
  6168. is a statement, in some ways.''
  6169. @cindex nested block
  6170. @cindex internal block
  6171. A block that isn't a function body is called an @dfn{internal block}
  6172. or a @dfn{nested block}. You can put a nested block directly inside
  6173. another block, but more often the nested block is inside some complex
  6174. statement, such as a @code{for} statement or an @code{if} statement.
  6175. There are two uses for nested blocks in C:
  6176. @itemize @bullet
  6177. @item
  6178. To specify the scope for local declarations. For instance, a local
  6179. variable's scope is the rest of the innermost containing block.
  6180. @item
  6181. To write a series of statements where, syntactically, one statement is
  6182. called for. For instance, the @var{execute-if-true} of an @code{if}
  6183. statement is one statement. To put multiple statements there, they
  6184. have to be wrapped in a block, like this:
  6185. @example
  6186. if (x < 0)
  6187. @{
  6188. printf ("x was negative\n");
  6189. x = -x;
  6190. @}
  6191. @end example
  6192. @end itemize
  6193. This example (repeated from above) shows a nested block which serves
  6194. both purposes: it includes two statements (plus a declaration) in the
  6195. body of a @code{while} statement, and it provides the scope for the
  6196. declaration of @code{q}.
  6197. @example
  6198. void
  6199. free_intlist (struct intlistlink *p)
  6200. @{
  6201. while (p)
  6202. @{
  6203. struct intlistlink *q = p;
  6204. p = p->next;
  6205. free (q);
  6206. @}
  6207. @}
  6208. @end example
  6209. @node return Statement
  6210. @section @code{return} Statement
  6211. @cindex @code{return} statement
  6212. @cindex statement, @code{return}
  6213. @findex return
  6214. The @code{return} statement makes the containing function return
  6215. immediately. It has two forms. This one specifies no value to
  6216. return:
  6217. @example
  6218. return;
  6219. @end example
  6220. @noindent
  6221. That form is meant for functions whose return type is @code{void}
  6222. (@pxref{The Void Type}). You can also use it in a function that
  6223. returns nonvoid data, but that's a bad idea, since it makes the
  6224. function return garbage.
  6225. The form that specifies a value looks like this:
  6226. @example
  6227. return @var{value};
  6228. @end example
  6229. @noindent
  6230. which computes the expression @var{value} and makes the function
  6231. return that. If necessary, the value undergoes type conversion to
  6232. the function's declared return value type, which works like
  6233. assigning the value to a variable of that type.
  6234. @node Loop Statements
  6235. @section Loop Statements
  6236. @cindex loop statements
  6237. @cindex statements, loop
  6238. @cindex iteration
  6239. You can use a loop statement when you need to execute a series of
  6240. statements repeatedly, making an @dfn{iteration}. C provides several
  6241. different kinds of loop statements, described in the following
  6242. subsections.
  6243. Every kind of loop statement is a complex statement because contains a
  6244. component, here called @var{body}, which is a nested statement.
  6245. Most often the body is a block.
  6246. @menu
  6247. * while Statement:: Loop as long as a test expression is true.
  6248. * do-while Statement:: Execute a loop once, with further looping
  6249. as long as a test expression is true.
  6250. * break Statement:: End a loop immediately.
  6251. * for Statement:: Iterative looping.
  6252. * Example of for:: An example of iterative looping.
  6253. * Omitted for-Expressions:: for-loop expression options.
  6254. * for-Index Declarations:: for-loop declaration options.
  6255. * continue Statement:: Begin the next cycle of a loop.
  6256. @end menu
  6257. @node while Statement
  6258. @subsection @code{while} Statement
  6259. @cindex @code{while} statement
  6260. @cindex statement, @code{while}
  6261. @findex while
  6262. The @code{while} statement is the simplest loop construct.
  6263. It looks like this:
  6264. @example
  6265. while (@var{test})
  6266. @var{body}
  6267. @end example
  6268. Here, @var{body} is a statement (often a nested block) to repeat, and
  6269. @var{test} is the test expression that controls whether to repeat it again.
  6270. Each iteration of the loop starts by computing @var{test} and, if it
  6271. is true (nonzero), that means the loop should execute @var{body} again
  6272. and then start over.
  6273. Here's an example of advancing to the last structure in a chain of
  6274. structures chained through the @code{next} field:
  6275. @example
  6276. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6277. @r{@dots{}}
  6278. while (chain->next != NULL)
  6279. chain = chain->next;
  6280. @end example
  6281. @noindent
  6282. This code assumes the chain isn't empty to start with; if the chain is
  6283. empty (that is, if @code{chain} is a null pointer), the code gets a
  6284. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6285. @node do-while Statement
  6286. @subsection @code{do-while} Statement
  6287. @cindex @code{do}--@code{while} statement
  6288. @cindex statement, @code{do}--@code{while}
  6289. @findex do
  6290. The @code{do}--@code{while} statement is a simple loop construct that
  6291. performs the test at the end of the iteration.
  6292. @example
  6293. do
  6294. @var{body}
  6295. while (@var{test});
  6296. @end example
  6297. Here, @var{body} is a statement (possibly a block) to repeat, and
  6298. @var{test} is an expression that controls whether to repeat it again.
  6299. Each iteration of the loop starts by executing @var{body}. Then it
  6300. computes @var{test} and, if it is true (nonzero), that means to go
  6301. back and start over with @var{body}. If @var{test} is false (zero),
  6302. then the loop stops repeating and execution moves on past it.
  6303. @node break Statement
  6304. @subsection @code{break} Statement
  6305. @cindex @code{break} statement
  6306. @cindex statement, @code{break}
  6307. @findex break
  6308. The @code{break} statement looks like @samp{break;}. Its effect is to
  6309. exit immediately from the innermost loop construct or @code{switch}
  6310. statement (@pxref{switch Statement}).
  6311. For example, this loop advances @code{p} until the next null
  6312. character or newline.
  6313. @example
  6314. while (*p)
  6315. @{
  6316. /* @r{End loop if we have reached a newline.} */
  6317. if (*p == '\n')
  6318. break;
  6319. p++
  6320. @}
  6321. @end example
  6322. When there are nested loops, the @code{break} statement exits from the
  6323. innermost loop containing it.
  6324. @example
  6325. struct list_if_tuples
  6326. @{
  6327. struct list_if_tuples next;
  6328. int length;
  6329. data *contents;
  6330. @};
  6331. void
  6332. process_all_elements (struct list_if_tuples *list)
  6333. @{
  6334. while (list)
  6335. @{
  6336. /* @r{Process all the elements in this node's vector,}
  6337. @r{stopping when we reach one that is null.} */
  6338. for (i = 0; i < list->length; i++
  6339. @{
  6340. /* @r{Null element terminates this node's vector.} */
  6341. if (list->contents[i] == NULL)
  6342. /* @r{Exit the @code{for} loop.} */
  6343. break;
  6344. /* @r{Operate on the next element.} */
  6345. process_element (list->contents[i]);
  6346. @}
  6347. list = list->next;
  6348. @}
  6349. @}
  6350. @end example
  6351. The only way in C to exit from an outer loop is with
  6352. @code{goto} (@pxref{goto Statement}).
  6353. @node for Statement
  6354. @subsection @code{for} Statement
  6355. @cindex @code{for} statement
  6356. @cindex statement, @code{for}
  6357. @findex for
  6358. A @code{for} statement uses three expressions written inside a
  6359. parenthetical group to define the repetition of the loop. The first
  6360. expression says how to prepare to start the loop. The second says how
  6361. to test, before each iteration, whether to continue looping. The
  6362. third says how to advance, at the end of an iteration, for the next
  6363. iteration. All together, it looks like this:
  6364. @example
  6365. for (@var{start}; @var{continue-test}; @var{advance})
  6366. @var{body}
  6367. @end example
  6368. The first thing the @code{for} statement does is compute @var{start}.
  6369. The next thing it does is compute the expression @var{continue-test}.
  6370. If that expression is false (zero), the @code{for} statement finishes
  6371. immediately, so @var{body} is executed zero times.
  6372. However, if @var{continue-test} is true (nonzero), the @code{for}
  6373. statement executes @var{body}, then @var{advance}. Then it loops back
  6374. to the not-quite-top to test @var{continue-test} again. But it does
  6375. not compute @var{start} again.
  6376. @node Example of for
  6377. @subsection Example of @code{for}
  6378. Here is the @code{for} statement from the iterative Fibonacci
  6379. function:
  6380. @example
  6381. int i;
  6382. for (i = 1; i < n; ++i)
  6383. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6384. /* @r{since @code{i < n} is false the first time.} */
  6385. @{
  6386. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6387. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6388. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6389. int next = prev + last;
  6390. /* @r{Shift the values down.} */
  6391. prev = last;
  6392. last = next;
  6393. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6394. @r{and @var{prev} is @code{fib (@var{i})}.}
  6395. @r{But that won't stay true for long,}
  6396. @r{because we are about to increment @var{i}.} */
  6397. @}
  6398. @end example
  6399. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6400. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6401. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6402. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6403. that contains a declaration and two statements.
  6404. @node Omitted for-Expressions
  6405. @subsection Omitted @code{for}-Expressions
  6406. A fully-fleshed @code{for} statement contains all these parts,
  6407. @example
  6408. for (@var{start}; @var{continue-test}; @var{advance})
  6409. @var{body}
  6410. @end example
  6411. @noindent
  6412. but you can omit any of the three expressions inside the parentheses.
  6413. The parentheses and the two semicolons are required syntactically, but
  6414. the expressions between them may be missing. A missing expression
  6415. means this loop doesn't use that particular feature of the @code{for}
  6416. statement.
  6417. Instead of using @var{start}, you can do the loop preparation
  6418. before the @code{for} statement: the effect is the same. So we
  6419. could have written the beginning of the previous example this way:
  6420. @example
  6421. int i = 0;
  6422. for (; i < n; ++i)
  6423. @end example
  6424. @noindent
  6425. instead of this way:
  6426. @example
  6427. int i;
  6428. for (i = 0; i < n; ++i)
  6429. @end example
  6430. Omitting @var{continue-test} means the loop runs forever (or until
  6431. something else causes exit from it). Statements inside the loop can
  6432. test conditions for termination and use @samp{break;} to exit. This
  6433. is more flexible since you can put those tests anywhere in the loop,
  6434. not solely at the beginning.
  6435. Putting an expression in @var{advance} is almost equivalent to writing
  6436. it at the end of the loop body; it does almost the same thing. The
  6437. only difference is for the @code{continue} statement (@pxref{continue
  6438. Statement}). So we could have written this:
  6439. @example
  6440. for (i = 0; i < n;)
  6441. @{
  6442. @r{@dots{}}
  6443. ++i;
  6444. @}
  6445. @end example
  6446. @noindent
  6447. instead of this:
  6448. @example
  6449. for (i = 0; i < n; ++i)
  6450. @{
  6451. @r{@dots{}}
  6452. @}
  6453. @end example
  6454. The choice is mainly a matter of what is more readable for
  6455. programmers. However, there is also a syntactic difference:
  6456. @var{advance} is an expression, not a statement. It can't include
  6457. loops, blocks, declarations, etc.
  6458. @node for-Index Declarations
  6459. @subsection @code{for}-Index Declarations
  6460. You can declare loop-index variables directly in the @var{start}
  6461. portion of the @code{for}-loop, like this:
  6462. @example
  6463. for (int i = 0; i < n; ++i)
  6464. @{
  6465. @r{@dots{}}
  6466. @}
  6467. @end example
  6468. This kind of @var{start} is limited to a single declaration; it can
  6469. declare one or more variables, separated by commas, all of which are
  6470. the same @var{basetype} (@code{int}, in this example):
  6471. @example
  6472. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6473. @{
  6474. @r{@dots{}}
  6475. @}
  6476. @end example
  6477. @noindent
  6478. The scope of these variables is the @code{for} statement as a whole.
  6479. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6480. Variables declared in @code{for} statements should have initializers.
  6481. Omitting the initialization gives the variables unpredictable initial
  6482. values, so this code is erroneous.
  6483. @example
  6484. for (int i; i < n; ++i)
  6485. @{
  6486. @r{@dots{}}
  6487. @}
  6488. @end example
  6489. @node continue Statement
  6490. @subsection @code{continue} Statement
  6491. @cindex @code{continue} statement
  6492. @cindex statement, @code{continue}
  6493. @findex continue
  6494. The @code{continue} statement looks like @samp{continue;}, and its
  6495. effect is to jump immediately to the end of the innermost loop
  6496. construct. If it is a @code{for}-loop, the next thing that happens
  6497. is to execute the loop's @var{advance} expression.
  6498. For example, this loop increments @code{p} until the next null character
  6499. or newline, and operates (in some way not shown) on all the characters
  6500. in the line except for spaces. All it does with spaces is skip them.
  6501. @example
  6502. for (;*p; ++p)
  6503. @{
  6504. /* @r{End loop if we have reached a newline.} */
  6505. if (*p == '\n')
  6506. break;
  6507. /* @r{Pay no attention to spaces.} */
  6508. if (*p == ' ')
  6509. continue;
  6510. /* @r{Operate on the next character.} */
  6511. @r{@dots{}}
  6512. @}
  6513. @end example
  6514. @noindent
  6515. Executing @samp{continue;} skips the loop body but it does not
  6516. skip the @var{advance} expression, @code{p++}.
  6517. We could also write it like this:
  6518. @example
  6519. for (;*p; ++p)
  6520. @{
  6521. /* @r{Exit if we have reached a newline.} */
  6522. if (*p == '\n')
  6523. break;
  6524. /* @r{Pay no attention to spaces.} */
  6525. if (*p != ' ')
  6526. @{
  6527. /* @r{Operate on the next character.} */
  6528. @r{@dots{}}
  6529. @}
  6530. @}
  6531. @end example
  6532. The advantage of using @code{continue} is that it reduces the
  6533. depth of nesting.
  6534. Contrast @code{continue} with the @code{break} statement. @xref{break
  6535. Statement}.
  6536. @node switch Statement
  6537. @section @code{switch} Statement
  6538. @cindex @code{switch} statement
  6539. @cindex statement, @code{switch}
  6540. @findex switch
  6541. @findex case
  6542. @findex default
  6543. The @code{switch} statement selects code to run according to the value
  6544. of an expression. The expression, in parentheses, follows the keyword
  6545. @code{switch}. After that come all the cases to select among,
  6546. inside braces. It looks like this:
  6547. @example
  6548. switch (@var{selector})
  6549. @{
  6550. @var{cases}@r{@dots{}}
  6551. @}
  6552. @end example
  6553. A case can look like this:
  6554. @example
  6555. case @var{value}:
  6556. @var{statements}
  6557. break;
  6558. @end example
  6559. @noindent
  6560. which means ``come here if @var{selector} happens to have the value
  6561. @var{value},'' or like this (a GNU C extension):
  6562. @example
  6563. case @var{rangestart} ... @var{rangeend}:
  6564. @var{statements}
  6565. break;
  6566. @end example
  6567. @noindent
  6568. which means ``come here if @var{selector} happens to have a value
  6569. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6570. Ranges}.
  6571. The values in @code{case} labels must reduce to integer constants.
  6572. They can use arithmetic, and @code{enum} constants, but they cannot
  6573. refer to data in memory, because they have to be computed at compile
  6574. time. It is an error if two @code{case} labels specify the same
  6575. value, or ranges that overlap, or if one is a range and the other is a
  6576. value in that range.
  6577. You can also define a default case to handle ``any other value,'' like
  6578. this:
  6579. @example
  6580. default:
  6581. @var{statements}
  6582. break;
  6583. @end example
  6584. If the @code{switch} statement has no @code{default:} label, then it
  6585. does nothing when the value matches none of the cases.
  6586. The brace-group inside the @code{switch} statement is a block, and you
  6587. can declare variables with that scope just as in any other block
  6588. (@pxref{Blocks}). However, initializers in these declarations won't
  6589. necessarily be executed every time the @code{switch} statement runs,
  6590. so it is best to avoid giving them initializers.
  6591. @code{break;} inside a @code{switch} statement exits immediately from
  6592. the @code{switch} statement. @xref{break Statement}.
  6593. If there is no @code{break;} at the end of the code for a case,
  6594. execution continues into the code for the following case. This
  6595. happens more often by mistake than intentionally, but since this
  6596. feature is used in real code, we cannot eliminate it.
  6597. @strong{Warning:} When one case is intended to fall through to the
  6598. next, write a comment like @samp{falls through} to say it's
  6599. intentional. That way, other programmers won't assume it was an error
  6600. and ``fix'' it erroneously.
  6601. Consecutive @code{case} statements could, pedantically, be considered
  6602. an instance of falling through, but we don't consider or treat them that
  6603. way because they won't confuse anyone.
  6604. @node switch Example
  6605. @section Example of @code{switch}
  6606. Here's an example of using the @code{switch} statement
  6607. to distinguish among characters:
  6608. @cindex counting vowels and punctuation
  6609. @example
  6610. struct vp @{ int vowels, punct; @};
  6611. struct vp
  6612. count_vowels_and_punct (char *string)
  6613. @{
  6614. int c;
  6615. int vowels = 0;
  6616. int punct = 0;
  6617. /* @r{Don't change the parameter itself.} */
  6618. /* @r{That helps in debugging.} */
  6619. char *p = string;
  6620. struct vp value;
  6621. while (c = *p++)
  6622. switch (c)
  6623. @{
  6624. case 'y':
  6625. case 'Y':
  6626. /* @r{We assume @code{y_is_consonant} will check surrounding
  6627. letters to determine whether this y is a vowel.} */
  6628. if (y_is_consonant (p - 1))
  6629. break;
  6630. /* @r{Falls through} */
  6631. case 'a':
  6632. case 'e':
  6633. case 'i':
  6634. case 'o':
  6635. case 'u':
  6636. case 'A':
  6637. case 'E':
  6638. case 'I':
  6639. case 'O':
  6640. case 'U':
  6641. vowels++;
  6642. break;
  6643. case '.':
  6644. case ',':
  6645. case ':':
  6646. case ';':
  6647. case '?':
  6648. case '!':
  6649. case '\"':
  6650. case '\'':
  6651. punct++;
  6652. break;
  6653. @}
  6654. value.vowels = vowels;
  6655. value.punct = punct;
  6656. return value;
  6657. @}
  6658. @end example
  6659. @node Duffs Device
  6660. @section Duff's Device
  6661. @cindex Duff's device
  6662. The cases in a @code{switch} statement can be inside other control
  6663. constructs. For instance, we can use a technique known as @dfn{Duff's
  6664. device} to optimize this simple function,
  6665. @example
  6666. void
  6667. copy (char *to, char *from, int count)
  6668. @{
  6669. while (count > 0)
  6670. *to++ = *from++, count--;
  6671. @}
  6672. @end example
  6673. @noindent
  6674. which copies memory starting at @var{from} to memory starting at
  6675. @var{to}.
  6676. Duff's device involves unrolling the loop so that it copies
  6677. several characters each time around, and using a @code{switch} statement
  6678. to enter the loop body at the proper point:
  6679. @example
  6680. void
  6681. copy (char *to, char *from, int count)
  6682. @{
  6683. if (count <= 0)
  6684. return;
  6685. int n = (count + 7) / 8;
  6686. switch (count % 8)
  6687. @{
  6688. do @{
  6689. case 0: *to++ = *from++;
  6690. case 7: *to++ = *from++;
  6691. case 6: *to++ = *from++;
  6692. case 5: *to++ = *from++;
  6693. case 4: *to++ = *from++;
  6694. case 3: *to++ = *from++;
  6695. case 2: *to++ = *from++;
  6696. case 1: *to++ = *from++;
  6697. @} while (--n > 0);
  6698. @}
  6699. @}
  6700. @end example
  6701. @node Case Ranges
  6702. @section Case Ranges
  6703. @cindex case ranges
  6704. @cindex ranges in case statements
  6705. You can specify a range of consecutive values in a single @code{case} label,
  6706. like this:
  6707. @example
  6708. case @var{low} ... @var{high}:
  6709. @end example
  6710. @noindent
  6711. This has the same effect as the proper number of individual @code{case}
  6712. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6713. This feature is especially useful for ranges of ASCII character codes:
  6714. @example
  6715. case 'A' ... 'Z':
  6716. @end example
  6717. @strong{Be careful:} with integers, write spaces around the @code{...}
  6718. to prevent it from being parsed wrong. For example, write this:
  6719. @example
  6720. case 1 ... 5:
  6721. @end example
  6722. @noindent
  6723. rather than this:
  6724. @example
  6725. case 1...5:
  6726. @end example
  6727. @node Null Statement
  6728. @section Null Statement
  6729. @cindex null statement
  6730. @cindex statement, null
  6731. A @dfn{null statement} is just a semicolon. It does nothing.
  6732. A null statement is a placeholder for use where a statement is
  6733. grammatically required, but there is nothing to be done. For
  6734. instance, sometimes all the work of a @code{for}-loop is done in the
  6735. @code{for}-header itself, leaving no work for the body. Here is an
  6736. example that searches for the first newline in @code{array}:
  6737. @example
  6738. for (p = array; *p != '\n'; p++)
  6739. ;
  6740. @end example
  6741. @node goto Statement
  6742. @section @code{goto} Statement and Labels
  6743. @cindex @code{goto} statement
  6744. @cindex statement, @code{goto}
  6745. @cindex label
  6746. @findex goto
  6747. The @code{goto} statement looks like this:
  6748. @example
  6749. goto @var{label};
  6750. @end example
  6751. @noindent
  6752. Its effect is to transfer control immediately to another part of the
  6753. current function---where the label named @var{label} is defined.
  6754. An ordinary label definition looks like this:
  6755. @example
  6756. @var{label}:
  6757. @end example
  6758. @noindent
  6759. and it can appear before any statement. You can't use @code{default}
  6760. as a label, since that has a special meaning for @code{switch}
  6761. statements.
  6762. An ordinary label doesn't need a separate declaration; defining it is
  6763. enough.
  6764. Here's an example of using @code{goto} to implement a loop
  6765. equivalent to @code{do}--@code{while}:
  6766. @example
  6767. @{
  6768. loop_restart:
  6769. @var{body}
  6770. if (@var{condition})
  6771. goto loop_restart;
  6772. @}
  6773. @end example
  6774. The name space of labels is separate from that of variables and functions.
  6775. Thus, there is no error in using a single name in both ways:
  6776. @example
  6777. @{
  6778. int foo; // @r{Variable @code{foo}.}
  6779. foo: // @r{Label @code{foo}.}
  6780. @var{body}
  6781. if (foo > 0) // @r{Variable @code{foo}.}
  6782. goto foo; // @r{Label @code{foo}.}
  6783. @}
  6784. @end example
  6785. Blocks have no effect on ordinary labels; each label name is defined
  6786. throughout the whole of the function it appears in. It looks strange to
  6787. jump into a block with @code{goto}, but it works. For example,
  6788. @example
  6789. if (x < 0)
  6790. goto negative;
  6791. if (y < 0)
  6792. @{
  6793. negative:
  6794. printf ("Negative\n");
  6795. return;
  6796. @}
  6797. @end example
  6798. If the goto jumps into the scope of a variable, it does not
  6799. initialize the variable. For example, if @code{x} is negative,
  6800. @example
  6801. if (x < 0)
  6802. goto negative;
  6803. if (y < 0)
  6804. @{
  6805. int i = 5;
  6806. negative:
  6807. printf ("Negative, and i is %d\n", i);
  6808. return;
  6809. @}
  6810. @end example
  6811. @noindent
  6812. prints junk because @code{i} was not initialized.
  6813. If the block declares a variable-length automatic array, jumping into
  6814. it gives a compilation error. However, jumping out of the scope of a
  6815. variable-length array works fine, and deallocates its storage.
  6816. A label can't come directly before a declaration, so the code can't
  6817. jump directly to one. For example, this is not allowed:
  6818. @example
  6819. @{
  6820. goto foo;
  6821. foo:
  6822. int x = 5;
  6823. bar(&x);
  6824. @}
  6825. @end example
  6826. @noindent
  6827. The workaround is to add a statement, even an empty statement,
  6828. directly after the label. For example:
  6829. @example
  6830. @{
  6831. goto foo;
  6832. foo:
  6833. ;
  6834. int x = 5;
  6835. bar(&x);
  6836. @}
  6837. @end example
  6838. Likewise, a label can't be the last thing in a block. The workaround
  6839. solution is the same: add a semicolon after the label.
  6840. These unnecessary restrictions on labels make no sense, and ought in
  6841. principle to be removed; but they do only a little harm since labels
  6842. and @code{goto} are rarely the best way to write a program.
  6843. These examples are all artificial; it would be more natural to
  6844. write them in other ways, without @code{goto}. For instance,
  6845. the clean way to write the example that prints @samp{Negative} is this:
  6846. @example
  6847. if (x < 0 || y < 0)
  6848. @{
  6849. printf ("Negative\n");
  6850. return;
  6851. @}
  6852. @end example
  6853. @noindent
  6854. It is hard to construct simple examples where @code{goto} is actually
  6855. the best way to write a program. Its rare good uses tend to be in
  6856. complex code, thus not apt for the purpose of explaining the meaning
  6857. of @code{goto}.
  6858. The only good time to use @code{goto} is when it makes the code
  6859. simpler than any alternative. Jumping backward is rarely desirable,
  6860. because usually the other looping and control constructs give simpler
  6861. code. Using @code{goto} to jump forward is more often desirable, for
  6862. instance when a function needs to do some processing in an error case
  6863. and errors can occur at various different places within the function.
  6864. @node Local Labels
  6865. @section Locally Declared Labels
  6866. @cindex local labels
  6867. @cindex macros, local labels
  6868. @findex __label__
  6869. In GNU C you can declare @dfn{local labels} in any nested block
  6870. scope. A local label is used in a @code{goto} statement just like an
  6871. ordinary label, but you can only reference it within the block in
  6872. which it was declared.
  6873. A local label declaration looks like this:
  6874. @example
  6875. __label__ @var{label};
  6876. @end example
  6877. @noindent
  6878. or
  6879. @example
  6880. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6881. @end example
  6882. Local label declarations must come at the beginning of the block,
  6883. before any ordinary declarations or statements.
  6884. The label declaration declares the label @emph{name}, but does not define
  6885. the label itself. That's done in the usual way, with
  6886. @code{@var{label}:}, before one of the statements in the block.
  6887. The local label feature is useful for complex macros. If a macro
  6888. contains nested loops, a @code{goto} can be useful for breaking out of
  6889. them. However, an ordinary label whose scope is the whole function
  6890. cannot be used: if the macro can be expanded several times in one
  6891. function, the label will be multiply defined in that function. A
  6892. local label avoids this problem. For example:
  6893. @example
  6894. #define SEARCH(value, array, target) \
  6895. do @{ \
  6896. __label__ found; \
  6897. __auto_type _SEARCH_target = (target); \
  6898. __auto_type _SEARCH_array = (array); \
  6899. int i, j; \
  6900. int value; \
  6901. for (i = 0; i < max; i++) \
  6902. for (j = 0; j < max; j++) \
  6903. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6904. @{ (value) = i; goto found; @} \
  6905. (value) = -1; \
  6906. found:; \
  6907. @} while (0)
  6908. @end example
  6909. This could also be written using a statement expression
  6910. (@pxref{Statement Exprs}):
  6911. @example
  6912. #define SEARCH(array, target) \
  6913. (@{ \
  6914. __label__ found; \
  6915. __auto_type _SEARCH_target = (target); \
  6916. __auto_type _SEARCH_array = (array); \
  6917. int i, j; \
  6918. int value; \
  6919. for (i = 0; i < max; i++) \
  6920. for (j = 0; j < max; j++) \
  6921. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6922. @{ value = i; goto found; @} \
  6923. value = -1; \
  6924. found: \
  6925. value; \
  6926. @})
  6927. @end example
  6928. Ordinary labels are visible throughout the function where they are
  6929. defined, and only in that function. However, explicitly declared
  6930. local labels of a block are visible in nested functions declared
  6931. within that block. @xref{Nested Functions}, for details.
  6932. @xref{goto Statement}.
  6933. @node Labels as Values
  6934. @section Labels as Values
  6935. @cindex labels as values
  6936. @cindex computed gotos
  6937. @cindex goto with computed label
  6938. @cindex address of a label
  6939. In GNU C, you can get the address of a label defined in the current
  6940. function (or a local label defined in the containing function) with
  6941. the unary operator @samp{&&}. The value has type @code{void *}. This
  6942. value is a constant and can be used wherever a constant of that type
  6943. is valid. For example:
  6944. @example
  6945. void *ptr;
  6946. @r{@dots{}}
  6947. ptr = &&foo;
  6948. @end example
  6949. To use these values requires a way to jump to one. This is done
  6950. with the computed goto statement@footnote{The analogous feature in
  6951. Fortran is called an assigned goto, but that name seems inappropriate in
  6952. C, since you can do more with label addresses than store them in special label
  6953. variables.}, @code{goto *@var{exp};}. For example,
  6954. @example
  6955. goto *ptr;
  6956. @end example
  6957. @noindent
  6958. Any expression of type @code{void *} is allowed.
  6959. @xref{goto Statement}.
  6960. @menu
  6961. * Label Value Uses:: Examples of using label values.
  6962. * Label Value Caveats:: Limitations of label values.
  6963. @end menu
  6964. @node Label Value Uses
  6965. @subsection Label Value Uses
  6966. One use for label-valued constants is to initialize a static array to
  6967. serve as a jump table:
  6968. @example
  6969. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6970. @end example
  6971. Then you can select a label with indexing, like this:
  6972. @example
  6973. goto *array[i];
  6974. @end example
  6975. @noindent
  6976. Note that this does not check whether the subscript is in bounds---array
  6977. indexing in C never checks that.
  6978. You can make the table entries offsets instead of addresses
  6979. by subtracting one label from the others. Here is an example:
  6980. @example
  6981. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6982. &&hack - &&foo @};
  6983. goto *(&&foo + array[i]);
  6984. @end example
  6985. @noindent
  6986. Using offsets is preferable in shared libraries, as it avoids the need
  6987. for dynamic relocation of the array elements; therefore, the array can
  6988. be read-only.
  6989. An array of label values or offsets serves a purpose much like that of
  6990. the @code{switch} statement. The @code{switch} statement is cleaner,
  6991. so use @code{switch} by preference when feasible.
  6992. Another use of label values is in an interpreter for threaded code.
  6993. The labels within the interpreter function can be stored in the
  6994. threaded code for super-fast dispatching.
  6995. @node Label Value Caveats
  6996. @subsection Label Value Caveats
  6997. Jumping to a label defined in another function does not work.
  6998. It can cause unpredictable results.
  6999. The best way to avoid this is to store label values only in
  7000. automatic variables, or static variables whose names are declared
  7001. within the function. Never pass them as arguments.
  7002. @cindex cloning
  7003. An optimization known as @dfn{cloning} generates multiple simplified
  7004. variants of a function's code, for use with specific fixed arguments.
  7005. Using label values in certain ways, such as saving the address in one
  7006. call to the function and using it again in another call, would make cloning
  7007. give incorrect results. These functions must disable cloning.
  7008. Inlining calls to the function would also result in multiple copies of
  7009. the code, each with its own value of the same label. Using the label
  7010. in a computed goto is no problem, because the computed goto inhibits
  7011. inlining. However, using the label value in some other way, such as
  7012. an indication of where an error occurred, would be optimized wrong.
  7013. These functions must disable inlining.
  7014. To prevent inlining or cloning of a function, specify
  7015. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7016. @xref{Attributes}.
  7017. When a function uses a label value in a static variable initializer,
  7018. that automatically prevents inlining or cloning the function.
  7019. @node Statement Exprs
  7020. @section Statements and Declarations in Expressions
  7021. @cindex statements inside expressions
  7022. @cindex declarations inside expressions
  7023. @cindex expressions containing statements
  7024. @c the above section title wrapped and causes an underfull hbox.. i
  7025. @c changed it from "within" to "in". --mew 4feb93
  7026. A block enclosed in parentheses can be used as an expression in GNU
  7027. C@. This provides a way to use local variables, loops and switches within
  7028. an expression. We call it a @dfn{statement expression}.
  7029. Recall that a block is a sequence of statements
  7030. surrounded by braces. In this construct, parentheses go around the
  7031. braces. For example:
  7032. @example
  7033. (@{ int y = foo (); int z;
  7034. if (y > 0) z = y;
  7035. else z = - y;
  7036. z; @})
  7037. @end example
  7038. @noindent
  7039. is a valid (though slightly more complex than necessary) expression
  7040. for the absolute value of @code{foo ()}.
  7041. The last statement in the block should be an expression statement; an
  7042. expression followed by a semicolon, that is. The value of this
  7043. expression serves as the value of statement expression. If the last
  7044. statement is anything else, the statement expression's value is
  7045. @code{void}.
  7046. This feature is mainly useful in making macro definitions compute each
  7047. operand exactly once. @xref{Macros and Auto Type}.
  7048. Statement expressions are not allowed in expressions that must be
  7049. constant, such as the value for an enumerator, the width of a
  7050. bit-field, or the initial value of a static variable.
  7051. Jumping into a statement expression---with @code{goto}, or using a
  7052. @code{switch} statement outside the statement expression---is an
  7053. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7054. compiler can't detect the error, but it still won't work.
  7055. Jumping out of a statement expression is permitted, but since
  7056. subexpressions in C are not computed in a strict order, it is
  7057. unpredictable which other subexpressions will have been computed by
  7058. then. For example,
  7059. @example
  7060. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7061. @end example
  7062. @noindent
  7063. calls @code{foo} and @code{bar1} before it jumps, and never
  7064. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7065. does get called, that occurs after @code{foo} and before @code{bar1}.
  7066. @node Variables
  7067. @chapter Variables
  7068. @cindex variables
  7069. Every variable used in a C program needs to be made known by a
  7070. @dfn{declaration}. It can be used only after it has been declared.
  7071. It is an error to declare a variable name more than once in the same
  7072. scope; an exception is that @code{extern} declarations and tentative
  7073. definitions can coexist with another declaration of the same
  7074. variable.
  7075. Variables can be declared anywhere within a block or file. (Older
  7076. versions of C required that all variable declarations within a block
  7077. occur before any statements.)
  7078. Variables declared within a function or block are @dfn{local} to
  7079. it. This means that the variable name is visible only until the end
  7080. of that function or block, and the memory space is allocated only
  7081. while control is within it.
  7082. Variables declared at the top level in a file are called @dfn{file-scope}.
  7083. They are assigned fixed, distinct memory locations, so they retain
  7084. their values for the whole execution of the program.
  7085. @menu
  7086. * Variable Declarations:: Name a variable and and reserve space for it.
  7087. * Initializers:: Assigning inital values to variables.
  7088. * Designated Inits:: Assigning initial values to array elements
  7089. at particular array indices.
  7090. * Auto Type:: Obtaining the type of a variable.
  7091. * Local Variables:: Variables declared in function definitions.
  7092. * File-Scope Variables:: Variables declared outside of
  7093. function definitions.
  7094. * Static Local Variables:: Variables declared within functions,
  7095. but with permanent storage allocation.
  7096. * Extern Declarations:: Declaring a variable
  7097. which is allocated somewhere else.
  7098. * Allocating File-Scope:: When is space allocated
  7099. for file-scope variables?
  7100. * auto and register:: Historically used storage directions.
  7101. * Omitting Types:: The bad practice of declaring variables
  7102. with implicit type.
  7103. @end menu
  7104. @node Variable Declarations
  7105. @section Variable Declarations
  7106. @cindex variable declarations
  7107. @cindex declaration of variables
  7108. Here's what a variable declaration looks like:
  7109. @example
  7110. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7111. @end example
  7112. The @var{keywords} specify how to handle the scope of the variable
  7113. name and the allocation of its storage. Most declarations have
  7114. no keywords because the defaults are right for them.
  7115. C allows these keywords to come before or after @var{basetype}, or
  7116. even in the middle of it as in @code{unsigned static int}, but don't
  7117. do that---it would surprise other programmers. Always write the
  7118. keywords first.
  7119. The @var{basetype} can be any of the predefined types of C, or a type
  7120. keyword defined with @code{typedef}. It can also be @code{struct
  7121. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7122. addition, it can include type qualifiers such as @code{const} and
  7123. @code{volatile} (@pxref{Type Qualifiers}).
  7124. In the simplest case, @var{decorated-variable} is just the variable
  7125. name. That declares the variable with the type specified by
  7126. @var{basetype}. For instance,
  7127. @example
  7128. int foo;
  7129. @end example
  7130. @noindent
  7131. uses @code{int} as the @var{basetype} and @code{foo} as the
  7132. @var{decorated-variable}. It declares @code{foo} with type
  7133. @code{int}.
  7134. @example
  7135. struct tree_node foo;
  7136. @end example
  7137. @noindent
  7138. declares @code{foo} with type @code{struct tree_node}.
  7139. @menu
  7140. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7141. array and pointer types.
  7142. * Combining Variable Declarations:: More than one variable declaration
  7143. in a single statement.
  7144. @end menu
  7145. @node Declaring Arrays and Pointers
  7146. @subsection Declaring Arrays and Pointers
  7147. @cindex declaring arrays and pointers
  7148. @cindex array, declaring
  7149. @cindex pointers, declaring
  7150. To declare a variable that is an array, write
  7151. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7152. @example
  7153. int foo[5];
  7154. @end example
  7155. To declare a variable that has a pointer type, write
  7156. @code{*@var{variable}} for @var{decorated-variable}:
  7157. @example
  7158. struct list_elt *foo;
  7159. @end example
  7160. These constructs nest. For instance,
  7161. @example
  7162. int foo[3][5];
  7163. @end example
  7164. @noindent
  7165. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7166. @example
  7167. struct list_elt *foo[5];
  7168. @end example
  7169. @noindent
  7170. declares @code{foo} as an array of 5 pointers to structures, and
  7171. @example
  7172. struct list_elt **foo;
  7173. @end example
  7174. @noindent
  7175. declares @code{foo} as a pointer to a pointer to a structure.
  7176. @example
  7177. int **(*foo[30])(int, double);
  7178. @end example
  7179. @noindent
  7180. declares @code{foo} as an array of 30 pointers to functions
  7181. (@pxref{Function Pointers}), each of which must accept two arguments
  7182. (one @code{int} and one @code{double}) and return type @code{int **}.
  7183. @example
  7184. void
  7185. bar (int size)
  7186. @{
  7187. int foo[size];
  7188. @r{@dots{}}
  7189. @}
  7190. @end example
  7191. @noindent
  7192. declares @code{foo} as an array of integers with a size specified at
  7193. run time when the function @code{bar} is called.
  7194. @node Combining Variable Declarations
  7195. @subsection Combining Variable Declarations
  7196. @cindex combining variable declarations
  7197. @cindex variable declarations, combining
  7198. @cindex declarations, combining
  7199. When multiple declarations have the same @var{keywords} and
  7200. @var{basetype}, you can combine them using commas. Thus,
  7201. @example
  7202. @var{keywords} @var{basetype}
  7203. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7204. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7205. @end example
  7206. @noindent
  7207. is equivalent to
  7208. @example
  7209. @var{keywords} @var{basetype}
  7210. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7211. @var{keywords} @var{basetype}
  7212. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7213. @end example
  7214. Here are some simple examples:
  7215. @example
  7216. int a, b;
  7217. int a = 1, b = 2;
  7218. int a, *p, array[5];
  7219. int a = 0, *p = &a, array[5] = @{1, 2@};
  7220. @end example
  7221. @noindent
  7222. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7223. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7224. Since the initializer for @code{array} specifies only two elements,
  7225. the other three elements are initialized to zero.
  7226. @node Initializers
  7227. @section Initializers
  7228. @cindex initializers
  7229. A variable's declaration, unless it is @code{extern}, should also
  7230. specify its initial value. For numeric and pointer-type variables,
  7231. the initializer is an expression for the value. If necessary, it is
  7232. converted to the variable's type, just as in an assignment.
  7233. You can also initialize a local structure-type (@pxref{Structures}) or
  7234. local union-type (@pxref{Unions}) variable this way, from an
  7235. expression whose value has the same type. But you can't initialize an
  7236. array this way (@pxref{Arrays}), since arrays are not first-class
  7237. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7238. assignment.
  7239. You can initialize arrays and structures componentwise,
  7240. with a list of the elements or components. You can initialize
  7241. a union with any one of its alternatives.
  7242. @itemize @bullet
  7243. @item
  7244. A component-wise initializer for an array consists of element values
  7245. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7246. don't cover all the elements in the array, the remaining elements are
  7247. initialized to zero.
  7248. You can omit the size of the array when you declare it, and let
  7249. the initializer specify the size:
  7250. @example
  7251. int array[] = @{ 3, 9, 12 @};
  7252. @end example
  7253. @item
  7254. A component-wise initializer for a structure consists of field values
  7255. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7256. order as the fields are declared in the structure. If the values in
  7257. the initializer don't cover all the fields in the structure, the
  7258. remaining fields are initialized to zero.
  7259. @item
  7260. The initializer for a union-type variable has the form @code{@{
  7261. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7262. in the union definition.
  7263. @end itemize
  7264. For an array of arrays, a structure containing arrays, an array of
  7265. structures, etc., you can nest these constructs. For example,
  7266. @example
  7267. struct point @{ double x, y; @};
  7268. struct point series[]
  7269. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7270. @end example
  7271. You can omit a pair of inner braces if they contain the right
  7272. number of elements for the sub-value they initialize, so that
  7273. no elements or fields need to be filled in with zeros.
  7274. But don't do that very much, as it gets confusing.
  7275. An array of @code{char} can be initialized using a string constant.
  7276. Recall that the string constant includes an implicit null character at
  7277. the end (@pxref{String Constants}). Using a string constant as
  7278. initializer means to use its contents as the initial values of the
  7279. array elements. Here are examples:
  7280. @example
  7281. char text[6] = "text!"; /* @r{Includes the null.} */
  7282. char text[5] = "text!"; /* @r{Excludes the null.} */
  7283. char text[] = "text!"; /* @r{Gets length 6.} */
  7284. char text[]
  7285. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7286. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7287. @end example
  7288. @noindent
  7289. and this kind of initializer can be nested inside braces to initialize
  7290. structures or arrays that contain a @code{char}-array.
  7291. In like manner, you can use a wide string constant to initialize
  7292. an array of @code{wchar_t}.
  7293. @node Designated Inits
  7294. @section Designated Initializers
  7295. @cindex initializers with labeled elements
  7296. @cindex labeled elements in initializers
  7297. @cindex case labels in initializers
  7298. @cindex designated initializers
  7299. In a complex structure or long array, it's useful to indicate
  7300. which field or element we are initializing.
  7301. To designate specific array elements during initialization, include
  7302. the array index in brackets, and an assignment operator, for each
  7303. element:
  7304. @example
  7305. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7306. @end example
  7307. @noindent
  7308. This does the same thing as:
  7309. @example
  7310. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7311. @end example
  7312. The array initialization can include non-designated element values
  7313. alongside designated indices; these follow the expected ordering
  7314. of the array initialization, so that
  7315. @example
  7316. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7317. @end example
  7318. @noindent
  7319. does the same thing as:
  7320. @example
  7321. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7322. @end example
  7323. Note that you can only use constant expressions as array index values,
  7324. not variables.
  7325. If you need to initialize a subsequence of sequential array elements to
  7326. the same value, you can specify a range:
  7327. @example
  7328. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7329. @end example
  7330. @noindent
  7331. Using a range this way is a GNU C extension.
  7332. When subsequence ranges overlap, each element is initialized by the
  7333. last specification that applies to it. Thus, this initialization is
  7334. equivalent to the previous one.
  7335. @example
  7336. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7337. @end example
  7338. @noindent
  7339. as the second overrides the first for elements 0 through 19.
  7340. The value used to initialize a range of elements is evaluated only
  7341. once, for the first element in the range. So for example, this code
  7342. @example
  7343. int random_values[100]
  7344. = @{ [0 ... 99] = get_random_number() @};
  7345. @end example
  7346. @noindent
  7347. would initialize all 100 elements of the array @code{random_values} to
  7348. the same value---probably not what is intended.
  7349. Similarly, you can initialize specific fields of a structure variable
  7350. by specifying the field name prefixed with a dot:
  7351. @example
  7352. struct point @{ int x; int y; @};
  7353. struct point foo = @{ .y = 42; @};
  7354. @end example
  7355. @noindent
  7356. The same syntax works for union variables as well:
  7357. @example
  7358. union int_double @{ int i; double d; @};
  7359. union int_double foo = @{ .d = 34 @};
  7360. @end example
  7361. @noindent
  7362. This casts the integer value 34 to a double and stores it
  7363. in the union variable @code{foo}.
  7364. You can designate both array elements and structure elements in
  7365. the same initialization; for example, here's an array of point
  7366. structures:
  7367. @example
  7368. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7369. @end example
  7370. Along with the capability to specify particular array and structure
  7371. elements to initialize comes the possibility of initializing the same
  7372. element more than once:
  7373. @example
  7374. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7375. @end example
  7376. @noindent
  7377. In such a case, the last initialization value is retained.
  7378. @node Auto Type
  7379. @section Referring to a Type with @code{__auto_type}
  7380. @findex __auto_type
  7381. @findex typeof
  7382. @cindex macros, types of arguments
  7383. You can declare a variable copying the type from
  7384. the initializer by using @code{__auto_type} instead of a particular type.
  7385. Here's an example:
  7386. @example
  7387. #define max(a,b) \
  7388. (@{ __auto_type _a = (a); \
  7389. __auto_type _b = (b); \
  7390. _a > _b ? _a : _b @})
  7391. @end example
  7392. This defines @code{_a} to be of the same type as @code{a}, and
  7393. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7394. to do in a macro that ought to be able to handle any type of data
  7395. (@pxref{Macros and Auto Type}).
  7396. The original GNU C method for obtaining the type of a value is to use
  7397. @code{typeof}, which takes as an argument either a value or the name of
  7398. a type. The previous example could also be written as:
  7399. @example
  7400. #define max(a,b) \
  7401. (@{ typeof(a) _a = (a); \
  7402. typeof(b) _b = (b); \
  7403. _a > _b ? _a : _b @})
  7404. @end example
  7405. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7406. principal use case for @code{typeof} is in variable declarations with
  7407. initialization, which is exactly what @code{__auto_type} handles.
  7408. @node Local Variables
  7409. @section Local Variables
  7410. @cindex local variables
  7411. @cindex variables, local
  7412. Declaring a variable inside a function definition (@pxref{Function
  7413. Definitions}) makes the variable name @dfn{local} to the containing
  7414. block---that is, the containing pair of braces. More precisely, the
  7415. variable's name is visible starting just after where it appears in the
  7416. declaration, and its visibility continues until the end of the block.
  7417. Local variables in C are generally @dfn{automatic} variables: each
  7418. variable's storage exists only from the declaration to the end of the
  7419. block. Execution of the declaration allocates the storage, computes
  7420. the initial value, and stores it in the variable. The end of the
  7421. block deallocates the storage.@footnote{Due to compiler optimizations,
  7422. allocation and deallocation don't necessarily really happen at
  7423. those times.}
  7424. @strong{Warning:} Two declarations for the same local variable
  7425. in the same scope are an error.
  7426. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7427. The total space for the program's stack may be limited; therefore,
  7428. in using very large arrays, it may be necessary to allocate
  7429. them in some other way to stop the program from crashing.
  7430. @strong{Warning:} If the declaration of an automatic variable does not
  7431. specify an initial value, the variable starts out containing garbage.
  7432. In this example, the value printed could be anything at all:
  7433. @example
  7434. @{
  7435. int i;
  7436. printf ("Print junk %d\n", i);
  7437. @}
  7438. @end example
  7439. In a simple test program, that statement is likely to print 0, simply
  7440. because every process starts with memory zeroed. But don't rely on it
  7441. to be zero---that is erroneous.
  7442. @strong{Note:} Make sure to store a value into each local variable (by
  7443. assignment, or by initialization) before referring to its value.
  7444. @node File-Scope Variables
  7445. @section File-Scope Variables
  7446. @cindex file-scope variables
  7447. @cindex global variables
  7448. @cindex variables, file-scope
  7449. @cindex variables, global
  7450. A variable declaration at the top level in a file (not inside a
  7451. function definition) declares a @dfn{file-scope variable}. Loading a
  7452. program allocates the storage for all the file-scope variables in it,
  7453. and initializes them too.
  7454. Each file-scope variable is either @dfn{static} (limited to one
  7455. compilation module) or @dfn{global} (shared with all compilation
  7456. modules in the program). To make the variable static, write the
  7457. keyword @code{static} at the start of the declaration. Omitting
  7458. @code{static} makes the variable global.
  7459. The initial value for a file-scope variable can't depend on the
  7460. contents of storage, and can't call any functions.
  7461. @example
  7462. int foo = 5; /* @r{Valid.} */
  7463. int bar = foo; /* @r{Invalid!} */
  7464. int bar = sin (1.0); /* @r{Invalid!} */
  7465. @end example
  7466. But it can use the address of another file-scope variable:
  7467. @example
  7468. int foo;
  7469. int *bar = &foo; /* @r{Valid.} */
  7470. int arr[5];
  7471. int *bar3 = &arr[3]; /* @r{Valid.} */
  7472. int *bar4 = arr + 4; /* @r{Valid.} */
  7473. @end example
  7474. It is valid for a module to have multiple declarations for a
  7475. file-scope variable, as long as they are all global or all static, but
  7476. at most one declaration can specify an initial value for it.
  7477. @node Static Local Variables
  7478. @section Static Local Variables
  7479. @cindex static local variables
  7480. @cindex variables, static local
  7481. @findex static
  7482. The keyword @code{static} in a local variable declaration says to
  7483. allocate the storage for the variable permanently, just like a
  7484. file-scope variable, even if the declaration is within a function.
  7485. Here's an example:
  7486. @example
  7487. int
  7488. increment_counter ()
  7489. @{
  7490. static int counter = 0;
  7491. return ++counter;
  7492. @}
  7493. @end example
  7494. The scope of the name @code{counter} runs from the declaration to the
  7495. end of the containing block, just like an automatic local variable,
  7496. but its storage is permanent, so the value persists from one call to
  7497. the next. As a result, each call to @code{increment_counter}
  7498. returns a different, unique value.
  7499. The initial value of a static local variable has the same limitations
  7500. as for file-scope variables: it can't depend on the contents of
  7501. storage or call any functions. It can use the address of a file-scope
  7502. variable or a static local variable, because those addresses are
  7503. determined before the program runs.
  7504. @node Extern Declarations
  7505. @section @code{extern} Declarations
  7506. @cindex @code{extern} declarations
  7507. @cindex declarations, @code{extern}
  7508. @findex extern
  7509. An @code{extern} declaration is used to refer to a global variable
  7510. whose principal declaration comes elsewhere---in the same module, or in
  7511. another compilation module. It looks like this:
  7512. @example
  7513. extern @var{basetype} @var{decorated-variable};
  7514. @end example
  7515. Its meaning is that, in the current scope, the variable name refers to
  7516. the file-scope variable of that name---which needs to be declared in a
  7517. non-@code{extern}, non-@code{static} way somewhere else.
  7518. For instance, if one compilation module has this global variable
  7519. declaration
  7520. @example
  7521. int error_count = 0;
  7522. @end example
  7523. @noindent
  7524. then other compilation modules can specify this
  7525. @example
  7526. extern int error_count;
  7527. @end example
  7528. @noindent
  7529. to allow reference to the same variable.
  7530. The usual place to write an @code{extern} declaration is at top level
  7531. in a source file, but you can write an @code{extern} declaration
  7532. inside a block to make a global or static file-scope variable
  7533. accessible in that block.
  7534. Since an @code{extern} declaration does not allocate space for the
  7535. variable, it can omit the size of an array:
  7536. @example
  7537. extern int array[];
  7538. @end example
  7539. You can use @code{array} normally in all contexts where it is
  7540. converted automatically to a pointer. However, to use it as the
  7541. operand of @code{sizeof} is an error, since the size is unknown.
  7542. It is valid to have multiple @code{extern} declarations for the same
  7543. variable, even in the same scope, if they give the same type. They do
  7544. not conflict---they agree. For an array, it is legitimate for some
  7545. @code{extern} declarations can specify the size while others omit it.
  7546. However, if two declarations give different sizes, that is an error.
  7547. Likewise, you can use @code{extern} declarations at file scope
  7548. (@pxref{File-Scope Variables}) followed by an ordinary global
  7549. (non-static) declaration of the same variable. They do not conflict,
  7550. because they say compatible things about the same meaning of the variable.
  7551. @node Allocating File-Scope
  7552. @section Allocating File-Scope Variables
  7553. @cindex allocation file-scope variables
  7554. @cindex file-scope variables, allocating
  7555. Some file-scope declarations allocate space for the variable, and some
  7556. don't.
  7557. A file-scope declaration with an initial value @emph{must} allocate
  7558. space for the variable; if there are two of such declarations for the
  7559. same variable, even in different compilation modules, they conflict.
  7560. An @code{extern} declaration @emph{never} allocates space for the variable.
  7561. If all the top-level declarations of a certain variable are
  7562. @code{extern}, the variable never gets memory space. If that variable
  7563. is used anywhere in the program, the use will be reported as an error,
  7564. saying that the variable is not defined.
  7565. @cindex tentative definition
  7566. A file-scope declaration without an initial value is called a
  7567. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7568. allocate space for the variable, but does not insist. So it causes no
  7569. conflict, no error, if the variable has another declaration that
  7570. allocates space for it, perhaps in another compilation module. But if
  7571. nothing else allocates space for the variable, the tentative
  7572. definition will do it. Any number of compilation modules can declare
  7573. the same variable in this way, and that is sufficient for all of them
  7574. to use the variable.
  7575. @c @opindex -fno-common
  7576. @c @opindex --warn_common
  7577. In programs that are very large or have many contributors, it may be
  7578. wise to adopt the convention of never using tentative definitions.
  7579. You can use the compilation option @option{-fno-common} to make them
  7580. an error, or @option{--warn-common} to warn about them.
  7581. If a file-scope variable gets its space through a tentative
  7582. definition, it starts out containing all zeros.
  7583. @node auto and register
  7584. @section @code{auto} and @code{register}
  7585. @cindex @code{auto} declarations
  7586. @cindex @code{register} declarations
  7587. @findex auto
  7588. @findex register
  7589. For historical reasons, you can write @code{auto} or @code{register}
  7590. before a local variable declaration. @code{auto} merely emphasizes
  7591. that the variable isn't static; it changes nothing.
  7592. @code{register} suggests to the compiler storing this variable in a
  7593. register. However, GNU C ignores this suggestion, since it can
  7594. choose the best variables to store in registers without any hints.
  7595. It is an error to take the address of a variable declared
  7596. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7597. If the variable is an array, you can't use it at all (other than as
  7598. the operand of @code{sizeof}), which makes it rather useless.
  7599. @node Omitting Types
  7600. @section Omitting Types in Declarations
  7601. @cindex omitting types in declarations
  7602. The syntax of C traditionally allows omitting the data type in a
  7603. declaration if it specifies a storage class, a type qualifier (see the
  7604. next chapter), or @code{auto} or @code{register}. Then the type
  7605. defaults to @code{int}. For example:
  7606. @example
  7607. auto foo = 42;
  7608. @end example
  7609. This is bad practice; if you see it, fix it.
  7610. @node Type Qualifiers
  7611. @chapter Type Qualifiers
  7612. A declaration can include type qualifiers to advise the compiler
  7613. about how the variable will be used. There are three different
  7614. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7615. pertain to different issues, so you can use more than one together.
  7616. For instance, @code{const volatile} describes a value that the
  7617. program is not allowed to change, but might have a different value
  7618. each time the program examines it. (This might perhaps be a special
  7619. hardware register, or part of shared memory.)
  7620. If you are just learning C, you can skip this chapter.
  7621. @menu
  7622. * const:: Variables whose values don't change.
  7623. * volatile:: Variables whose values may be accessed
  7624. or changed outside of the control of
  7625. this program.
  7626. * restrict Pointers:: Restricted pointers for code optimization.
  7627. * restrict Pointer Example:: Example of how that works.
  7628. @end menu
  7629. @node const
  7630. @section @code{const} Variables and Fields
  7631. @cindex @code{const} variables and fields
  7632. @cindex variables, @code{const}
  7633. @findex const
  7634. You can mark a variable as ``constant'' by writing @code{const} in
  7635. front of the declaration. This says to treat any assignment to that
  7636. variable as an error. It may also permit some compiler
  7637. optimizations---for instance, to fetch the value only once to satisfy
  7638. multiple references to it. The construct looks like this:
  7639. @example
  7640. const double pi = 3.14159;
  7641. @end example
  7642. After this definition, the code can use the variable @code{pi}
  7643. but cannot assign a different value to it.
  7644. @example
  7645. pi = 3.0; /* @r{Error!} */
  7646. @end example
  7647. Simple variables that are constant can be used for the same purposes
  7648. as enumeration constants, and they are not limited to integers. The
  7649. constantness of the variable propagates into pointers, too.
  7650. A pointer type can specify that the @emph{target} is constant. For
  7651. example, the pointer type @code{const double *} stands for a pointer
  7652. to a constant @code{double}. That's the typethat results from taking
  7653. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7654. left side of an assignment.
  7655. @example
  7656. *(&pi) = 3.0; /* @r{Error!} */
  7657. @end example
  7658. Nonconstant pointers can be converted automatically to constant
  7659. pointers, but not vice versa. For instance,
  7660. @example
  7661. const double *cptr;
  7662. double *ptr;
  7663. cptr = &pi; /* @r{Valid.} */
  7664. cptr = ptr; /* @r{Valid.} */
  7665. ptr = cptr; /* @r{Error!} */
  7666. ptr = &pi; /* @r{Error!} */
  7667. @end example
  7668. This is not an ironclad protection against modifying the value. You
  7669. can always cast the constant pointer to a nonconstant pointer type:
  7670. @example
  7671. ptr = (double *)cptr; /* @r{Valid.} */
  7672. ptr = (double *)&pi; /* @r{Valid.} */
  7673. @end example
  7674. However, @code{const} provides a way to show that a certain function
  7675. won't modify the data structure whose address is passed to it. Here's
  7676. an example:
  7677. @example
  7678. int
  7679. string_length (const char *string)
  7680. @{
  7681. int count = 0;
  7682. while (*string++)
  7683. count++;
  7684. return count;
  7685. @}
  7686. @end example
  7687. @noindent
  7688. Using @code{const char *} for the parameter is a way of saying this
  7689. function never modifies the memory of the string itself.
  7690. In calling @code{string_length}, you can specify an ordinary
  7691. @code{char *} since that can be converted automatically to @code{const
  7692. char *}.
  7693. @node volatile
  7694. @section @code{volatile} Variables and Fields
  7695. @cindex @code{volatile} variables and fields
  7696. @cindex variables, @code{volatile}
  7697. @findex volatile
  7698. The GNU C compiler often performs optimizations that eliminate the
  7699. need to write or read a variable. For instance,
  7700. @example
  7701. int foo;
  7702. foo = 1;
  7703. foo++;
  7704. @end example
  7705. @noindent
  7706. might simply store the value 2 into @code{foo}, without ever storing 1.
  7707. These optimizations can also apply to structure fields in some cases.
  7708. If the memory containing @code{foo} is shared with another program,
  7709. or if it is examined asynchronously by hardware, such optimizations
  7710. could confuse the communication. Using @code{volatile} is one way
  7711. to prevent them.
  7712. Writing @code{volatile} with the type in a variable or field declaration
  7713. says that the value may be examined or changed for reasons outside the
  7714. control of the program at any moment. Therefore, the program must
  7715. execute in a careful way to assure correct interaction with those
  7716. accesses, whenever they may occur.
  7717. The simplest use looks like this:
  7718. @example
  7719. volatile int lock;
  7720. @end example
  7721. This directs the compiler not to do certain common optimizations on
  7722. use of the variable @code{lock}. All the reads and writes for a volatile
  7723. variable or field are really done, and done in the order specified
  7724. by the source code. Thus, this code:
  7725. @example
  7726. lock = 1;
  7727. list = list->next;
  7728. if (lock)
  7729. lock_broken (&lock);
  7730. lock = 0;
  7731. @end example
  7732. @noindent
  7733. really stores the value 1 in @code{lock}, even though there is no
  7734. sign it is really used, and the @code{if} statement reads and
  7735. checks the value of @code{lock}, rather than assuming it is still 1.
  7736. A limited amount of optimization can be done, in principle, on
  7737. @code{volatile} variables and fields: multiple references between two
  7738. sequence points (@pxref{Sequence Points}) can be simplified together.
  7739. Use of @code{volatile} does not eliminate the flexibility in ordering
  7740. the computation of the operands of most operators. For instance, in
  7741. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7742. @code{foo} is not specified, so they may be done in either order; the
  7743. fact that @code{lock} is @code{volatile} has no effect on that.
  7744. @node restrict Pointers
  7745. @section @code{restrict}-Qualified Pointers
  7746. @cindex @code{restrict} pointers
  7747. @cindex pointers, @code{restrict}-qualified
  7748. @findex restrict
  7749. You can declare a pointer as ``restricted'' using the @code{restrict}
  7750. type qualifier, like this:
  7751. @example
  7752. int *restrict p = x;
  7753. @end example
  7754. @noindent
  7755. This enables better optimization of code that uses the pointer.
  7756. If @code{p} is declared with @code{restrict}, and then the code
  7757. references the object that @code{p} points to (using @code{*p} or
  7758. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7759. code will not access that object in any other way---only through
  7760. @code{p}.
  7761. For instance, it means the code must not use another pointer
  7762. to access the same space, as shown here:
  7763. @example
  7764. int *restrict p = @var{whatever};
  7765. int *q = p;
  7766. foo (*p, *q);
  7767. @end example
  7768. @noindent
  7769. That contradicts the @code{restrict} promise by accessing the object
  7770. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7771. Likewise, it must not do this:
  7772. @example
  7773. int *restrict p = @var{whatever};
  7774. struct @{ int *a, *b; @} s;
  7775. s.a = p;
  7776. foo (*p, *s.a);
  7777. @end example
  7778. @noindent
  7779. This example uses a structure field instead of the variable @code{q}
  7780. to hold the other pointer, and that contradicts the promise just the
  7781. same.
  7782. The keyword @code{restrict} also promises that @code{p} won't point to
  7783. the allocated space of any automatic or static variable. So the code
  7784. must not do this:
  7785. @example
  7786. int a;
  7787. int *restrict p = &a;
  7788. foo (*p, a);
  7789. @end example
  7790. @noindent
  7791. because that does direct access to the object (@code{a}) that @code{p}
  7792. points to, which bypasses @code{p}.
  7793. If the code makes such promises with @code{restrict} then breaks them,
  7794. execution is unpredictable.
  7795. @node restrict Pointer Example
  7796. @section @code{restrict} Pointer Example
  7797. Here are examples where @code{restrict} enables real optimization.
  7798. In this example, @code{restrict} assures GCC that the array @code{out}
  7799. points to does not overlap with the array @code{in} points to.
  7800. @example
  7801. void
  7802. process_data (const char *in,
  7803. char * restrict out,
  7804. size_t size)
  7805. @{
  7806. for (i = 0; i < size; i++)
  7807. out[i] = in[i] + in[i + 1];
  7808. @}
  7809. @end example
  7810. Here's a simple tree structure, where each tree node holds data of
  7811. type @code{PAYLOAD} plus two subtrees.
  7812. @example
  7813. struct foo
  7814. @{
  7815. PAYLOAD payload;
  7816. struct foo *left;
  7817. struct foo *right;
  7818. @};
  7819. @end example
  7820. Now here's a function to null out both pointers in the @code{left}
  7821. subtree.
  7822. @example
  7823. void
  7824. null_left (struct foo *a)
  7825. @{
  7826. a->left->left = NULL;
  7827. a->left->right = NULL;
  7828. @}
  7829. @end example
  7830. Since @code{*a} and @code{*a->left} have the same data type,
  7831. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7832. the compiled code for @code{null_left} must read @code{a->left}
  7833. again from memory when executing the second assignment statement.
  7834. We can enable optimization, so that it does not need to read
  7835. @code{a->left} again, by writing @code{null_left} this in a less
  7836. obvious way.
  7837. @example
  7838. void
  7839. null_left (struct foo *a)
  7840. @{
  7841. struct foo *b = a->left;
  7842. b->left = NULL;
  7843. b->right = NULL;
  7844. @}
  7845. @end example
  7846. A more elegant way to fix this is with @code{restrict}.
  7847. @example
  7848. void
  7849. null_left (struct foo *restrict a)
  7850. @{
  7851. a->left->left = NULL;
  7852. a->left->right = NULL;
  7853. @}
  7854. @end example
  7855. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7856. as @code{a->left} will not point to the same memory space as @code{a}.
  7857. Therefore, the memory location @code{a->left->left} cannot be the same
  7858. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7859. reloading @code{a->left} for the second statement.
  7860. @node Functions
  7861. @chapter Functions
  7862. @cindex functions
  7863. We have already presented many examples of functions, so if you've
  7864. read this far, you basically understand the concept of a function. It
  7865. is vital, nonetheless, to have a chapter in the manual that collects
  7866. all the information about functions.
  7867. @menu
  7868. * Function Definitions:: Writing the body of a function.
  7869. * Function Declarations:: Declaring the interface of a function.
  7870. * Function Calls:: Using functions.
  7871. * Function Call Semantics:: Call-by-value argument passing.
  7872. * Function Pointers:: Using references to functions.
  7873. * The main Function:: Where execution of a GNU C program begins.
  7874. * Advanced Definitions:: Advanced features of function definitions.
  7875. * Obsolete Definitions:: Obsolete features still used
  7876. in function definitions in old code.
  7877. @end menu
  7878. @node Function Definitions
  7879. @section Function Definitions
  7880. @cindex function definitions
  7881. @cindex defining functions
  7882. We have already presented many examples of function definitions. To
  7883. summarize the rules, a function definition looks like this:
  7884. @example
  7885. @var{returntype}
  7886. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7887. @{
  7888. @var{body}
  7889. @}
  7890. @end example
  7891. The part before the open-brace is called the @dfn{function header}.
  7892. Write @code{void} as the @var{returntype} if the function does
  7893. not return a value.
  7894. @menu
  7895. * Function Parameter Variables:: Syntax and semantics
  7896. of function parameters.
  7897. * Forward Function Declarations:: Functions can only be called after
  7898. they have been defined or declared.
  7899. * Static Functions:: Limiting visibility of a function.
  7900. * Arrays as Parameters:: Functions that accept array arguments.
  7901. * Structs as Parameters:: Functions that accept structure arguments.
  7902. @end menu
  7903. @node Function Parameter Variables
  7904. @subsection Function Parameter Variables
  7905. @cindex function parameter variables
  7906. @cindex parameter variables in functions
  7907. @cindex parameter list
  7908. A function parameter variable is a local variable (@pxref{Local
  7909. Variables}) used within the function to store the value passed as an
  7910. argument in a call to the function. Usually we say ``function
  7911. parameter'' or ``parameter'' for short, not mentioning the fact that
  7912. it's a variable.
  7913. We declare these variables in the beginning of the function
  7914. definition, in the @dfn{parameter list}. For example,
  7915. @example
  7916. fib (int n)
  7917. @end example
  7918. @noindent
  7919. has a parameter list with one function parameter @code{n}, which has
  7920. type @code{int}.
  7921. Function parameter declarations differ from ordinary variable
  7922. declarations in several ways:
  7923. @itemize @bullet
  7924. @item
  7925. Inside the function definition header, commas separate parameter
  7926. declarations, and each parameter needs a complete declaration
  7927. including the type. For instance, if a function @code{foo} has two
  7928. @code{int} parameters, write this:
  7929. @example
  7930. foo (int a, int b)
  7931. @end example
  7932. You can't share the common @code{int} between the two declarations:
  7933. @example
  7934. foo (int a, b) /* @r{Invalid!} */
  7935. @end example
  7936. @item
  7937. A function parameter variable is initialized to whatever value is
  7938. passed in the function call, so its declaration cannot specify an
  7939. initial value.
  7940. @item
  7941. Writing an array type in a function parameter declaration has the
  7942. effect of declaring it as a pointer. The size specified for the array
  7943. has no effect at all, and we normally omit the size. Thus,
  7944. @example
  7945. foo (int a[5])
  7946. foo (int a[])
  7947. foo (int *a)
  7948. @end example
  7949. @noindent
  7950. are equivalent.
  7951. @item
  7952. The scope of the parameter variables is the entire function body,
  7953. notwithstanding the fact that they are written in the function header,
  7954. which is just outside the function body.
  7955. @end itemize
  7956. If a function has no parameters, it would be most natural for the
  7957. list of parameters in its definition to be empty. But that, in C, has
  7958. a special meaning for historical reasons: ``Do not check that calls to
  7959. this function have the right number of arguments.'' Thus,
  7960. @example
  7961. int
  7962. foo ()
  7963. @{
  7964. return 5;
  7965. @}
  7966. int
  7967. bar (int x)
  7968. @{
  7969. return foo (x);
  7970. @}
  7971. @end example
  7972. @noindent
  7973. would not report a compilation error in passing @code{x} as an
  7974. argument to @code{foo}. By contrast,
  7975. @example
  7976. int
  7977. foo (void)
  7978. @{
  7979. return 5;
  7980. @}
  7981. int
  7982. bar (int x)
  7983. @{
  7984. return foo (x);
  7985. @}
  7986. @end example
  7987. @noindent
  7988. would report an error because @code{foo} is supposed to receive
  7989. no arguments.
  7990. @node Forward Function Declarations
  7991. @subsection Forward Function Declarations
  7992. @cindex forward function declarations
  7993. @cindex function declarations, forward
  7994. The order of the function definitions in the source code makes no
  7995. difference, except that each function needs to be defined or declared
  7996. before code uses it.
  7997. The definition of a function also declares its name for the rest of
  7998. the containing scope. But what if you want to call the function
  7999. before its definition? To permit that, write a compatible declaration
  8000. of the same function, before the first call. A declaration that
  8001. prefigures a subsequent definition in this way is called a
  8002. @dfn{forward declaration}. The function declaration can be at top
  8003. @c ??? file scope
  8004. level or within a block, and it applies until the end of the containing
  8005. scope.
  8006. @xref{Function Declarations}, for more information about these
  8007. declarations.
  8008. @node Static Functions
  8009. @subsection Static Functions
  8010. @cindex static functions
  8011. @cindex functions, static
  8012. @findex static
  8013. The keyword @code{static} in a function definition limits the
  8014. visibility of the name to the current compilation module. (That's the
  8015. same thing @code{static} does in variable declarations;
  8016. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8017. contains this code:
  8018. @example
  8019. static int
  8020. foo (void)
  8021. @{
  8022. @r{@dots{}}
  8023. @}
  8024. @end example
  8025. @noindent
  8026. then the code of that compilation module can call @code{foo} anywhere
  8027. after the definition, but other compilation modules cannot refer to it
  8028. at all.
  8029. @cindex forward declaration
  8030. @cindex static function, declaration
  8031. To call @code{foo} before its definition, it needs a forward
  8032. declaration, which should use @code{static} since the function
  8033. definition does. For this function, it looks like this:
  8034. @example
  8035. static int foo (void);
  8036. @end example
  8037. It is generally wise to use @code{static} on the definitions of
  8038. functions that won't be called from outside the same compilation
  8039. module. This makes sure that calls are not added in other modules.
  8040. If programmers decide to change the function's calling convention, or
  8041. understand all the consequences of its use, they will only have to
  8042. check for calls in the same compilation module.
  8043. @node Arrays as Parameters
  8044. @subsection Arrays as Parameters
  8045. @cindex array as parameters
  8046. @cindex functions with array parameters
  8047. Arrays in C are not first-class objects: it is impossible to copy
  8048. them. So they cannot be passed as arguments like other values.
  8049. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8050. a special way.
  8051. @menu
  8052. * Array Parm Pointer::
  8053. * Passing Array Args::
  8054. * Array Parm Qualifiers::
  8055. @end menu
  8056. @node Array Parm Pointer
  8057. @subsubsection Array parameters are pointers
  8058. Declaring a function parameter variable as an array really gives it a
  8059. pointer type. C does this because an expression with array type, if
  8060. used as an argument in a function call, is converted automatically to
  8061. a pointer (to the zeroth element of the array). If you declare the
  8062. corresponding parameter as an ``array'', it will work correctly with
  8063. the pointer value that really gets passed.
  8064. This relates to the fact that C does not check array bounds in access
  8065. to elements of the array (@pxref{Accessing Array Elements}).
  8066. For example, in this function,
  8067. @example
  8068. void
  8069. clobber4 (int array[20])
  8070. @{
  8071. array[4] = 0;
  8072. @}
  8073. @end example
  8074. @noindent
  8075. the parameter @code{array}'s real type is @code{int *}; the specified
  8076. length, 20, has no effect on the program. You can leave out the length
  8077. and write this:
  8078. @example
  8079. void
  8080. clobber4 (int array[])
  8081. @{
  8082. array[4] = 0;
  8083. @}
  8084. @end example
  8085. @noindent
  8086. or write the parameter declaration explicitly as a pointer:
  8087. @example
  8088. void
  8089. clobber4 (int *array)
  8090. @{
  8091. array[4] = 0;
  8092. @}
  8093. @end example
  8094. They are all equivalent.
  8095. @node Passing Array Args
  8096. @subsubsection Passing array arguments
  8097. The function call passes this pointer by
  8098. value, like all argument values in C@. However, the result is
  8099. paradoxical in that the array itself is passed by reference: its
  8100. contents are treated as shared memory---shared between the caller and
  8101. the called function, that is. When @code{clobber4} assigns to element
  8102. 4 of @code{array}, the effect is to alter element 4 of the array
  8103. specified in the call.
  8104. @example
  8105. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8106. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8107. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8108. int
  8109. main (void)
  8110. @{
  8111. int data[] = @{1, 2, 3, 4, 5, 6@};
  8112. int i;
  8113. /* @r{Show the initial value of element 4.} */
  8114. for (i = 0; i < 6; i++)
  8115. printf ("data[%d] = %d\n", i, data[i]);
  8116. printf ("\n");
  8117. clobber4 (data);
  8118. /* @r{Show that element 4 has been changed.} */
  8119. for (i = 0; i < 6; i++)
  8120. printf ("data[%d] = %d\n", i, data[i]);
  8121. printf ("\n");
  8122. return EXIT_SUCCESS;
  8123. @}
  8124. @end example
  8125. @noindent
  8126. shows that @code{data[4]} has become zero after the call to
  8127. @code{clobber4}.
  8128. The array @code{data} has 6 elements, but passing it to a function
  8129. whose argument type is written as @code{int [20]} is not an error,
  8130. because that really stands for @code{int *}. The pointer that is the
  8131. real argument carries no indication of the length of the array it
  8132. points into. It is not required to point to the beginning of the
  8133. array, either. For instance,
  8134. @example
  8135. clobber4 (data+1);
  8136. @end example
  8137. @noindent
  8138. passes an ``array'' that starts at element 1 of @code{data}, and the
  8139. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8140. If all calls to the function will provide an array of a particular
  8141. size, you can specify the size of the array to be @code{static}:
  8142. @example
  8143. void
  8144. clobber4 (int array[static 20])
  8145. @r{@dots{}}
  8146. @end example
  8147. @noindent
  8148. This is a promise to the compiler that the function will always be
  8149. called with an array of 20 elements, so that the compiler can optimize
  8150. code accordingly. If the code breaks this promise and calls the
  8151. function with, for example, a shorter array, unpredictable things may
  8152. happen.
  8153. @node Array Parm Qualifiers
  8154. @subsubsection Type qualifiers on array parameters
  8155. You can use the type qualifiers @code{const}, @code{restrict}, and
  8156. @code{volatile} with array parameters; for example:
  8157. @example
  8158. void
  8159. clobber4 (volatile int array[20])
  8160. @r{@dots{}}
  8161. @end example
  8162. @noindent
  8163. denotes that @code{array} is equivalent to a pointer to a volatile
  8164. @code{int}. Alternatively:
  8165. @example
  8166. void
  8167. clobber4 (int array[const 20])
  8168. @r{@dots{}}
  8169. @end example
  8170. @noindent
  8171. makes the array parameter equivalent to a constant pointer to an
  8172. @code{int}. If we want the @code{clobber4} function to succeed, it
  8173. would not make sense to write
  8174. @example
  8175. void
  8176. clobber4 (const int array[20])
  8177. @r{@dots{}}
  8178. @end example
  8179. @noindent
  8180. as this would tell the compiler that the parameter should point to an
  8181. array of constant @code{int} values, and then we would not be able to
  8182. store zeros in them.
  8183. In a function with multiple array parameters, you can use @code{restrict}
  8184. to tell the compiler that each array parameter passed in will be distinct:
  8185. @example
  8186. void
  8187. foo (int array1[restrict 10], int array2[restrict 10])
  8188. @r{@dots{}}
  8189. @end example
  8190. @noindent
  8191. Using @code{restrict} promises the compiler that callers will
  8192. not pass in the same array for more than one @code{restrict} array
  8193. parameter. Knowing this enables the compiler to perform better code
  8194. optimization. This is the same effect as using @code{restrict}
  8195. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8196. the code that an array of a specific size is expected.
  8197. @node Structs as Parameters
  8198. @subsection Functions That Accept Structure Arguments
  8199. Structures in GNU C are first-class objects, so using them as function
  8200. parameters and arguments works in the natural way. This function
  8201. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8202. and returns a structure of the same type but with the fields
  8203. exchanged.
  8204. @example
  8205. struct foo @{ int a, b; @};
  8206. struct foo x;
  8207. struct foo
  8208. swapfoo (struct foo inval)
  8209. @{
  8210. struct foo outval;
  8211. outval.a = inval.b;
  8212. outval.b = inval.a;
  8213. return outval;
  8214. @}
  8215. @end example
  8216. This simpler definition of @code{swapfoo} avoids using a local
  8217. variable to hold the result about to be return, by using a structure
  8218. constructor (@pxref{Structure Constructors}), like this:
  8219. @example
  8220. struct foo
  8221. swapfoo (struct foo inval)
  8222. @{
  8223. return (struct foo) @{ inval.b, inval.a @};
  8224. @}
  8225. @end example
  8226. It is valid to define a structure type in a function's parameter list,
  8227. as in
  8228. @example
  8229. int
  8230. frob_bar (struct bar @{ int a, b; @} inval)
  8231. @{
  8232. @var{body}
  8233. @}
  8234. @end example
  8235. @noindent
  8236. and @var{body} can access the fields of @var{inval} since the
  8237. structure type @code{struct bar} is defined for the whole function
  8238. body. However, there is no way to create a @code{struct bar} argument
  8239. to pass to @code{frob_bar}, except with kludges. As a result,
  8240. defining a structure type in a parameter list is useless in practice.
  8241. @node Function Declarations
  8242. @section Function Declarations
  8243. @cindex function declarations
  8244. @cindex declararing functions
  8245. To call a function, or use its name as a pointer, a @dfn{function
  8246. declaration} for the function name must be in effect at that point in
  8247. the code. The function's definition serves as a declaration of that
  8248. function for the rest of the containing scope, but to use the function
  8249. in code before the definition, or from another compilation module, a
  8250. separate function declaration must precede the use.
  8251. A function declaration looks like the start of a function definition.
  8252. It begins with the return value type (@code{void} if none) and the
  8253. function name, followed by argument declarations in parentheses
  8254. (though these can sometimes be omitted). But that's as far as the
  8255. similarity goes: instead of the function body, the declaration uses a
  8256. semicolon.
  8257. @cindex function prototype
  8258. @cindex prototype of a function
  8259. A declaration that specifies argument types is called a @dfn{function
  8260. prototype}. You can include the argument names or omit them. The
  8261. names, if included in the declaration, have no effect, but they may
  8262. serve as documentation.
  8263. This form of prototype specifies fixed argument types:
  8264. @example
  8265. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8266. @end example
  8267. @noindent
  8268. This form says the function takes no arguments:
  8269. @example
  8270. @var{rettype} @var{function} (void);
  8271. @end example
  8272. @noindent
  8273. This form declares types for some arguments, and allows additional
  8274. arguments whose types are not specified:
  8275. @example
  8276. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8277. @end example
  8278. For a parameter that's an array of variable length, you can write
  8279. its declaration with @samp{*} where the ``length'' of the array would
  8280. normally go; for example, these are all equivalent.
  8281. @example
  8282. double maximum (int n, int m, double a[n][m]);
  8283. double maximum (int n, int m, double a[*][*]);
  8284. double maximum (int n, int m, double a[ ][*]);
  8285. double maximum (int n, int m, double a[ ][m]);
  8286. @end example
  8287. @noindent
  8288. The old-fashioned form of declaration, which is not a prototype, says
  8289. nothing about the types of arguments or how many they should be:
  8290. @example
  8291. @var{rettype} @var{function} ();
  8292. @end example
  8293. @strong{Warning:} Arguments passed to a function declared without a
  8294. prototype are converted with the default argument promotions
  8295. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8296. types are unspecified.
  8297. Function declarations are usually written at the top level in a source file,
  8298. but you can also put them inside code blocks. Then the function name
  8299. is visible for the rest of the containing scope. For example:
  8300. @example
  8301. void
  8302. foo (char *file_name)
  8303. @{
  8304. void save_file (char *);
  8305. save_file (file_name);
  8306. @}
  8307. @end example
  8308. If another part of the code tries to call the function
  8309. @code{save_file}, this declaration won't be in effect there. So the
  8310. function will get an implicit declaration of the form @code{extern int
  8311. save_file ();}. That conflicts with the explicit declaration
  8312. here, and the discrepancy generates a warning.
  8313. The syntax of C traditionally allows omitting the data type in a
  8314. function declaration if it specifies a storage class or a qualifier.
  8315. Then the type defaults to @code{int}. For example:
  8316. @example
  8317. static foo (double x);
  8318. @end example
  8319. @noindent
  8320. defaults the return type to @code{int}.
  8321. This is bad practice; if you see it, fix it.
  8322. Calling a function that is undeclared has the effect of an creating
  8323. @dfn{implicit} declaration in the innermost containing scope,
  8324. equivalent to this:
  8325. @example
  8326. extern int @dfn{function} ();
  8327. @end example
  8328. @noindent
  8329. This declaration says that the function returns @code{int} but leaves
  8330. its argument types unspecified. If that does not accurately fit the
  8331. function, then the program @strong{needs} an explicit declaration of
  8332. the function with argument types in order to call it correctly.
  8333. Implicit declarations are deprecated, and a function call that creates one
  8334. causes a warning.
  8335. @node Function Calls
  8336. @section Function Calls
  8337. @cindex function calls
  8338. @cindex calling functions
  8339. Starting a program automatically calls the function named @code{main}
  8340. (@pxref{The main Function}). Aside from that, a function does nothing
  8341. except when it is @dfn{called}. That occurs during the execution of a
  8342. function-call expression specifying that function.
  8343. A function-call expression looks like this:
  8344. @example
  8345. @var{function} (@var{arguments}@r{@dots{}})
  8346. @end example
  8347. Most of the time, @var{function} is a function name. However, it can
  8348. also be an expression with a function pointer value; that way, the
  8349. program can determine at run time which function to call.
  8350. The @var{arguments} are a series of expressions separated by commas.
  8351. Each expression specifies one argument to pass to the function.
  8352. The list of arguments in a function call looks just like use of the
  8353. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8354. the parentheses of a function call gives it a different meaning.
  8355. Here's an example of a function call, taken from an example near the
  8356. beginning (@pxref{Complete Program}).
  8357. @example
  8358. printf ("Fibonacci series item %d is %d\n",
  8359. 19, fib (19));
  8360. @end example
  8361. The three arguments given to @code{printf} are a constant string, the
  8362. integer 19, and the integer returned by @code{fib (19)}.
  8363. @node Function Call Semantics
  8364. @section Function Call Semantics
  8365. @cindex function call semantics
  8366. @cindex semantics of function calls
  8367. @cindex call-by-value
  8368. The meaning of a function call is to compute the specified argument
  8369. expressions, convert their values according to the function's
  8370. declaration, then run the function giving it copies of the converted
  8371. values. (This method of argument passing is known as
  8372. @dfn{call-by-value}.) When the function finishes, the value it
  8373. returns becomes the value of the function-call expression.
  8374. Call-by-value implies that an assignment to the function argument
  8375. variable has no direct effect on the caller. For instance,
  8376. @example
  8377. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8378. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8379. void
  8380. subroutine (int x)
  8381. @{
  8382. x = 5;
  8383. @}
  8384. void
  8385. main (void)
  8386. @{
  8387. int y = 20;
  8388. subroutine (y);
  8389. printf ("y is %d\n", y);
  8390. return EXIT_SUCCESS;
  8391. @}
  8392. @end example
  8393. @noindent
  8394. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8395. from the value of @code{y}, but this does not establish any other
  8396. relationship between the two variables. Thus, the assignment to
  8397. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8398. If an argument's type is specified by the function's declaration, the
  8399. function call converts the argument expression to that type if
  8400. possible. If the conversion is impossible, that is an error.
  8401. If the function's declaration doesn't specify the type of that
  8402. argument, then the @emph{default argument promotions} apply.
  8403. @xref{Argument Promotions}.
  8404. @node Function Pointers
  8405. @section Function Pointers
  8406. @cindex function pointers
  8407. @cindex pointers to functions
  8408. A function name refers to a fixed function. Sometimes it is useful to
  8409. call a function to be determined at run time; to do this, you can use
  8410. a @dfn{function pointer value} that points to the chosen function
  8411. (@pxref{Pointers}).
  8412. Pointer-to-function types can be used to declare variables and other
  8413. data, including array elements, structure fields, and union
  8414. alternatives. They can also be used for function arguments and return
  8415. values. These types have the peculiarity that they are never
  8416. converted automatically to @code{void *} or vice versa. However, you
  8417. can do that conversion with a cast.
  8418. @menu
  8419. * Declaring Function Pointers:: How to declare a pointer to a function.
  8420. * Assigning Function Pointers:: How to assign values to function pointers.
  8421. * Calling Function Pointers:: How to call functions through pointers.
  8422. @end menu
  8423. @node Declaring Function Pointers
  8424. @subsection Declaring Function Pointers
  8425. @cindex declaring function pointers
  8426. @cindex function pointers, declaring
  8427. The declaration of a function pointer variable (or structure field)
  8428. looks almost like a function declaration, except it has an additional
  8429. @samp{*} just before the variable name. Proper nesting requires a
  8430. pair of parentheses around the two of them. For instance, @code{int
  8431. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8432. an @code{int}-returning function.''
  8433. Contrast these three declarations:
  8434. @example
  8435. /* @r{Declare a function returning @code{char *}.} */
  8436. char *a (char *);
  8437. /* @r{Declare a pointer to a function returning @code{char}.} */
  8438. char (*a) (char *);
  8439. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8440. char *(*a) (char *);
  8441. @end example
  8442. The possible argument types of the function pointed to are the same
  8443. as in a function declaration. You can write a prototype
  8444. that specifies all the argument types:
  8445. @example
  8446. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8447. @end example
  8448. @noindent
  8449. or one that specifies some and leaves the rest unspecified:
  8450. @example
  8451. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8452. @end example
  8453. @noindent
  8454. or one that says there are no arguments:
  8455. @example
  8456. @var{rettype} (*@var{function}) (void);
  8457. @end example
  8458. You can also write a non-prototype declaration that says
  8459. nothing about the argument types:
  8460. @example
  8461. @var{rettype} (*@var{function}) ();
  8462. @end example
  8463. For example, here's a declaration for a variable that should
  8464. point to some arithmetic function that operates on two @code{double}s:
  8465. @example
  8466. double (*binary_op) (double, double);
  8467. @end example
  8468. Structure fields, union alternatives, and array elements can be
  8469. function pointers; so can parameter variables. The function pointer
  8470. declaration construct can also be combined with other operators
  8471. allowed in declarations. For instance,
  8472. @example
  8473. int **(*foo)();
  8474. @end example
  8475. @noindent
  8476. declares @code{foo} as a pointer to a function that returns
  8477. type @code{int **}, and
  8478. @example
  8479. int **(*foo[30])();
  8480. @end example
  8481. @noindent
  8482. declares @code{foo} as an array of 30 pointers to functions that
  8483. return type @code{int **}.
  8484. @example
  8485. int **(**foo)();
  8486. @end example
  8487. @noindent
  8488. declares @code{foo} as a pointer to a pointer to a function that
  8489. returns type @code{int **}.
  8490. @node Assigning Function Pointers
  8491. @subsection Assigning Function Pointers
  8492. @cindex assigning function pointers
  8493. @cindex function pointers, assigning
  8494. Assuming we have declared the variable @code{binary_op} as in the
  8495. previous section, giving it a value requires a suitable function to
  8496. use. So let's define a function suitable for the variable to point
  8497. to. Here's one:
  8498. @example
  8499. double
  8500. double_add (double a, double b)
  8501. @{
  8502. return a+b;
  8503. @}
  8504. @end example
  8505. Now we can give it a value:
  8506. @example
  8507. binary_op = double_add;
  8508. @end example
  8509. The target type of the function pointer must be upward compatible with
  8510. the type of the function (@pxref{Compatible Types}).
  8511. There is no need for @samp{&} in front of @code{double_add}.
  8512. Using a function name such as @code{double_add} as an expression
  8513. automatically converts it to the function's address, with the
  8514. appropriate function pointer type. However, it is ok to use
  8515. @samp{&} if you feel that is clearer:
  8516. @example
  8517. binary_op = &double_add;
  8518. @end example
  8519. @node Calling Function Pointers
  8520. @subsection Calling Function Pointers
  8521. @cindex calling function pointers
  8522. @cindex function pointers, calling
  8523. To call the function specified by a function pointer, just write the
  8524. function pointer value in a function call. For instance, here's a
  8525. call to the function @code{binary_op} points to:
  8526. @example
  8527. binary_op (x, 5)
  8528. @end example
  8529. Since the data type of @code{binary_op} explicitly specifies type
  8530. @code{double} for the arguments, the call converts @code{x} and 5 to
  8531. @code{double}.
  8532. The call conceptually dereferences the pointer @code{binary_op} to
  8533. ``get'' the function it points to, and calls that function. If you
  8534. wish, you can explicitly represent the derefence by writing the
  8535. @code{*} operator:
  8536. @example
  8537. (*binary_op) (x, 5)
  8538. @end example
  8539. The @samp{*} reminds people reading the code that @code{binary_op} is
  8540. a function pointer rather than the name of a specific function.
  8541. @node The main Function
  8542. @section The @code{main} Function
  8543. @cindex @code{main} function
  8544. @findex main
  8545. Every complete executable program requires at least one function,
  8546. called @code{main}, which is where execution begins. You do not have
  8547. to explicitly declare @code{main}, though GNU C permits you to do so.
  8548. Conventionally, @code{main} should be defined to follow one of these
  8549. calling conventions:
  8550. @example
  8551. int main (void) @{@r{@dots{}}@}
  8552. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8553. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8554. @end example
  8555. @noindent
  8556. Using @code{void} as the parameter list means that @code{main} does
  8557. not use the arguments. You can write @code{char **argv} instead of
  8558. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8559. constructs are equivalent.
  8560. @ignore @c Not so at present
  8561. Defining @code{main} in any other way generates a warning. Your
  8562. program will still compile, but you may get unexpected results when
  8563. executing it.
  8564. @end ignore
  8565. You can call @code{main} from C code, as you can call any other
  8566. function, though that is an unusual thing to do. When you do that,
  8567. you must write the call to pass arguments that match the parameters in
  8568. the definition of @code{main}.
  8569. The @code{main} function is not actually the first code that runs when
  8570. a program starts. In fact, the first code that runs is system code
  8571. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8572. code, but in GNU we replaced it with C code. Its job is to find
  8573. the arguments for @code{main} and call that.
  8574. @menu
  8575. * Values from main:: Returning values from the main function.
  8576. * Command-line Parameters:: Accessing command-line parameters
  8577. provided to the program.
  8578. * Environment Variables:: Accessing system environment variables.
  8579. @end menu
  8580. @node Values from main
  8581. @subsection Returning Values from @code{main}
  8582. @cindex returning values from @code{main}
  8583. @cindex success
  8584. @cindex failure
  8585. @cindex exit status
  8586. When @code{main} returns, the process terminates. Whatever value
  8587. @code{main} returns becomes the exit status which is reported to the
  8588. parent process. While nominally the return value is of type
  8589. @code{int}, in fact the exit status gets truncated to eight bits; if
  8590. @code{main} returns the value 256, the exit status is 0.
  8591. Normally, programs return only one of two values: 0 for success,
  8592. and 1 for failure. For maximum portability, use the macro
  8593. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8594. @code{stdlib.h}. Here's an example:
  8595. @cindex @code{EXIT_FAILURE}
  8596. @cindex @code{EXIT_SUCCESS}
  8597. @example
  8598. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8599. /* @r{and @code{EXIT_FAILURE}.} */
  8600. int
  8601. main (void)
  8602. @{
  8603. @r{@dots{}}
  8604. if (foo)
  8605. return EXIT_SUCCESS;
  8606. else
  8607. return EXIT_FAILURE;
  8608. @}
  8609. @end example
  8610. Some types of programs maintain special conventions for various return
  8611. values; for example, comparison programs including @code{cmp} and
  8612. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8613. the comparison couldn't be performed.
  8614. @node Command-line Parameters
  8615. @subsection Accessing Command-line Parameters
  8616. @cindex command-line parameters
  8617. @cindex parameters, command-line
  8618. If the program was invoked with any command-line arguments, it can
  8619. access them through the arguments of @code{main}, @code{argc} and
  8620. @code{argv}. (You can give these arguments any names, but the names
  8621. @code{argc} and @code{argv} are customary.)
  8622. The value of @code{argv} is an array containing all of the
  8623. command-line arguments as strings, with the name of the command
  8624. invoked as the first string. @code{argc} is an integer that says how
  8625. many strings @code{argv} contains. Here is an example of accessing
  8626. the command-line parameters, retrieving the program's name and
  8627. checking for the standard @option{--version} and @option{--help} options:
  8628. @example
  8629. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8630. int
  8631. main (int argc, char *argv[])
  8632. @{
  8633. char *program_name = argv[0];
  8634. for (int i = 1; i < argc; i++)
  8635. @{
  8636. if (!strcmp (argv[i], "--version"))
  8637. @{
  8638. /* @r{Print version information and exit.} */
  8639. @r{@dots{}}
  8640. @}
  8641. else if (!strcmp (argv[i], "--help"))
  8642. @{
  8643. /* @r{Print help information and exit.} */
  8644. @r{@dots{}}
  8645. @}
  8646. @}
  8647. @r{@dots{}}
  8648. @}
  8649. @end example
  8650. @node Environment Variables
  8651. @subsection Accessing Environment Variables
  8652. @cindex environment variables
  8653. You can optionally include a third parameter to @code{main}, another
  8654. array of strings, to capture the environment variables available to
  8655. the program. Unlike what happens with @code{argv}, there is no
  8656. additional parameter for the count of environment variables; rather,
  8657. the array of environment variables concludes with a null pointer.
  8658. @example
  8659. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8660. int
  8661. main (int argc, char *argv[], char *envp[])
  8662. @{
  8663. /* @r{Print out all environment variables.} */
  8664. int i = 0;
  8665. while (envp[i])
  8666. @{
  8667. printf ("%s\n", envp[i]);
  8668. i++;
  8669. @}
  8670. @}
  8671. @end example
  8672. Another method of retrieving environment variables is to use the
  8673. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8674. Using @code{getenv} does not require defining @code{main} to accept the
  8675. @code{envp} pointer. For example, here is a program that fetches and prints
  8676. the user's home directory (if defined):
  8677. @example
  8678. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8679. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8680. int
  8681. main (void)
  8682. @{
  8683. char *home_directory = getenv ("HOME");
  8684. if (home_directory)
  8685. printf ("My home directory is: %s\n", home_directory);
  8686. else
  8687. printf ("My home directory is not defined!\n");
  8688. @}
  8689. @end example
  8690. @node Advanced Definitions
  8691. @section Advanced Function Features
  8692. This section describes some advanced or obscure features for GNU C
  8693. function definitions. If you are just learning C, you can skip the
  8694. rest of this chapter.
  8695. @menu
  8696. * Variable-Length Array Parameters:: Functions that accept arrays
  8697. of variable length.
  8698. * Variable Number of Arguments:: Variadic functions.
  8699. * Nested Functions:: Defining functions within functions.
  8700. * Inline Function Definitions:: A function call optimization technique.
  8701. @end menu
  8702. @node Variable-Length Array Parameters
  8703. @subsection Variable-Length Array Parameters
  8704. @cindex variable-length array parameters
  8705. @cindex array parameters, variable-length
  8706. @cindex functions that accept variable-length arrays
  8707. An array parameter can have variable length: simply declare the array
  8708. type with a size that isn't constant. In a nested function, the
  8709. length can refer to a variable defined in a containing scope. In any
  8710. function, it can refer to a previous parameter, like this:
  8711. @example
  8712. struct entry
  8713. tester (int len, char data[len][len])
  8714. @{
  8715. @r{@dots{}}
  8716. @}
  8717. @end example
  8718. Alternatively, in function declarations (but not in function
  8719. definitions), you can use @code{[*]} to denote that the array
  8720. parameter is of a variable length, such that these two declarations
  8721. mean the same thing:
  8722. @example
  8723. struct entry
  8724. tester (int len, char data[len][len]);
  8725. @end example
  8726. @example
  8727. struct entry
  8728. tester (int len, char data[*][*]);
  8729. @end example
  8730. @noindent
  8731. The two forms of input are equivalent in GNU C, but emphasizing that
  8732. the array parameter is variable-length may be helpful to those
  8733. studying the code.
  8734. You can also omit the length parameter, and instead use some other
  8735. in-scope variable for the length in the function definition:
  8736. @example
  8737. struct entry
  8738. tester (char data[*][*]);
  8739. @r{@dots{}}
  8740. int dataLength = 20;
  8741. @r{@dots{}}
  8742. struct entry
  8743. tester (char data[dataLength][dataLength])
  8744. @{
  8745. @r{@dots{}}
  8746. @}
  8747. @end example
  8748. @c ??? check text above
  8749. @cindex parameter forward declaration
  8750. In GNU C, to pass the array first and the length afterward, you can
  8751. use a @dfn{parameter forward declaration}, like this:
  8752. @example
  8753. struct entry
  8754. tester (int len; char data[len][len], int len)
  8755. @{
  8756. @r{@dots{}}
  8757. @}
  8758. @end example
  8759. The @samp{int len} before the semicolon is the parameter forward
  8760. declaration; it serves the purpose of making the name @code{len} known
  8761. when the declaration of @code{data} is parsed.
  8762. You can write any number of such parameter forward declarations in the
  8763. parameter list. They can be separated by commas or semicolons, but
  8764. the last one must end with a semicolon, which is followed by the
  8765. ``real'' parameter declarations. Each forward declaration must match
  8766. a subsequent ``real'' declaration in parameter name and data type.
  8767. Standard C does not support parameter forward declarations.
  8768. @node Variable Number of Arguments
  8769. @subsection Variable-Length Parameter Lists
  8770. @cindex variable-length parameter lists
  8771. @cindex parameters lists, variable length
  8772. @cindex function parameter lists, variable length
  8773. @cindex variadic function
  8774. A function that takes a variable number of arguments is called a
  8775. @dfn{variadic function}. In C, a variadic function must specify at
  8776. least one fixed argument with an explicitly declared data type.
  8777. Additional arguments can follow, and can vary in both quantity and
  8778. data type.
  8779. In the function header, declare the fixed parameters in the normal
  8780. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8781. example of a variadic function header:
  8782. @example
  8783. int add_multiple_values (int number, ...)
  8784. @end example
  8785. @cindex @code{va_list}
  8786. @cindex @code{va_start}
  8787. @cindex @code{va_end}
  8788. The function body can refer to fixed arguments by their parameter
  8789. names, but the additional arguments have no names. Accessing them in
  8790. the function body uses certain standard macros. They are defined in
  8791. the library header file @file{stdarg.h}, so the code must
  8792. @code{#include} that file.
  8793. In the body, write
  8794. @example
  8795. va_list ap;
  8796. va_start (ap, @var{last_fixed_parameter});
  8797. @end example
  8798. @noindent
  8799. This declares the variable @code{ap} (you can use any name for it)
  8800. and then sets it up to point before the first additional argument.
  8801. Then, to fetch the next consecutive additional argument, write this:
  8802. @example
  8803. va_arg (ap, @var{type})
  8804. @end example
  8805. After fetching all the additional arguments (or as many as need to be
  8806. used), write this:
  8807. @example
  8808. va_end (ap);
  8809. @end example
  8810. Here's an example of a variadic function definition that adds any
  8811. number of @code{int} arguments. The first (fixed) argument says how
  8812. many more arguments follow.
  8813. @example
  8814. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8815. @r{@dots{}}
  8816. int
  8817. add_multiple_values (int argcount, ...)
  8818. @{
  8819. int counter, total = 0;
  8820. /* @r{Declare a variable of type @code{va_list}.} */
  8821. va_list argptr;
  8822. /* @r{Initialize that variable..} */
  8823. va_start (argptr, argcount);
  8824. for (counter = 0; counter < argcount; counter++)
  8825. @{
  8826. /* @r{Get the next additional argument.} */
  8827. total += va_arg (argptr, int);
  8828. @}
  8829. /* @r{End use of the @code{argptr} variable.} */
  8830. va_end (argptr);
  8831. return total;
  8832. @}
  8833. @end example
  8834. With GNU C, @code{va_end} is superfluous, but some other compilers
  8835. might make @code{va_start} allocate memory so that calling
  8836. @code{va_end} is necessary to avoid a memory leak. Before doing
  8837. @code{va_start} again with the same variable, do @code{va_end}
  8838. first.
  8839. @cindex @code{va_copy}
  8840. Because of this possible memory allocation, it is risky (in principle)
  8841. to copy one @code{va_list} variable to another with assignment.
  8842. Instead, use @code{va_copy}, which copies the substance but allocates
  8843. separate memory in the variable you copy to. The call looks like
  8844. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8845. @var{from} should be variables of type @code{va_list}. In principle,
  8846. do @code{va_end} on each of these variables before its scope ends.
  8847. Since the additional arguments' types are not specified in the
  8848. function's definition, the default argument promotions
  8849. (@pxref{Argument Promotions}) apply to them in function calls. The
  8850. function definition must take account of this; thus, if an argument
  8851. was passed as @code{short}, the function should get it as @code{int}.
  8852. If an argument was passed as @code{float}, the function should get it
  8853. as @code{double}.
  8854. C has no mechanism to tell the variadic function how many arguments
  8855. were passed to it, so its calling convention must give it a way to
  8856. determine this. That's why @code{add_multiple_values} takes a fixed
  8857. argument that says how many more arguments follow. Thus, you can
  8858. call the function like this:
  8859. @example
  8860. sum = add_multiple_values (3, 12, 34, 190);
  8861. /* @r{Value is 12+34+190.} */
  8862. @end example
  8863. In GNU C, there is no actual need to use the @code{va_end} function.
  8864. In fact, it does nothing. It's used for compatibility with other
  8865. compilers, when that matters.
  8866. It is a mistake to access variables declared as @code{va_list} except
  8867. in the specific ways described here. Just what that type consists of
  8868. is an implementation detail, which could vary from one platform to
  8869. another.
  8870. @node Nested Functions
  8871. @subsection Nested Functions
  8872. @cindex nested functions
  8873. @cindex functions, nested
  8874. @cindex downward funargs
  8875. @cindex thunks
  8876. A @dfn{nested function} is a function defined inside another function.
  8877. The nested function's name is local to the block where it is defined.
  8878. For example, here we define a nested function named @code{square}, and
  8879. call it twice:
  8880. @example
  8881. @group
  8882. foo (double a, double b)
  8883. @{
  8884. double square (double z) @{ return z * z; @}
  8885. return square (a) + square (b);
  8886. @}
  8887. @end group
  8888. @end example
  8889. The nested function can access all the variables of the containing
  8890. function that are visible at the point of its definition. This is
  8891. called @dfn{lexical scoping}. For example, here we show a nested
  8892. function that uses an inherited variable named @code{offset}:
  8893. @example
  8894. @group
  8895. bar (int *array, int offset, int size)
  8896. @{
  8897. int access (int *array, int index)
  8898. @{ return array[index + offset]; @}
  8899. int i;
  8900. @r{@dots{}}
  8901. for (i = 0; i < size; i++)
  8902. @r{@dots{}} access (array, i) @r{@dots{}}
  8903. @}
  8904. @end group
  8905. @end example
  8906. Nested function definitions can appear wherever automatic variable
  8907. declarations are allowed; that is, in any block, interspersed with the
  8908. other declarations and statements in the block.
  8909. The nested function's name is visible only within the parent block;
  8910. the name's scope starts from its definition and continues to the end
  8911. of the containing block. If the nested function's name
  8912. is the same as the parent function's name, there wil be
  8913. no way to refer to the parent function inside the scope of the
  8914. name of the nested function.
  8915. Using @code{extern} or @code{static} on a nested function definition
  8916. is an error.
  8917. It is possible to call the nested function from outside the scope of its
  8918. name by storing its address or passing the address to another function.
  8919. You can do this safely, but you must be careful:
  8920. @example
  8921. @group
  8922. hack (int *array, int size, int addition)
  8923. @{
  8924. void store (int index, int value)
  8925. @{ array[index] = value + addition; @}
  8926. intermediate (store, size);
  8927. @}
  8928. @end group
  8929. @end example
  8930. Here, the function @code{intermediate} receives the address of
  8931. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8932. the arguments given to @code{store} are used to store into @code{array}.
  8933. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8934. It is safe for @code{intermediate} to call @code{store} because
  8935. @code{hack}'s stack frame, with its arguments and local variables,
  8936. continues to exist during the call to @code{intermediate}.
  8937. Calling the nested function through its address after the containing
  8938. function has exited is asking for trouble. If it is called after a
  8939. containing scope level has exited, and if it refers to some of the
  8940. variables that are no longer in scope, it will refer to memory
  8941. containing junk or other data. It's not wise to take the risk.
  8942. The GNU C Compiler implements taking the address of a nested function
  8943. using a technique called @dfn{trampolines}. This technique was
  8944. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8945. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8946. A nested function can jump to a label inherited from a containing
  8947. function, provided the label was explicitly declared in the containing
  8948. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8949. containing function, exiting the nested function that did the
  8950. @code{goto} and any intermediate function invocations as well. Here
  8951. is an example:
  8952. @example
  8953. @group
  8954. bar (int *array, int offset, int size)
  8955. @{
  8956. /* @r{Explicitly declare the label @code{failure}.} */
  8957. __label__ failure;
  8958. int access (int *array, int index)
  8959. @{
  8960. if (index > size)
  8961. /* @r{Exit this function,}
  8962. @r{and return to @code{bar}.} */
  8963. goto failure;
  8964. return array[index + offset];
  8965. @}
  8966. @end group
  8967. @group
  8968. int i;
  8969. @r{@dots{}}
  8970. for (i = 0; i < size; i++)
  8971. @r{@dots{}} access (array, i) @r{@dots{}}
  8972. @r{@dots{}}
  8973. return 0;
  8974. /* @r{Control comes here from @code{access}
  8975. if it does the @code{goto}.} */
  8976. failure:
  8977. return -1;
  8978. @}
  8979. @end group
  8980. @end example
  8981. To declare the nested function before its definition, use
  8982. @code{auto} (which is otherwise meaningless for function declarations;
  8983. @pxref{auto and register}). For example,
  8984. @example
  8985. bar (int *array, int offset, int size)
  8986. @{
  8987. auto int access (int *, int);
  8988. @r{@dots{}}
  8989. @r{@dots{}} access (array, i) @r{@dots{}}
  8990. @r{@dots{}}
  8991. int access (int *array, int index)
  8992. @{
  8993. @r{@dots{}}
  8994. @}
  8995. @r{@dots{}}
  8996. @}
  8997. @end example
  8998. @node Inline Function Definitions
  8999. @subsection Inline Function Definitions
  9000. @cindex inline function definitions
  9001. @cindex function definitions, inline
  9002. @findex inline
  9003. To declare a function inline, use the @code{inline} keyword in its
  9004. definition. Here's a simple function that takes a pointer-to-@code{int}
  9005. and increments the integer stored there---declared inline.
  9006. @example
  9007. struct list
  9008. @{
  9009. struct list *first, *second;
  9010. @};
  9011. inline struct list *
  9012. list_first (struct list *p)
  9013. @{
  9014. return p->first;
  9015. @}
  9016. inline struct list *
  9017. list_second (struct list *p)
  9018. @{
  9019. return p->second;
  9020. @}
  9021. @end example
  9022. optimized compilation can substitute the inline function's body for
  9023. any call to it. This is called @emph{inlining} the function. It
  9024. makes the code that contains the call run faster, significantly so if
  9025. the inline function is small.
  9026. Here's a function that uses @code{pair_second}:
  9027. @example
  9028. int
  9029. pairlist_length (struct list *l)
  9030. @{
  9031. int length = 0;
  9032. while (l)
  9033. @{
  9034. length++;
  9035. l = pair_second (l);
  9036. @}
  9037. return length;
  9038. @}
  9039. @end example
  9040. Substituting the code of @code{pair_second} into the definition of
  9041. @code{pairlist_length} results in this code, in effect:
  9042. @example
  9043. int
  9044. pairlist_length (struct list *l)
  9045. @{
  9046. int length = 0;
  9047. while (l)
  9048. @{
  9049. length++;
  9050. l = l->second;
  9051. @}
  9052. return length;
  9053. @}
  9054. @end example
  9055. Since the definition of @code{pair_second} does not say @code{extern}
  9056. or @code{static}, that definition is used only for inlining. It
  9057. doesn't generate code that can be called at run time. If not all the
  9058. calls to the function are inlined, there must be a definition of the
  9059. same function name in another module for them to call.
  9060. @cindex inline functions, omission of
  9061. @c @opindex fkeep-inline-functions
  9062. Adding @code{static} to an inline function definition means the
  9063. function definition is limited to this compilation module. Also, it
  9064. generates run-time code if necessary for the sake of any calls that
  9065. were not inlined. If all calls are inlined then the function
  9066. definition does not generate run-time code, but you can force
  9067. generation of run-time code with the option
  9068. @option{-fkeep-inline-functions}.
  9069. @cindex extern inline function
  9070. Specifying @code{extern} along with @code{inline} means the function is
  9071. external and generates run-time code to be called from other
  9072. separately compiled modules, as well as inlined. You can define the
  9073. function as @code{inline} without @code{extern} in other modules so as
  9074. to inline calls to the same function in those modules.
  9075. Why are some calls not inlined? First of all, inlining is an
  9076. optimization, so non-optimized compilation does not inline.
  9077. Some calls cannot be inlined for technical reasons. Also, certain
  9078. usages in a function definition can make it unsuitable for inline
  9079. substitution. Among these usages are: variadic functions, use of
  9080. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9081. use of nonlocal goto. The option @option{-Winline} requests a warning
  9082. when a function marked @code{inline} is unsuitable to be inlined. The
  9083. warning explains what obstacle makes it unsuitable.
  9084. Just because a call @emph{can} be inlined does not mean it
  9085. @emph{should} be inlined. The GNU C compiler weighs costs and
  9086. benefits to decide whether inlining a particular call is advantageous.
  9087. You can force inlining of all calls to a given function that can be
  9088. inlined, even in a non-optimized compilation. by specifying the
  9089. @samp{always_inline} attribute for the function, like this:
  9090. @example
  9091. /* @r{Prototype.} */
  9092. inline void foo (const char) __attribute__((always_inline));
  9093. @end example
  9094. @noindent
  9095. This is a GNU C extension. @xref{Attributes}.
  9096. A function call may be inlined even if not declared @code{inline} in
  9097. special cases where the compiler can determine this is correct and
  9098. desirable. For instance, when a static function is called only once,
  9099. it will very likely be inlined. With @option{-flto}, link-time
  9100. optimization, any function might be inlined. To absolutely prevent
  9101. inlining of a specific function, specify
  9102. @code{__attribute__((__noinline__))} in the function's definition.
  9103. @node Obsolete Definitions
  9104. @section Obsolete Function Features
  9105. These features of function definitions are still used in old
  9106. programs, but you shouldn't write code this way today.
  9107. If you are just learning C, you can skip this section.
  9108. @menu
  9109. * Old GNU Inlining:: An older inlining technique.
  9110. * Old-Style Function Definitions:: Original K&R style functions.
  9111. @end menu
  9112. @node Old GNU Inlining
  9113. @subsection Older GNU C Inlining
  9114. The GNU C spec for inline functions, before GCC version 5, defined
  9115. @code{extern inline} on a function definition to mean to inline calls
  9116. to it but @emph{not} generate code for the function that could be
  9117. called at run time. By contrast, @code{inline} without @code{extern}
  9118. specified to generate run-time code for the function. In effect, ISO
  9119. incompatibly flipped the meanings of these two cases. We changed GCC
  9120. in version 5 to adopt the ISO specification.
  9121. Many programs still use these cases with the previous GNU C meanings.
  9122. You can specify use of those meanings with the option
  9123. @option{-fgnu89-inline}. You can also specify this for a single
  9124. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9125. @example
  9126. inline __attribute__ ((gnu_inline))
  9127. int
  9128. inc (int *a)
  9129. @{
  9130. (*a)++;
  9131. @}
  9132. @end example
  9133. @node Old-Style Function Definitions
  9134. @subsection Old-Style Function Definitions
  9135. @cindex old-style function definitions
  9136. @cindex function definitions, old-style
  9137. @cindex K&R-style function definitions
  9138. The syntax of C traditionally allows omitting the data type in a
  9139. function declaration if it specifies a storage class or a qualifier.
  9140. Then the type defaults to @code{int}. For example:
  9141. @example
  9142. static foo (double x);
  9143. @end example
  9144. @noindent
  9145. defaults the return type to @code{int}. This is bad practice; if you
  9146. see it, fix it.
  9147. An @dfn{old-style} (or ``K&R'') function definition is the way
  9148. function definitions were written in the 1980s. It looks like this:
  9149. @example
  9150. @var{rettype}
  9151. @var{function} (@var{parmnames})
  9152. @var{parm_declarations}
  9153. @{
  9154. @var{body}
  9155. @}
  9156. @end example
  9157. In @var{parmnames}, only the parameter names are listed, separated by
  9158. commas. Then @var{parm_declarations} declares their data types; these
  9159. declarations look just like variable declarations. If a parameter is
  9160. listed in @var{parmnames} but has no declaration, it is implicitly
  9161. declared @code{int}.
  9162. There is no reason to write a definition this way nowadays, but they
  9163. can still be seen in older GNU programs.
  9164. An old-style variadic function definition looks like this:
  9165. @example
  9166. #include <varargs.h>
  9167. int
  9168. add_multiple_values (va_alist)
  9169. va_dcl
  9170. @{
  9171. int argcount;
  9172. int counter, total = 0;
  9173. /* @r{Declare a variable of type @code{va_list}.} */
  9174. va_list argptr;
  9175. /* @r{Initialize that variable.} */
  9176. va_start (argptr);
  9177. /* @r{Get the first argument (fixed).} */
  9178. argcount = va_arg (int);
  9179. for (counter = 0; counter < argcount; counter++)
  9180. @{
  9181. /* @r{Get the next additional argument.} */
  9182. total += va_arg (argptr, int);
  9183. @}
  9184. /* @r{End use of the @code{argptr} variable.} */
  9185. va_end (argptr);
  9186. return total;
  9187. @}
  9188. @end example
  9189. Note that the old-style variadic function definition has no fixed
  9190. parameter variables; all arguments must be obtained with
  9191. @code{va_arg}.
  9192. @node Compatible Types
  9193. @chapter Compatible Types
  9194. @cindex compatible types
  9195. @cindex types, compatible
  9196. Declaring a function or variable twice is valid in C only if the two
  9197. declarations specify @dfn{compatible} types. In addition, some
  9198. operations on pointers require operands to have compatible target
  9199. types.
  9200. In C, two different primitive types are never compatible. Likewise for
  9201. the defined types @code{struct}, @code{union} and @code{enum}: two
  9202. separately defined types are incompatible unless they are defined
  9203. exactly the same way.
  9204. However, there are a few cases where different types can be
  9205. compatible:
  9206. @itemize @bullet
  9207. @item
  9208. Every enumeration type is compatible with some integer type. In GNU
  9209. C, the choice of integer type depends on the largest enumeration
  9210. value.
  9211. @c ??? Which one, in GCC?
  9212. @c ??? ... it varies, depending on the enum values. Testing on
  9213. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9214. @c ??? then moves on to an 8-byte signed integer. These details
  9215. @c ??? might be platform-dependent, as the C standard says that even
  9216. @c ??? char could be used as an enum type, but it's at least true
  9217. @c ??? that GCC chooses a type that is at least large enough to
  9218. @c ??? hold the largest enum value.
  9219. @item
  9220. Array types are compatible if the element types are compatible
  9221. and the sizes (when specified) match.
  9222. @item
  9223. Pointer types are compatible if the pointer target types are
  9224. compatible.
  9225. @item
  9226. Function types that specify argument types are compatible if the
  9227. return types are compatible and the argument types are compatible,
  9228. argument by argument. In addition, they must all agree in whether
  9229. they use @code{...} to allow additional arguments.
  9230. @item
  9231. Function types that don't specify argument types are compatible if the
  9232. return types are.
  9233. @item
  9234. Function types that specify the argument types are compatible with
  9235. function types that omit them, if the return types are compatible and
  9236. the specified argument types are unaltered by the argument promotions
  9237. (@pxref{Argument Promotions}).
  9238. @end itemize
  9239. In order for types to be compatible, they must agree in their type
  9240. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9241. It follows that @code{const int *} and @code{int *} are incompatible
  9242. too (they are pointers to types that are not compatible).
  9243. If two types are compatible ignoring the qualifiers, we call them
  9244. @dfn{nearly compatible}. (If they are array types, we ignore
  9245. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9246. Comparison of pointers is valid if the pointers' target types are
  9247. nearly compatible. Likewise, the two branches of a conditional
  9248. expression may be pointers to nearly compatible target types.
  9249. If two types are compatible ignoring the qualifiers, and the first
  9250. type has all the qualifiers of the second type, we say the first is
  9251. @dfn{upward compatible} with the second. Assignment of pointers
  9252. requires the assigned pointer's target type to be upward compatible
  9253. with the right operand (the new value)'s target type.
  9254. @node Type Conversions
  9255. @chapter Type Conversions
  9256. @cindex type conversions
  9257. @cindex conversions, type
  9258. C converts between data types automatically when that seems clearly
  9259. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9260. @menu
  9261. * Explicit Type Conversion:: Casting a value from one type to another.
  9262. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9263. * Argument Promotions:: Automatic conversion of function parameters.
  9264. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9265. * Common Type:: When operand types differ, which one is used?
  9266. @end menu
  9267. @node Explicit Type Conversion
  9268. @section Explicit Type Conversion
  9269. @cindex cast
  9270. @cindex explicit type conversion
  9271. You can do explicit conversions using the unary @dfn{cast} operator,
  9272. which is written as a type designator (@pxref{Type Designators}) in
  9273. parentheses. For example, @code{(int)} is the operator to cast to
  9274. type @code{int}. Here's an example of using it:
  9275. @example
  9276. @{
  9277. double d = 5.5;
  9278. printf ("Floating point value: %f\n", d);
  9279. printf ("Rounded to integer: %d\n", (int) d);
  9280. @}
  9281. @end example
  9282. Using @code{(int) d} passes an @code{int} value as argument to
  9283. @code{printf}, so you can print it with @samp{%d}. Using just
  9284. @code{d} without the cast would pass the value as @code{double}.
  9285. That won't work at all with @samp{%d}; the results would be gibberish.
  9286. To divide one integer by another without rounding,
  9287. cast either of the integers to @code{double} first:
  9288. @example
  9289. (double) @var{dividend} / @var{divisor}
  9290. @var{dividend} / (double) @var{divisor}
  9291. @end example
  9292. It is enough to cast one of them, because that forces the common type
  9293. to @code{double} so the other will be converted automatically.
  9294. The valid cast conversions are:
  9295. @itemize @bullet
  9296. @item
  9297. One numerical type to another.
  9298. @item
  9299. One pointer type to another.
  9300. (Converting between pointers that point to functions
  9301. and pointers that point to data is not standard C.)
  9302. @item
  9303. A pointer type to an integer type.
  9304. @item
  9305. An integer type to a pointer type.
  9306. @item
  9307. To a union type, from the type of any alternative in the union
  9308. (@pxref{Unions}). (This is a GNU extension.)
  9309. @item
  9310. Anything, to @code{void}.
  9311. @end itemize
  9312. @node Assignment Type Conversions
  9313. @section Assignment Type Conversions
  9314. @cindex assignment type conversions
  9315. Certain type conversions occur automatically in assignments
  9316. and certain other contexts. These are the conversions
  9317. assignments can do:
  9318. @itemize @bullet
  9319. @item
  9320. Converting any numeric type to any other numeric type.
  9321. @item
  9322. Converting @code{void *} to any other pointer type
  9323. (except pointer-to-function types).
  9324. @item
  9325. Converting any other pointer type to @code{void *}.
  9326. (except pointer-to-function types).
  9327. @item
  9328. Converting 0 (a null pointer constant) to any pointer type.
  9329. @item
  9330. Converting any pointer type to @code{bool}. (The result is
  9331. 1 if the pointer is not null.)
  9332. @item
  9333. Converting between pointer types when the left-hand target type is
  9334. upward compatible with the right-hand target type. @xref{Compatible
  9335. Types}.
  9336. @end itemize
  9337. These type conversions occur automatically in certain contexts,
  9338. which are:
  9339. @itemize @bullet
  9340. @item
  9341. An assignment converts the type of the right-hand expression
  9342. to the type wanted by the left-hand expression. For example,
  9343. @example
  9344. double i;
  9345. i = 5;
  9346. @end example
  9347. @noindent
  9348. converts 5 to @code{double}.
  9349. @item
  9350. A function call, when the function specifies the type for that
  9351. argument, converts the argument value to that type. For example,
  9352. @example
  9353. void foo (double);
  9354. foo (5);
  9355. @end example
  9356. @noindent
  9357. converts 5 to @code{double}.
  9358. @item
  9359. A @code{return} statement converts the specified value to the type
  9360. that the function is declared to return. For example,
  9361. @example
  9362. double
  9363. foo ()
  9364. @{
  9365. return 5;
  9366. @}
  9367. @end example
  9368. @noindent
  9369. also converts 5 to @code{double}.
  9370. @end itemize
  9371. In all three contexts, if the conversion is impossible, that
  9372. constitutes an error.
  9373. @node Argument Promotions
  9374. @section Argument Promotions
  9375. @cindex argument promotions
  9376. @cindex promotion of arguments
  9377. When a function's definition or declaration does not specify the type
  9378. of an argument, that argument is passed without conversion in whatever
  9379. type it has, with these exceptions:
  9380. @itemize @bullet
  9381. @item
  9382. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9383. expression is a narrow integer, such as @code{char} or @code{short},
  9384. the call converts it automatically to @code{int} (@pxref{Integer
  9385. Types}).@footnote{On an embedded controller where @code{char}
  9386. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9387. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9388. never occurs in GNU C on real computers.}
  9389. In this example, the expression @code{c} is passed as an @code{int}:
  9390. @example
  9391. char c = '$';
  9392. printf ("Character c is '%c'\n", c);
  9393. @end example
  9394. @item
  9395. If the expression
  9396. has type @code{float}, the call converts it automatically to
  9397. @code{double}.
  9398. @item
  9399. An array as argument is converted to a pointer to its zeroth element.
  9400. @item
  9401. A function name as argument is converted to a pointer to that function.
  9402. @end itemize
  9403. @node Operand Promotions
  9404. @section Operand Promotions
  9405. @cindex operand promotions
  9406. The operands in arithmetic operations undergo type conversion automatically.
  9407. These @dfn{operand promotions} are the same as the argument promotions
  9408. except without converting @code{float} to @code{double}. In other words,
  9409. the operand promotions convert
  9410. @itemize @bullet
  9411. @item
  9412. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9413. @item
  9414. an array to a pointer to its zeroth element, and
  9415. @item
  9416. a function name to a pointer to that function.
  9417. @end itemize
  9418. @node Common Type
  9419. @section Common Type
  9420. @cindex common type
  9421. Arithmetic binary operators (except the shift operators) convert their
  9422. operands to the @dfn{common type} before operating on them.
  9423. Conditional expressions also convert the two possible results to their
  9424. common type. Here are the rules for determining the common type.
  9425. If one of the numbers has a floating-point type and the other is an
  9426. integer, the common type is that floating-point type. For instance,
  9427. @example
  9428. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9429. @end example
  9430. If both are floating point, the type with the larger range is the
  9431. common type.
  9432. If both are integers but of different widths, the common type
  9433. is the wider of the two.
  9434. If they are integer types of the same width, the common type is
  9435. unsigned if either operand is unsigned, and it's @code{long} if either
  9436. operand is @code{long}. It's @code{long long} if either operand is
  9437. @code{long long}.
  9438. These rules apply to addition, subtraction, multiplication, division,
  9439. remainder, comparisons, and bitwise operations. They also apply to
  9440. the two branches of a conditional expression, and to the arithmetic
  9441. done in a modifying assignment operation.
  9442. @node Scope
  9443. @chapter Scope
  9444. @cindex scope
  9445. @cindex block scope
  9446. @cindex function scope
  9447. @cindex function prototype scope
  9448. Each definition or declaration of an identifier is visible
  9449. in certain parts of the program, which is typically less than the whole
  9450. of the program. The parts where it is visible are called its @dfn{scope}.
  9451. Normally, declarations made at the top-level in the source -- that is,
  9452. not within any blocks and function definitions -- are visible for the
  9453. entire contents of the source file after that point. This is called
  9454. @dfn{file scope} (@pxref{File-Scope Variables}).
  9455. Declarations made within blocks of code, including within function
  9456. definitions, are visible only within those blocks. This is called
  9457. @dfn{block scope}. Here is an example:
  9458. @example
  9459. @group
  9460. void
  9461. foo (void)
  9462. @{
  9463. int x = 42;
  9464. @}
  9465. @end group
  9466. @end example
  9467. @noindent
  9468. In this example, the variable @code{x} has block scope; it is visible
  9469. only within the @code{foo} function definition block. Thus, other
  9470. blocks could have their own variables, also named @code{x}, without
  9471. any conflict between those variables.
  9472. A variable declared inside a subblock has a scope limited to
  9473. that subblock,
  9474. @example
  9475. @group
  9476. void
  9477. foo (void)
  9478. @{
  9479. @{
  9480. int x = 42;
  9481. @}
  9482. // @r{@code{x} is out of scope here.}
  9483. @}
  9484. @end group
  9485. @end example
  9486. If a variable declared within a block has the same name as a variable
  9487. declared outside of that block, the definition within the block
  9488. takes precedence during its scope:
  9489. @example
  9490. @group
  9491. int x = 42;
  9492. void
  9493. foo (void)
  9494. @{
  9495. int x = 17;
  9496. printf ("%d\n", x);
  9497. @}
  9498. @end group
  9499. @end example
  9500. @noindent
  9501. This prints 17, the value of the variable @code{x} declared in the
  9502. function body block, rather than the value of the variable @code{x} at
  9503. file scope. We say that the inner declaration of @code{x}
  9504. @dfn{shadows} the outer declaration, for the extent of the inner
  9505. declaration's scope.
  9506. A declaration with block scope can be shadowed by another declaration
  9507. with the same name in a subblock.
  9508. @example
  9509. @group
  9510. void
  9511. foo (void)
  9512. @{
  9513. char *x = "foo";
  9514. @{
  9515. int x = 42;
  9516. @r{@dots{}}
  9517. exit (x / 6);
  9518. @}
  9519. @}
  9520. @end group
  9521. @end example
  9522. A function parameter's scope is the entire function body, but it can
  9523. be shadowed. For example:
  9524. @example
  9525. @group
  9526. int x = 42;
  9527. void
  9528. foo (int x)
  9529. @{
  9530. printf ("%d\n", x);
  9531. @}
  9532. @end group
  9533. @end example
  9534. @noindent
  9535. This prints the value of @code{x} the function parameter, rather than
  9536. the value of the file-scope variable @code{x}. However,
  9537. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9538. is visible for the whole of the containing function body, both before
  9539. and after the label declaration:
  9540. @example
  9541. @group
  9542. void
  9543. foo (void)
  9544. @{
  9545. @r{@dots{}}
  9546. goto bar;
  9547. @r{@dots{}}
  9548. @{ // @r{Subblock does not affect labels.}
  9549. bar:
  9550. @r{@dots{}}
  9551. @}
  9552. goto bar;
  9553. @}
  9554. @end group
  9555. @end example
  9556. Except for labels, a declared identifier is not
  9557. visible to code before its declaration. For example:
  9558. @example
  9559. @group
  9560. int x = 5;
  9561. int y = x + 10;
  9562. @end group
  9563. @end example
  9564. @noindent
  9565. will work, but:
  9566. @example
  9567. @group
  9568. int x = y + 10;
  9569. int y = 5;
  9570. @end group
  9571. @end example
  9572. @noindent
  9573. cannot refer to the variable @code{y} before its declaration.
  9574. @include cpp.texi
  9575. @node Integers in Depth
  9576. @chapter Integers in Depth
  9577. This chapter explains the machine-level details of integer types: how
  9578. they are represented as bits in memory, and the range of possible
  9579. values for each integer type.
  9580. @menu
  9581. * Integer Representations:: How integer values appear in memory.
  9582. * Maximum and Minimum Values:: Value ranges of integer types.
  9583. @end menu
  9584. @node Integer Representations
  9585. @section Integer Representations
  9586. @cindex integer representations
  9587. @cindex representation of integers
  9588. Modern computers store integer values as binary (base-2) numbers that
  9589. occupy a single unit of storage, typically either as an 8-bit
  9590. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9591. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9592. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9593. any of these types could have some other size, bit it's not worth even
  9594. a minute to cater to that possibility. It never happens on
  9595. GNU/Linux.}
  9596. @cindex @code{CHAR_BIT}
  9597. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9598. of bits in type @code{char}. On any real operating system, the value
  9599. is 8.
  9600. The fixed sizes of numeric types necessarily limits their @dfn{range
  9601. of values}, and the particular encoding of integers decides what that
  9602. range is.
  9603. @cindex two's-complement representation
  9604. For unsigned integers, the entire space is used to represent a
  9605. nonnegative value. Signed integers are stored using
  9606. @dfn{two's-complement representation}: a signed integer with @var{n}
  9607. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9608. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9609. high-order, bit is called the @dfn{sign bit}.
  9610. @c ??? Needs correcting
  9611. There is only one value that means zero, and the most negative number
  9612. lacks a positive counterpart. As a result, negating that number
  9613. causes overflow; in practice, its result is that number back again.
  9614. For example, a two's-complement signed 8-bit integer can represent all
  9615. decimal numbers from @minus{}128 to +127. We will revisit that
  9616. peculiarity shortly.
  9617. Decades ago, there were computers that didn't use two's-complement
  9618. representation for integers (@pxref{Integers in Depth}), but they are
  9619. long gone and not worth any effort to support.
  9620. @c ??? Is this duplicate?
  9621. When an arithmetic operation produces a value that is too big to
  9622. represent, the operation is said to @dfn{overflow}. In C, integer
  9623. overflow does not interrupt the control flow or signal an error.
  9624. What it does depends on signedness.
  9625. For unsigned arithmetic, the result of an operation that overflows is
  9626. the @var{n} low-order bits of the correct value. If the correct value
  9627. is representable in @var{n} bits, that is always the result;
  9628. thus we often say that ``integer arithmetic is exact,'' omitting the
  9629. crucial qualifying phrase ``as long as the exact result is
  9630. representable.''
  9631. In principle, a C program should be written so that overflow never
  9632. occurs for signed integers, but in GNU C you can specify various ways
  9633. of handling such overflow (@pxref{Integer Overflow}).
  9634. Integer representations are best understood by looking at a table for
  9635. a tiny integer size; here are the possible values for an integer with
  9636. three bits:
  9637. @multitable @columnfractions .25 .25 .25 .25
  9638. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9639. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9640. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9641. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9642. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9643. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9644. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9645. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9646. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9647. @end multitable
  9648. The parenthesized decimal numbers in the last column represent the
  9649. signed meanings of the two's-complement of the line's value. Recall
  9650. that, in two's-complement encoding, the high-order bit is 0 when
  9651. the number is nonnegative.
  9652. We can now understand the peculiar behavior of negation of the
  9653. most negative two's-complement integer: start with 0b100,
  9654. invert the bits to get 0b011, and add 1: we get
  9655. 0b100, the value we started with.
  9656. We can also see overflow behavior in two's-complement:
  9657. @example
  9658. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9659. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9660. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9661. @end example
  9662. @noindent
  9663. A sum of two nonnegative signed values that overflows has a 1 in the
  9664. sign bit, so the exact positive result is truncated to a negative
  9665. value.
  9666. @c =====================================================================
  9667. @node Maximum and Minimum Values
  9668. @section Maximum and Minimum Values
  9669. @cindex maximum integer values
  9670. @cindex minimum integer values
  9671. @cindex integer ranges
  9672. @cindex ranges of integer types
  9673. @findex INT_MAX
  9674. @findex UINT_MAX
  9675. @findex SHRT_MAX
  9676. @findex LONG_MAX
  9677. @findex LLONG_MAX
  9678. @findex USHRT_MAX
  9679. @findex ULONG_MAX
  9680. @findex ULLONG_MAX
  9681. @findex CHAR_MAX
  9682. @findex SCHAR_MAX
  9683. @findex UCHAR_MAX
  9684. For each primitive integer type, there is a standard macro defined in
  9685. @file{limits.h} that gives the largest value that type can hold. For
  9686. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9687. On a 32-bit computer, that is equal to 2,147,483,647. The
  9688. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9689. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9690. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9691. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9692. @code{ULLONG_MAX}.
  9693. Since there are three ways to specify a @code{char} type, there are
  9694. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9695. @code{UCHAR_MAX}.
  9696. For each type that is or might be signed, there is another symbol that
  9697. gives the minimum value it can hold. (Just replace @code{MAX} with
  9698. @code{MIN} in the names listed above.) There is no minimum limit
  9699. symbol for types specified with @code{unsigned} because the
  9700. minimum for them is universally zero.
  9701. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9702. two's-complement representation, the most negative number is 1 less
  9703. than the negative of the most positive number. Thus, @code{INT_MIN}
  9704. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9705. actually write the value that way in C, since it would overflow.
  9706. That's a good reason to use @code{INT_MIN} to specify
  9707. that value. Its definition is written to avoid overflow.
  9708. @include fp.texi
  9709. @node Compilation
  9710. @chapter Compilation
  9711. @cindex object file
  9712. @cindex compilation module
  9713. @cindex make rules
  9714. Early in the manual we explained how to compile a simple C program
  9715. that consists of a single source file (@pxref{Compile Example}).
  9716. However, we handle only short programs that way. A typical C program
  9717. consists of many source files, each of which is a separate
  9718. @dfn{compilation module}---meaning that it has to be compiled
  9719. separately.
  9720. The full details of how to compile with GCC are documented in xxxx.
  9721. @c ??? ref
  9722. Here we give only a simple introduction.
  9723. These are the commands to compile two compilation modules,
  9724. @file{foo.c} and @file{bar.c}, with a command for each module:
  9725. @example
  9726. gcc -c -O -g foo.c
  9727. gcc -c -O -g bar.c
  9728. @end example
  9729. @noindent
  9730. In these commands, @option{-g} says to generate debugging information,
  9731. @option{-O} says to do some optimization, and @option{-c} says to put
  9732. the compiled code for that module into a corresponding @dfn{object
  9733. file} and go no further. The object file for @file{foo.c} is called
  9734. @file{foo.o}, and so on.
  9735. If you wish, you can specify the additional options @option{-Wformat
  9736. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9737. One reason to divide a large program into multiple compilation modules
  9738. is to control how each module can access the internals of the others.
  9739. When a module declares a function or variable @code{extern}, other
  9740. modules can access it. The other functions and variables in
  9741. a module can't be accessed from outside that module.
  9742. The other reason for using multiple modules is so that changing
  9743. one source file does not require recompiling all of them in order
  9744. to try the modified program. Dividing a large program into many
  9745. substantial modules in this way typically makes recompilation much faster.
  9746. @cindex linking object files
  9747. After you compile all the program's modules, in order to run the
  9748. program you must @dfn{link} the object files into a combined
  9749. executable, like this:
  9750. @example
  9751. gcc -o foo foo.o bar.o
  9752. @end example
  9753. @noindent
  9754. In this command, @option{-o foo} species the file name for the
  9755. executable file, and the other arguments are the object files to link.
  9756. Always specify the executable file name in a command that generates
  9757. one.
  9758. Normally we don't run any of these commands directly. Instead we
  9759. write a set of @dfn{make rules} for the program, then use the
  9760. @command{make} program to recompile only the source files that need to
  9761. be recompiled.
  9762. @c ??? ref to make manual
  9763. @node Directing Compilation
  9764. @chapter Directing Compilation
  9765. This chapter describes C constructs that don't alter the program's
  9766. meaning @emph{as such}, but rather direct the compiler how to treat
  9767. some aspects of the program.
  9768. @menu
  9769. * Pragmas:: Controling compilation of some constructs.
  9770. * Static Assertions:: Compile-time tests for conditions.
  9771. @end menu
  9772. @node Pragmas
  9773. @section Pragmas
  9774. A @dfn{pragma} is an annotation in a program that gives direction to
  9775. the compiler.
  9776. @menu
  9777. * Pragma Basics:: Pragma syntax and usage.
  9778. * Severity Pragmas:: Settings for compile-time pragma output.
  9779. * Optimization Pragmas:: Controlling optimizations.
  9780. @end menu
  9781. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9782. @node Pragma Basics
  9783. @subsection Pragma Basics
  9784. C defines two syntactical forms for pragmas, the line form and the
  9785. token form. You can write any pragma in either form, with the same
  9786. meaning.
  9787. The line form is a line in the source code, like this:
  9788. @example
  9789. #pragma @var{line}
  9790. @end example
  9791. @noindent
  9792. The line pragma has no effect on the parsing of the lines around it.
  9793. This form has the drawback that it can't be generated by a macro expansion.
  9794. The token form is a series of tokens; it can appear anywhere in the
  9795. program between the other tokens.
  9796. @example
  9797. _Pragma (@var{stringconstant})
  9798. @end example
  9799. @noindent
  9800. The pragma has no effect on the syntax of the tokens that surround it;
  9801. thus, here's a pragma in the middle of an @code{if} statement:
  9802. @example
  9803. if _Pragma ("hello") (x > 1)
  9804. @end example
  9805. @noindent
  9806. However, that's an unclear thing to do; for the sake of
  9807. understandability, it is better to put a pragma on a line by itself
  9808. and not embedded in the middle of another construct.
  9809. Both forms of pragma have a textual argument. In a line pragma, the
  9810. text is the rest of the line. The textual argument to @code{_Pragma}
  9811. uses the same syntax as a C string constant: surround the text with
  9812. two @samp{"} characters, and add a backslash before each @samp{"} or
  9813. @samp{\} character in it.
  9814. With either syntax, the textual argument specifies what to do.
  9815. It begins with one or several words that specify the operation.
  9816. If the compiler does not recognize them, it ignores the pragma.
  9817. Here are the pragma operations supported in GNU C@.
  9818. @c ??? Verify font for []
  9819. @table @code
  9820. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9821. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9822. Declares that the current source file depends on @var{file}, so GNU C
  9823. compares the file times and gives a warning if @var{file} is newer
  9824. than the current source file.
  9825. This directive searches for @var{file} the way @code{#include}
  9826. searches for a non-system header file.
  9827. If @var{message} is given, the warning message includes that text.
  9828. Examples:
  9829. @example
  9830. #pragma GCC dependency "parse.y"
  9831. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9832. rerun fixincludes")
  9833. @end example
  9834. @item #pragma GCC poison @var{identifiers}
  9835. @itemx _Pragma ("GCC poison @var{identifiers}")
  9836. Poisons the identifiers listed in @var{identifiers}.
  9837. This is useful to make sure all mention of @var{identifiers} has been
  9838. deleted from the program and that no reference to them creeps back in.
  9839. If any of those identifiers appears anywhere in the source after the
  9840. directive, it causes a compilation error. For example,
  9841. @example
  9842. #pragma GCC poison printf sprintf fprintf
  9843. sprintf(some_string, "hello");
  9844. @end example
  9845. @noindent
  9846. generates an error.
  9847. If a poisoned identifier appears as part of the expansion of a macro
  9848. that was defined before the identifier was poisoned, it will @emph{not}
  9849. cause an error. Thus, system headers that define macros that use
  9850. the identifier will not cause errors.
  9851. For example,
  9852. @example
  9853. #define strrchr rindex
  9854. _Pragma ("GCC poison rindex")
  9855. strrchr(some_string, 'h');
  9856. @end example
  9857. @noindent
  9858. does not cause a compilation error.
  9859. @item #pragma GCC system_header
  9860. @itemx _Pragma ("GCC system_header")
  9861. Specify treating the rest of the current source file as if it came
  9862. from a system header file. @xref{System Headers, System Headers,
  9863. System Headers, gcc, Using the GNU Compiler Collection}.
  9864. @item #pragma GCC warning @var{message}
  9865. @itemx _Pragma ("GCC warning @var{message}")
  9866. Equivalent to @code{#warning}. Its advantage is that the
  9867. @code{_Pragma} form can be included in a macro definition.
  9868. @item #pragma GCC error @var{message}
  9869. @itemx _Pragma ("GCC error @var{message}")
  9870. Equivalent to @code{#error}. Its advantage is that the
  9871. @code{_Pragma} form can be included in a macro definition.
  9872. @item #pragma GCC message @var{message}
  9873. @itemx _Pragma ("GCC message @var{message}")
  9874. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9875. informational message, and could be used to include additional warning
  9876. or error text without triggering more warnings or errors. (Note that
  9877. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9878. @samp{GCC} as part of the pragma.)
  9879. @end table
  9880. @node Severity Pragmas
  9881. @subsection Severity Pragmas
  9882. These pragmas control the severity of classes of diagnostics.
  9883. You can specify the class of diagnostic with the GCC option that causes
  9884. those diagnostics to be generated.
  9885. @table @code
  9886. @item #pragma GCC diagnostic error @var{option}
  9887. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9888. For code following this pragma, treat diagnostics of the variety
  9889. specified by @var{option} as errors. For example:
  9890. @example
  9891. _Pragma ("GCC diagnostic error -Wformat")
  9892. @end example
  9893. @noindent
  9894. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9895. as errors rather than warnings.
  9896. @item #pragma GCC diagnostic warning @var{option}
  9897. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9898. For code following this pragma, treat diagnostics of the variety
  9899. specified by @var{option} as warnings. This overrides the
  9900. @var{-Werror} option which says to treat warnings as errors.
  9901. @item #pragma GCC diagnostic ignore @var{option}
  9902. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9903. For code following this pragma, refrain from reporting any diagnostics
  9904. of the variety specified by @var{option}.
  9905. @item #pragma GCC diagnostic push
  9906. @itemx _Pragma ("GCC diagnostic push")
  9907. @itemx #pragma GCC diagnostic pop
  9908. @itemx _Pragma ("GCC diagnostic pop")
  9909. These pragmas maintain a stack of states for severity settings.
  9910. @samp{GCC diagnostic push} saves the current settings on the stack,
  9911. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9912. the current settings from that.
  9913. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9914. restores the settings to what they were at the start of compilation.
  9915. Here is an example:
  9916. @example
  9917. _Pragma ("GCC diagnostic error -Wformat")
  9918. /* @r{@option{-Wformat} messages treated as errors. } */
  9919. _Pragma ("GCC diagnostic push")
  9920. _Pragma ("GCC diagnostic warning -Wformat")
  9921. /* @r{@option{-Wformat} messages treated as warnings. } */
  9922. _Pragma ("GCC diagnostic push")
  9923. _Pragma ("GCC diagnostic ignored -Wformat")
  9924. /* @r{@option{-Wformat} messages suppressed. } */
  9925. _Pragma ("GCC diagnostic pop")
  9926. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9927. _Pragma ("GCC diagnostic pop")
  9928. /* @r{@option{-Wformat} messages treated as errors again. } */
  9929. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9930. _Pragma ("GCC diagnostic pop")
  9931. /* @r{@option{-Wformat} messages treated once again}
  9932. @r{as specified by the GCC command-line options.} */
  9933. @end example
  9934. @end table
  9935. @node Optimization Pragmas
  9936. @subsection Optimization Pragmas
  9937. These pragmas enable a particular optimization for specific function
  9938. definitions. The settings take effect at the end of a function
  9939. definition, so the clean place to use these pragmas is between
  9940. function definitions.
  9941. @table @code
  9942. @item #pragma GCC optimize @var{optimization}
  9943. @itemx _Pragma ("GCC optimize @var{optimization}")
  9944. These pragmas enable the optimization @var{optimization} for the
  9945. following functions. For example,
  9946. @example
  9947. _Pragma ("GCC optimize -fforward-propagate")
  9948. @end example
  9949. @noindent
  9950. says to apply the @samp{forward-propagate} optimization to all
  9951. following function definitions. Specifying optimizations for
  9952. individual functions, rather than for the entire program, is rare but
  9953. can be useful for getting around a bug in the compiler.
  9954. If @var{optimization} does not correspond to a defined optimization
  9955. option, the pragma is erroneous. To turn off an optimization, use the
  9956. corresponding @samp{-fno-} option, such as
  9957. @samp{-fno-forward-propagate}.
  9958. @item #pragma GCC target @var{optimizations}
  9959. @itemx _Pragma ("GCC target @var{optimizations}")
  9960. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9961. used for platform-specific optimizations. Thus,
  9962. @example
  9963. _Pragma ("GCC target popcnt")
  9964. @end example
  9965. @noindent
  9966. activates the optimization @samp{popcnt} for all
  9967. following function definitions. This optimization is supported
  9968. on a few common targets but not on others.
  9969. @item #pragma GCC push_options
  9970. @itemx _Pragma ("GCC push_options")
  9971. The @samp{push_options} pragma saves on a stack the current settings
  9972. specified with the @samp{target} and @samp{optimize} pragmas.
  9973. @item #pragma GCC pop_options
  9974. @itemx _Pragma ("GCC pop_options")
  9975. The @samp{pop_options} pragma pops saved settings from that stack.
  9976. Here's an example of using this stack.
  9977. @example
  9978. _Pragma ("GCC push_options")
  9979. _Pragma ("GCC optimize forward-propagate")
  9980. /* @r{Functions to compile}
  9981. @r{with the @code{forward-propagate} optimization.} */
  9982. _Pragma ("GCC pop_options")
  9983. /* @r{Ends enablement of @code{forward-propagate}.} */
  9984. @end example
  9985. @item #pragma GCC reset_options
  9986. @itemx _Pragma ("GCC reset_options")
  9987. Clears all pragma-defined @samp{target} and @samp{optimize}
  9988. optimization settings.
  9989. @end table
  9990. @node Static Assertions
  9991. @section Static Assertions
  9992. @cindex static assertions
  9993. @findex _Static_assert
  9994. You can add compiler-time tests for necessary conditions into your
  9995. code using @code{_Static_assert}. This can be useful, for example, to
  9996. check that the compilation target platform supports the type sizes
  9997. that the code expects. For example,
  9998. @example
  9999. _Static_assert ((sizeof (long int) >= 8),
  10000. "long int needs to be at least 8 bytes");
  10001. @end example
  10002. @noindent
  10003. reports a compile-time error if compiled on a system with long
  10004. integers smaller than 8 bytes, with @samp{long int needs to be at
  10005. least 8 bytes} as the error message.
  10006. Since calls @code{_Static_assert} are processed at compile time, the
  10007. expression must be computable at compile time and the error message
  10008. must be a literal string. The expression can refer to the sizes of
  10009. variables, but can't refer to their values. For example, the
  10010. following static assertion is invalid for two reasons:
  10011. @example
  10012. char *error_message
  10013. = "long int needs to be at least 8 bytes";
  10014. int size_of_long_int = sizeof (long int);
  10015. _Static_assert (size_of_long_int == 8, error_message);
  10016. @end example
  10017. @noindent
  10018. The expression @code{size_of_long_int == 8} isn't computable at
  10019. compile time, and the error message isn't a literal string.
  10020. You can, though, use preprocessor definition values with
  10021. @code{_Static_assert}:
  10022. @example
  10023. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10024. at least 8 bytes"
  10025. _Static_assert ((sizeof (long int) == 8),
  10026. LONG_INT_ERROR_MESSAGE);
  10027. @end example
  10028. Static assertions are permitted wherever a statement or declaration is
  10029. permitted, including at top level in the file, and also inside the
  10030. definition of a type.
  10031. @example
  10032. union y
  10033. @{
  10034. int i;
  10035. int *ptr;
  10036. _Static_assert (sizeof (int *) == sizeof (int),
  10037. "Pointer and int not same size");
  10038. @};
  10039. @end example
  10040. @node Type Alignment
  10041. @appendix Type Alignment
  10042. @cindex type alignment
  10043. @cindex alignment of type
  10044. @findex _Alignof
  10045. @findex __alignof__
  10046. Code for device drivers and other communication with low-level
  10047. hardware sometimes needs to be concerned with the alignment of
  10048. data objects in memory.
  10049. Each data type has a required @dfn{alignment}, always a power of 2,
  10050. that says at which memory addresses an object of that type can validly
  10051. start. A valid address for the type must be a multiple of its
  10052. alignment. If a type's alignment is 1, that means it can validly
  10053. start at any address. If a type's alignment is 2, that means it can
  10054. only start at an even address. If a type's alignment is 4, that means
  10055. it can only start at an address that is a multiple of 4.
  10056. The alignment of a type (except @code{char}) can vary depending on the
  10057. kind of computer in use. To refer to the alignment of a type in a C
  10058. program, use @code{_Alignof}, whose syntax parallels that of
  10059. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10060. operation, and it doesn't compute the value of the expression used
  10061. as its argument.
  10062. Nominally, each integer and floating-point type has an alignment equal to
  10063. the largest power of 2 that divides its size. Thus, @code{int} with
  10064. size 4 has a nominal alignment of 4, and @code{long long int} with
  10065. size 8 has a nominal alignment of 8.
  10066. However, each kind of computer generally has a maximum alignment, and
  10067. no type needs more alignment than that. If the computer's maximum
  10068. alignment is 4 (which is common), then no type's alignment is more
  10069. than 4.
  10070. The size of any type is always a multiple of its alignment; that way,
  10071. in an array whose elements have that type, all the elements are
  10072. properly aligned if the first one is.
  10073. These rules apply to all real computers today, but some embedded
  10074. controllers have odd exceptions. We don't have references to cite for
  10075. them.
  10076. @c We can't cite a nonfree manual as documentation.
  10077. Ordinary C code guarantees that every object of a given type is in
  10078. fact aligned as that type requires.
  10079. If the operand of @code{_Alignof} is a structure field, the value
  10080. is the alignment it requires. It may have a greater alignment by
  10081. coincidence, due to the other fields, but @code{_Alignof} is not
  10082. concerned about that. @xref{Structures}.
  10083. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10084. but now that the feature has been standardized, it is better
  10085. to use the standard keyword @code{_Alignof}.
  10086. @findex _Alignas
  10087. @findex __aligned__
  10088. You can explicitly specify an alignment requirement for a particular
  10089. variable or structure field by adding @code{_Alignas
  10090. (@var{alignment})} to the declaration, where @var{alignment} is a
  10091. power of 2 or a type name. For instance:
  10092. @example
  10093. char _Alignas (8) x;
  10094. @end example
  10095. @noindent
  10096. or
  10097. @example
  10098. char _Alignas (double) x;
  10099. @end example
  10100. @noindent
  10101. specifies that @code{x} must start on an address that is a multiple of
  10102. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10103. machine, that maximum is how much alignment @code{x} will get.
  10104. The older GNU C syntax for this feature looked like
  10105. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10106. declaration, and was added after the variable. For instance:
  10107. @example
  10108. char x __attribute__ ((__aligned__ 8));
  10109. @end example
  10110. @xref{Attributes}.
  10111. @node Aliasing
  10112. @appendix Aliasing
  10113. @cindex aliasing (of storage)
  10114. @cindex pointer type conversion
  10115. @cindex type conversion, pointer
  10116. We have already presented examples of casting a @code{void *} pointer
  10117. to another pointer type, and casting another pointer type to
  10118. @code{void *}.
  10119. One common kind of pointer cast is guaranteed safe: casting the value
  10120. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10121. Allocation}). It is safe because these functions do not save the
  10122. pointer anywhere else; the only way the program will access the newly
  10123. allocated memory is via the pointer just returned.
  10124. In fact, C allows casting any pointer type to any other pointer type.
  10125. Using this to access the same place in memory using two
  10126. different data types is called @dfn{aliasing}.
  10127. Aliasing is necessary in some programs that do sophisticated memory
  10128. management, such as GNU Emacs, but most C programs don't need to do
  10129. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10130. aliasing correctly requires following the rules stated below.
  10131. Otherwise, the aliasing may result in malfunctions when the program
  10132. runs.
  10133. The rest of this appendix explains the pitfalls and rules of aliasing.
  10134. @menu
  10135. * Aliasing Alignment:: Memory alignment considerations for
  10136. casting between pointer types.
  10137. * Aliasing Length:: Type size considerations for
  10138. casting between pointer types.
  10139. * Aliasing Type Rules:: Even when type alignment and size matches,
  10140. aliasing can still have surprising results.
  10141. @end menu
  10142. @node Aliasing Alignment
  10143. @appendixsection Aliasing and Alignment
  10144. In order for a type-converted pointer to be valid, it must have the
  10145. alignment that the new pointer type requires. For instance, on most
  10146. computers, @code{int} has alignment 4; the address of an @code{int}
  10147. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10148. address of a @code{char} is usually not a multiple of 4. Taking the
  10149. address of such a @code{char} and casting it to @code{int *} probably
  10150. results in an invalid pointer. Trying to dereference it may cause a
  10151. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10152. @example
  10153. foo ()
  10154. @{
  10155. char i[4];
  10156. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10157. return *p; /* @r{Crash!} */
  10158. @}
  10159. @end example
  10160. This requirement is never a problem when casting the return value
  10161. of @code{malloc} because that function always returns a pointer
  10162. with as much alignment as any type can require.
  10163. @node Aliasing Length
  10164. @appendixsection Aliasing and Length
  10165. When converting a pointer to a different pointer type, make sure the
  10166. object it really points to is at least as long as the target of the
  10167. converted pointer. For instance, suppose @code{p} has type @code{int
  10168. *} and it's cast as follows:
  10169. @example
  10170. int *p;
  10171. struct
  10172. @{
  10173. double d, e, f;
  10174. @} foo;
  10175. struct foo *q = (struct foo *)p;
  10176. q->f = 5.14159;
  10177. @end example
  10178. @noindent
  10179. the value @code{q->f} will run past the end of the @code{int} that
  10180. @code{p} points to. If @code{p} was initialized to the start of an
  10181. array of type @code{int[6]}, the object is long enough for three
  10182. @code{double}s. But if @code{p} points to something shorter,
  10183. @code{q->f} will run on beyond the end of that, overlaying some other
  10184. data. Storing that will garble that other data. Or it could extend
  10185. past the end of memory space and cause a @code{SIGSEGV} signal
  10186. (@pxref{Signals}).
  10187. @node Aliasing Type Rules
  10188. @appendixsection Type Rules for Aliasing
  10189. C code that converts a pointer to a different pointer type can use the
  10190. pointers to access the same memory locations with two different data
  10191. types. If the same address is accessed with different types in a
  10192. single control thread, optimization can make the code do surprising
  10193. things (in effect, make it malfunction).
  10194. Here's a concrete example where aliasing that can change the code's
  10195. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10196. long, like @code{int}, and so is every pointer. Thus, the structures
  10197. @code{struct a} and @code{struct b} are both 8 bytes.
  10198. @example
  10199. #include <stdio.h>
  10200. struct a @{ int size; char *data; @};
  10201. struct b @{ float size; char *data; @};
  10202. void sub (struct a *p, struct b *q)
  10203. @{
  10204.   int x;
  10205.   p->size = 0;
  10206.   q->size = 1;
  10207.   x = p->size;
  10208.   printf("x       =%d\n", x);
  10209.   printf("p->size =%d\n", (int)p->size);
  10210.   printf("q->size =%d\n", (int)q->size);
  10211. @}
  10212. int main(void)
  10213. @{
  10214.   struct a foo;
  10215.   struct a *p = &foo;
  10216.   struct b *q = (struct b *) &foo;
  10217.   sub (p, q);
  10218. @}
  10219. @end example
  10220. This code works as intended when compiled without optimization. All
  10221. the operations are carried out sequentially as written. The code
  10222. sets @code{x} to @code{p->size}, but what it actually gets is the
  10223. bits of the floating point number 1, as type @code{int}.
  10224. However, when optimizing, the compiler is allowed to assume
  10225. (mistakenly, here) that @code{q} does not point to the same storage as
  10226. @code{p}, because their data types are not allowed to alias.
  10227. From this assumption, the compiler can deduce (falsely, here) that the
  10228. assignment into @code{q->size} has no effect on the value of
  10229. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10230. be set to 0.
  10231. GNU C, following the C standard, @emph{defines} this optimization as
  10232. legitimate. Code that misbehaves when optimized following these rules
  10233. is, by definition, incorrect C code.
  10234. The rules for storage aliasing in C are based on the two data types:
  10235. the type of the object, and the type it is accessed through. The
  10236. rules permit accessing part of a storage object of type @var{t} using
  10237. only these types:
  10238. @itemize @bullet
  10239. @item
  10240. @var{t}.
  10241. @item
  10242. A type compatible with @var{t}. @xref{Compatible Types}.
  10243. @item
  10244. A signed or unsigned version of one of the above.
  10245. @item
  10246. A qualifed version of one of the above.
  10247. @xref{Type Qualifiers}.
  10248. @item
  10249. An array, structure (@pxref{Structures}), or union type
  10250. (@code{Unions}) that contains one of the above, either directly as a
  10251. field or through multiple levels of fields. If @var{t} is
  10252. @code{double}, this would include @code{struct s @{ union @{ double
  10253. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10254. inside it somewhere.
  10255. @item
  10256. A character type.
  10257. @end itemize
  10258. What do these rules say about the example in this subsection?
  10259. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10260. @code{int}. The type @code{float} is not allowed as an aliasing type
  10261. by those rules, so @code{b->size} is not supposed to alias with
  10262. elements of @code{j}. Based on that assumption, GNU C makes a
  10263. permitted optimization that was not, in this case, consistent with
  10264. what the programmer intended the program to do.
  10265. Whether GCC actually performs type-based aliasing analysis depends on
  10266. the details of the code. GCC has other ways to determine (in some cases)
  10267. whether objects alias, and if it gets a reliable answer that way, it won't
  10268. fall back on type-based heuristics.
  10269. @c @opindex -fno-strict-aliasing
  10270. The importance of knowing the type-based aliasing rules is not so as
  10271. to ensure that the optimization is done where it would be safe, but so
  10272. as to ensure it is @emph{not} done in a way that would break the
  10273. program. You can turn off type-based aliasing analysis by giving GCC
  10274. the option @option{-fno-strict-aliasing}.
  10275. @node Digraphs
  10276. @appendix Digraphs
  10277. @cindex digraphs
  10278. C accepts aliases for certain characters. Apparently in the 1990s
  10279. some computer systems had trouble inputting these characters, or
  10280. trouble displaying them. These digraphs almost never appear in C
  10281. programs nowadays, but we mention them for completeness.
  10282. @table @samp
  10283. @item <:
  10284. An alias for @samp{[}.
  10285. @item :>
  10286. An alias for @samp{]}.
  10287. @item <%
  10288. An alias for @samp{@{}.
  10289. @item %>
  10290. An alias for @samp{@}}.
  10291. @item %:
  10292. An alias for @samp{#},
  10293. used for preprocessing directives (@pxref{Directives}) and
  10294. macros (@pxref{Macros}).
  10295. @end table
  10296. @node Attributes
  10297. @appendix Attributes in Declarations
  10298. @cindex attributes
  10299. @findex __attribute__
  10300. You can specify certain additional requirements in a declaration, to
  10301. get fine-grained control over code generation, and helpful
  10302. informational messages during compilation. We use a few attributes in
  10303. code examples throughout this manual, including
  10304. @table @code
  10305. @item aligned
  10306. The @code{aligned} attribute specifies a minimum alignment for a
  10307. variable or structure field, measured in bytes:
  10308. @example
  10309. int foo __attribute__ ((aligned (8))) = 0;
  10310. @end example
  10311. @noindent
  10312. This directs GNU C to allocate @code{foo} at an address that is a
  10313. multiple of 8 bytes. However, you can't force an alignment bigger
  10314. than the computer's maximum meaningful alignment.
  10315. @item packed
  10316. The @code{packed} attribute specifies to compact the fields of a
  10317. structure by not leaving gaps between fields. For example,
  10318. @example
  10319. struct __attribute__ ((packed)) bar
  10320. @{
  10321. char a;
  10322. int b;
  10323. @};
  10324. @end example
  10325. @noindent
  10326. allocates the integer field @code{b} at byte 1 in the structure,
  10327. immediately after the character field @code{a}. The packed structure
  10328. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10329. alignment is 1, that of @code{char}.
  10330. @item deprecated
  10331. Applicable to both variables and functions, the @code{deprecated}
  10332. attribute tells the compiler to issue a warning if the variable or
  10333. function is ever used in the source file.
  10334. @example
  10335. int old_foo __attribute__ ((deprecated));
  10336. int old_quux () __attribute__ ((deprecated));
  10337. @end example
  10338. @item __noinline__
  10339. The @code{__noinline__} attribute, in a function's declaration or
  10340. definition, specifies never to inline calls to that function. All
  10341. calls to that function, in a compilation unit where it has this
  10342. attribute, will be compiled to invoke the separately compiled
  10343. function. @xref{Inline Function Definitions}.
  10344. @item __noclone__
  10345. The @code{__noclone__} attribute, in a function's declaration or
  10346. definition, specifies never to clone that function. Thus, there will
  10347. be only one compiled version of the function. @xref{Label Value
  10348. Caveats}, for more information about cloning.
  10349. @item always_inline
  10350. The @code{always_inline} attribute, in a function's declaration or
  10351. definition, specifies to inline all calls to that function (unless
  10352. something about the function makes inlining impossible). This applies
  10353. to all calls to that function in a compilation unit where it has this
  10354. attribute. @xref{Inline Function Definitions}.
  10355. @item gnu_inline
  10356. The @code{gnu_inline} attribute, in a function's declaration or
  10357. definition, specifies to handle the @code{inline} keywprd the way GNU
  10358. C originally implemented it, many years before ISO C said anything
  10359. about inlining. @xref{Inline Function Definitions}.
  10360. @end table
  10361. For full documentation of attributes, see the GCC manual.
  10362. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10363. the GNU Compiler Collection}.
  10364. @node Signals
  10365. @appendix Signals
  10366. @cindex signal
  10367. @cindex handler (for signal)
  10368. @cindex @code{SIGSEGV}
  10369. @cindex @code{SIGFPE}
  10370. @cindex @code{SIGBUS}
  10371. Some program operations bring about an error condition called a
  10372. @dfn{signal}. These signals terminate the program, by default.
  10373. There are various different kinds of signals, each with a name. We
  10374. have seen several such error conditions through this manual:
  10375. @table @code
  10376. @item SIGSEGV
  10377. This signal is generated when a program tries to read or write outside
  10378. the memory that is allocated for it, or to write memory that can only
  10379. be read. The name is an abbreviation for ``segmentation violation''.
  10380. @item SIGFPE
  10381. This signal indicates a fatal arithmetic error. The name is an
  10382. abbreviation for ``floating-point exception'', but covers all types of
  10383. arithmetic errors, including division by zero and overflow.
  10384. @item SIGBUS
  10385. This signal is generated when an invalid pointer is dereferenced,
  10386. typically the result of dereferencing an uninintalized pointer. It is
  10387. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10388. invalid access to valid memory, while @code{SIGBUS} indicates an
  10389. attempt to access an invalid address.
  10390. @end table
  10391. These kinds of signal allow the program to specify a function as a
  10392. @dfn{signal handler}. When a signal has a handler, it doesn't
  10393. terminate the program; instead it calls the handler.
  10394. There are many other kinds of signal; here we list only those that
  10395. come from run-time errors in C operations. The rest have to do with
  10396. the functioning of the operating system. The GNU C Library Reference
  10397. Manual gives more explanation about signals (@pxref{Program Signal
  10398. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10399. Manual}).
  10400. @node GNU Free Documentation License
  10401. @appendix GNU Free Documentation License
  10402. @include fdl.texi
  10403. @node Symbol Index
  10404. @unnumbered Index of Symbols and Keywords
  10405. @printindex fn
  10406. @node Concept Index
  10407. @unnumbered Concept Index
  10408. @printindex cp
  10409. @bye