c.texi 419 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019
  1. \input texinfo
  2. @c Copyright (C) 2022 Richard Stallman and Free Software Foundation, Inc.
  3. @c (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. @c licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual.''
  24. @end quotation
  25. @end copying
  26. @dircategory Programming
  27. @direntry
  28. * C: (c). GNU C Language Intro and Reference Manual
  29. @end direntry
  30. @documentencoding UTF-8
  31. @titlepage
  32. @sp 6
  33. @center @titlefont{GNU C Language Introduction}
  34. @center @titlefont{and Reference Manual}
  35. @sp 4
  36. @c @center @value{EDITION} Edition
  37. @sp 5
  38. @center Richard Stallman
  39. @center and
  40. @center Trevis Rothwell
  41. @center plus Nelson Beebe
  42. @center on floating point
  43. @page
  44. @vskip 0pt plus 1filll
  45. @insertcopying
  46. @sp 2
  47. @ignore
  48. WILL BE Published by the Free Software Foundation @*
  49. 51 Franklin Street, Fifth Floor @*
  50. Boston, MA 02110-1301 USA @*
  51. ISBN ?-??????-??-?
  52. @end ignore
  53. @ignore
  54. @sp 1
  55. Cover art by J. Random Artist
  56. @end ignore
  57. @end titlepage
  58. @summarycontents
  59. @contents
  60. @node Top
  61. @ifnottex
  62. @top GNU C Manual
  63. @end ifnottex
  64. @iftex
  65. @top Preface
  66. @end iftex
  67. This manual explains the C language for use with the GNU Compiler
  68. Collection (GCC) on the GNU/Linux system and other systems. We refer
  69. to this dialect as GNU C. If you already know C, you can use this as
  70. a reference manual.
  71. If you understand basic concepts of programming but know nothing about
  72. C, you can read this manual sequentially from the beginning to learn
  73. the C language.
  74. If you are a beginner to programming, we recommend you first learn a
  75. language with automatic garbage collection and no explicit pointers,
  76. rather than starting with C@. Good choices include Lisp, Scheme,
  77. Python and Java. C's explicit pointers mean that programmers must be
  78. careful to avoid certain kinds of errors.
  79. C is a venerable language; it was first used in 1973. The GNU C
  80. Compiler, which was subsequently extended into the GNU Compiler
  81. Collection, was first released in 1987. Other important languages
  82. were designed based on C: once you know C, it gives you a useful base
  83. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  84. The special advantage of C is that it is fairly simple while allowing
  85. close access to the computer's hardware, which previously required
  86. writing in assembler language to describe the individual machine
  87. instructions. Some have called C a ``high-level assembler language''
  88. because of its explicit pointers and lack of automatic management of
  89. storage. As one wag put it, ``C combines the power of assembler
  90. language with the convenience of assembler language.'' However, C is
  91. far more portable, and much easier to read and write, than assembler
  92. language.
  93. This manual describes the GNU C language supported by the GNU Compiler
  94. Collection, as of roughly 2017. Please inform us of any changes
  95. needed to match the current version of GNU C.
  96. When a construct may be absent or work differently in other C
  97. compilers, we say so. When it is not part of ISO standard C, we say
  98. it is a ``GNU C extension,'' because it is useful to know that.
  99. However, standards and other dialects are secondary topics for this
  100. manual. For simplicity's sake, we keep those notes short, unless it
  101. is vital to say more.
  102. Likewise, we hardly mention C@t{++} or other languages that the GNU
  103. Compiler Collection supports. We hope this manual will serve as a
  104. base for writing manuals for those languages, but languages so
  105. different can't share one common manual.
  106. Some aspects of the meaning of C programs depend on the target
  107. platform: which computer, and which operating system, the compiled
  108. code will run on. Where this is the case, we say so.
  109. The C language provides no built-in facilities for performing such
  110. common operations as input/output, memory management, string
  111. manipulation, and the like. Instead, these facilities are defined in
  112. a standard library, which is automatically available in every C
  113. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  114. Reference Manual}.
  115. This manual incorporates the former GNU C Preprocessor Manual, which
  116. was among the earliest GNU Manuals. It also uses some text from the
  117. earlier GNU C Manual that was written by Trevis Rothwell and James
  118. Youngman.
  119. GNU C has many obscure features, each one either for historical
  120. compatibility or meant for very special situations. We have left them
  121. to a companion manual, the GNU C Obscurities Manual, which will be
  122. published digitally later.
  123. Please report errors and suggestions to c-manual@@gnu.org.
  124. @menu
  125. * The First Example:: Getting started with basic C code.
  126. * Complete Program:: A whole example program
  127. that can be compiled and run.
  128. * Storage:: Basic layout of storage; bytes.
  129. * Beyond Integers:: Exploring different numeric types.
  130. * Lexical Syntax:: The various lexical components of C programs.
  131. * Arithmetic:: Numeric computations.
  132. * Assignment Expressions:: Storing values in variables.
  133. * Execution Control Expressions:: Expressions combining values in various ways.
  134. * Binary Operator Grammar:: An overview of operator precedence.
  135. * Order of Execution:: The order of program execution.
  136. * Primitive Types:: More details about primitive data types.
  137. * Constants:: Explicit constant values:
  138. details and examples.
  139. * Type Size:: The memory space occupied by a type.
  140. * Pointers:: Creating and manipulating memory pointers.
  141. * Structures:: Compound data types built
  142. by grouping other types.
  143. * Arrays:: Creating and manipulating arrays.
  144. * Enumeration Types:: Sets of integers with named values.
  145. * Defining Typedef Names:: Using @code{typedef} to define type names.
  146. * Statements:: Controling program flow.
  147. * Variables:: Details about declaring, initializing,
  148. and using variables.
  149. * Type Qualifiers:: Mark variables for certain intended uses.
  150. * Functions:: Declaring, defining, and calling functions.
  151. * Compatible Types:: How to tell if two types are compatible
  152. with each other.
  153. * Type Conversions:: Converting between types.
  154. * Scope:: Different categories of identifier scope.
  155. * Preprocessing:: Using the GNU C preprocessor.
  156. * Integers in Depth:: How integer numbers are represented.
  157. * Floating Point in Depth:: How floating-point numbers are represented.
  158. * Compilation:: How to compile multi-file programs.
  159. * Directing Compilation:: Operations that affect compilation
  160. but don't change the program.
  161. Appendices
  162. * Type Alignment:: Where in memory a type can validly start.
  163. * Aliasing:: Accessing the same data in two types.
  164. * Digraphs:: Two-character aliases for some characters.
  165. * Attributes:: Specifying additional information
  166. in a declaration.
  167. * Signals:: Fatal errors triggered in various scenarios.
  168. * GNU Free Documentation License:: The license for this manual.
  169. * Symbol Index:: Keyword and symbol index.
  170. * Concept Index:: Detailed topical index.
  171. @detailmenu
  172. --- The Detailed Node Listing ---
  173. * Recursive Fibonacci:: Writing a simple function recursively.
  174. * Stack:: Each function call uses space in the stack.
  175. * Iterative Fibonacci:: Writing the same function iteratively.
  176. * Complete Example:: Turn the simple function into a full program.
  177. * Complete Explanation:: Explanation of each part of the example.
  178. * Complete Line-by-Line:: Explaining each line of the example.
  179. * Compile Example:: Using GCC to compile the example.
  180. * Float Example:: A function that uses floating-point numbers.
  181. * Array Example:: A function that works with arrays.
  182. * Array Example Call:: How to call that function.
  183. * Array Example Variations:: Different ways to write the call example.
  184. Lexical Syntax
  185. * English:: Write programs in English!
  186. * Characters:: The characters allowed in C programs.
  187. * Whitespace:: The particulars of whitespace characters.
  188. * Comments:: How to include comments in C code.
  189. * Identifiers:: How to form identifiers (names).
  190. * Operators/Punctuation:: Characters used as operators or punctuation.
  191. * Line Continuation:: Splitting one line into multiple lines.
  192. * Digraphs:: Two-character substitutes for some characters.
  193. Arithmetic
  194. * Basic Arithmetic:: Addition, subtraction, multiplication,
  195. and division.
  196. * Integer Arithmetic:: How C performs arithmetic with integer values.
  197. * Integer Overflow:: When an integer value exceeds the range
  198. of its type.
  199. * Mixed Mode:: Calculating with both integer values
  200. and floating-point values.
  201. * Division and Remainder:: How integer division works.
  202. * Numeric Comparisons:: Comparing numeric values for
  203. equality or order.
  204. * Shift Operations:: Shift integer bits left or right.
  205. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  206. Assignment Expressions
  207. * Simple Assignment:: The basics of storing a value.
  208. * Lvalues:: Expressions into which a value can be stored.
  209. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  210. * Increment/Decrement:: Shorthand for incrementing and decrementing
  211. an lvalue's contents.
  212. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  213. * Assignment in Subexpressions:: How to avoid ambiguity.
  214. * Write Assignments Separately:: Write assignments as separate statements.
  215. Execution Control Expressions
  216. * Logical Operators:: Logical conjunction, disjunction, negation.
  217. * Logicals and Comparison:: Logical operators with comparison operators.
  218. * Logicals and Assignments:: Assignments with logical operators.
  219. * Conditional Expression:: An if/else construct inside expressions.
  220. * Comma Operator:: Build a sequence of subexpressions.
  221. Order of Execution
  222. * Reordering of Operands:: Operations in C are not necessarily computed
  223. in the order they are written.
  224. * Associativity and Ordering:: Some associative operations are performed
  225. in a particular order; others are not.
  226. * Sequence Points:: Some guarantees about the order of operations.
  227. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  228. * Ordering of Operands:: Evaluation order of operands
  229. and function arguments.
  230. * Optimization and Ordering:: Compiler optimizations can reorder operations
  231. only if it has no impact on program results.
  232. Primitive Data Types
  233. * Integer Types:: Description of integer types.
  234. * Floating-Point Data Types:: Description of floating-point types.
  235. * Complex Data Types:: Description of complex number types.
  236. * The Void Type:: A type indicating no value at all.
  237. * Other Data Types:: A brief summary of other types.
  238. Constants
  239. * Integer Constants:: Literal integer values.
  240. * Integer Const Type:: Types of literal integer values.
  241. * Floating Constants:: Literal floating-point values.
  242. * Imaginary Constants:: Literal imaginary number values.
  243. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  244. * Character Constants:: Literal character values.
  245. * Unicode Character Codes:: Unicode characters represented
  246. in either UTF-16 or UTF-32.
  247. * Wide Character Constants:: Literal characters values larger than 8 bits.
  248. * String Constants:: Literal string values.
  249. * UTF-8 String Constants:: Literal UTF-8 string values.
  250. * Wide String Constants:: Literal string values made up of
  251. 16- or 32-bit characters.
  252. Pointers
  253. * Address of Data:: Using the ``address-of'' operator.
  254. * Pointer Types:: For each type, there is a pointer type.
  255. * Pointer Declarations:: Declaring variables with pointer types.
  256. * Pointer Type Designators:: Designators for pointer types.
  257. * Pointer Dereference:: Accessing what a pointer points at.
  258. * Null Pointers:: Pointers which do not point to any object.
  259. * Invalid Dereference:: Dereferencing null or invalid pointers.
  260. * Void Pointers:: Totally generic pointers, can cast to any.
  261. * Pointer Comparison:: Comparing memory address values.
  262. * Pointer Arithmetic:: Computing memory address values.
  263. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  264. * Pointer Arithmetic Low Level:: More about computing memory address values.
  265. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  266. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  267. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  268. * Printing Pointers:: Using @code{printf} for a pointer's value.
  269. Structures
  270. * Referencing Fields:: Accessing field values in a structure object.
  271. * Dynamic Memory Allocation:: Allocating space for objects
  272. while the program is running.
  273. * Field Offset:: Memory layout of fields within a structure.
  274. * Structure Layout:: Planning the memory layout of fields.
  275. * Packed Structures:: Packing structure fields as close as possible.
  276. * Bit Fields:: Dividing integer fields
  277. into fields with fewer bits.
  278. * Bit Field Packing:: How bit fields pack together in integers.
  279. * const Fields:: Making structure fields immutable.
  280. * Zero Length:: Zero-length array as a variable-length object.
  281. * Flexible Array Fields:: Another approach to variable-length objects.
  282. * Overlaying Structures:: Casting one structure type
  283. over an object of another structure type.
  284. * Structure Assignment:: Assigning values to structure objects.
  285. * Unions:: Viewing the same object in different types.
  286. * Packing With Unions:: Using a union type to pack various types into
  287. the same memory space.
  288. * Cast to Union:: Casting a value one of the union's alternative
  289. types to the type of the union itself.
  290. * Structure Constructors:: Building new structure objects.
  291. * Unnamed Types as Fields:: Fields' types do not always need names.
  292. * Incomplete Types:: Types which have not been fully defined.
  293. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  294. * Type Tags:: Scope of structure and union type tags.
  295. Arrays
  296. * Accessing Array Elements:: How to access individual elements of an array.
  297. * Declaring an Array:: How to name and reserve space for a new array.
  298. * Strings:: A string in C is a special case of array.
  299. * Incomplete Array Types:: Naming, but not allocating, a new array.
  300. * Limitations of C Arrays:: Arrays are not first-class objects.
  301. * Multidimensional Arrays:: Arrays of arrays.
  302. * Constructing Array Values:: Assigning values to an entire array at once.
  303. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  304. Statements
  305. * Expression Statement:: Evaluate an expression, as a statement,
  306. usually done for a side effect.
  307. * if Statement:: Basic conditional execution.
  308. * if-else Statement:: Multiple branches for conditional execution.
  309. * Blocks:: Grouping multiple statements together.
  310. * return Statement:: Return a value from a function.
  311. * Loop Statements:: Repeatedly executing a statement or block.
  312. * switch Statement:: Multi-way conditional choices.
  313. * switch Example:: A plausible example of using @code{switch}.
  314. * Duffs Device:: A special way to use @code{switch}.
  315. * Case Ranges:: Ranges of values for @code{switch} cases.
  316. * Null Statement:: A statement that does nothing.
  317. * goto Statement:: Jump to another point in the source code,
  318. identified by a label.
  319. * Local Labels:: Labels with limited scope.
  320. * Labels as Values:: Getting the address of a label.
  321. * Statement Exprs:: A series of statements used as an expression.
  322. Variables
  323. * Variable Declarations:: Name a variable and and reserve space for it.
  324. * Initializers:: Assigning inital values to variables.
  325. * Designated Inits:: Assigning initial values to array elements
  326. at particular array indices.
  327. * Auto Type:: Obtaining the type of a variable.
  328. * Local Variables:: Variables declared in function definitions.
  329. * File-Scope Variables:: Variables declared outside of
  330. function definitions.
  331. * Static Local Variables:: Variables declared within functions,
  332. but with permanent storage allocation.
  333. * Extern Declarations:: Declaring a variable
  334. which is allocated somewhere else.
  335. * Allocating File-Scope:: When is space allocated
  336. for file-scope variables?
  337. * auto and register:: Historically used storage directions.
  338. * Omitting Types:: The bad practice of declaring variables
  339. with implicit type.
  340. Type Qualifiers
  341. * const:: Variables whose values don't change.
  342. * volatile:: Variables whose values may be accessed
  343. or changed outside of the control of
  344. this program.
  345. * restrict Pointers:: Restricted pointers for code optimization.
  346. * restrict Pointer Example:: Example of how that works.
  347. Functions
  348. * Function Definitions:: Writing the body of a function.
  349. * Function Declarations:: Declaring the interface of a function.
  350. * Function Calls:: Using functions.
  351. * Function Call Semantics:: Call-by-value argument passing.
  352. * Function Pointers:: Using references to functions.
  353. * The main Function:: Where execution of a GNU C program begins.
  354. Type Conversions
  355. * Explicit Type Conversion:: Casting a value from one type to another.
  356. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  357. * Argument Promotions:: Automatic conversion of function parameters.
  358. * Operand Promotions:: Automatic conversion of arithmetic operands.
  359. * Common Type:: When operand types differ, which one is used?
  360. Scope
  361. * Scope:: Different categories of identifier scope.
  362. Preprocessing
  363. * Preproc Overview:: Introduction to the C preprocessor.
  364. * Directives:: The form of preprocessor directives.
  365. * Preprocessing Tokens:: The lexical elements of preprocessing.
  366. * Header Files:: Including one source file in another.
  367. * Macros:: Macro expansion by the preprocessor.
  368. * Conditionals:: Controling whether to compile some lines
  369. or ignore them.
  370. * Diagnostics:: Reporting warnings and errors.
  371. * Line Control:: Reporting source line numbers.
  372. * Null Directive:: A preprocessing no-op.
  373. Integers in Depth
  374. * Integer Representations:: How integer values appear in memory.
  375. * Maximum and Minimum Values:: Value ranges of integer types.
  376. Floating Point in Depth
  377. * Floating Representations:: How floating-point values appear in memory.
  378. * Floating Type Specs:: Precise details of memory representations.
  379. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  380. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  381. * Exception Flags:: Handling certain conditions in floating point.
  382. * Exact Floating-Point:: Not all floating calculations lose precision.
  383. * Rounding:: When a floating result can't be represented
  384. exactly in the floating-point type in use.
  385. * Rounding Issues:: Avoid magnifying rounding errors.
  386. * Significance Loss:: Subtracting numbers that are almost equal.
  387. * Fused Multiply-Add:: Taking advantage of a special floating-point
  388. instruction for faster execution.
  389. * Error Recovery:: Determining rounding errors.
  390. * Exact Floating Constants:: Precisely specified floating-point numbers.
  391. * Handling Infinity:: When floating calculation is out of range.
  392. * Handling NaN:: What floating calculation is undefined.
  393. * Signed Zeros:: Positive zero vs. negative zero.
  394. * Scaling by the Base:: A useful exact floating-point operation.
  395. * Rounding Control:: Specifying some rounding behaviors.
  396. * Machine Epsilon:: The smallest number you can add to 1.0
  397. and get a sum which is larger than 1.0.
  398. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  399. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  400. * Further Reading:: References for floating-point numbers.
  401. Directing Compilation
  402. * Pragmas:: Controling compilation of some constructs.
  403. * Static Assertions:: Compile-time tests for conditions.
  404. @end detailmenu
  405. @end menu
  406. @node The First Example
  407. @chapter The First Example
  408. This chapter presents the source code for a very simple C program and
  409. uses it to explain a few features of the language. If you already
  410. know the basic points of C presented in this chapter, you can skim it
  411. or skip it.
  412. @menu
  413. * Recursive Fibonacci:: Writing a simple function recursively.
  414. * Stack:: Each function call uses space in the stack.
  415. * Iterative Fibonacci:: Writing the same function iteratively.
  416. @end menu
  417. @node Recursive Fibonacci
  418. @section Example: Recursive Fibonacci
  419. @cindex recursive Fibonacci function
  420. @cindex Fibonacci function, recursive
  421. To introduce the most basic features of C, let's look at code for a
  422. simple mathematical function that does calculations on integers. This
  423. function calculates the @var{n}th number in the Fibonacci series, in
  424. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  425. 13, 21, 34, 55, @dots{}.
  426. @example
  427. int
  428. fib (int n)
  429. @{
  430. if (n <= 2) /* @r{This avoids infinite recursion.} */
  431. return 1;
  432. else
  433. return fib (n - 1) + fib (n - 2);
  434. @}
  435. @end example
  436. This very simple program illustrates several features of C:
  437. @itemize @bullet
  438. @item
  439. A function definition, whose first two lines constitute the function
  440. header. @xref{Function Definitions}.
  441. @item
  442. A function parameter @code{n}, referred to as the variable @code{n}
  443. inside the function body. @xref{Function Parameter Variables}.
  444. A function definition uses parameters to refer to the argument
  445. values provided in a call to that function.
  446. @item
  447. Arithmetic. C programs add with @samp{+} and subtract with
  448. @samp{-}. @xref{Arithmetic}.
  449. @item
  450. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  451. equal.'' @xref{Numeric Comparisons}.
  452. @item
  453. Integer constants written in base 10.
  454. @xref{Integer Constants}.
  455. @item
  456. A function call. The function call @code{fib (n - 1)} calls the
  457. function @code{fib}, passing as its argument the value @code{n - 1}.
  458. @xref{Function Calls}.
  459. @item
  460. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  461. comment has no effect on the execution of the program. Its purpose is
  462. to provide explanations to people reading the source code. Including
  463. comments in the code is tremendously important---they provide
  464. background information so others can understand the code more quickly.
  465. @xref{Comments}.
  466. @item
  467. Two kinds of statements, the @code{return} statement and the
  468. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  469. @item
  470. Recursion. The function @code{fib} calls itself; that is called a
  471. @dfn{recursive call}. These are valid in C, and quite common.
  472. The @code{fib} function would not be useful if it didn't return.
  473. Thus, recursive definitions, to be of any use, must avoid infinite
  474. recursion.
  475. This function definition prevents infinite recursion by specially
  476. handling the case where @code{n} is two or less. Thus the maximum
  477. depth of recursive calls is less than @code{n}.
  478. @end itemize
  479. @menu
  480. * Function Header:: The function's name and how it is called.
  481. * Function Body:: Declarations and statements that implement the function.
  482. @end menu
  483. @node Function Header
  484. @subsection Function Header
  485. @cindex function header
  486. In our example, the first two lines of the function definition are the
  487. @dfn{header}. Its purpose is to state the function's name and say how
  488. it is called:
  489. @example
  490. int
  491. fib (int n)
  492. @end example
  493. @noindent
  494. says that the function returns an integer (type @code{int}), its name is
  495. @code{fib}, and it takes one argument named @code{n} which is also an
  496. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  497. @node Function Body
  498. @subsection Function Body
  499. @cindex function body
  500. @cindex recursion
  501. The rest of the function definition is called the @dfn{function body}.
  502. Like every function body, this one starts with @samp{@{}, ends with
  503. @samp{@}}, and contains zero or more @dfn{statements} and
  504. @dfn{declarations}. Statements specify actions to take, whereas
  505. declarations define names of variables, functions, and so on. Each
  506. statement and each declaration ends with a semicolon (@samp{;}).
  507. Statements and declarations often contain @dfn{expressions}; an
  508. expression is a construct whose execution produces a @dfn{value} of
  509. some data type, but may also take actions through ``side effects''
  510. that alter subsequent execution. A statement, by contrast, does not
  511. have a value; it affects further execution of the program only through
  512. the actions it takes.
  513. This function body contains no declarations, and just one statement,
  514. but that one is a complex statement in that it contains nested
  515. statements. This function uses two kinds of statements:
  516. @table @code
  517. @item return
  518. The @code{return} statement makes the function return immediately.
  519. It looks like this:
  520. @example
  521. return @var{value};
  522. @end example
  523. Its meaning is to compute the expression @var{value} and exit the
  524. function, making it return whatever value that expression produced.
  525. For instance,
  526. @example
  527. return 1;
  528. @end example
  529. @noindent
  530. returns the integer 1 from the function, and
  531. @example
  532. return fib (n - 1) + fib (n - 2);
  533. @end example
  534. @noindent
  535. returns a value computed by performing two function calls
  536. as specified and adding their results.
  537. @item @code{if}@dots{}@code{else}
  538. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  539. Each time it executes, it chooses one of its two substatements to execute
  540. and ignores the other. It looks like this:
  541. @example
  542. if (@var{condition})
  543. @var{if-true-statement}
  544. else
  545. @var{if-false-statement}
  546. @end example
  547. Its meaning is to compute the expression @var{condition} and, if it's
  548. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  549. @var{if-false-statement}. @xref{if-else Statement}.
  550. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  551. simply an expression. It's considered ``true'' if its value is
  552. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  553. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  554. Comparisons}.) Thus,
  555. @example
  556. if (n <= 2)
  557. return 1;
  558. else
  559. return fib (n - 1) + fib (n - 2);
  560. @end example
  561. @noindent
  562. first tests whether the value of @code{n} is less than or equal to 2.
  563. If so, the expression @code{n <= 2} has the value 1. So execution
  564. continues with the statement
  565. @example
  566. return 1;
  567. @end example
  568. @noindent
  569. Otherwise, execution continues with this statement:
  570. @example
  571. return fib (n - 1) + fib (n - 2);
  572. @end example
  573. Each of these statements ends the execution of the function and
  574. provides a value for it to return. @xref{return Statement}.
  575. @end table
  576. Calculating @code{fib} using ordinary integers in C works only for
  577. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  578. in type @code{int}. The addition operation that tries to add
  579. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  580. This occurrence is called @dfn{integer overflow}.
  581. Overflow can manifest itself in various ways, but one thing that can't
  582. possibly happen is to produce the correct value, since that can't fit
  583. in the space for the value. @xref{Integer Overflow}.
  584. @xref{Functions}, for a full explanation about functions.
  585. @node Stack
  586. @section The Stack, And Stack Overflow
  587. @cindex stack
  588. @cindex stack frame
  589. @cindex stack overflow
  590. @cindex recursion, drawbacks of
  591. @cindex stack frame
  592. Recursion has a drawback: there are limits to how many nested function
  593. calls a program can make. In C, each function call allocates a block
  594. of memory which it uses until the call returns. C allocates these
  595. blocks consecutively within a large area of memory known as the
  596. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  597. The size of the stack is limited; if the program tries to use too
  598. much, that causes the program to fail because the stack is full. This
  599. is called @dfn{stack overflow}.
  600. @cindex crash
  601. @cindex segmentation fault
  602. Stack overflow on GNU/Linux typically manifests itself as the
  603. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  604. fault.'' By default, this signal terminates the program immediately,
  605. rather than letting the program try to recover, or reach an expected
  606. ending point. (We commonly say in this case that the program
  607. ``crashes''). @xref{Signals}.
  608. It is inconvenient to observe a crash by passing too large
  609. an argument to recursive Fibonacci, because the program would run a
  610. long time before it crashes. This algorithm is simple but
  611. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  612. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  613. the final result.
  614. However, you can observe stack overflow very quickly if you use
  615. this function instead:
  616. @example
  617. int
  618. fill_stack (int n)
  619. @{
  620. if (n <= 1) /* @r{This limits the depth of recursion.} */
  621. return 1;
  622. else
  623. return fill_stack (n - 1);
  624. @}
  625. @end example
  626. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  627. and using the default configuration, an experiment showed there is
  628. enough stack space to do 261906 nested calls to that function. One
  629. more, and the stack overflows and the program crashes. On another
  630. platform, with a different configuration, or with a different
  631. function, the limit might be bigger or smaller.
  632. @node Iterative Fibonacci
  633. @section Example: Iterative Fibonacci
  634. @cindex iterative Fibonacci function
  635. @cindex Fibonacci function, iterative
  636. Here's a much faster algorithm for computing the same Fibonacci
  637. series. It is faster for two reasons. First, it uses @dfn{iteration}
  638. (that is, repetition or looping) rather than recursion, so it doesn't
  639. take time for a large number of function calls. But mainly, it is
  640. faster because the number of repetitions is small---only @code{@var{n}}.
  641. @c If you change this, change the duplicate in node Example of for.
  642. @example
  643. int
  644. fib (int n)
  645. @{
  646. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  647. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  648. int i;
  649. for (i = 1; i < n; ++i)
  650. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  651. /* @r{since @code{i < n} is false the first time.} */
  652. @{
  653. /* @r{Now @code{last} is @code{fib (@code{i})}}
  654. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  655. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  656. int next = prev + last;
  657. /* @r{Shift the values down.} */
  658. prev = last;
  659. last = next;
  660. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  661. @r{and @code{prev} is @code{fib (@code{i})}.}
  662. @r{But that won't stay true for long,}
  663. @r{because we are about to increment @code{i}.} */
  664. @}
  665. return last;
  666. @}
  667. @end example
  668. This definition computes @code{fib (@var{n})} in a time proportional
  669. to @code{@var{n}}. The comments in the definition explain how it works: it
  670. advances through the series, always keeps the last two values in
  671. @code{last} and @code{prev}, and adds them to get the next value.
  672. Here are the additional C features that this definition uses:
  673. @table @asis
  674. @item Internal blocks
  675. Within a function, wherever a statement is called for, you can write a
  676. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  677. more statements and declarations. (You can also use additional
  678. blocks as statements in a block.)
  679. The function body also counts as a block, which is why it can contain
  680. statements and declarations.
  681. @xref{Blocks}.
  682. @item Declarations of local variables
  683. This function body contains declarations as well as statements. There
  684. are three declarations directly in the function body, as well as a
  685. fourth declaration in an internal block. Each starts with @code{int}
  686. because it declares a variable whose type is integer. One declaration
  687. can declare several variables, but each of these declarations is
  688. simple and declares just one variable.
  689. Variables declared inside a block (either a function body or an
  690. internal block) are @dfn{local variables}. These variables exist only
  691. within that block; their names are not defined outside the block, and
  692. exiting the block deallocates their storage. This example declares
  693. four local variables: @code{last}, @code{prev}, @code{i}, and
  694. @code{next}.
  695. The most basic local variable declaration looks like this:
  696. @example
  697. @var{type} @var{variablename};
  698. @end example
  699. For instance,
  700. @example
  701. int i;
  702. @end example
  703. @noindent
  704. declares the local variable @code{i} as an integer.
  705. @xref{Variable Declarations}.
  706. @item Initializers
  707. When you declare a variable, you can also specify its initial value,
  708. like this:
  709. @example
  710. @var{type} @var{variablename} = @var{value};
  711. @end example
  712. For instance,
  713. @example
  714. int last = 1;
  715. @end example
  716. @noindent
  717. declares the local variable @code{last} as an integer (type
  718. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  719. @item Assignment
  720. Assignment: a specific kind of expression, written with the @samp{=}
  721. operator, that stores a new value in a variable or other place. Thus,
  722. @example
  723. @var{variable} = @var{value}
  724. @end example
  725. @noindent
  726. is an expression that computes @code{@var{value}} and stores the value in
  727. @code{@var{variable}}. @xref{Assignment Expressions}.
  728. @item Expression statements
  729. An expression statement is an expression followed by a semicolon.
  730. That computes the value of the expression, then ignores the value.
  731. An expression statement is useful when the expression changes some
  732. data or has other side effects---for instance, with function calls, or
  733. with assignments as in this example. @xref{Expression Statement}.
  734. Using an expression with no side effects in an expression statement is
  735. pointless except in very special cases. For instance, the expression
  736. statement @code{x;} would examine the value of @code{x} and ignore it.
  737. That is not useful.
  738. @item Increment operator
  739. The increment operator is @samp{++}. @code{++i} is an
  740. expression that is short for @code{i = i + 1}.
  741. @xref{Increment/Decrement}.
  742. @item @code{for} statements
  743. A @code{for} statement is a clean way of executing a statement
  744. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  745. @example
  746. for (i = 1; i < n; ++i)
  747. @var{body}
  748. @end example
  749. @noindent
  750. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  751. for the loop. The loop itself consists of
  752. @itemize @bullet
  753. @item
  754. Testing @code{i < n} and exiting the loop if that's false.
  755. @item
  756. Executing @var{body}.
  757. @item
  758. Advancing the loop (executing @code{++i}, which increments @code{i}).
  759. @end itemize
  760. The net result is to execute @var{body} with 1 in @code{i},
  761. then with 2 in @code{i}, and so on, stopping just before the repetition
  762. where @code{i} would equal @code{n}. If @code{n} is less than 1,
  763. the loop will execute the body zero times.
  764. The body of the @code{for} statement must be one and only one
  765. statement. You can't write two statements in a row there; if you try
  766. to, only the first of them will be treated as part of the loop.
  767. The way to put multiple statements in such a place is to group them
  768. with a block, and that's what we do in this example.
  769. @end table
  770. @node Complete Program
  771. @chapter A Complete Program
  772. @cindex complete example program
  773. @cindex example program, complete
  774. It's all very well to write a Fibonacci function, but you cannot run
  775. it by itself. It is a useful program, but it is not a complete
  776. program.
  777. In this chapter we present a complete program that contains the
  778. @code{fib} function. This example shows how to make the program
  779. start, how to make it finish, how to do computation, and how to print
  780. a result.
  781. @menu
  782. * Complete Example:: Turn the simple function into a full program.
  783. * Complete Explanation:: Explanation of each part of the example.
  784. * Complete Line-by-Line:: Explaining each line of the example.
  785. * Compile Example:: Using GCC to compile the example.
  786. @end menu
  787. @node Complete Example
  788. @section Complete Program Example
  789. Here is the complete program that uses the simple, recursive version
  790. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  791. @example
  792. #include <stdio.h>
  793. int
  794. fib (int n)
  795. @{
  796. if (n <= 2) /* @r{This avoids infinite recursion.} */
  797. return 1;
  798. else
  799. return fib (n - 1) + fib (n - 2);
  800. @}
  801. int
  802. main (void)
  803. @{
  804. printf ("Fibonacci series item %d is %d\n",
  805. 20, fib (20));
  806. return 0;
  807. @}
  808. @end example
  809. @noindent
  810. This program prints a message that shows the value of @code{fib (20)}.
  811. Now for an explanation of what that code means.
  812. @node Complete Explanation
  813. @section Complete Program Explanation
  814. @ifnottex
  815. Here's the explanation of the code of the example in the
  816. previous section.
  817. @end ifnottex
  818. This sample program prints a message that shows the value of @code{fib
  819. (20)}, and exits with code 0 (which stands for successful execution).
  820. Every C program is started by running the function named @code{main}.
  821. Therefore, the example program defines a function named @code{main} to
  822. provide a way to start it. Whatever that function does is what the
  823. program does. @xref{The main Function}.
  824. The @code{main} function is the first one called when the program
  825. runs, but it doesn't come first in the example code. The order of the
  826. function definitions in the source code makes no difference to the
  827. program's meaning.
  828. The initial call to @code{main} always passes certain arguments, but
  829. @code{main} does not have to pay attention to them. To ignore those
  830. arguments, define @code{main} with @code{void} as the parameter list.
  831. (@code{void} as a function's parameter list normally means ``call with
  832. no arguments,'' but @code{main} is a special case.)
  833. The function @code{main} returns 0 because that is
  834. the conventional way for @code{main} to indicate successful execution.
  835. It could instead return a positive integer to indicate failure, and
  836. some utility programs have specific conventions for the meaning of
  837. certain numeric @dfn{failure codes}. @xref{Values from main}.
  838. @cindex @code{printf}
  839. The simplest way to print text in C is by calling the @code{printf}
  840. function, so here we explain what that does.
  841. @cindex standard output
  842. The first argument to @code{printf} is a @dfn{string constant}
  843. (@pxref{String Constants}) that is a template for output. The
  844. function @code{printf} copies most of that string directly as output,
  845. including the newline character at the end of the string, which is
  846. written as @samp{\n}. The output goes to the program's @dfn{standard
  847. output} destination, which in the usual case is the terminal.
  848. @samp{%} in the template introduces a code that substitutes other text
  849. into the output. Specifically, @samp{%d} means to take the next
  850. argument to @code{printf} and substitute it into the text as a decimal
  851. number. (The argument for @samp{%d} must be of type @code{int}; if it
  852. isn't, @code{printf} will malfunction.) So the output is a line that
  853. looks like this:
  854. @example
  855. Fibonacci series item 20 is 6765
  856. @end example
  857. This program does not contain a definition for @code{printf} because
  858. it is defined by the C library, which makes it available in all C
  859. programs. However, each program does need to @dfn{declare}
  860. @code{printf} so it will be called correctly. The @code{#include}
  861. line takes care of that; it includes a @dfn{header file} called
  862. @file{stdio.h} into the program's code. That file is provided by the
  863. operating system and it contains declarations for the many standard
  864. input/output functions in the C library, one of which is
  865. @code{printf}.
  866. Don't worry about header files for now; we'll explain them later in
  867. @ref{Header Files}.
  868. The first argument of @code{printf} does not have to be a string
  869. constant; it can be any string (@pxref{Strings}). However, using a
  870. constant is the most common case.
  871. To learn more about @code{printf} and other facilities of the C
  872. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  873. Reference Manual}.
  874. @node Complete Line-by-Line
  875. @section Complete Program, Line by Line
  876. Here's the same example, explained line by line.
  877. @strong{Beginners, do you find this helpful or not?
  878. Would you prefer a different layout for the example?
  879. Please tell rms@@gnu.org.}
  880. @example
  881. #include <stdio.h> /* @r{Include declaration of usual} */
  882. /* @r{I/O functions such as @code{printf}.} */
  883. /* @r{Most programs need these.} */
  884. int /* @r{This function returns an @code{int}.} */
  885. fib (int n) /* @r{Its name is @code{fib};} */
  886. /* @r{its argument is called @code{n}.} */
  887. @{ /* @r{Start of function body.} */
  888. /* @r{This stops the recursion from being infinite.} */
  889. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  890. return 1; /* @r{make @code{fib} return 1.} */
  891. else /* @r{otherwise, add the two previous} */
  892. /* @r{fibonacci numbers.} */
  893. return fib (n - 1) + fib (n - 2);
  894. @}
  895. int /* @r{This function returns an @code{int}.} */
  896. main (void) /* @r{Start here; ignore arguments.} */
  897. @{ /* @r{Print message with numbers in it.} */
  898. printf ("Fibonacci series item %d is %d\n",
  899. 20, fib (20));
  900. return 0; /* @r{Terminate program, report success.} */
  901. @}
  902. @end example
  903. @node Compile Example
  904. @section Compiling the Example Program
  905. @cindex compiling
  906. @cindex executable file
  907. To run a C program requires converting the source code into an
  908. @dfn{executable file}. This is called @dfn{compiling} the program,
  909. and the command to do that using GNU C is @command{gcc}.
  910. This example program consists of a single source file. If we
  911. call that file @file{fib1.c}, the complete command to compile it is
  912. this:
  913. @example
  914. gcc -g -O -o fib1 fib1.c
  915. @end example
  916. @noindent
  917. Here, @option{-g} says to generate debugging information, @option{-O}
  918. says to optimize at the basic level, and @option{-o fib1} says to put
  919. the executable program in the file @file{fib1}.
  920. To run the program, use its file name as a shell command.
  921. For instance,
  922. @example
  923. ./fib1
  924. @end example
  925. @noindent
  926. However, unless you are sure the program is correct, you should
  927. expect to need to debug it. So use this command,
  928. @example
  929. gdb fib1
  930. @end example
  931. @noindent
  932. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  933. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  934. debug the executable program @code{fib1}.
  935. @xref{Compilation}, for an introduction to compiling more complex
  936. programs which consist of more than one source file.
  937. @node Storage
  938. @chapter Storage and Data
  939. @cindex bytes
  940. @cindex storage organization
  941. @cindex memory organization
  942. Storage in C programs is made up of units called @dfn{bytes}. On
  943. nearly all computers, a byte consists of 8 bits, but there are a few
  944. peculiar computers (mostly ``embedded controllers'' for very small
  945. systems) where a byte is longer than that. This manual does not try
  946. to explain the peculiarity of those computers; we assume that a byte
  947. is 8 bits.
  948. Every C data type is made up of a certain number of bytes; that number
  949. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  950. types @code{signed char} and @code{unsigned char} are one byte long;
  951. use those types to operate on data byte by byte. @xref{Signed and
  952. Unsigned Types}. You can refer to a series of consecutive bytes as an
  953. array of @code{char} elements; that's what an ASCII string looks like
  954. in memory. @xref{String Constants}.
  955. @node Beyond Integers
  956. @chapter Beyond Integers
  957. So far we've presented programs that operate on integers. In this
  958. chapter we'll present examples of handling non-integral numbers and
  959. arrays of numbers.
  960. @menu
  961. * Float Example:: A function that uses floating-point numbers.
  962. * Array Example:: A function that works with arrays.
  963. * Array Example Call:: How to call that function.
  964. * Array Example Variations:: Different ways to write the call example.
  965. @end menu
  966. @node Float Example
  967. @section An Example with Non-Integer Numbers
  968. @cindex floating point example
  969. Here's a function that operates on and returns @dfn{floating point}
  970. numbers that don't have to be integers. Floating point represents a
  971. number as a fraction together with a power of 2. (For more detail,
  972. @pxref{Floating-Point Data Types}.) This example calculates the
  973. average of three floating point numbers that are passed to it as
  974. arguments:
  975. @example
  976. double
  977. average_of_three (double a, double b, double c)
  978. @{
  979. return (a + b + c) / 3;
  980. @}
  981. @end example
  982. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  983. integers, and even when they happen to be integers, most likely their
  984. average is not an integer.
  985. @code{double} is the usual data type in C for calculations on
  986. floating-point numbers.
  987. To print a @code{double} with @code{printf}, we must use @samp{%f}
  988. instead of @samp{%d}:
  989. @example
  990. printf ("Average is %f\n",
  991. average_of_three (1.1, 9.8, 3.62));
  992. @end example
  993. The code that calls @code{printf} must pass a @code{double} for
  994. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  995. If the argument has the wrong type, @code{printf} will produce garbage
  996. output.
  997. Here's a complete program that computes the average of three
  998. specific numbers and prints the result:
  999. @example
  1000. double
  1001. average_of_three (double a, double b, double c)
  1002. @{
  1003. return (a + b + c) / 3;
  1004. @}
  1005. int
  1006. main (void)
  1007. @{
  1008. printf ("Average is %f\n",
  1009. average_of_three (1.1, 9.8, 3.62));
  1010. return 0;
  1011. @}
  1012. @end example
  1013. From now on we will not present examples of calls to @code{main}.
  1014. Instead we encourage you to write them for yourself when you want
  1015. to test executing some code.
  1016. @node Array Example
  1017. @section An Example with Arrays
  1018. @cindex array example
  1019. A function to take the average of three numbers is very specific and
  1020. limited. A more general function would take the average of any number
  1021. of numbers. That requires passing the numbers in an array. An array
  1022. is an object in memory that contains a series of values of the same
  1023. data type. This chapter presents the basic concepts and use of arrays
  1024. through an example; for the full explanation, see @ref{Arrays}.
  1025. Here's a function definition to take the average of several
  1026. floating-point numbers, passed as type @code{double}. The first
  1027. parameter, @code{length}, specifies how many numbers are passed. The
  1028. second parameter, @code{input_data}, is an array that holds those
  1029. numbers.
  1030. @example
  1031. double
  1032. avg_of_double (int length, double input_data[])
  1033. @{
  1034. double sum = 0;
  1035. int i;
  1036. for (i = 0; i < length; i++)
  1037. sum = sum + input_data[i];
  1038. return sum / length;
  1039. @}
  1040. @end example
  1041. This introduces the expression to refer to an element of an array:
  1042. @code{input_data[i]} means the element at index @code{i} in
  1043. @code{input_data}. The index of the element can be any expression
  1044. with an integer value; in this case, the expression is @code{i}.
  1045. @xref{Accessing Array Elements}.
  1046. @cindex zero-origin indexing
  1047. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1048. valid index is one less than the number of elements. (This is known
  1049. as @dfn{zero-origin indexing}.)
  1050. This example also introduces the way to declare that a function
  1051. parameter is an array. Such declarations are modeled after the syntax
  1052. for an element of the array. Just as @code{double foo} declares that
  1053. @code{foo} is of type @code{double}, @code{double input_data[]}
  1054. declares that each element of @code{input_data} is of type
  1055. @code{double}. Therefore, @code{input_data} itself has type ``array
  1056. of @code{double}.''
  1057. When declaring an array parameter, it's not necessary to say how long
  1058. the array is. In this case, the parameter @code{input_data} has no
  1059. length information. That's why the function needs another parameter,
  1060. @code{length}, for the caller to provide that information to the
  1061. function @code{avg_of_double}.
  1062. @node Array Example Call
  1063. @section Calling the Array Example
  1064. To call the function @code{avg_of_double} requires making an
  1065. array and then passing it as an argument. Here is an example.
  1066. @example
  1067. @{
  1068. /* @r{The array of values to average.} */
  1069. double nums_to_average[5];
  1070. /* @r{The average, once we compute it.} */
  1071. double average;
  1072. /* @r{Fill in elements of @code{nums_to_average}.} */
  1073. nums_to_average[0] = 58.7;
  1074. nums_to_average[1] = 5.1;
  1075. nums_to_average[2] = 7.7;
  1076. nums_to_average[3] = 105.2;
  1077. nums_to_average[4] = -3.14159;
  1078. average = avg_of_double (5, nums_to_average);
  1079. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1080. @}
  1081. @end example
  1082. This shows an array subscripting expression again, this time
  1083. on the left side of an assignment, storing a value into an
  1084. element of an array.
  1085. It also shows how to declare a local variable that is an array:
  1086. @code{double nums_to_average[5];}. Since this declaration allocates the
  1087. space for the array, it needs to know the array's length. You can
  1088. specify the length with any expression whose value is an integer, but
  1089. in this declaration the length is a constant, the integer 5.
  1090. The name of the array, when used by itself as an expression, stands
  1091. for the address of the array's data, and that's what gets passed to
  1092. the function @code{avg_of_double} in @code{avg_of_double (5,
  1093. nums_to_average)}.
  1094. We can make the code easier to maintain by avoiding the need to write
  1095. 5, the array length, when calling @code{avg_of_double}. That way, if
  1096. we change the array to include more elements, we won't have to change
  1097. that call. One way to do this is with the @code{sizeof} operator:
  1098. @example
  1099. average = avg_of_double ((sizeof (nums_to_average)
  1100. / sizeof (nums_to_average[0])),
  1101. nums_to_average);
  1102. @end example
  1103. This computes the number of elements in @code{nums_to_average} by dividing
  1104. its total size by the size of one element. @xref{Type Size}, for more
  1105. details of using @code{sizeof}.
  1106. We don't show in this example what happens after storing the result of
  1107. @code{avg_of_double} in the variable @code{average}. Presumably
  1108. more code would follow that uses that result somehow. (Why compute
  1109. the average and not use it?) But that isn't part of this topic.
  1110. @node Array Example Variations
  1111. @section Variations for Array Example
  1112. The code to call @code{avg_of_double} has two declarations that
  1113. start with the same data type:
  1114. @example
  1115. /* @r{The array of values to average.} */
  1116. double nums_to_average[5];
  1117. /* @r{The average, once we compute it.} */
  1118. double average;
  1119. @end example
  1120. In C, you can combine the two, like this:
  1121. @example
  1122. double nums_to_average[5], average;
  1123. @end example
  1124. This declares @code{nums_to_average} so each of its elements is a
  1125. @code{double}, and @code{average} so that it simply is a
  1126. @code{double}.
  1127. However, while you @emph{can} combine them, that doesn't mean you
  1128. @emph{should}. If it is useful to write comments about the variables,
  1129. and usually it is, then it's clearer to keep the declarations separate
  1130. so you can put a comment on each one.
  1131. We set all of the elements of the array @code{nums_to_average} with
  1132. assignments, but it is more convenient to use an initializer in the
  1133. declaration:
  1134. @example
  1135. @{
  1136. /* @r{The array of values to average.} */
  1137. double nums_to_average[]
  1138. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1139. /* @r{The average, once we compute it.} */
  1140. average = avg_of_double ((sizeof (nums_to_average)
  1141. / sizeof (nums_to_average[0])),
  1142. nums_to_average);
  1143. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1144. @}
  1145. @end example
  1146. The array initializer is a comma-separated list of values, delimited
  1147. by braces. @xref{Initializers}.
  1148. Note that the declaration does not specify a size for
  1149. @code{nums_to_average}, so the size is determined from the
  1150. initializer. There are five values in the initializer, so
  1151. @code{nums_to_average} gets length 5. If we add another element to
  1152. the initializer, @code{nums_to_average} will have six elements.
  1153. Because the code computes the number of elements from the size of
  1154. the array, using @code{sizeof}, the program will operate on all the
  1155. elements in the initializer, regardless of how many those are.
  1156. @node Lexical Syntax
  1157. @chapter Lexical Syntax
  1158. @cindex lexical syntax
  1159. @cindex token
  1160. To start the full description of the C language, we explain the
  1161. lexical syntax and lexical units of C code. The lexical units of a
  1162. programming language are known as @dfn{tokens}. This chapter covers
  1163. all the tokens of C except for constants, which are covered in a later
  1164. chapter (@pxref{Constants}). One vital kind of token is the
  1165. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1166. kind.
  1167. @menu
  1168. * English:: Write programs in English!
  1169. * Characters:: The characters allowed in C programs.
  1170. * Whitespace:: The particulars of whitespace characters.
  1171. * Comments:: How to include comments in C code.
  1172. * Identifiers:: How to form identifiers (names).
  1173. * Operators/Punctuation:: Characters used as operators or punctuation.
  1174. * Line Continuation:: Splitting one line into multiple lines.
  1175. @end menu
  1176. @node English
  1177. @section Write Programs in English!
  1178. In principle, you can write the function and variable names in a
  1179. program, and the comments, in any human language. C allows any kinds
  1180. of characters in comments, and you can put non-ASCII characters into
  1181. identifiers with a special prefix. However, to enable programmers in
  1182. all countries to understand and develop the program, it is best given
  1183. today's circumstances to write identifiers and comments in
  1184. English.
  1185. English is the one language that programmers in all countries
  1186. generally study. If a program's names are in English, most
  1187. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1188. understand them. Most programmers in those countries can speak
  1189. English, or at least read it, but they do not read each other's
  1190. languages at all. In India, with so many languages, two programmers
  1191. may have no common language other than English.
  1192. If you don't feel confident in writing English, do the best you can,
  1193. and follow each English comment with a version in a language you
  1194. write better; add a note asking others to translate that to English.
  1195. Someone will eventually do that.
  1196. The program's user interface is a different matter. We don't need to
  1197. choose one language for that; it is easy to support multiple languages
  1198. and let each user choose the language to use. This requires writing
  1199. the program to support localization of its interface. (The
  1200. @code{gettext} package exists to support this; @pxref{Message
  1201. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1202. Manual}.) Then a community-based translation effort can provide
  1203. support for all the languages users want to use.
  1204. @node Characters
  1205. @section Characters
  1206. @cindex character set
  1207. @cindex Unicode
  1208. @c ??? How to express ¶?
  1209. GNU C source files are usually written in the
  1210. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1211. was defined in the 1960s for English. However, they can also include
  1212. Unicode characters represented in the
  1213. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1214. This makes it possible to represent accented letters such as @samp{á},
  1215. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1216. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1217. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1218. manual.}
  1219. In C source code, non-ASCII characters are valid in comments, in wide
  1220. character constants (@pxref{Wide Character Constants}), and in string
  1221. constants (@pxref{String Constants}).
  1222. @c ??? valid in identifiers?
  1223. Another way to specify non-ASCII characters in constants (character or
  1224. string) and identifiers is with an escape sequence starting with
  1225. backslash, specifying the intended Unicode character. (@xref{Unicode
  1226. Character Codes}.) This specifies non-ASCII characters without
  1227. putting a real non-ASCII character in the source file itself.
  1228. C accepts two-character aliases called @dfn{digraphs} for certain
  1229. characters. @xref{Digraphs}.
  1230. @node Whitespace
  1231. @section Whitespace
  1232. @cindex whitespace characters in source files
  1233. @cindex space character in source
  1234. @cindex tab character in source
  1235. @cindex formfeed in source
  1236. @cindex linefeed in source
  1237. @cindex newline in source
  1238. @cindex carriage return in source
  1239. @cindex vertical tab in source
  1240. Whitespace means characters that exist in a file but appear blank in a
  1241. printed listing of a file (or traditionally did appear blank, several
  1242. decades ago). The C language requires whitespace in order to separate
  1243. two consecutive identifiers, or to separate an identifier from a
  1244. numeric constant. Other than that, and a few special situations
  1245. described later, whitespace is optional; you can put it in when you
  1246. wish, to make the code easier to read.
  1247. Space and tab in C code are treated as whitespace characters. So are
  1248. line breaks. You can represent a line break with the newline
  1249. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1250. the CRLF sequence (two characters: carriage return followed by a
  1251. newline character).
  1252. The @dfn{formfeed} character, Control-L, was traditionally used to
  1253. divide a file into pages. It is still used this way in source code,
  1254. and the tools that generate nice printouts of source code still start
  1255. a new page after each ``formfeed'' character. Dividing code into
  1256. pages separated by formfeed characters is a good way to break it up
  1257. into comprehensible pieces and show other programmers where they start
  1258. and end.
  1259. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1260. make printing advance down to the next section of a page. We know of
  1261. no particular reason to use it in source code, but it is still
  1262. accepted as whitespace in C.
  1263. Comments are also syntactically equivalent to whitespace.
  1264. @ifinfo
  1265. @xref{Comments}.
  1266. @end ifinfo
  1267. @node Comments
  1268. @section Comments
  1269. @cindex comments
  1270. A comment encapsulates text that has no effect on the program's
  1271. execution or meaning.
  1272. The purpose of comments is to explain the code to people that read it.
  1273. Writing good comments for your code is tremendously important---they
  1274. should provide background information that helps programmers
  1275. understand the reasons why the code is written the way it is. You,
  1276. returning to the code six months from now, will need the help of these
  1277. comments to remember why you wrote it this way.
  1278. Outdated comments that become incorrect are counterproductive, so part
  1279. of the software developer's responsibility is to update comments as
  1280. needed to correspond with changes to the program code.
  1281. C allows two kinds of comment syntax, the traditional style and the
  1282. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1283. with @samp{*/}. For instance,
  1284. @example
  1285. /* @r{This is a comment in traditional C syntax.} */
  1286. @end example
  1287. A traditional comment can contain @samp{/*}, but these delimiters do
  1288. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1289. whether it contains @samp{/*} sequences.
  1290. @example
  1291. /* @r{This} /* @r{is a comment} */ But this is not! */
  1292. @end example
  1293. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1294. For instance,
  1295. @example
  1296. // @r{This is a comment in C@t{++} style.}
  1297. @end example
  1298. Line comments do nest, in effect, because @samp{//} inside a line
  1299. comment is part of that comment:
  1300. @example
  1301. // @r{this whole line is} // @r{one comment}
  1302. This is code, not comment.
  1303. @end example
  1304. It is safe to put line comments inside block comments, or vice versa.
  1305. @example
  1306. @group
  1307. /* @r{traditional comment}
  1308. // @r{contains line comment}
  1309. @r{more traditional comment}
  1310. */ text here is not a comment
  1311. // @r{line comment} /* @r{contains traditional comment} */
  1312. @end group
  1313. @end example
  1314. But beware of commenting out one end of a traditional comment with a line
  1315. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1316. inside an already-started comment.
  1317. @example
  1318. @group
  1319. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1320. Oops! The line comment has ended;
  1321. this isn't a comment any more. */
  1322. @end group
  1323. @end example
  1324. Comments are not recognized within string constants. @t{@w{"/* blah
  1325. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1326. string.
  1327. In this manual we show the text in comments in a variable-width font,
  1328. for readability, but this font distinction does not exist in source
  1329. files.
  1330. A comment is syntactically equivalent to whitespace, so it always
  1331. separates tokens. Thus,
  1332. @example
  1333. @group
  1334. int/* @r{comment} */foo;
  1335. @r{is equivalent to}
  1336. int foo;
  1337. @end group
  1338. @end example
  1339. @noindent
  1340. but clean code always uses real whitespace to separate the comment
  1341. visually from surrounding code.
  1342. @node Identifiers
  1343. @section Identifiers
  1344. @cindex identifiers
  1345. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1346. as well as @samp{_}, that does not start with a digit. Most compilers
  1347. also allow @samp{$}. An identifier can be as long as you like; for
  1348. example,
  1349. @example
  1350. int anti_dis_establishment_arian_ism;
  1351. @end example
  1352. @cindex case of letters in identifiers
  1353. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1354. and @code{A} are two different identifiers.
  1355. @cindex keyword
  1356. @cindex reserved words
  1357. Identifiers in C are used as variable names, function names, typedef
  1358. names, enumeration constants, type tags, field names, and labels.
  1359. Certain identifiers in C are @dfn{keywords}, which means they have
  1360. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1361. meaning you cannot use them in any other way. For instance, you can't
  1362. define a variable or function named @code{return} or @code{if}.
  1363. You can also include other characters, even non-ASCII characters, in
  1364. identifiers by writing their Unicode character names, which start with
  1365. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1366. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1367. characters in identifiers, and when they are written in English, they
  1368. never need non-ASCII characters. @xref{English}.
  1369. Whitespace is required to separate two consecutive identifiers, or to
  1370. separate an identifier from a preceding or following numeric
  1371. constant.
  1372. @node Operators/Punctuation
  1373. @section Operators and Punctuation
  1374. @cindex operators
  1375. @cindex punctuation
  1376. Here we describe the lexical syntax of operators and punctuation in C.
  1377. The specific operators of C and their meanings are presented in
  1378. subsequent chapters.
  1379. Most operators in C consist of one or two characters that can't be
  1380. used in identifiers. The characters used for operators in C are
  1381. @samp{!~^&|*/%+-=<>,.?:}.
  1382. Some operators are a single character. For instance, @samp{-} is the
  1383. operator for negation (with one operand) and the operator for
  1384. subtraction (with two operands).
  1385. Some operators are two characters. For example, @samp{++} is the
  1386. increment operator. Recognition of multicharacter operators works by
  1387. grouping together as many consecutive characters as can constitute one
  1388. operator.
  1389. For instance, the character sequence @samp{++} is always interpreted
  1390. as the increment operator; therefore, if we want to write two
  1391. consecutive instances of the operator @samp{+}, we must separate them
  1392. with a space so that they do not combine as one token. Applying the
  1393. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1394. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1395. of a valid C program and the former could not (since @code{a++}
  1396. is not an lvalue and thus can't be the operand of @code{++}).
  1397. A few C operators are keywords rather than special characters. They
  1398. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1399. (@pxref{Type Alignment}).
  1400. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1401. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1402. @samp{@}}) begin and end a block at the statement level
  1403. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1404. for a variable with multiple elements or components (such as arrays or
  1405. structures).
  1406. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1407. @code{array[5]}.
  1408. Parentheses are used in expressions for explicit nesting of
  1409. expressions (@pxref{Basic Arithmetic}), around the parameter
  1410. declarations in a function declaration or definition, and around the
  1411. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1412. (@pxref{Function Calls}). Several kinds of statements also use
  1413. parentheses as part of their syntax---for instance, @code{if}
  1414. statements, @code{for} statements, @code{while} statements, and
  1415. @code{switch} statements. @xref{if Statement}, and following
  1416. sections.
  1417. Parentheses are also required around the operand of the operator
  1418. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1419. type rather than a value. @xref{Type Size}.
  1420. @node Line Continuation
  1421. @section Line Continuation
  1422. @cindex line continuation
  1423. @cindex continuation of lines
  1424. The sequence of a backslash and a newline is ignored absolutely
  1425. anywhere in a C program. This makes it possible to split a single
  1426. source line into multiple lines in the source file. GNU C tolerates
  1427. and ignores other whitespace between the backslash and the newline.
  1428. In particular, it always ignores a CR (carriage return) character
  1429. there, in case some text editor decided to end the line with the CRLF
  1430. sequence.
  1431. The main use of line continuation in C is for macro definitions that
  1432. would be inconveniently long for a single line (@pxref{Macros}).
  1433. It is possible to continue a line comment onto another line with
  1434. backslash-newline. You can put backslash-newline in the middle of an
  1435. identifier, even a keyword, or an operator. You can even split
  1436. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1437. backslash-newline. Here's an ugly example:
  1438. @example
  1439. @group
  1440. /\
  1441. *
  1442. */ fo\
  1443. o +\
  1444. = 1\
  1445. 0;
  1446. @end group
  1447. @end example
  1448. @noindent
  1449. That's equivalent to @samp{/* */ foo += 10;}.
  1450. Don't do those things in real programs, since they make code hard to
  1451. read.
  1452. @strong{Note:} For the sake of using certain tools on the source code, it is
  1453. wise to end every source file with a newline character which is not
  1454. preceded by a backslash, so that it really ends the last line.
  1455. @node Arithmetic
  1456. @chapter Arithmetic
  1457. @cindex arithmetic operators
  1458. @cindex operators, arithmetic
  1459. @c ??? Duplication with other sections -- get rid of that?
  1460. Arithmetic operators in C attempt to be as similar as possible to the
  1461. abstract arithmetic operations, but it is impossible to do this
  1462. perfectly. Numbers in a computer have a finite range of possible
  1463. values, and non-integer values have a limit on their possible
  1464. accuracy. Nonetheless, in most cases you will encounter no surprises
  1465. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1466. for multiplication.
  1467. Each C operator has a @dfn{precedence}, which is its rank in the
  1468. grammatical order of the various operators. The operators with the
  1469. highest precedence grab adjoining operands first; these expressions
  1470. then become operands for operators of lower precedence. We give some
  1471. information about precedence of operators in this chapter where we
  1472. describe the operators; for the full explanation, see @ref{Binary
  1473. Operator Grammar}.
  1474. The arithmetic operators always @dfn{promote} their operands before
  1475. operating on them. This means converting narrow integer data types to
  1476. a wider data type (@pxref{Operand Promotions}). If you are just
  1477. learning C, don't worry about this yet.
  1478. Given two operands that have different types, most arithmetic
  1479. operations convert them both to their @dfn{common type}. For
  1480. instance, if one is @code{int} and the other is @code{double}, the
  1481. common type is @code{double}. (That's because @code{double} can
  1482. represent all the values that an @code{int} can hold, but not vice
  1483. versa.) For the full details, see @ref{Common Type}.
  1484. @menu
  1485. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1486. and division.
  1487. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1488. * Integer Overflow:: When an integer value exceeds the range
  1489. of its type.
  1490. * Mixed Mode:: Calculating with both integer values
  1491. and floating-point values.
  1492. * Division and Remainder:: How integer division works.
  1493. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1494. * Shift Operations:: Shift integer bits left or right.
  1495. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1496. @end menu
  1497. @node Basic Arithmetic
  1498. @section Basic Arithmetic
  1499. @cindex addition operator
  1500. @cindex subtraction operator
  1501. @cindex multiplication operator
  1502. @cindex division operator
  1503. @cindex negation operator
  1504. @cindex operator, addition
  1505. @cindex operator, subtraction
  1506. @cindex operator, multiplication
  1507. @cindex operator, division
  1508. @cindex operator, negation
  1509. Basic arithmetic in C is done with the usual binary operators of
  1510. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1511. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1512. used to change the sign of a number. The unary @code{+} operator also
  1513. exists; it yields its operand unaltered.
  1514. @samp{/} is the division operator, but dividing integers may not give
  1515. the result you expect. Its value is an integer, which is not equal to
  1516. the mathematical quotient when that is a fraction. Use @samp{%} to
  1517. get the corresponding integer remainder when necessary.
  1518. @xref{Division and Remainder}. Floating point division yields value
  1519. as close as possible to the mathematical quotient.
  1520. These operators use algebraic syntax with the usual algebraic
  1521. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1522. and division are done before addition and subtraction, but you can use
  1523. parentheses to explicitly specify how the operators nest. They are
  1524. left-associative (@pxref{Associativity and Ordering}). Thus,
  1525. @example
  1526. -a + b - c + d * e / f
  1527. @end example
  1528. @noindent
  1529. is equivalent to
  1530. @example
  1531. (((-a) + b) - c) + ((d * e) / f)
  1532. @end example
  1533. @node Integer Arithmetic
  1534. @section Integer Arithmetic
  1535. @cindex integer arithmetic
  1536. Each of the basic arithmetic operations in C has two variants for
  1537. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1538. by the data types of their operands.
  1539. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1540. A signed type can hold a range of positive and negative numbers, with
  1541. zero near the middle of the range. An unsigned type can hold only
  1542. nonnegative numbers; its range starts with zero and runs upward.
  1543. The most basic integer types are @code{int}, which normally can hold
  1544. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1545. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1546. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1547. computers but not always on embedded controllers.) @xref{Integer
  1548. Types}, for full information about integer types.
  1549. When a basic arithmetic operation is given two signed operands, it
  1550. does signed arithmetic. Given two unsigned operands, it does
  1551. unsigned arithmetic.
  1552. If one operand is @code{unsigned int} and the other is @code{int}, the
  1553. operator treats them both as unsigned. More generally, the common
  1554. type of the operands determines whether the operation is signed or
  1555. not. @xref{Common Type}.
  1556. Printing the results of unsigned arithmetic with @code{printf} using
  1557. @samp{%d} can produce surprising results for values far away from
  1558. zero. Even though the rules above say that the computation was done
  1559. with unsigned arithmetic, the printed result may appear to be signed!
  1560. The explanation is that the bit pattern resulting from addition,
  1561. subtraction or multiplication is actually the same for signed and
  1562. unsigned operations. The difference is only in the data type of the
  1563. result, which affects the @emph{interpretation} of the result bit pattern,
  1564. and whether the arithmetic operation can overflow (see the next section).
  1565. But @samp{%d} doesn't know its argument's data type. It sees only the
  1566. value's bit pattern, and it is defined to interpret that as
  1567. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1568. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1569. libc, The GNU C Library Reference Manual}.
  1570. Arithmetic in C never operates directly on narrow integer types (those
  1571. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1572. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1573. @node Integer Overflow
  1574. @section Integer Overflow
  1575. @cindex integer overflow
  1576. @cindex overflow, integer
  1577. When the mathematical value of an arithmetic operation doesn't fit in
  1578. the range of the data type in use, that's called @dfn{overflow}.
  1579. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1580. Integer overflow happens only in arithmetic operations. Type conversion
  1581. operations, by definition, do not cause overflow, not even when the
  1582. result can't fit in its new type. @xref{Integer Conversion}.
  1583. Signed numbers use two's-complement representation, in which the most
  1584. negative number lacks a positive counterpart (@pxref{Integers in
  1585. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1586. overflow.
  1587. @menu
  1588. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1589. * Signed Overflow:: Overlow in signed integer arithmetic.
  1590. @end menu
  1591. @node Unsigned Overflow
  1592. @subsection Overflow with Unsigned Integers
  1593. Unsigned arithmetic in C ignores overflow; it produces the true result
  1594. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1595. in the data type. We say it ``truncates'' the true result to the
  1596. lowest @var{n} bits.
  1597. A true result that is negative, when taken modulo the @var{n}th power
  1598. of 2, yields a positive number. For instance,
  1599. @example
  1600. unsigned int x = 1;
  1601. unsigned int y;
  1602. y = -x;
  1603. @end example
  1604. @noindent
  1605. causes overflow because the negative number @minus{}1 can't be stored
  1606. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1607. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1608. is the largest value that the unsigned data type can store. For a
  1609. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1610. and Minimum Values}.
  1611. Adding that number to itself, as here,
  1612. @example
  1613. unsigned int z;
  1614. z = y + y;
  1615. @end example
  1616. @noindent
  1617. ought to yield 8,489,934,590; however, that is again too large to fit,
  1618. so overflow truncates the value to 4,294,967,294. If that were a
  1619. signed integer, it would mean @minus{}2, which (not by coincidence)
  1620. equals @minus{}1 + @minus{}1.
  1621. @node Signed Overflow
  1622. @subsection Overflow with Signed Integers
  1623. @cindex compiler options for integer overflow
  1624. @cindex integer overflow, compiler options
  1625. @cindex overflow, compiler options
  1626. For signed integers, the result of overflow in C is @emph{in
  1627. principle} undefined, meaning that anything whatsoever could happen.
  1628. Therefore, C compilers can do optimizations that treat the overflow
  1629. case with total unconcern. (Since the result of overflow is undefined
  1630. in principle, one cannot claim that these optimizations are
  1631. erroneous.)
  1632. @strong{Watch out:} These optimizations can do surprising things. For
  1633. instance,
  1634. @example
  1635. int i;
  1636. @r{@dots{}}
  1637. if (i < i + 1)
  1638. x = 5;
  1639. @end example
  1640. @noindent
  1641. could be optimized to do the assignment unconditionally, because the
  1642. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1643. GCC offers compiler options to control handling signed integer
  1644. overflow. These options operate per module; that is, each module
  1645. behaves according to the options it was compiled with.
  1646. These two options specify particular ways to handle signed integer
  1647. overflow, other than the default way:
  1648. @table @option
  1649. @item -fwrapv
  1650. Make signed integer operations well-defined, like unsigned integer
  1651. operations: they produce the @var{n} low-order bits of the true
  1652. result. The highest of those @var{n} bits is the sign bit of the
  1653. result. With @option{-fwrapv}, these out-of-range operations are not
  1654. considered overflow, so (strictly speaking) integer overflow never
  1655. happens.
  1656. The option @option{-fwrapv} enables some optimizations based on the
  1657. defined values of out-of-range results. In GCC 8, it disables
  1658. optimizations that are based on assuming signed integer operations
  1659. will not overflow.
  1660. @item -ftrapv
  1661. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1662. This terminates the program unless the program handles the signal.
  1663. @xref{Signals}.
  1664. @end table
  1665. One other option is useful for finding where overflow occurs:
  1666. @ignore
  1667. @item -fno-strict-overflow
  1668. Disable optimizations that are based on assuming signed integer
  1669. operations will not overflow.
  1670. @end ignore
  1671. @table @option
  1672. @item -fsanitize=signed-integer-overflow
  1673. Output a warning message at run time when signed integer overflow
  1674. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1675. This takes priority over @option{-ftrapv}.
  1676. @end table
  1677. @node Mixed Mode
  1678. @section Mixed-Mode Arithmetic
  1679. Mixing integers and floating-point numbers in a basic arithmetic
  1680. operation converts the integers automatically to floating point.
  1681. In most cases, this gives exactly the desired results.
  1682. But sometimes it matters precisely where the conversion occurs.
  1683. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1684. as an integer, then converts the sum to floating point for the
  1685. multiplication. If the addition gets an overflow, that is not
  1686. equivalent to converting both integers to floating point and then
  1687. adding them. You can get the latter result by explicitly converting
  1688. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1689. @xref{Explicit Type Conversion}.
  1690. @c Eggert's report
  1691. Adding or multiplying several values, including some integers and some
  1692. floating point, does the operations left to right. Thus, @code{3.0 +
  1693. i + j} converts @code{i} to floating point, then adds 3.0, then
  1694. converts @code{j} to floating point and adds that. You can specify a
  1695. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1696. and @code{j} first and then adds that result (converting to floating
  1697. point) to 3.0. In this respect, C differs from other languages, such
  1698. as Fortran.
  1699. @node Division and Remainder
  1700. @section Division and Remainder
  1701. @cindex remainder operator
  1702. @cindex modulus
  1703. @cindex operator, remainder
  1704. Division of integers in C rounds the result to an integer. The result
  1705. is always rounded towards zero.
  1706. @example
  1707. 16 / 3 @result{} 5
  1708. -16 / 3 @result{} -5
  1709. 16 / -3 @result{} -5
  1710. -16 / -3 @result{} 5
  1711. @end example
  1712. @noindent
  1713. To get the corresponding remainder, use the @samp{%} operator:
  1714. @example
  1715. 16 % 3 @result{} 1
  1716. -16 % 3 @result{} -1
  1717. 16 % -3 @result{} 1
  1718. -16 % -3 @result{} -1
  1719. @end example
  1720. @noindent
  1721. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1722. From the rounded quotient and the remainder, you can reconstruct
  1723. the dividend, like this:
  1724. @example
  1725. int
  1726. original_dividend (int divisor, int quotient, int remainder)
  1727. @{
  1728. return divisor * quotient + remainder;
  1729. @}
  1730. @end example
  1731. To do unrounded division, use floating point. If only one operand is
  1732. floating point, @samp{/} converts the other operand to floating
  1733. point.
  1734. @example
  1735. 16.0 / 3 @result{} 5.333333333333333
  1736. 16 / 3.0 @result{} 5.333333333333333
  1737. 16.0 / 3.0 @result{} 5.333333333333333
  1738. 16 / 3 @result{} 5
  1739. @end example
  1740. The remainder operator @samp{%} is not allowed for floating-point
  1741. operands, because it is not needed. The concept of remainder makes
  1742. sense for integers because the result of division of integers has to
  1743. be an integer. For floating point, the result of division is a
  1744. floating-point number, in other words a fraction, which will differ
  1745. from the exact result only by a very small amount.
  1746. There are functions in the standard C library to calculate remainders
  1747. from integral-values division of floating-point numbers.
  1748. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1749. Reference Manual}.
  1750. Integer division overflows in one specific case: dividing the smallest
  1751. negative value for the data type (@pxref{Maximum and Minimum Values})
  1752. by @minus{}1. That's because the correct result, which is the
  1753. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1754. in the same number of bits. On some computers now in use, this always
  1755. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1756. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1757. Division by zero leads to unpredictable results---depending on the
  1758. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1759. produce a numeric result.
  1760. @cindex division by zero
  1761. @cindex zero, division by
  1762. @strong{Watch out:} Make sure the program does not divide by zero. If
  1763. you can't prove that the divisor is not zero, test whether it is zero,
  1764. and skip the division if so.
  1765. @node Numeric Comparisons
  1766. @section Numeric Comparisons
  1767. @cindex numeric comparisons
  1768. @cindex comparisons
  1769. @cindex operators, comparison
  1770. @cindex equal operator
  1771. @cindex not-equal operator
  1772. @cindex less-than operator
  1773. @cindex greater-than operator
  1774. @cindex less-or-equal operator
  1775. @cindex greater-or-equal operator
  1776. @cindex operator, equal
  1777. @cindex operator, not-equal
  1778. @cindex operator, less-than
  1779. @cindex operator, greater-than
  1780. @cindex operator, less-or-equal
  1781. @cindex operator, greater-or-equal
  1782. @cindex truth value
  1783. There are two kinds of comparison operators: @dfn{equality} and
  1784. @dfn{ordering}. Equality comparisons test whether two expressions
  1785. have the same value. The result is a @dfn{truth value}: a number that
  1786. is 1 for ``true'' and 0 for ``false.''
  1787. @example
  1788. a == b /* @r{Test for equal.} */
  1789. a != b /* @r{Test for not equal.} */
  1790. @end example
  1791. The equality comparison is written @code{==} because plain @code{=}
  1792. is the assignment operator.
  1793. Ordering comparisons test which operand is greater or less. Their
  1794. results are truth values. These are the ordering comparisons of C:
  1795. @example
  1796. a < b /* @r{Test for less-than.} */
  1797. a > b /* @r{Test for greater-than.} */
  1798. a <= b /* @r{Test for less-than-or-equal.} */
  1799. a >= b /* @r{Test for greater-than-or-equal.} */
  1800. @end example
  1801. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1802. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1803. mathematics. However, if @code{a} and @code{b} are special floating
  1804. point values (not ordinary numbers), all three can be false.
  1805. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1806. @node Shift Operations
  1807. @section Shift Operations
  1808. @cindex shift operators
  1809. @cindex operators, shift
  1810. @cindex operators, shift
  1811. @cindex shift count
  1812. @dfn{Shifting} an integer means moving the bit values to the left or
  1813. right within the bits of the data type. Shifting is defined only for
  1814. integers. Here's the way to write it:
  1815. @example
  1816. /* @r{Left shift.} */
  1817. 5 << 2 @result{} 20
  1818. /* @r{Right shift.} */
  1819. 5 >> 2 @result{} 1
  1820. @end example
  1821. @noindent
  1822. The left operand is the value to be shifted, and the right operand
  1823. says how many bits to shift it (the @dfn{shift count}). The left
  1824. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1825. operates on a narrow integer type; it's always either @code{int} or
  1826. wider. The value of the shift operator has the same type as the
  1827. promoted left operand.
  1828. @menu
  1829. * Bits Shifted In:: How shifting makes new bits to shift in.
  1830. * Shift Caveats:: Caveats of shift operations.
  1831. * Shift Hacks:: Clever tricks with shift operations.
  1832. @end menu
  1833. @node Bits Shifted In
  1834. @subsection Shifting Makes New Bits
  1835. A shift operation shifts towards one end of the number and has to
  1836. generate new bits at the other end.
  1837. Shifting left one bit must generate a new least significant bit. It
  1838. always brings in zero there. It is equivalent to multiplying by the
  1839. appropriate power of 2. For example,
  1840. @example
  1841. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1842. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1843. @end example
  1844. The meaning of shifting right depends on whether the data type is
  1845. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1846. data type, it performs ``arithmetic shift,'' which keeps the number's
  1847. sign unchanged by duplicating the sign bit. For an unsigned data
  1848. type, it performs ``logical shift,'' which always shifts in zeros at
  1849. the most significant bit.
  1850. In both cases, shifting right one bit is division by two, rounding
  1851. towards negative infinity. For example,
  1852. @example
  1853. (unsigned) 19 >> 2 @result{} 4
  1854. (unsigned) 20 >> 2 @result{} 5
  1855. (unsigned) 21 >> 2 @result{} 5
  1856. @end example
  1857. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1858. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1859. zero.
  1860. The shift count must be zero or greater. Shifting by a negative
  1861. number of bits gives machine-dependent results.
  1862. @node Shift Caveats
  1863. @subsection Caveats for Shift Operations
  1864. @strong{Warning:} If the shift count is greater than or equal to the
  1865. width in bits of the first operand, the results are machine-dependent.
  1866. Logically speaking, the ``correct'' value would be either -1 (for
  1867. right shift of a negative number) or 0 (in all other cases), but what
  1868. it really generates is whatever the machine's shift instruction does in
  1869. that case. So unless you can prove that the second operand is not too
  1870. large, write code to check it at run time.
  1871. @strong{Warning:} Never rely on how the shift operators relate in
  1872. precedence to other arithmetic binary operators. Programmers don't
  1873. remember these precedences, and won't understand the code. Always use
  1874. parentheses to explicitly specify the nesting, like this:
  1875. @example
  1876. a + (b << 5) /* @r{Shift first, then add.} */
  1877. (a + b) << 5 /* @r{Add first, then shift.} */
  1878. @end example
  1879. Note: according to the C standard, shifting of signed values isn't
  1880. guaranteed to work properly when the value shifted is negative, or
  1881. becomes negative during the operation of shifting left. However, only
  1882. pedants have a reason to be concerned about this; only computers with
  1883. strange shift instructions could plausibly do this wrong. In GNU C,
  1884. the operation always works as expected,
  1885. @node Shift Hacks
  1886. @subsection Shift Hacks
  1887. You can use the shift operators for various useful hacks. For
  1888. example, given a date specified by day of the month @code{d}, month
  1889. @code{m}, and year @code{y}, you can store the entire date in a single
  1890. integer @code{date}:
  1891. @example
  1892. unsigned int d = 12;
  1893. unsigned int m = 6;
  1894. unsigned int y = 1983;
  1895. unsigned int date = ((y << 4) + m) << 5) + d;
  1896. @end example
  1897. @noindent
  1898. To extract the original day, month, and year out of
  1899. @code{date}, use a combination of shift and remainder.
  1900. @example
  1901. d = date % 32;
  1902. m = (date >> 5) % 16;
  1903. y = date >> 9;
  1904. @end example
  1905. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1906. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1907. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1908. multiplication, since negating a value is equivalent to multiplying it
  1909. by @minus{}1.
  1910. @node Bitwise Operations
  1911. @section Bitwise Operations
  1912. @cindex bitwise operators
  1913. @cindex operators, bitwise
  1914. @cindex negation, bitwise
  1915. @cindex conjunction, bitwise
  1916. @cindex disjunction, bitwise
  1917. Bitwise operators operate on integers, treating each bit independently.
  1918. They are not allowed for floating-point types.
  1919. The examples in this section use binary constants, starting with
  1920. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1921. of type @code{int}.
  1922. @table @code
  1923. @item ~@code{a}
  1924. Unary operator for bitwise negation; this changes each bit of
  1925. @code{a} from 1 to 0 or from 0 to 1.
  1926. @example
  1927. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1928. ~0 @result{} 0b11111111111111111111111111111111
  1929. ~0b11111111111111111111111111111111 @result{} 0
  1930. ~ (-1) @result{} 0
  1931. @end example
  1932. It is useful to remember that @code{~@var{x} + 1} equals
  1933. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1934. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1935. as @var{x}.
  1936. @item @code{a} & @code{b}
  1937. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1938. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1939. @example
  1940. 0b10101010 & 0b11001100 @result{} 0b10001000
  1941. @end example
  1942. @item @code{a} | @code{b}
  1943. Binary operator for bitwise ``or'' (``inclusive or'' or
  1944. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1945. either @code{a} or @code{b}.
  1946. @example
  1947. 0b10101010 | 0b11001100 @result{} 0b11101110
  1948. @end example
  1949. @item @code{a} ^ @code{b}
  1950. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1951. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1952. @example
  1953. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1954. @end example
  1955. @end table
  1956. To understand the effect of these operators on signed integers, keep
  1957. in mind that all modern computers use two's-complement representation
  1958. (@pxref{Integer Representations}) for negative integers. This means
  1959. that the highest bit of the number indicates the sign; it is 1 for a
  1960. negative number and 0 for a positive number. In a negative number,
  1961. the value in the other bits @emph{increases} as the number gets closer
  1962. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1963. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1964. @strong{Warning:} C defines a precedence ordering for the bitwise
  1965. binary operators, but you should never rely on it. You should
  1966. never rely on how bitwise binary operators relate in precedence to the
  1967. arithmetic and shift binary operators. Other programmers don't
  1968. remember this precedence ordering, so always use parentheses to
  1969. explicitly specify the nesting.
  1970. For example, suppose @code{offset} is an integer that specifies
  1971. the offset within shared memory of a table, except that its bottom few
  1972. bits (@code{LOWBITS} says how many) are special flags. Here's
  1973. how to get just that offset and add it to the base address.
  1974. @example
  1975. shared_mem_base + (offset & (-1 << LOWBITS))
  1976. @end example
  1977. Thanks to the outer set of parentheses, we don't need to know whether
  1978. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1979. set, we don't need to know whether @samp{&} has higher precedence than
  1980. @samp{<<}. But we can rely on all unary operators to have higher
  1981. precedence than any binary operator, so we don't need parentheses
  1982. around the left operand of @samp{<<}.
  1983. @node Assignment Expressions
  1984. @chapter Assignment Expressions
  1985. @cindex assignment expressions
  1986. @cindex operators, assignment
  1987. As a general concept in programming, an @dfn{assignment} is a
  1988. construct that stores a new value into a place where values can be
  1989. stored---for instance, in a variable. Such places are called
  1990. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1991. An assignment in C is an expression because it has a value; we call
  1992. it an @dfn{assignment expression}. A simple assignment looks like
  1993. @example
  1994. @var{lvalue} = @var{value-to-store}
  1995. @end example
  1996. @noindent
  1997. We say it assigns the value of the expression @var{value-to-store} to
  1998. the location @var{lvalue}, or that it stores @var{value-to-store}
  1999. there. You can think of the ``l'' in ``lvalue'' as standing for
  2000. ``left,'' since that's what you put on the left side of the assignment
  2001. operator.
  2002. However, that's not the only way to use an lvalue, and not all lvalues
  2003. can be assigned to. To use the lvalue in the left side of an
  2004. assignment, it has to be @dfn{modifiable}. In C, that means it was
  2005. not declared with the type qualifier @code{const} (@pxref{const}).
  2006. The value of the assignment expression is that of @var{lvalue} after
  2007. the new value is stored in it. This means you can use an assignment
  2008. inside other expressions. Assignment operators are right-associative
  2009. so that
  2010. @example
  2011. x = y = z = 0;
  2012. @end example
  2013. @noindent
  2014. is equivalent to
  2015. @example
  2016. x = (y = (z = 0));
  2017. @end example
  2018. This is the only useful way for them to associate;
  2019. the other way,
  2020. @example
  2021. ((x = y) = z) = 0;
  2022. @end example
  2023. @noindent
  2024. would be invalid since an assignment expression such as @code{x = y}
  2025. is not valid as an lvalue.
  2026. @strong{Warning:} Write parentheses around an assignment if you nest
  2027. it inside another expression, unless that is a conditional expression,
  2028. or comma-separated series, or another assignment.
  2029. @menu
  2030. * Simple Assignment:: The basics of storing a value.
  2031. * Lvalues:: Expressions into which a value can be stored.
  2032. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2033. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2034. an lvalue's contents.
  2035. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2036. * Assignment in Subexpressions:: How to avoid ambiguity.
  2037. * Write Assignments Separately:: Write assignments as separate statements.
  2038. @end menu
  2039. @node Simple Assignment
  2040. @section Simple Assignment
  2041. @cindex simple assignment
  2042. @cindex assignment, simple
  2043. A @dfn{simple assignment expression} computes the value of the right
  2044. operand and stores it into the lvalue on the left. Here is a simple
  2045. assignment expression that stores 5 in @code{i}:
  2046. @example
  2047. i = 5
  2048. @end example
  2049. @noindent
  2050. We say that this is an @dfn{assignment to} the variable @code{i} and
  2051. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2052. because it is an expression (so it has a value). Adding a semicolon
  2053. at the end would make it a statement (@pxref{Expression Statement}).
  2054. Here is another example of a simple assignment expression. Its
  2055. operands are not simple, but the kind of assignment done here is
  2056. simple assignment.
  2057. @example
  2058. x[foo ()] = y + 6
  2059. @end example
  2060. A simple assignment with two different numeric data types converts the
  2061. right operand value to the lvalue's type, if possible. It can convert
  2062. any numeric type to any other numeric type.
  2063. Simple assignment is also allowed on some non-numeric types: pointers
  2064. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2065. unions (@pxref{Unions}).
  2066. @strong{Warning:} Assignment is not allowed on arrays because
  2067. there are no array values in C; C variables can be arrays, but these
  2068. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2069. Arrays}.
  2070. @xref{Assignment Type Conversions}, for the complete rules about data
  2071. types used in assignments.
  2072. @node Lvalues
  2073. @section Lvalues
  2074. @cindex lvalues
  2075. An expression that identifies a memory space that holds a value is
  2076. called an @dfn{lvalue}, because it is a location that can hold a value.
  2077. The standard kinds of lvalues are:
  2078. @itemize @bullet
  2079. @item
  2080. A variable.
  2081. @item
  2082. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2083. unary @samp{*}.
  2084. @item
  2085. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2086. the structure value is an lvalue.
  2087. @item
  2088. A structure field reference using @samp{->}. This is always an lvalue
  2089. since @samp{->} implies pointer dereference.
  2090. @item
  2091. A union alternative reference (@pxref{Unions}), on the same conditions
  2092. as for structure fields.
  2093. @item
  2094. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2095. is an lvalue.
  2096. @end itemize
  2097. If an expression's outermost operation is any other operator, that
  2098. expression is not an lvalue. Thus, the variable @code{x} is an
  2099. lvalue, but @code{x + 0} is not, even though these two expressions
  2100. compute the same value (assuming @code{x} is a number).
  2101. An array can be an lvalue (the rules above determine whether it is
  2102. one), but using the array in an expression converts it automatically
  2103. to a pointer to the first element. The result of this conversion is
  2104. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2105. use @code{a} by itself as the left operand of an assignment. But you
  2106. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2107. lvalue since @code{a} is an lvalue.
  2108. @node Modifying Assignment
  2109. @section Modifying Assignment
  2110. @cindex modifying assignment
  2111. @cindex assignment, modifying
  2112. You can abbreviate the common construct
  2113. @example
  2114. @var{lvalue} = @var{lvalue} + @var{expression}
  2115. @end example
  2116. @noindent
  2117. as
  2118. @example
  2119. @var{lvalue} += @var{expression}
  2120. @end example
  2121. This is known as a @dfn{modifying assignment}. For instance,
  2122. @example
  2123. i = i + 5;
  2124. i += 5;
  2125. @end example
  2126. @noindent
  2127. shows two statements that are equivalent. The first uses
  2128. simple assignment; the second uses modifying assignment.
  2129. Modifying assignment works with any binary arithmetic operator. For
  2130. instance, you can subtract something from an lvalue like this,
  2131. @example
  2132. @var{lvalue} -= @var{expression}
  2133. @end example
  2134. @noindent
  2135. or multiply it by a certain amount like this,
  2136. @example
  2137. @var{lvalue} *= @var{expression}
  2138. @end example
  2139. @noindent
  2140. or shift it by a certain amount like this.
  2141. @example
  2142. @var{lvalue} <<= @var{expression}
  2143. @var{lvalue} >>= @var{expression}
  2144. @end example
  2145. In most cases, this feature adds no power to the language, but it
  2146. provides substantial convenience. Also, when @var{lvalue} contains
  2147. code that has side effects, the simple assignment performs those side
  2148. effects twice, while the modifying assignment performs them once. For
  2149. instance,
  2150. @example
  2151. x[foo ()] = x[foo ()] + 5;
  2152. @end example
  2153. @noindent
  2154. calls @code{foo} twice, and it could return different values each
  2155. time. If @code{foo ()} returns 1 the first time and 3 the second
  2156. time, then the effect could be to add @code{x[3]} and 5 and store the
  2157. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2158. result in @code{x[3]}. We don't know which of the two it will do,
  2159. because C does not specify which call to @code{foo} is computed first.
  2160. Such a statement is not well defined, and shouldn't be used.
  2161. By contrast,
  2162. @example
  2163. x[foo ()] += 5;
  2164. @end example
  2165. @noindent
  2166. is well defined: it calls @code{foo} only once to determine which
  2167. element of @code{x} to adjust, and it adjusts that element by adding 5
  2168. to it.
  2169. @node Increment/Decrement
  2170. @section Increment and Decrement Operators
  2171. @cindex increment operator
  2172. @cindex decrement operator
  2173. @cindex operator, increment
  2174. @cindex operator, decrement
  2175. @cindex preincrement expression
  2176. @cindex predecrement expression
  2177. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2178. @dfn{decrement} operators. When used on a numeric value, they add or
  2179. subtract 1. We don't consider them assignments, but they are
  2180. equivalent to assignments.
  2181. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2182. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2183. and the result becomes the expression's value. For instance,
  2184. @example
  2185. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2186. int
  2187. main (void)
  2188. @{
  2189. int i = 5;
  2190. printf ("%d\n", i);
  2191. printf ("%d\n", ++i);
  2192. printf ("%d\n", i);
  2193. return 0;
  2194. @}
  2195. @end example
  2196. @noindent
  2197. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2198. increments @code{i} from 5 to 6, and has the value 6, so the output
  2199. from @code{printf} on that line says @samp{6}.
  2200. Using @samp{--} instead, for predecrement,
  2201. @example
  2202. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2203. int
  2204. main (void)
  2205. @{
  2206. int i = 5;
  2207. printf ("%d\n", i);
  2208. printf ("%d\n", --i);
  2209. printf ("%d\n", i);
  2210. return 0;
  2211. @}
  2212. @end example
  2213. @noindent
  2214. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2215. again @samp{4}.
  2216. @node Postincrement/Postdecrement
  2217. @section Postincrement and Postdecrement
  2218. @cindex postincrement expression
  2219. @cindex postdecrement expression
  2220. @cindex operator, postincrement
  2221. @cindex operator, postdecrement
  2222. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2223. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2224. increments or decrement it. Thus, the value of @code{i++} is the same
  2225. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2226. little later.'' This is called @dfn{postincrement} or
  2227. @dfn{postdecrement}.
  2228. For example,
  2229. @example
  2230. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2231. int
  2232. main (void)
  2233. @{
  2234. int i = 5;
  2235. printf ("%d\n", i);
  2236. printf ("%d\n", i++);
  2237. printf ("%d\n", i);
  2238. return 0;
  2239. @}
  2240. @end example
  2241. @noindent
  2242. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2243. has the value 5, which is the value of @code{i} at the time,
  2244. but it increments @code{i} from 5 to 6 just a little later.
  2245. How much later is ``just a little later''? That is flexible. The
  2246. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2247. that means by the end of the statement. @xref{Sequence Points}.
  2248. If a unary operator precedes a postincrement or postincrement expression,
  2249. the increment nests inside:
  2250. @example
  2251. -a++ @r{is equivalent to} -(a++)
  2252. @end example
  2253. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2254. it can't be incremented.
  2255. @node Assignment in Subexpressions
  2256. @section Pitfall: Assignment in Subexpressions
  2257. @cindex assignment in subexpressions
  2258. @cindex subexpressions, assignment in
  2259. In C, the order of computing parts of an expression is not fixed.
  2260. Aside from a few special cases, the operations can be computed in any
  2261. order. If one part of the expression has an assignment to @code{x}
  2262. and another part of the expression uses @code{x}, the result is
  2263. unpredictable because that use might be computed before or after the
  2264. assignment.
  2265. Here's an example of ambiguous code:
  2266. @example
  2267. x = 20;
  2268. printf ("%d %d\n", x, x = 4);
  2269. @end example
  2270. @noindent
  2271. If the second argument, @code{x}, is computed before the third argument,
  2272. @code{x = 4}, the second argument's value will be 20. If they are
  2273. computed in the other order, the second argument's value will be 4.
  2274. Here's one way to make that code unambiguous:
  2275. @example
  2276. y = 20;
  2277. printf ("%d %d\n", y, x = 4);
  2278. @end example
  2279. Here's another way, with the other meaning:
  2280. @example
  2281. x = 4;
  2282. printf ("%d %d\n", x, x);
  2283. @end example
  2284. This issue applies to all kinds of assignments, and to the increment
  2285. and decrement operators, which are equivalent to assignments.
  2286. @xref{Order of Execution}, for more information about this.
  2287. However, it can be useful to write assignments inside an
  2288. @code{if}-condition or @code{while}-test along with logical operators.
  2289. @xref{Logicals and Assignments}.
  2290. @node Write Assignments Separately
  2291. @section Write Assignments in Separate Statements
  2292. It is often convenient to write an assignment inside an
  2293. @code{if}-condition, but that can reduce the readability of the
  2294. program. Here's an example of what to avoid:
  2295. @example
  2296. if (x = advance (x))
  2297. @r{@dots{}}
  2298. @end example
  2299. The idea here is to advance @code{x} and test if the value is nonzero.
  2300. However, readers might miss the fact that it uses @samp{=} and not
  2301. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2302. inside a condition is a common error, so GNU C can give warnings when
  2303. @samp{=} appears in a way that suggests it's an error.
  2304. It is much clearer to write the assignment as a separate statement, like this:
  2305. @example
  2306. x = advance (x);
  2307. if (x != 0)
  2308. @r{@dots{}}
  2309. @end example
  2310. @noindent
  2311. This makes it unmistakably clear that @code{x} is assigned a new value.
  2312. Another method is to use the comma operator (@pxref{Comma Operator}),
  2313. like this:
  2314. @example
  2315. if (x = advance (x), x != 0)
  2316. @r{@dots{}}
  2317. @end example
  2318. @noindent
  2319. However, putting the assignment in a separate statement is usually clearer
  2320. unless the assignment is very short, because it reduces nesting.
  2321. @node Execution Control Expressions
  2322. @chapter Execution Control Expressions
  2323. @cindex execution control expressions
  2324. @cindex expressions, execution control
  2325. This chapter describes the C operators that combine expressions to
  2326. control which of those expressions execute, or in which order.
  2327. @menu
  2328. * Logical Operators:: Logical conjunction, disjunction, negation.
  2329. * Logicals and Comparison:: Logical operators with comparison operators.
  2330. * Logicals and Assignments:: Assignments with logical operators.
  2331. * Conditional Expression:: An if/else construct inside expressions.
  2332. * Comma Operator:: Build a sequence of subexpressions.
  2333. @end menu
  2334. @node Logical Operators
  2335. @section Logical Operators
  2336. @cindex logical operators
  2337. @cindex operators, logical
  2338. @cindex conjunction operator
  2339. @cindex disjunction operator
  2340. @cindex negation operator, logical
  2341. The @dfn{logical operators} combine truth values, which are normally
  2342. represented in C as numbers. Any expression with a numeric value is a
  2343. valid truth value: zero means false, and any other value means true.
  2344. A pointer type is also meaningful as a truth value; a null pointer
  2345. (which is zero) means false, and a non-null pointer means true
  2346. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2347. or 0 and has type @code{int} (@pxref{Integer Types}).
  2348. The logical operators are used mainly in the condition of an @code{if}
  2349. statement, or in the end test in a @code{for} statement or
  2350. @code{while} statement (@pxref{Statements}). However, they are valid
  2351. in any context where an integer-valued expression is allowed.
  2352. @table @samp
  2353. @item ! @var{exp}
  2354. Unary operator for logical ``not.'' The value is 1 (true) if
  2355. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2356. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2357. function call, you should write parentheses around it.
  2358. @item @var{left} && @var{right}
  2359. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2360. @var{right}. If both of the operands are true, the @samp{&&} expression
  2361. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2362. gives the value 0 (false). If @var{left} yields a false value,
  2363. that determines the overall result, so @var{right} is not computed.
  2364. @item @var{left} || @var{right}
  2365. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2366. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2367. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2368. gives the value 0 (false). If @var{left} yields a true value,
  2369. that determines the overall result, so @var{right} is not computed.
  2370. @end table
  2371. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2372. and @samp{||}. When you use them together, always use parentheses to
  2373. specify explicitly how they nest, as shown here:
  2374. @example
  2375. if ((r != 0 && x % r == 0)
  2376. ||
  2377. (s != 0 && x % s == 0))
  2378. @end example
  2379. @node Logicals and Comparison
  2380. @section Logical Operators and Comparisons
  2381. The most common thing to use inside the logical operators is a
  2382. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2383. precedence than comparison operators and arithmetic operators, so we
  2384. can write expressions like this without parentheses and get the
  2385. nesting that is natural: two comparison operations that must both be
  2386. true.
  2387. @example
  2388. if (r != 0 && x % r == 0)
  2389. @end example
  2390. @noindent
  2391. This example also shows how it is useful that @samp{&&} guarantees to
  2392. skip the right operand if the left one turns out false. Because of
  2393. that, this code never tries to divide by zero.
  2394. This is equivalent:
  2395. @example
  2396. if (r && x % r == 0)
  2397. @end example
  2398. @noindent
  2399. A truth value is simply a number, so @code{r}
  2400. as a truth value tests whether it is nonzero.
  2401. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2402. So it is better style to write the explicit @code{!= 0}.
  2403. Here's another equivalent way to write it:
  2404. @example
  2405. if (!(r == 0) && x % r == 0)
  2406. @end example
  2407. @noindent
  2408. This illustrates the unary @samp{!} operator, and the need to
  2409. write parentheses around its operand.
  2410. @node Logicals and Assignments
  2411. @section Logical Operators and Assignments
  2412. There are cases where assignments nested inside the condition can
  2413. actually make a program @emph{easier} to read. Here is an example
  2414. using a hypothetical type @code{list} which represents a list; it
  2415. tests whether the list has at least two links, using hypothetical
  2416. functions, @code{nonempty} which is true of the argument is a nonempty
  2417. list, and @code{list_next} which advances from one list link to the
  2418. next. We assume that a list is never a null pointer, so that the
  2419. assignment expressions are always ``true.''
  2420. @example
  2421. if (nonempty (list)
  2422. && (temp1 = list_next (list))
  2423. && nonempty (temp1)
  2424. && (temp2 = list_next (temp1)))
  2425. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2426. @end example
  2427. @noindent
  2428. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2429. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2430. only natural place to put the assignments is among those calls.
  2431. It would be possible to rewrite this as several statements, but that
  2432. could make it much more cumbersome. On the other hand, when the test
  2433. is even more complex than this one, splitting it into multiple
  2434. statements might be necessary for clarity.
  2435. If an empty list is a null pointer, we can dispense with calling
  2436. @code{nonempty}:
  2437. @example
  2438. if ((temp1 = list_next (list))
  2439. && (temp2 = list_next (temp1)))
  2440. @r{@dots{}}
  2441. @end example
  2442. @node Conditional Expression
  2443. @section Conditional Expression
  2444. @cindex conditional expression
  2445. @cindex expression, conditional
  2446. C has a conditional expression that selects one of two expressions
  2447. to compute and get the value from. It looks like this:
  2448. @example
  2449. @var{condition} ? @var{iftrue} : @var{iffalse}
  2450. @end example
  2451. @menu
  2452. * Conditional Rules:: Rules for the conditional operator.
  2453. * Conditional Branches:: About the two branches in a conditional.
  2454. @end menu
  2455. @node Conditional Rules
  2456. @subsection Rules for Conditional Operator
  2457. The first operand, @var{condition}, should be a value that can be
  2458. compared with zero---a number or a pointer. If it is true (nonzero),
  2459. then the conditional expression computes @var{iftrue} and its value
  2460. becomes the value of the conditional expression. Otherwise the
  2461. conditional expression computes @var{iffalse} and its value becomes
  2462. the value of the conditional expression. The conditional expression
  2463. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2464. of them.
  2465. Here's an example: the absolute value of a number @code{x}
  2466. can be written as @code{(x >= 0 ? x : -x)}.
  2467. @strong{Warning:} The conditional expression operators have rather low
  2468. syntactic precedence. Except when the conditional expression is used
  2469. as an argument in a function call, write parentheses around it. For
  2470. clarity, always write parentheses around it if it extends across more
  2471. than one line.
  2472. Assignment operators and the comma operator (@pxref{Comma Operator})
  2473. have lower precedence than conditional expression operators, so write
  2474. parentheses around those when they appear inside a conditional
  2475. expression. @xref{Order of Execution}.
  2476. @node Conditional Branches
  2477. @subsection Conditional Operator Branches
  2478. @cindex branches of conditional expression
  2479. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2480. conditional.
  2481. The two branches should normally have the same type, but a few
  2482. exceptions are allowed. If they are both numeric types, the
  2483. conditional converts both to their common type (@pxref{Common Type}).
  2484. With pointers (@pxref{Pointers}), the two values can be pointers to
  2485. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2486. result type is a similar pointer whose target type combines all the
  2487. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2488. If one branch has type @code{void *} and the other is a pointer to an
  2489. object (not to a function), the conditional converts the @code{void *}
  2490. branch to the type of the other.
  2491. If one branch is an integer constant with value zero and the other is
  2492. a pointer, the conditional converts zero to the pointer's type.
  2493. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2494. that case, if @var{condition} is nonzero, its value becomes the value of
  2495. the conditional expression, after conversion to the common type.
  2496. Thus,
  2497. @example
  2498. x ? : y
  2499. @end example
  2500. @noindent
  2501. has the value of @code{x} if that is nonzero; otherwise, the value of
  2502. @code{y}.
  2503. @cindex side effect in ?:
  2504. @cindex ?: side effect
  2505. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2506. In that case, writing that expression twice would carry out the side
  2507. effects twice, but writing it once does them just once. For example,
  2508. if we suppose that the function @code{next_element} advances a pointer
  2509. variable to point to the next element in a list and returns the new
  2510. pointer,
  2511. @example
  2512. next_element () ? : default_pointer
  2513. @end example
  2514. @noindent
  2515. is a way to advance the pointer and use its new value if it isn't
  2516. null, but use @code{default_pointer} if that is null. We must not do
  2517. it this way,
  2518. @example
  2519. next_element () ? next_element () : default_pointer
  2520. @end example
  2521. @noindent
  2522. because it would advance the pointer a second time.
  2523. @node Comma Operator
  2524. @section Comma Operator
  2525. @cindex comma operator
  2526. @cindex operator, comma
  2527. The comma operator stands for sequential execution of expressions.
  2528. The value of the comma expression comes from the last expression in
  2529. the sequence; the previous expressions are computed only for their
  2530. side effects. It looks like this:
  2531. @example
  2532. @var{exp1}, @var{exp2} @r{@dots{}}
  2533. @end example
  2534. @noindent
  2535. You can bundle any number of expressions together this way, by putting
  2536. commas between them.
  2537. @menu
  2538. * Uses of Comma:: When to use the comma operator.
  2539. * Clean Comma:: Clean use of the comma operator.
  2540. * Avoid Comma:: When to not use the comma operator.
  2541. @end menu
  2542. @node Uses of Comma
  2543. @subsection The Uses of the Comma Operator
  2544. With commas, you can put several expressions into a place that
  2545. requires just one expression---for example, in the header of a
  2546. @code{for} statement. This statement
  2547. @example
  2548. for (i = 0, j = 10, k = 20; i < n; i++)
  2549. @end example
  2550. @noindent
  2551. contains three assignment expressions, to initialize @code{i}, @code{j}
  2552. and @code{k}. The syntax of @code{for} requires just one expression
  2553. for initialization; to include three assignments, we use commas to
  2554. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2555. 20}. This technique is also useful in the loop-advance expression,
  2556. the last of the three inside the @code{for} parentheses.
  2557. In the @code{for} statement and the @code{while} statement
  2558. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2559. effect before the loop-exit test. For example,
  2560. @example
  2561. while (printf ("At the test, x = %d\n", x), x != 0)
  2562. @end example
  2563. @node Clean Comma
  2564. @subsection Clean Use of the Comma Operator
  2565. Always write parentheses around a series of comma operators, except
  2566. when it is at top level in an expression statement, or within the
  2567. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2568. statement (@pxref{Statements}). For instance, in
  2569. @example
  2570. for (i = 0, j = 10, k = 20; i < n; i++)
  2571. @end example
  2572. @noindent
  2573. the commas between the assignments are clear because they are between
  2574. a parenthesis and a semicolon.
  2575. The arguments in a function call are also separated by commas, but that is
  2576. not an instance of the comma operator. Note the difference between
  2577. @example
  2578. foo (4, 5, 6)
  2579. @end example
  2580. @noindent
  2581. which passes three arguments to @code{foo} and
  2582. @example
  2583. foo ((4, 5, 6))
  2584. @end example
  2585. @noindent
  2586. which uses the comma operator and passes just one argument
  2587. (with value 6).
  2588. @strong{Warning:} don't use the comma operator around an argument
  2589. of a function unless it helps understand the code. When you do so,
  2590. don't put part of another argument on the same line. Instead, add a
  2591. line break to make the parentheses around the comma operator easier to
  2592. see, like this.
  2593. @example
  2594. foo ((mumble (x, y), frob (z)),
  2595. *p)
  2596. @end example
  2597. @node Avoid Comma
  2598. @subsection When Not to Use the Comma Operator
  2599. You can use a comma in any subexpression, but in most cases it only
  2600. makes the code confusing, and it is clearer to raise all but the last
  2601. of the comma-separated expressions to a higher level. Thus, instead
  2602. of this:
  2603. @example
  2604. x = (y += 4, 8);
  2605. @end example
  2606. @noindent
  2607. it is much clearer to write this:
  2608. @example
  2609. y += 4, x = 8;
  2610. @end example
  2611. @noindent
  2612. or this:
  2613. @example
  2614. y += 4;
  2615. x = 8;
  2616. @end example
  2617. Use commas only in the cases where there is no clearer alternative
  2618. involving multiple statements.
  2619. By contrast, don't hesitate to use commas in the expansion in a macro
  2620. definition. The trade-offs of code clarity are different in that
  2621. case, because the @emph{use} of the macro may improve overall clarity
  2622. so much that the ugliness of the macro's @emph{definition} is a small
  2623. price to pay. @xref{Macros}.
  2624. @node Binary Operator Grammar
  2625. @chapter Binary Operator Grammar
  2626. @cindex binary operator grammar
  2627. @cindex grammar, binary operator
  2628. @cindex operator precedence
  2629. @cindex precedence, operator
  2630. @cindex left-associative
  2631. @dfn{Binary operators} are those that take two operands, one
  2632. on the left and one on the right.
  2633. All the binary operators in C are syntactically left-associative.
  2634. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2635. @var{op} b) @var{op} c}}. However, you should only write repeated
  2636. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2637. @samp{/}, because those cases are clear from algebra. So it is ok to
  2638. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2639. c} or @code{a % b % c}.
  2640. Each C operator has a @dfn{precedence}, which is its rank in the
  2641. grammatical order of the various operators. The operators with the
  2642. highest precedence grab adjoining operands first; these expressions
  2643. then become operands for operators of lower precedence.
  2644. The precedence order of operators in C is fully specified, so any
  2645. combination of operations leads to a well-defined nesting. We state
  2646. only part of the full precedence ordering here because it is bad
  2647. practice for C code to depend on the other cases. For cases not
  2648. specified in this chapter, always use parentheses to make the nesting
  2649. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2650. remembering anything about the C precedence order beyond what's stated
  2651. here. I studied the full precedence table to write the parser, and
  2652. promptly forgot it again. If you need to look up the full precedence order
  2653. to understand some C code, fix the code with parentheses so nobody else
  2654. needs to do that.}
  2655. You can depend on this subsequence of the precedence ordering
  2656. (stated from highest precedence to lowest):
  2657. @enumerate
  2658. @item
  2659. Component access (@samp{.} and @samp{->}).
  2660. @item
  2661. Unary prefix operators.
  2662. @item
  2663. Unary postfix operators.
  2664. @item
  2665. Multiplication, division, and remainder (they have the same precedence).
  2666. @item
  2667. Addition and subtraction (they have the same precedence).
  2668. @item
  2669. Comparisons---but watch out!
  2670. @item
  2671. Logical operators @samp{&&} and @samp{||}---but watch out!
  2672. @item
  2673. Conditional expression with @samp{?} and @samp{:}.
  2674. @item
  2675. Assignments.
  2676. @item
  2677. Sequential execution (the comma operator, @samp{,}).
  2678. @end enumerate
  2679. Two of the lines in the above list say ``but watch out!'' That means
  2680. that the line covers operators with subtly different precedence.
  2681. Never depend on the grammar of C to decide how two comparisons nest;
  2682. instead, always use parentheses to specify their nesting.
  2683. You can let several @samp{&&} operators associate, or several
  2684. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2685. and @samp{||} nest with each other. @xref{Logical Operators}.
  2686. There is one other precedence ordering that code can depend on:
  2687. @enumerate
  2688. @item
  2689. Unary postfix operators.
  2690. @item
  2691. Bitwise and shift operators---but watch out!
  2692. @item
  2693. Conditional expression with @samp{?} and @samp{:}.
  2694. @end enumerate
  2695. The caveat for bitwise and shift operators is like that for logical
  2696. operators: you can let multiple uses of one bitwise operator
  2697. associate, but always use parentheses to control nesting of dissimilar
  2698. operators.
  2699. These lists do not specify any precedence ordering between the bitwise
  2700. and shift operators of the second list and the binary operators above
  2701. conditional expressions in the first list. When they come together,
  2702. parenthesize them. @xref{Bitwise Operations}.
  2703. @node Order of Execution
  2704. @chapter Order of Execution
  2705. @cindex order of execution
  2706. The order of execution of a C program is not always obvious, and not
  2707. necessarily predictable. This chapter describes what you can count on.
  2708. @menu
  2709. * Reordering of Operands:: Operations in C are not necessarily computed
  2710. in the order they are written.
  2711. * Associativity and Ordering:: Some associative operations are performed
  2712. in a particular order; others are not.
  2713. * Sequence Points:: Some guarantees about the order of operations.
  2714. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2715. * Ordering of Operands:: Evaluation order of operands
  2716. and function arguments.
  2717. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2718. only if it has no impact on program results.
  2719. @end menu
  2720. @node Reordering of Operands
  2721. @section Reordering of Operands
  2722. @cindex ordering of operands
  2723. @cindex reordering of operands
  2724. @cindex operand execution ordering
  2725. The C language does not necessarily carry out operations within an
  2726. expression in the order they appear in the code. For instance, in
  2727. this expression,
  2728. @example
  2729. foo () + bar ()
  2730. @end example
  2731. @noindent
  2732. @code{foo} might be called first or @code{bar} might be called first.
  2733. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2734. results can be unpredictable.
  2735. The unpredictable order of computation of subexpressions also makes a
  2736. difference when one of them contains an assignment. We already saw
  2737. this example of bad code,
  2738. @example
  2739. x = 20;
  2740. printf ("%d %d\n", x, x = 4);
  2741. @end example
  2742. @noindent
  2743. in which the second argument, @code{x}, has a different value
  2744. depending on whether it is computed before or after the assignment in
  2745. the third argument.
  2746. @node Associativity and Ordering
  2747. @section Associativity and Ordering
  2748. @cindex associativity and ordering
  2749. An associative binary operator, such as @code{+}, when used repeatedly
  2750. can combine any number of operands. The operands' values may be
  2751. computed in any order.
  2752. If the values are integers and overflow can be ignored, they may be
  2753. combined in any order. Thus, given four functions that return
  2754. @code{unsigned int}, calling them and adding their results as here
  2755. @example
  2756. (foo () + bar ()) + (baz () + quux ())
  2757. @end example
  2758. @noindent
  2759. may add up the results in any order.
  2760. By contrast, arithmetic on signed integers, with overflow significant,
  2761. is not really associative (@pxref{Integer Overflow}). Thus, the
  2762. additions must be done in the order specified, obeying parentheses and
  2763. left-association. That means computing @code{(foo () + bar ())} and
  2764. @code{(baz () + quux ())} first (in either order), then adding the
  2765. two.
  2766. The same applies to arithmetic on floating-point values, since that
  2767. too is not really associative. However, the GCC option
  2768. @option{-funsafe-math-optimizations} allows the compiler to change the
  2769. order of calculation when an associative operation (associative in
  2770. exact mathematics) combines several operands. The option takes effect
  2771. when compiling a module (@pxref{Compilation}). Changing the order
  2772. of association can enable the program to pipeline the floating point
  2773. operations.
  2774. In all these cases, the four function calls can be done in any order.
  2775. There is no right or wrong about that.
  2776. @node Sequence Points
  2777. @section Sequence Points
  2778. @cindex sequence points
  2779. @cindex full expression
  2780. There are some points in the code where C makes limited guarantees
  2781. about the order of operations. These are called @dfn{sequence
  2782. points}. Here is where they occur:
  2783. @itemize @bullet
  2784. @item
  2785. At the end of a @dfn{full expression}; that is to say, an expression
  2786. that is not part of a larger expression. All side effects specified
  2787. by that expression are carried out before execution moves
  2788. on to subsequent code.
  2789. @item
  2790. At the end of the first operand of certain operators: @samp{,},
  2791. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2792. that expression are carried out before any execution of the
  2793. next operand.
  2794. The commas that separate arguments in a function call are @emph{not}
  2795. comma operators, and they do not create sequence points. The rule
  2796. for function arguments and the rule for operands are different
  2797. (@pxref{Ordering of Operands}).
  2798. @item
  2799. Just before calling a function. All side effects specified by the
  2800. argument expressions are carried out before calling the function.
  2801. If the function to be called is not constant---that is, if it is
  2802. computed by an expression---all side effects in that expression are
  2803. carried out before calling the function.
  2804. @end itemize
  2805. The ordering imposed by a sequence point applies locally to a limited
  2806. range of code, as stated above in each case. For instance, the
  2807. ordering imposed by the comma operator does not apply to code outside
  2808. that comma operator. Thus, in this code,
  2809. @example
  2810. (x = 5, foo (x)) + x * x
  2811. @end example
  2812. @noindent
  2813. the sequence point of the comma operator orders @code{x = 5} before
  2814. @code{foo (x)}, but @code{x * x} could be computed before or after
  2815. them.
  2816. @node Postincrement and Ordering
  2817. @section Postincrement and Ordering
  2818. @cindex postincrement and ordering
  2819. @cindex ordering and postincrement
  2820. Ordering requirements are loose with the postincrement and
  2821. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2822. specify side effects to happen ``a little later.'' They must happen
  2823. before the next sequence point, but that still leaves room for various
  2824. meanings. In this expression,
  2825. @example
  2826. z = x++ - foo ()
  2827. @end example
  2828. @noindent
  2829. it's unpredictable whether @code{x} gets incremented before or after
  2830. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2831. it might see the old value or it might see the incremented value.
  2832. In this perverse expression,
  2833. @example
  2834. x = x++
  2835. @end example
  2836. @noindent
  2837. @code{x} will certainly be incremented but the incremented value may
  2838. not stick. If the incrementation of @code{x} happens after the
  2839. assignment to @code{x}, the incremented value will remain in place.
  2840. But if the incrementation happens first, the assignment will overwrite
  2841. that with the not-yet-incremented value, so the expression as a whole
  2842. will leave @code{x} unchanged.
  2843. @node Ordering of Operands
  2844. @section Ordering of Operands
  2845. @cindex ordering of operands
  2846. @cindex operand ordering
  2847. Operands and arguments can be computed in any order, but there are limits to
  2848. this intermixing in GNU C:
  2849. @itemize @bullet
  2850. @item
  2851. The operands of a binary arithmetic operator can be computed in either
  2852. order, but they can't be intermixed: one of them has to come first,
  2853. followed by the other. Any side effects in the operand that's computed
  2854. first are executed before the other operand is computed.
  2855. @item
  2856. That applies to assignment operators too, except that in simple assignment
  2857. the previous value of the left operand is unused.
  2858. @item
  2859. The arguments in a function call can be computed in any order, but
  2860. they can't be intermixed. Thus, one argument is fully computed, then
  2861. another, and so on until they are all done. Any side effects in one argument
  2862. are executed before computation of another argument begins.
  2863. @end itemize
  2864. These rules don't cover side effects caused by postincrement and
  2865. postdecrement operators---those can be deferred up to the next
  2866. sequence point.
  2867. If you want to get pedantic, the fact is that GCC can reorder the
  2868. computations in many other ways provided that doesn't alter the result
  2869. of running the program. However, because they don't alter the result
  2870. of running the program, they are negligible, unless you are concerned
  2871. with the values in certain variables at various times as seen by other
  2872. processes. In those cases, you can use @code{volatile} to prevent
  2873. optimizations that would make them behave strangely. @xref{volatile}.
  2874. @node Optimization and Ordering
  2875. @section Optimization and Ordering
  2876. @cindex optimization and ordering
  2877. @cindex ordering and optimization
  2878. Sequence points limit the compiler's freedom to reorder operations
  2879. arbitrarily, but optimizations can still reorder them if the compiler
  2880. concludes that this won't alter the results. Thus, in this code,
  2881. @example
  2882. x++;
  2883. y = z;
  2884. x++;
  2885. @end example
  2886. @noindent
  2887. there is a sequence point after each statement, so the code is
  2888. supposed to increment @code{x} once before the assignment to @code{y}
  2889. and once after. However, incrementing @code{x} has no effect on
  2890. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2891. the code could be optimized into this:
  2892. @example
  2893. y = z;
  2894. x += 2;
  2895. @end example
  2896. Normally that has no effect except to make the program faster. But
  2897. there are special situations where it can cause trouble due to things
  2898. that the compiler cannot know about, such as shared memory. To limit
  2899. optimization in those places, use the @code{volatile} type qualifier
  2900. (@pxref{volatile}).
  2901. @node Primitive Types
  2902. @chapter Primitive Data Types
  2903. @cindex primitive types
  2904. @cindex types, primitive
  2905. This chapter describes all the primitive data types of C---that is,
  2906. all the data types that aren't built up from other types. They
  2907. include the types @code{int} and @code{double} that we've already covered.
  2908. @menu
  2909. * Integer Types:: Description of integer types.
  2910. * Floating-Point Data Types:: Description of floating-point types.
  2911. * Complex Data Types:: Description of complex number types.
  2912. * The Void Type:: A type indicating no value at all.
  2913. * Other Data Types:: A brief summary of other types.
  2914. * Type Designators:: Referring to a data type abstractly.
  2915. @end menu
  2916. These types are all made up of bytes (@pxref{Storage}).
  2917. @node Integer Types
  2918. @section Integer Data Types
  2919. @cindex integer types
  2920. @cindex types, integer
  2921. Here we describe all the integer types and their basic
  2922. characteristics. @xref{Integers in Depth}, for more information about
  2923. the bit-level integer data representations and arithmetic.
  2924. @menu
  2925. * Basic Integers:: Overview of the various kinds of integers.
  2926. * Signed and Unsigned Types:: Integers can either hold both negative and
  2927. non-negative values, or only non-negative.
  2928. * Narrow Integers:: When to use smaller integer types.
  2929. * Integer Conversion:: Casting a value from one integer type
  2930. to another.
  2931. * Boolean Type:: An integer type for boolean values.
  2932. * Integer Variations:: Sizes of integer types can vary
  2933. across platforms.
  2934. @end menu
  2935. @node Basic Integers
  2936. @subsection Basic Integers
  2937. @findex char
  2938. @findex int
  2939. @findex short int
  2940. @findex long int
  2941. @findex long long int
  2942. Integer data types in C can be signed or unsigned. An unsigned type
  2943. can represent only positive numbers and zero. A signed type can
  2944. represent both positive and negative numbers, in a range spread almost
  2945. equally on both sides of zero.
  2946. Aside from signedness, the integer data types vary in size: how many
  2947. bytes long they are. The size determines how many different integer
  2948. values the type can hold.
  2949. Here's a list of the signed integer data types, with the sizes they
  2950. have on most computers. Each has a corresponding unsigned type; see
  2951. @ref{Signed and Unsigned Types}.
  2952. @table @code
  2953. @item signed char
  2954. One byte (8 bits). This integer type is used mainly for integers that
  2955. represent characters, as part of arrays or other data structures.
  2956. @item short
  2957. @itemx short int
  2958. Two bytes (16 bits).
  2959. @item int
  2960. Four bytes (32 bits).
  2961. @item long
  2962. @itemx long int
  2963. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2964. platform. Typically it is 32 bits on 32-bit computers
  2965. and 64 bits on 64-bit computers, but there are exceptions.
  2966. @item long long
  2967. @itemx long long int
  2968. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2969. incorporated into standard C as of ISO C99.
  2970. @end table
  2971. You can omit @code{int} when you use @code{long} or @code{short}.
  2972. This is harmless and customary.
  2973. @node Signed and Unsigned Types
  2974. @subsection Signed and Unsigned Types
  2975. @cindex signed types
  2976. @cindex unsigned types
  2977. @cindex types, signed
  2978. @cindex types, unsigned
  2979. @findex signed
  2980. @findex unsigned
  2981. An unsigned integer type can represent only positive numbers and zero.
  2982. A signed type can represent both positive and negative number, in a
  2983. range spread almost equally on both sides of zero. For instance,
  2984. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2985. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2986. these types holds 256 different possible values, since they are both 8
  2987. bits wide.
  2988. Write @code{signed} or @code{unsigned} before the type keyword to
  2989. specify a signed or an unsigned type. However, the integer types
  2990. other than @code{char} are signed by default; with them, @code{signed}
  2991. is a no-op.
  2992. Plain @code{char} may be signed or unsigned; this depends on the
  2993. compiler, the machine in use, and its operating system.
  2994. In many programs, it makes no difference whether @code{char} is
  2995. signed. When it does matter, don't leave it to chance; write
  2996. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2997. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2998. Arctic Char. When my meal arrived, I noted that the chef had not
  2999. signed it. So I complained, ``This char is unsigned---I wanted a
  3000. signed char!'' Or rather, I would have said this if I had thought of
  3001. it fast enough.}
  3002. @node Narrow Integers
  3003. @subsection Narrow Integers
  3004. The types that are narrower than @code{int} are rarely used for
  3005. ordinary variables---we declare them @code{int} instead. This is
  3006. because C converts those narrower types to @code{int} for any
  3007. arithmetic. There is literally no reason to declare a local variable
  3008. @code{char}, for instance.
  3009. In particular, if the value is really a character, you should declare
  3010. the variable @code{int}. Not @code{char}! Using that narrow type can
  3011. force the compiler to truncate values for conversion, which is a
  3012. waste. Furthermore, some functions return either a character value,
  3013. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3014. values distinct.
  3015. The narrow integer types are useful as parts of other objects, such as
  3016. arrays and structures. Compare these array declarations, whose sizes
  3017. on 32-bit processors are shown:
  3018. @example
  3019. signed char ac[1000]; /* @r{1000 bytes} */
  3020. short as[1000]; /* @r{2000 bytes} */
  3021. int ai[1000]; /* @r{4000 bytes} */
  3022. long long all[1000]; /* @r{8000 bytes} */
  3023. @end example
  3024. In addition, character strings must be made up of @code{char}s,
  3025. because that's what all the standard library string functions expect.
  3026. Thus, array @code{ac} could be used as a character string, but the
  3027. others could not be.
  3028. @node Integer Conversion
  3029. @subsection Conversion among Integer Types
  3030. C converts between integer types implicitly in many situations. It
  3031. converts the narrow integer types, @code{char} and @code{short}, to
  3032. @code{int} whenever they are used in arithmetic. Assigning a new
  3033. value to an integer variable (or other lvalue) converts the value to
  3034. the variable's type.
  3035. You can also convert one integer type to another explicitly with a
  3036. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3037. The process of conversion to a wider type is straightforward: the
  3038. value is unchanged. The only exception is when converting a negative
  3039. value (in a signed type, obviously) to a wider unsigned type. In that
  3040. case, the result is a positive value with the same bits
  3041. (@pxref{Integers in Depth}).
  3042. @cindex truncation
  3043. Converting to a narrower type, also called @dfn{truncation}, involves
  3044. discarding some of the value's bits. This is not considered overflow
  3045. (@pxref{Integer Overflow}) because loss of significant bits is a
  3046. normal consequence of truncation. Likewise for conversion between
  3047. signed and unsigned types of the same width.
  3048. More information about conversion for assignment is in
  3049. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3050. see @ref{Argument Promotions}.
  3051. @node Boolean Type
  3052. @subsection Boolean Type
  3053. @cindex boolean type
  3054. @cindex type, boolean
  3055. @findex bool
  3056. The unsigned integer type @code{bool} holds truth values: its possible
  3057. values are 0 and 1. Converting any nonzero value to @code{bool}
  3058. results in 1. For example:
  3059. @example
  3060. bool a = 0;
  3061. bool b = 1;
  3062. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3063. @end example
  3064. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3065. the header file @file{stdbool.h}.
  3066. @node Integer Variations
  3067. @subsection Integer Variations
  3068. The integer types of C have standard @emph{names}, but what they
  3069. @emph{mean} varies depending on the kind of platform in use:
  3070. which kind of computer, which operating system, and which compiler.
  3071. It may even depend on the compiler options used.
  3072. Plain @code{char} may be signed or unsigned; this depends on the
  3073. platform, too. Even for GNU C, there is no general rule.
  3074. In theory, all of the integer types' sizes can vary. @code{char} is
  3075. always considered one ``byte'' for C, but it is not necessarily an
  3076. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3077. specifies only that none of these types is narrower than the ones
  3078. above it in the list in @ref{Basic Integers}, and that @code{short}
  3079. has at least 16 bits.
  3080. It is possible that in the future GNU C will support platforms where
  3081. @code{int} is 64 bits long. In practice, however, on today's real
  3082. computers, there is little variation; you can rely on the table
  3083. given previously (@pxref{Basic Integers}).
  3084. To be completely sure of the size of an integer type,
  3085. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3086. Their corresponding unsigned types add @samp{u} at the front.
  3087. To define these, include the header file @file{stdint.h}.
  3088. The GNU C Compiler compiles for some embedded controllers that use two
  3089. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3090. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3091. 32 bits. These processors can't support an ordinary operating system
  3092. (they may have their own specialized operating systems), and most C
  3093. programs do not try to support them.
  3094. @node Floating-Point Data Types
  3095. @section Floating-Point Data Types
  3096. @cindex floating-point types
  3097. @cindex types, floating-point
  3098. @findex double
  3099. @findex float
  3100. @findex long double
  3101. @dfn{Floating point} is the binary analogue of scientific notation:
  3102. internally it represents a number as a fraction and a binary exponent; the
  3103. value is that fraction multiplied by the specified power of 2.
  3104. For instance, to represent 6, the fraction would be 0.75 and the
  3105. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3106. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3107. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3108. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3109. -1 as the exponent.
  3110. These binary exponents are used by machine instructions. You can
  3111. write a floating-point constant this way if you wish, using
  3112. hexadecimal; but normally we write floating-point numbers in decimal.
  3113. @xref{Floating Constants}.
  3114. C has three floating-point data types:
  3115. @table @code
  3116. @item double
  3117. ``Double-precision'' floating point, which uses 64 bits. This is the
  3118. normal floating-point type, and modern computers normally do
  3119. their floating-point computations in this type, or some wider type.
  3120. Except when there is a special reason to do otherwise, this is the
  3121. type to use for floating-point values.
  3122. @item float
  3123. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3124. for floating-point values stored in structures and arrays, to save
  3125. space when the full precision of @code{double} is not needed. In
  3126. addition, single-precision arithmetic is faster on some computers, and
  3127. occasionally that is useful. But not often---most programs don't use
  3128. the type @code{float}.
  3129. C would be cleaner if @code{float} were the name of the type we
  3130. use for most floating-point values; however, for historical reasons,
  3131. that's not so.
  3132. @item long double
  3133. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3134. precision, depending on the machine in use. On some machines, which
  3135. have no floating-point format wider than @code{double}, this is
  3136. equivalent to @code{double}.
  3137. @end table
  3138. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3139. Point in Depth}, for more information.
  3140. @node Complex Data Types
  3141. @section Complex Data Types
  3142. @cindex complex numbers
  3143. @cindex types, complex
  3144. @cindex @code{_Complex} keyword
  3145. @cindex @code{__complex__} keyword
  3146. @findex _Complex
  3147. @findex __complex__
  3148. Complex numbers can include both a real part and an imaginary part.
  3149. The numeric constants covered above have real-numbered values. An
  3150. imaginary-valued constant is an ordinary real-valued constant followed
  3151. by @samp{i}.
  3152. To declare numeric variables as complex, use the @code{_Complex}
  3153. keyword.@footnote{For compatibility with older versions of GNU C, the
  3154. keyword @code{__complex__} is also allowed. Going forward, however,
  3155. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3156. standard C complex data types are floating point,
  3157. @example
  3158. _Complex float foo;
  3159. _Complex double bar;
  3160. _Complex long double quux;
  3161. @end example
  3162. @noindent
  3163. but GNU C supports integer complex types as well.
  3164. Since @code{_Complex} is a keyword just like @code{float} and
  3165. @code{double} and @code{long}, the keywords can appear in any order,
  3166. but the order shown above seems most logical.
  3167. GNU C supports constants for complex values; for instance, @code{4.0 +
  3168. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3169. @xref{Imaginary Constants}.
  3170. To pull the real and imaginary parts of the number back out, GNU C
  3171. provides the keywords @code{__real__} and @code{__imag__}:
  3172. @example
  3173. _Complex double foo = 4.0 + 3.0i;
  3174. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3175. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3176. @end example
  3177. @noindent
  3178. Standard C does not include these keywords, and instead relies on
  3179. functions defined in @code{complex.h} for accessing the real and
  3180. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3181. @code{creall} extract the real part of a float, double, or long double
  3182. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3183. @code{cimagl} extract the imaginary part.
  3184. @cindex complex conjugation
  3185. GNU C also defines @samp{~} as an operator for complex conjugation,
  3186. which means negating the imaginary part of a complex number:
  3187. @example
  3188. _Complex double foo = 4.0 + 3.0i;
  3189. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3190. @end example
  3191. @noindent
  3192. For standard C compatibility, you can use the appropriate library
  3193. function: @code{conjf}, @code{conj}, or @code{confl}.
  3194. @node The Void Type
  3195. @section The Void Type
  3196. @cindex void type
  3197. @cindex type, void
  3198. @findex void
  3199. The data type @code{void} is a dummy---it allows no operations. It
  3200. really means ``no value at all.'' When a function is meant to return
  3201. no value, we write @code{void} for its return type. Then
  3202. @code{return} statements in that function should not specify a value
  3203. (@pxref{return Statement}). Here's an example:
  3204. @example
  3205. void
  3206. print_if_positive (double x, double y)
  3207. @{
  3208. if (x <= 0)
  3209. return;
  3210. if (y <= 0)
  3211. return;
  3212. printf ("Next point is (%f,%f)\n", x, y);
  3213. @}
  3214. @end example
  3215. A @code{void}-returning function is comparable to what some other languages
  3216. call a ``procedure'' instead of a ``function.''
  3217. @c ??? Already presented
  3218. @c @samp{%f} in an output template specifies to format a @code{double} value
  3219. @c as a decimal number, using a decimal point if needed.
  3220. @node Other Data Types
  3221. @section Other Data Types
  3222. Beyond the primitive types, C provides several ways to construct new
  3223. data types. For instance, you can define @dfn{pointers}, values that
  3224. represent the addresses of other data (@pxref{Pointers}). You can
  3225. define @dfn{structures}, as in many other languages
  3226. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3227. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3228. are collections of named integer codes (@pxref{Enumeration Types}).
  3229. @dfn{Array types} in C are used for allocating space for objects,
  3230. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3231. @node Type Designators
  3232. @section Type Designators
  3233. @cindex type designator
  3234. Some C constructs require a way to designate a specific data type
  3235. independent of any particular variable or expression which has that
  3236. type. The way to do this is with a @dfn{type designator}. The
  3237. constucts that need one include casts (@pxref{Explicit Type
  3238. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3239. We also use type designators to talk about the type of a value in C,
  3240. so you will see many type designators in this manual. When we say,
  3241. ``The value has type @code{int},'' @code{int} is a type designator.
  3242. To make the designator for any type, imagine a variable declaration
  3243. for a variable of that type and delete the variable name and the final
  3244. semicolon.
  3245. For example, to designate the type of full-word integers, we start
  3246. with the declaration for a variable @code{foo} with that type,
  3247. which is this:
  3248. @example
  3249. int foo;
  3250. @end example
  3251. @noindent
  3252. Then we delete the variable name @code{foo} and the semicolon, leaving
  3253. @code{int}---exactly the keyword used in such a declaration.
  3254. Therefore, the type designator for this type is @code{int}.
  3255. What about long unsigned integers? From the declaration
  3256. @example
  3257. unsigned long int foo;
  3258. @end example
  3259. @noindent
  3260. we determine that the designator is @code{unsigned long int}.
  3261. Following this procedure, the designator for any primitive type is
  3262. simply the set of keywords which specifies that type in a declaration.
  3263. The same is true for compound types such as structures, unions, and
  3264. enumerations.
  3265. Designators for pointer types do follow the rule of deleting the
  3266. variable name and semicolon, but the result is not so simple.
  3267. @xref{Pointer Type Designators}, as part of the chapter about
  3268. pointers. @xref{Array Type Designators}), for designators for array
  3269. types.
  3270. To understand what type a designator stands for, imagine a variable
  3271. name inserted into the right place in the designator to make a valid
  3272. declaration. What type would that variable be declared as? That is the
  3273. type the designator designates.
  3274. @node Constants
  3275. @chapter Constants
  3276. @cindex constants
  3277. A @dfn{constant} is an expression that stands for a specific value by
  3278. explicitly representing the desired value. C allows constants for
  3279. numbers, characters, and strings. We have already seen numeric and
  3280. string constants in the examples.
  3281. @menu
  3282. * Integer Constants:: Literal integer values.
  3283. * Integer Const Type:: Types of literal integer values.
  3284. * Floating Constants:: Literal floating-point values.
  3285. * Imaginary Constants:: Literal imaginary number values.
  3286. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3287. * Character Constants:: Literal character values.
  3288. * String Constants:: Literal string values.
  3289. * UTF-8 String Constants:: Literal UTF-8 string values.
  3290. * Unicode Character Codes:: Unicode characters represented
  3291. in either UTF-16 or UTF-32.
  3292. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3293. * Wide String Constants:: Literal string values made up of
  3294. 16- or 32-bit characters.
  3295. @end menu
  3296. @node Integer Constants
  3297. @section Integer Constants
  3298. @cindex integer constants
  3299. @cindex constants, integer
  3300. An integer constant consists of a number to specify the value,
  3301. followed optionally by suffix letters to specify the data type.
  3302. The simplest integer constants are numbers written in base 10
  3303. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3304. constant cannot start with the character @samp{0} (zero) because
  3305. that makes the constant octal.
  3306. You can get the effect of a negative integer constant by putting a
  3307. minus sign at the beginning. Grammatically speaking, that is an
  3308. arithmetic expression rather than a constant, but it behaves just like
  3309. a true constant.
  3310. Integer constants can also be written in octal (base 8), hexadecimal
  3311. (base 16), or binary (base 2). An octal constant starts with the
  3312. character @samp{0} (zero), followed by any number of octal digits
  3313. (@samp{0} to @samp{7}):
  3314. @example
  3315. 0 // @r{zero}
  3316. 077 // @r{63}
  3317. 0403 // @r{259}
  3318. @end example
  3319. @noindent
  3320. Pedantically speaking, the constant @code{0} is an octal constant, but
  3321. we can think of it as decimal; it has the same value either way.
  3322. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3323. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3324. through @samp{f} in upper or lower case):
  3325. @example
  3326. 0xff // @r{255}
  3327. 0XA0 // @r{160}
  3328. 0xffFF // @r{65535}
  3329. @end example
  3330. @cindex binary integer constants
  3331. A binary constant starts with @samp{0b} (upper or lower case) followed
  3332. by bits (each represented by the characters @samp{0} or @samp{1}):
  3333. @example
  3334. 0b101 // @r{5}
  3335. @end example
  3336. Binary constants are a GNU C extension, not part of the C standard.
  3337. Sometimes a space is needed after an integer constant to avoid
  3338. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3339. @node Integer Const Type
  3340. @section Integer Constant Data Types
  3341. @cindex integer constant data types
  3342. @cindex constant data types, integer
  3343. @cindex types of integer constants
  3344. The type of an integer constant is normally @code{int}, if the value
  3345. fits in that type, but here are the complete rules. The type
  3346. of an integer constant is the first one in this sequence that can
  3347. properly represent the value,
  3348. @enumerate
  3349. @item
  3350. @code{int}
  3351. @item
  3352. @code{unsigned int}
  3353. @item
  3354. @code{long int}
  3355. @item
  3356. @code{unsigned long int}
  3357. @item
  3358. @code{long long int}
  3359. @item
  3360. @code{unsigned long long int}
  3361. @end enumerate
  3362. @noindent
  3363. and that isn't excluded by the following rules.
  3364. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3365. first two types (non-@code{long}).
  3366. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3367. first four types (non-@code{long long}).
  3368. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3369. the signed types.
  3370. Otherwise, if the constant is decimal, that excludes the unsigned
  3371. types.
  3372. @c ### This said @code{unsigned int} is excluded.
  3373. @c ### See 17 April 2016
  3374. Here are some examples of the suffixes.
  3375. @example
  3376. 3000000000u // @r{three billion as @code{unsigned int}.}
  3377. 0LL // @r{zero as a @code{long long int}.}
  3378. 0403l // @r{259 as a @code{long int}.}
  3379. @end example
  3380. Suffixes in integer constants are rarely used. When the precise type
  3381. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3382. Type Conversion}).
  3383. @xref{Integer Types}.
  3384. @node Floating Constants
  3385. @section Floating-Point Constants
  3386. @cindex floating-point constants
  3387. @cindex constants, floating-point
  3388. A floating-point constant must have either a decimal point, an
  3389. exponent-of-ten, or both; they distinguish it from an integer
  3390. constant.
  3391. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3392. value follows. It is always written as a decimal number; it can
  3393. optionally start with a sign. The exponent @var{n} means to multiply
  3394. the constant's value by ten to the @var{n}th power.
  3395. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3396. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3397. writing a floating-point number whose value is 1500. They are all
  3398. equivalent.
  3399. Here are more examples with decimal points:
  3400. @example
  3401. 1.0
  3402. 1000.
  3403. 3.14159
  3404. .05
  3405. .0005
  3406. @end example
  3407. For each of them, here are some equivalent constants written with
  3408. exponents:
  3409. @example
  3410. 1e0, 1.0000e0
  3411. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3412. 3.14159e0
  3413. 5e-2, .0005e+2, 5E-2, .0005E2
  3414. .05e-2
  3415. @end example
  3416. A floating-point constant normally has type @code{double}. You can
  3417. force it to type @code{float} by adding @samp{f} or @samp{F}
  3418. at the end. For example,
  3419. @example
  3420. 3.14159f
  3421. 3.14159e0f
  3422. 1000.f
  3423. 100E1F
  3424. .0005f
  3425. .05e-2f
  3426. @end example
  3427. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3428. to type @code{long double}.
  3429. You can use exponents in hexadecimal floating constants, but since
  3430. @samp{e} would be interpreted as a hexadecimal digit, the character
  3431. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3432. The exponent in a hexadecimal floating constant is a possibly-signed
  3433. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3434. multiply into the number.
  3435. Here are some examples:
  3436. @example
  3437. @group
  3438. 0xAp2 // @r{40 in decimal}
  3439. 0xAp-1 // @r{5 in decimal}
  3440. 0x2.0Bp4 // @r{16.75 decimal}
  3441. 0xE.2p3 // @r{121 decimal}
  3442. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3443. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3444. 0x100p-8 // @r{1}
  3445. 0x10p-4 // @r{1}
  3446. 0x1p+4 // @r{16}
  3447. 0x1p+8 // @r{256}
  3448. @end group
  3449. @end example
  3450. @xref{Floating-Point Data Types}.
  3451. @node Imaginary Constants
  3452. @section Imaginary Constants
  3453. @cindex imaginary constants
  3454. @cindex complex constants
  3455. @cindex constants, imaginary
  3456. A complex number consists of a real part plus an imaginary part.
  3457. (Either or both parts may be zero.) This section explains how to
  3458. write numeric constants with imaginary values. By adding these to
  3459. ordinary real-valued numeric constants, we can make constants with
  3460. complex values.
  3461. The simple way to write an imaginary-number constant is to attach the
  3462. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3463. floating-point constant. For example, @code{2.5fi} has type
  3464. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3465. The four alternative suffix letters are all equivalent.
  3466. @cindex _Complex_I
  3467. The other way to write an imaginary constant is to multiply a real
  3468. constant by @code{_Complex_I}, which represents the imaginary number
  3469. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3470. this clunky way is needed.
  3471. To write a complex constant with a nonzero real part and a nonzero
  3472. imaginary part, write the two separately and add them, like this:
  3473. @example
  3474. 4.0 + 3.0i
  3475. @end example
  3476. @noindent
  3477. That gives the value 4 + 3i, with type @code{_Complex double}.
  3478. Such a sum can include multiple real constants, or none. Likewise, it
  3479. can include multiple imaginary constants, or none. For example:
  3480. @example
  3481. _Complex double foo, bar, quux;
  3482. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3483. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3484. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3485. @end example
  3486. @xref{Complex Data Types}.
  3487. @node Invalid Numbers
  3488. @section Invalid Numbers
  3489. Some number-like constructs which are not really valid as numeric
  3490. constants are treated as numbers in preprocessing directives. If
  3491. these constructs appear outside of preprocessing, they are erroneous.
  3492. @xref{Preprocessing Tokens}.
  3493. Sometimes we need to insert spaces to separate tokens so that they
  3494. won't be combined into a single number-like construct. For example,
  3495. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3496. constant, so it is a syntax error. If what we want is the three
  3497. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3498. @node Character Constants
  3499. @section Character Constants
  3500. @cindex character constants
  3501. @cindex constants, character
  3502. @cindex escape sequence
  3503. A @dfn{character constant} is written with single quotes, as in
  3504. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3505. character that the constant should represent. The constant has type
  3506. @code{int}, and its value is the character code of that character.
  3507. For instance, @code{'a'} represents the character code for the letter
  3508. @samp{a}: 97, that is.
  3509. To put the @samp{'} character (single quote) in the character
  3510. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3511. constant looks like @code{'\''}. This sort of sequence, starting with
  3512. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3513. here functions as a kind of @dfn{escape character}.
  3514. To put the @samp{\} character (backslash) in the character constant,
  3515. quote it likewise with @samp{\} (another backslash). This character
  3516. constant looks like @code{'\\'}.
  3517. @cindex bell character
  3518. @cindex @samp{\a}
  3519. @cindex backspace
  3520. @cindex @samp{\b}
  3521. @cindex tab (ASCII character)
  3522. @cindex @samp{\t}
  3523. @cindex vertical tab
  3524. @cindex @samp{\v}
  3525. @cindex formfeed
  3526. @cindex @samp{\f}
  3527. @cindex newline
  3528. @cindex @samp{\n}
  3529. @cindex return (ASCII character)
  3530. @cindex @samp{\r}
  3531. @cindex escape (ASCII character)
  3532. @cindex @samp{\e}
  3533. Here are all the escape sequences that represent specific
  3534. characters in a character constant. The numeric values shown are
  3535. the corresponding ASCII character codes, as decimal numbers.
  3536. @example
  3537. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3538. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3539. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3540. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3541. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3542. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3543. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3544. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3545. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3546. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3547. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3548. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3549. @end example
  3550. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3551. You can also write octal and hex character codes as
  3552. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3553. option here, so octal codes do not need to start with @samp{0}.
  3554. The character constant's value has type @code{int}. However, the
  3555. character code is treated initially as a @code{char} value, which is
  3556. then converted to @code{int}. If the character code is greater than
  3557. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3558. on a platform where the type @code{char} is 8 bits long and signed.
  3559. @node String Constants
  3560. @section String Constants
  3561. @cindex string constants
  3562. @cindex constants, string
  3563. A @dfn{string constant} represents a series of characters. It starts
  3564. with @samp{"} and ends with @samp{"}; in between are the contents of
  3565. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3566. newline in the contents works in string constants as in character
  3567. constants. In a string constant, @samp{'} does not need to be quoted.
  3568. A string constant defines an array of characters which contains the
  3569. specified characters followed by the null character (code 0). Using
  3570. the string constant is equivalent to using the name of an array with
  3571. those contents. In simple cases, the length in bytes of the string
  3572. constant is one greater than the number of characters written in it.
  3573. As with any array in C, using the string constant in an expression
  3574. converts the array to a pointer (@pxref{Pointers}) to the array's
  3575. first element (@pxref{Accessing Array Elements}). This pointer will
  3576. have type @code{char *} because it points to an element of type
  3577. @code{char}. @code{char *} is an example of a type designator for a
  3578. pointer type (@pxref{Pointer Type Designators}). That type is used
  3579. for strings generally, not just the strings expressed as constants
  3580. in a program.
  3581. Thus, the string constant @code{"Foo!"} is almost
  3582. equivalent to declaring an array like this
  3583. @example
  3584. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3585. @end example
  3586. @noindent
  3587. and then using @code{string_array_1} in the program. There
  3588. are two differences, however:
  3589. @itemize @bullet
  3590. @item
  3591. The string constant doesn't define a name for the array.
  3592. @item
  3593. The string constant is probably stored in a read-only area of memory.
  3594. @end itemize
  3595. Newlines are not allowed in the text of a string constant. The motive
  3596. for this prohibition is to catch the error of omitting the closing
  3597. @samp{"}. To put a newline in a constant string, write it as
  3598. @samp{\n} in the string constant.
  3599. A real null character in the source code inside a string constant
  3600. causes a warning. To put a null character in the middle of a string
  3601. constant, write @samp{\0} or @samp{\000}.
  3602. Consecutive string constants are effectively concatenated. Thus,
  3603. @example
  3604. "Fo" "o!" @r{is equivalent to} "Foo!"
  3605. @end example
  3606. This is useful for writing a string containing multiple lines,
  3607. like this:
  3608. @example
  3609. "This message is so long that it needs more than\n"
  3610. "a single line of text. C does not allow a newline\n"
  3611. "to represent itself in a string constant, so we have to\n"
  3612. "write \\n to put it in the string. For readability of\n"
  3613. "the source code, it is advisable to put line breaks in\n"
  3614. "the source where they occur in the contents of the\n"
  3615. "constant.\n"
  3616. @end example
  3617. The sequence of a backslash and a newline is ignored anywhere
  3618. in a C program, and that includes inside a string constant.
  3619. Thus, you can write multi-line string constants this way:
  3620. @example
  3621. "This is another way to put newlines in a string constant\n\
  3622. and break the line after them in the source code."
  3623. @end example
  3624. @noindent
  3625. However, concatenation is the recommended way to do this.
  3626. You can also write perverse string constants like this,
  3627. @example
  3628. "Fo\
  3629. o!"
  3630. @end example
  3631. @noindent
  3632. but don't do that---write it like this instead:
  3633. @example
  3634. "Foo!"
  3635. @end example
  3636. Be careful to avoid passing a string constant to a function that
  3637. modifies the string it receives. The memory where the string constant
  3638. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3639. signal that normally terminates the function (@pxref{Signals}. Even
  3640. worse, the memory may not be read-only. Then the function might
  3641. modify the string constant, thus spoiling the contents of other string
  3642. constants that are supposed to contain the same value and are unified
  3643. by the compiler.
  3644. @node UTF-8 String Constants
  3645. @section UTF-8 String Constants
  3646. @cindex UTF-8 String Constants
  3647. Writing @samp{u8} immediately before a string constant, with no
  3648. intervening space, means to represent that string in UTF-8 encoding as
  3649. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3650. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3651. as multibyte sequences. Here is an example of a UTF-8 constant:
  3652. @example
  3653. u8"A cónstàñt"
  3654. @end example
  3655. This constant occupies 13 bytes plus the terminating null,
  3656. because each of the accented letters is a two-byte sequence.
  3657. Concatenating an ordinary string with a UTF-8 string conceptually
  3658. produces another UTF-8 string. However, if the ordinary string
  3659. contains character codes 128 and up, the results cannot be relied on.
  3660. @node Unicode Character Codes
  3661. @section Unicode Character Codes
  3662. @cindex Unicode character codes
  3663. @cindex universal character names
  3664. You can specify Unicode characters, for individual character constants
  3665. or as part of string constants (@pxref{String Constants}), using
  3666. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3667. hexadecimal Unicode character code. If the code value is too big for
  3668. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3669. Unicode character code. (These codes are called @dfn{universal
  3670. character names}.) For example,
  3671. @example
  3672. \u6C34 /* @r{16-bit code (UTF-16)} */
  3673. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3674. @end example
  3675. @noindent
  3676. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3677. Constants}). For instance,
  3678. @example
  3679. u8"fóó \u6C34 \U0010ABCD"
  3680. @end example
  3681. You can also use them in wide character constants (@pxref{Wide
  3682. Character Constants}), like this:
  3683. @example
  3684. u'\u6C34' /* @r{16-bit code} */
  3685. U'\U0010ABCD' /* @r{32-bit code} */
  3686. @end example
  3687. @noindent
  3688. and in wide string constants (@pxref{Wide String Constants}), like
  3689. this:
  3690. @example
  3691. u"\u6C34\u6C33" /* @r{16-bit code} */
  3692. U"\U0010ABCD" /* @r{32-bit code} */
  3693. @end example
  3694. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3695. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3696. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3697. actually ASCII control characters, and you can specify them with other
  3698. escape sequences (@pxref{Character Constants}).
  3699. @node Wide Character Constants
  3700. @section Wide Character Constants
  3701. @cindex wide character constants
  3702. @cindex constants, wide character
  3703. A @dfn{wide character constant} represents characters with more than 8
  3704. bits of character code. This is an obscure feature that we need to
  3705. document but that you probably won't ever use. If you're just
  3706. learning C, you may as well skip this section.
  3707. The original C wide character constant looks like @samp{L} (upper
  3708. case!) followed immediately by an ordinary character constant (with no
  3709. intervening space). Its data type is @code{wchar_t}, which is an
  3710. alias defined in @file{stddef.h} for one of the standard integer
  3711. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3712. it is 16 bits, these character constants use the UTF-16 form of
  3713. Unicode; if 32 bits, UTF-32.
  3714. There are also Unicode wide character constants which explicitly
  3715. specify the width. These constants start with @samp{u} or @samp{U}
  3716. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3717. character constant, and @samp{U} a 32-bit Unicode wide character
  3718. constant. Their types are, respectively, @code{char16_t} and
  3719. @w{@code{char32_t}}; they are declared in the header file
  3720. @file{uchar.h}. These character constants are valid even if
  3721. @file{uchar.h} is not included, but some uses of them may be
  3722. inconvenient without including it to declare those type names.
  3723. The character represented in a wide character constant can be an
  3724. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3725. are all valid, and they are all equal to @code{'a'}.
  3726. In all three kinds of wide character constants, you can write a
  3727. non-ASCII Unicode character in the constant itself; the constant's
  3728. value is the character's Unicode character code. Or you can specify
  3729. the Unicode character with an escape sequence (@pxref{Unicode
  3730. Character Codes}).
  3731. @node Wide String Constants
  3732. @section Wide String Constants
  3733. @cindex wide string constants
  3734. @cindex constants, wide string
  3735. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3736. characters. They are rarely used; if you're just
  3737. learning C, you may as well skip this section.
  3738. There are three kinds of wide string constants, which differ in the
  3739. data type used for each character in the string. Each wide string
  3740. constant is equivalent to an array of integers, but the data type of
  3741. those integers depends on the kind of wide string. Using the constant
  3742. in an expression will convert the array to a pointer to its first
  3743. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3744. For each kind of wide string constant, we state here what type that
  3745. pointer will be.
  3746. @table @code
  3747. @item char16_t
  3748. This is a 16-bit Unicode wide string constant: each element is a
  3749. 16-bit Unicode character code with type @code{char16_t}, so the string
  3750. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3751. @pxref{Pointer Type Designators}.) The constant is written as
  3752. @samp{u} (which must be lower case) followed (with no intervening
  3753. space) by a string constant with the usual syntax.
  3754. @item char32_t
  3755. This is a 32-bit Unicode wide string constant: each element is a
  3756. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3757. It's written as @samp{U} (which must be upper case) followed (with no
  3758. intervening space) by a string constant with the usual syntax.
  3759. @item wchar_t
  3760. This is the original kind of wide string constant. It's written as
  3761. @samp{L} (which must be upper case) followed (with no intervening
  3762. space) by a string constant with the usual syntax, and the string has
  3763. type @code{wchar_t@ *}.
  3764. The width of the data type @code{wchar_t} depends on the target
  3765. platform, which makes this kind of wide string somewhat less useful
  3766. than the newer kinds.
  3767. @end table
  3768. @code{char16_t} and @code{char32_t} are declared in the header file
  3769. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3770. Consecutive wide string constants of the same kind concatenate, just
  3771. like ordinary string constants. A wide string constant concatenated
  3772. with an ordinary string constant results in a wide string constant.
  3773. You can't concatenate two wide string constants of different kinds.
  3774. You also can't concatenate a wide string constant (of any kind) with a
  3775. UTF-8 string constant.
  3776. @node Type Size
  3777. @chapter Type Size
  3778. @cindex type size
  3779. @cindex size of type
  3780. @findex sizeof
  3781. Each data type has a @dfn{size}, which is the number of bytes
  3782. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3783. a C program, use @code{sizeof}. There are two ways to use it:
  3784. @table @code
  3785. @item sizeof @var{expression}
  3786. This gives the size of @var{expression}, based on its data type. It
  3787. does not calculate the value of @var{expression}, only its size, so if
  3788. @var{expression} includes side effects or function calls, they do not
  3789. happen. Therefore, @code{sizeof} is always a compile-time operation
  3790. that has zero run-time cost.
  3791. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3792. operand of @code{sizeof}.
  3793. For example,
  3794. @example
  3795. double a;
  3796. i = sizeof a + 10;
  3797. @end example
  3798. @noindent
  3799. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3800. Here's how to determine the number of elements in an array
  3801. @code{array}:
  3802. @example
  3803. (sizeof array / sizeof array[0])
  3804. @end example
  3805. @noindent
  3806. The expression @code{sizeof array} gives the size of the array, not
  3807. the size of a pointer to an element. However, if @var{expression} is
  3808. a function parameter that was declared as an array, that
  3809. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3810. the result is the size of that pointer.
  3811. @item sizeof (@var{type})
  3812. This gives the size of @var{type}.
  3813. For example,
  3814. @example
  3815. i = sizeof (double) + 10;
  3816. @end example
  3817. @noindent
  3818. is equivalent to the previous example.
  3819. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3820. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3821. C, which makes adding an integer to a function pointer work as desired
  3822. (@pxref{Pointer Arithmetic}).
  3823. @end table
  3824. @strong{Warning}: When you use @code{sizeof} with a type
  3825. instead of an expression, you must write parentheses around the type.
  3826. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3827. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3828. the cast expression to avoid an ambiguity in the grammar of C@.
  3829. Specifically,
  3830. @example
  3831. sizeof (int) -x
  3832. @end example
  3833. @noindent
  3834. parses as
  3835. @example
  3836. (sizeof (int)) - x
  3837. @end example
  3838. @noindent
  3839. If what you want is
  3840. @example
  3841. sizeof ((int) -x)
  3842. @end example
  3843. @noindent
  3844. you must write it that way, with parentheses.
  3845. The data type of the value of the @code{sizeof} operator is always one
  3846. of the unsigned integer types; which one of those types depends on the
  3847. machine. The header file @code{stddef.h} defines the typedef name
  3848. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3849. Names}.
  3850. @node Pointers
  3851. @chapter Pointers
  3852. @cindex pointers
  3853. Among high-level languages, C is rather low level, close to the
  3854. machine. This is mainly because it has explicit @dfn{pointers}. A
  3855. pointer value is the numeric address of data in memory. The type of
  3856. data to be found at that address is specified by the data type of the
  3857. pointer itself. The unary operator @samp{*} gets the data that a
  3858. pointer points to---this is called @dfn{dereferencing the pointer}.
  3859. C also allows pointers to functions, but since there are some
  3860. differences in how they work, we treat them later. @xref{Function
  3861. Pointers}.
  3862. @menu
  3863. * Address of Data:: Using the ``address-of'' operator.
  3864. * Pointer Types:: For each type, there is a pointer type.
  3865. * Pointer Declarations:: Declaring variables with pointer types.
  3866. * Pointer Type Designators:: Designators for pointer types.
  3867. * Pointer Dereference:: Accessing what a pointer points at.
  3868. * Null Pointers:: Pointers which do not point to any object.
  3869. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3870. * Void Pointers:: Totally generic pointers, can cast to any.
  3871. * Pointer Comparison:: Comparing memory address values.
  3872. * Pointer Arithmetic:: Computing memory address values.
  3873. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3874. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3875. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3876. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3877. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3878. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3879. @end menu
  3880. @node Address of Data
  3881. @section Address of Data
  3882. @cindex address-of operator
  3883. The most basic way to make a pointer is with the ``address-of''
  3884. operator, @samp{&}. Let's suppose we have these variables available:
  3885. @example
  3886. int i;
  3887. double a[5];
  3888. @end example
  3889. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3890. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3891. address of the element 3 of @code{a}. (It is actually the fourth
  3892. element in the array, since the first element has index 0.)
  3893. The address-of operator is unusual because it operates on a place to
  3894. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3895. stored there. (The left argument of a simple assignment is unusual in
  3896. the same way.) You can use it on any lvalue except a bit field
  3897. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3898. Constructors}).
  3899. @node Pointer Types
  3900. @section Pointer Types
  3901. For each data type @var{t}, there is a type for pointers to type
  3902. @var{t}. For these variables,
  3903. @example
  3904. int i;
  3905. double a[5];
  3906. @end example
  3907. @itemize @bullet
  3908. @item
  3909. @code{i} has type @code{int}; we say
  3910. @code{&i} is a ``pointer to @code{int}.''
  3911. @item
  3912. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3913. arrays of five @code{double}s.''
  3914. @item
  3915. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3916. to @code{double}.''
  3917. @end itemize
  3918. @node Pointer Declarations
  3919. @section Pointer-Variable Declarations
  3920. The way to declare that a variable @code{foo} points to type @var{t} is
  3921. @example
  3922. @var{t} *foo;
  3923. @end example
  3924. To remember this syntax, think ``if you dereference @code{foo}, using
  3925. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3926. points to type @var{t}.''
  3927. Thus, we can declare variables that hold pointers to these three
  3928. types, like this:
  3929. @example
  3930. int *ptri; /* @r{Pointer to @code{int}.} */
  3931. double *ptrd; /* @r{Pointer to @code{double}.} */
  3932. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3933. @end example
  3934. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3935. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3936. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3937. @code{double}.'' The parentheses express the point that you would
  3938. dereference it first, then subscript it.
  3939. Contrast the last one with this:
  3940. @example
  3941. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3942. @end example
  3943. @noindent
  3944. Because @samp{*} has higher syntactic precedence than subscripting,
  3945. you would subscript @code{aptrd} then dereference it. Therefore, it
  3946. declares an array of pointers, not a pointer.
  3947. @node Pointer Type Designators
  3948. @section Pointer-Type Designators
  3949. Every type in C has a designator; you make it by deleting the variable
  3950. name and the semicolon from a declaration (@pxref{Type
  3951. Designators}). Here are the designators for the pointer
  3952. types of the example declarations in the previous section:
  3953. @example
  3954. int * /* @r{Pointer to @code{int}.} */
  3955. double * /* @r{Pointer to @code{double}.} */
  3956. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3957. @end example
  3958. Remember, to understand what type a designator stands for, imagine the
  3959. variable name that would be in the declaration, and figure out what
  3960. type it would declare that variable with. @code{double (*)[5]} can
  3961. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3962. which, when dereferenced, gives an array of 5 @code{double}s.
  3963. @node Pointer Dereference
  3964. @section Dereferencing Pointers
  3965. @cindex dereferencing pointers
  3966. @cindex pointer dereferencing
  3967. The main use of a pointer value is to @dfn{dereference it} (access the
  3968. data it points at) with the unary @samp{*} operator. For instance,
  3969. @code{*&i} is the value at @code{i}'s address---which is just
  3970. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3971. valid.
  3972. A pointer-dereference expression whose type is data (not a function)
  3973. is an lvalue.
  3974. Pointers become really useful when we store them somewhere and use
  3975. them later. Here's a simple example to illustrate the practice:
  3976. @example
  3977. @{
  3978. int i;
  3979. int *ptr;
  3980. ptr = &i;
  3981. i = 5;
  3982. @r{@dots{}}
  3983. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3984. @}
  3985. @end example
  3986. This shows how to declare the variable @code{ptr} as type
  3987. @code{int *} (pointer to @code{int}), store a pointer value into it
  3988. (pointing at @code{i}), and use it later to get the value of the
  3989. object it points at (the value in @code{i}).
  3990. If anyone can provide a useful example which is this basic,
  3991. I would be grateful.
  3992. @node Null Pointers
  3993. @section Null Pointers
  3994. @cindex null pointers
  3995. @cindex pointers, null
  3996. @c ???stdio loads sttddef
  3997. A pointer value can be @dfn{null}, which means it does not point to
  3998. any object. The cleanest way to get a null pointer is by writing
  3999. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  4000. also do it by casting 0 to the desired pointer type, as in
  4001. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  4002. @xref{Explicit Type Conversion}.)
  4003. You can store a null pointer in any lvalue whose data type
  4004. is a pointer type:
  4005. @example
  4006. char *foo;
  4007. foo = NULL;
  4008. @end example
  4009. These two, if consecutive, can be combined into a declaration with
  4010. initializer,
  4011. @example
  4012. char *foo = NULL;
  4013. @end example
  4014. You can also explicitly cast @code{NULL} to the specific pointer type
  4015. you want---it makes no difference.
  4016. @example
  4017. char *foo;
  4018. foo = (char *) NULL;
  4019. @end example
  4020. To test whether a pointer is null, compare it with zero or
  4021. @code{NULL}, as shown here:
  4022. @example
  4023. if (p != NULL)
  4024. /* @r{@code{p} is not null.} */
  4025. operate (p);
  4026. @end example
  4027. Since testing a pointer for not being null is basic and frequent, all
  4028. but beginners in C will understand the conditional without need for
  4029. @code{!= NULL}:
  4030. @example
  4031. if (p)
  4032. /* @r{@code{p} is not null.} */
  4033. operate (p);
  4034. @end example
  4035. @node Invalid Dereference
  4036. @section Dereferencing Null or Invalid Pointers
  4037. Trying to dereference a null pointer is an error. On most platforms,
  4038. it generally causes a signal, usually @code{SIGSEGV}
  4039. (@pxref{Signals}).
  4040. @example
  4041. char *foo = NULL;
  4042. c = *foo; /* @r{This causes a signal and terminates.} */
  4043. @end example
  4044. @noindent
  4045. Likewise a pointer that has the wrong alignment for the target data type
  4046. (on most types of computer), or points to a part of memory that has
  4047. not been allocated in the process's address space.
  4048. The signal terminates the program, unless the program has arranged to
  4049. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4050. The GNU C Library Reference Manual}).
  4051. However, the signal might not happen if the dereference is optimized
  4052. away. In the example above, if you don't subsequently use the value
  4053. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4054. can prevent such optimization using the @code{volatile} qualifier, as
  4055. shown here:
  4056. @example
  4057. volatile char *p;
  4058. volatile char c;
  4059. c = *p;
  4060. @end example
  4061. You can use this to test whether @code{p} points to unallocated
  4062. memory. Set up a signal handler first, so the signal won't terminate
  4063. the program.
  4064. @node Void Pointers
  4065. @section Void Pointers
  4066. @cindex void pointers
  4067. @cindex pointers, void
  4068. The peculiar type @code{void *}, a pointer whose target type is
  4069. @code{void}, is used often in C@. It represents a pointer to
  4070. we-don't-say-what. Thus,
  4071. @example
  4072. void *numbered_slot_pointer (int);
  4073. @end example
  4074. @noindent
  4075. declares a function @code{numbered_slot_pointer} that takes an
  4076. integer parameter and returns a pointer, but we don't say what type of
  4077. data it points to.
  4078. With type @code{void *}, you can pass the pointer around and test
  4079. whether it is null. However, dereferencing it gives a @code{void}
  4080. value that can't be used (@pxref{The Void Type}). To dereference the
  4081. pointer, first convert it to some other pointer type.
  4082. Assignments convert @code{void *} automatically to any other pointer
  4083. type, if the left operand has a pointer type; for instance,
  4084. @example
  4085. @{
  4086. int *p;
  4087. /* @r{Converts return value to @code{int *}.} */
  4088. p = numbered_slot_pointer (5);
  4089. @r{@dots{}}
  4090. @}
  4091. @end example
  4092. Passing an argument of type @code{void *} for a parameter that has a
  4093. pointer type also converts. For example, supposing the function
  4094. @code{hack} is declared to require type @code{float *} for its
  4095. argument, this will convert the null pointer to that type.
  4096. @example
  4097. /* @r{Declare @code{hack} that way.}
  4098. @r{We assume it is defined somewhere else.} */
  4099. void hack (float *);
  4100. @dots{}
  4101. /* @r{Now call @code{hack}.} */
  4102. @{
  4103. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4104. @r{to @code{float *} to pass it to @code{hack}.} */
  4105. hack (numbered_slot_pointer (5));
  4106. @r{@dots{}}
  4107. @}
  4108. @end example
  4109. You can also convert to another pointer type with an explicit cast
  4110. (@pxref{Explicit Type Conversion}), like this:
  4111. @example
  4112. (int *) numbered_slot_pointer (5)
  4113. @end example
  4114. Here is an example which decides at run time which pointer
  4115. type to convert to:
  4116. @example
  4117. void
  4118. extract_int_or_double (void *ptr, bool its_an_int)
  4119. @{
  4120. if (its_an_int)
  4121. handle_an_int (*(int *)ptr);
  4122. else
  4123. handle_a_double (*(double *)ptr);
  4124. @}
  4125. @end example
  4126. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4127. to type @code{int *}, then dereference it.
  4128. @node Pointer Comparison
  4129. @section Pointer Comparison
  4130. @cindex pointer comparison
  4131. @cindex comparison, pointer
  4132. Two pointer values are equal if they point to the same location, or if
  4133. they are both null. You can test for this with @code{==} and
  4134. @code{!=}. Here's a trivial example:
  4135. @example
  4136. @{
  4137. int i;
  4138. int *p, *q;
  4139. p = &i;
  4140. q = &i;
  4141. if (p == q)
  4142. printf ("This will be printed.\n");
  4143. if (p != q)
  4144. printf ("This won't be printed.\n");
  4145. @}
  4146. @end example
  4147. Ordering comparisons such as @code{>} and @code{>=} operate on
  4148. pointers by converting them to unsigned integers. The C standard says
  4149. the two pointers must point within the same object in memory, but on
  4150. GNU/Linux systems these operations simply compare the numeric values
  4151. of the pointers.
  4152. The pointer values to be compared should in principle have the same type, but
  4153. they are allowed to differ in limited cases. First of all, if the two
  4154. pointers' target types are nearly compatible (@pxref{Compatible
  4155. Types}), the comparison is allowed.
  4156. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4157. the other is another pointer type, the comparison operator converts
  4158. the @code{void *} pointer to the other type so as to compare them.
  4159. (In standard C, this is not allowed if the other type is a function
  4160. pointer type, but that works in GNU C@.)
  4161. Comparison operators also allow comparing the integer 0 with a pointer
  4162. value. Thus works by converting 0 to a null pointer of the same type
  4163. as the other operand.
  4164. @node Pointer Arithmetic
  4165. @section Pointer Arithmetic
  4166. @cindex pointer arithmetic
  4167. @cindex arithmetic, pointer
  4168. Adding an integer (positive or negative) to a pointer is valid in C@.
  4169. It assumes that the pointer points to an element in an array, and
  4170. advances or retracts the pointer across as many array elements as the
  4171. integer specifies. Here is an example, in which adding a positive
  4172. integer advances the pointer to a later element in the same array.
  4173. @example
  4174. void
  4175. incrementing_pointers ()
  4176. @{
  4177. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4178. int elt0, elt1, elt4;
  4179. int *p = &array[0];
  4180. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4181. elt0 = *p;
  4182. ++p;
  4183. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4184. elt1 = *p;
  4185. p += 3;
  4186. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4187. elt4 = *p;
  4188. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4189. elt0, elt1, elt4);
  4190. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4191. @}
  4192. @end example
  4193. Here's an example where adding a negative integer retracts the pointer
  4194. to an earlier element in the same array.
  4195. @example
  4196. void
  4197. decrementing_pointers ()
  4198. @{
  4199. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4200. int elt0, elt3, elt4;
  4201. int *p = &array[4];
  4202. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4203. elt4 = *p;
  4204. --p;
  4205. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4206. elt3 = *p;
  4207. p -= 3;
  4208. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4209. elt0 = *p;
  4210. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4211. elt0, elt3, elt4);
  4212. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4213. @}
  4214. @end example
  4215. If one pointer value was made by adding an integer to another
  4216. pointer value, it should be possible to subtract the pointer values
  4217. and recover that integer. That works too in C@.
  4218. @example
  4219. void
  4220. subtract_pointers ()
  4221. @{
  4222. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4223. int *p0, *p3, *p4;
  4224. int *p = &array[4];
  4225. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4226. p4 = p;
  4227. --p;
  4228. /* @r{Now @code{p} points at element 3. Save the value.} */
  4229. p3 = p;
  4230. p -= 3;
  4231. /* @r{Now @code{p} points at element 0. Save the value.} */
  4232. p0 = p;
  4233. printf ("%d, %d, %d, %d\n",
  4234. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4235. /* @r{Prints 4, 0, 3, -3.} */
  4236. @}
  4237. @end example
  4238. The addition operation does not know where arrays are. All it does is
  4239. add the integer (multiplied by object size) to the value of the
  4240. pointer. When the initial pointer and the result point into a single
  4241. array, the result is well-defined.
  4242. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4243. into different memory objects.
  4244. The difference between two pointers has type @code{int}, or
  4245. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4246. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4247. file @file{stddef.h}.
  4248. This definition of pointer subtraction is consistent with
  4249. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4250. @code{p3}, as in ordinary algebra.
  4251. In standard C, addition and subtraction are not allowed on @code{void
  4252. *}, since the target type's size is not defined in that case.
  4253. Likewise, they are not allowed on pointers to function types.
  4254. However, these operations work in GNU C, and the ``size of the target
  4255. type'' is taken as 1.
  4256. @node Pointers and Arrays
  4257. @section Pointers and Arrays
  4258. @cindex pointers and arrays
  4259. @cindex arrays and pointers
  4260. The clean way to refer to an array element is
  4261. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4262. same job is to get the address of that element as a pointer, then
  4263. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4264. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4265. pointer to element zero, then increments it with @code{+} to point to
  4266. the desired element, then gets the value from there.
  4267. That pointer-arithmetic construct is the @emph{definition} of square
  4268. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4269. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4270. symmetrically, so one must be a pointer and the other an integer; it
  4271. does not matter which comes first.
  4272. Since indexing with square brackets is defined in terms of addition
  4273. and dereference, that too is symmetrical. Thus, you can write
  4274. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4275. would be foolish to write @code{3[array]}, since it has no advantage
  4276. and could confuse people who read the code.
  4277. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4278. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4279. instead. Why is this valid? The name of the array, when used by
  4280. itself as an expression (other than in @code{sizeof}), stands for a
  4281. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4282. converts @code{array} implicitly to @code{&array[0]}, and the result
  4283. is a pointer to element 3, equivalent to @code{&array[3]}.
  4284. Since square brackets are defined in terms of such addition,
  4285. @code{array[3]} first converts @code{array} to a pointer. That's why
  4286. it works to use an array directly in that construct.
  4287. @node Pointer Arithmetic Low Level
  4288. @section Pointer Arithmetic at Low Level
  4289. @cindex pointer arithmetic, low level
  4290. @cindex low level pointer arithmetic
  4291. The behavior of pointer arithmetic is theoretically defined only when
  4292. the pointer values all point within one object allocated in memory.
  4293. But the addition and subtraction operators can't tell whether the
  4294. pointer values are all within one object. They don't know where
  4295. objects start and end. So what do they really do?
  4296. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4297. address, which is in fact an integer---call it @var{pint}. It treats
  4298. @var{i} as a number of elements of the type that @var{p} points to.
  4299. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4300. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4301. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4302. If the starting pointer value @var{p} and the result do not point at
  4303. parts of the same object, the operation is not officially legitimate,
  4304. and C code is not ``supposed'' to do it. But you can do it anyway,
  4305. and it gives precisely the results described by the procedure above.
  4306. In some special situations it can do something useful, but non-wizards
  4307. should avoid it.
  4308. Here's a function to offset a pointer value @emph{as if} it pointed to
  4309. an object of any given size, by explicitly performing that calculation:
  4310. @example
  4311. #include <stdint.h>
  4312. void *
  4313. ptr_add (void *p, int i, int objsize)
  4314. @{
  4315. intptr_t p_address = (long) p;
  4316. intptr_t totalsize = i * objsize;
  4317. intptr_t new_address = p_address + totalsize;
  4318. return (void *) new_address;
  4319. @}
  4320. @end example
  4321. @noindent
  4322. @cindex @code{intptr_t}
  4323. This does the same job as @code{@var{p} + @var{i}} with the proper
  4324. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4325. defined in the header file @file{stdint.h}. (In practice, @code{long
  4326. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4327. @node Pointer Increment/Decrement
  4328. @section Pointer Increment and Decrement
  4329. @cindex pointer increment and decrement
  4330. @cindex incrementing pointers
  4331. @cindex decrementing pointers
  4332. The @samp{++} operator adds 1 to a variable. We have seen it for
  4333. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4334. For instance, suppose we have a series of positive integers,
  4335. terminated by a zero, and we want to add them all up.
  4336. @example
  4337. int
  4338. sum_array_till_0 (int *p)
  4339. @{
  4340. int sum = 0;
  4341. for (;;)
  4342. @{
  4343. /* @r{Fetch the next integer.} */
  4344. int next = *p++;
  4345. /* @r{Exit the loop if it's 0.} */
  4346. if (next == 0)
  4347. break;
  4348. /* @r{Add it into running total.} */
  4349. sum += next;
  4350. @}
  4351. return sum;
  4352. @}
  4353. @end example
  4354. @noindent
  4355. The statement @samp{break;} will be explained further on (@pxref{break
  4356. Statement}). Used in this way, it immediately exits the surrounding
  4357. @code{for} statement.
  4358. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4359. takes precedence over a prefix operator. Therefore, it dereferences
  4360. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4361. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4362. pointer, adding 1 to it advances it by the width of the datum it
  4363. points to---in this case, one @code{int}. Therefore, each iteration
  4364. of the loop picks up the next integer from the series and puts it into
  4365. @code{next}.
  4366. This @code{for}-loop has no initialization expression since @code{p}
  4367. and @code{sum} are already initialized, it has no end-test since the
  4368. @samp{break;} statement will exit it, and needs no expression to
  4369. advance it since that's done within the loop by incrementing @code{p}
  4370. and @code{sum}. Thus, those three expressions after @code{for} are
  4371. left empty.
  4372. Another way to write this function is by keeping the parameter value unchanged
  4373. and using indexing to access the integers in the table.
  4374. @example
  4375. int
  4376. sum_array_till_0_indexing (int *p)
  4377. @{
  4378. int i;
  4379. int sum = 0;
  4380. for (i = 0; ; i++)
  4381. @{
  4382. /* @r{Fetch the next integer.} */
  4383. int next = p[i];
  4384. /* @r{Exit the loop if it's 0.} */
  4385. if (next == 0)
  4386. break;
  4387. /* @r{Add it into running total.} */
  4388. sum += next;
  4389. @}
  4390. return sum;
  4391. @}
  4392. @end example
  4393. In this program, instead of advancing @code{p}, we advance @code{i}
  4394. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4395. i)}.) Either way, it uses the same address to get the next integer.
  4396. It makes no difference in this program whether we write @code{i++} or
  4397. @code{++i}, because the value is not used. All that matters is the
  4398. effect, to increment @code{i}.
  4399. The @samp{--} operator also works on pointers; it can be used
  4400. to scan backwards through an array, like this:
  4401. @example
  4402. int
  4403. after_last_nonzero (int *p, int len)
  4404. @{
  4405. /* @r{Set up @code{q} to point just after the last array element.} */
  4406. int *q = p + len;
  4407. while (q != p)
  4408. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4409. if (*--q != 0)
  4410. /* @r{Return the index of the element after that nonzero.} */
  4411. return q - p + 1;
  4412. return 0;
  4413. @}
  4414. @end example
  4415. That function returns the length of the nonzero part of the
  4416. array specified by its arguments; that is, the index of the
  4417. first zero of the run of zeros at the end.
  4418. @node Pointer Arithmetic Drawbacks
  4419. @section Drawbacks of Pointer Arithmetic
  4420. @cindex drawbacks of pointer arithmetic
  4421. @cindex pointer arithmetic, drawbacks
  4422. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4423. major security flaw in the C language. Theoretically, it is only
  4424. valid to adjust a pointer within one object allocated as a unit in
  4425. memory. However, if you unintentionally adjust a pointer across the
  4426. bounds of the object and into some other object, the system has no way
  4427. to detect this error.
  4428. A bug which does that can easily result in clobbering part of another
  4429. object. For example, with @code{array[-1]} you can read or write the
  4430. nonexistent element before the beginning of an array---probably part
  4431. of some other data.
  4432. Combining pointer arithmetic with casts between pointer types, you can
  4433. create a pointer that fails to be properly aligned for its type. For
  4434. example,
  4435. @example
  4436. int a[2];
  4437. char *pa = (char *)a;
  4438. int *p = (int *)(pa + 1);
  4439. @end example
  4440. @noindent
  4441. gives @code{p} a value pointing to an ``integer'' that includes part
  4442. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4443. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4444. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4445. ``works,'' it may be quite slow. It can also cause aliasing
  4446. confusions (@pxref{Aliasing}).
  4447. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4448. unless it is really necessary.
  4449. @node Pointer-Integer Conversion
  4450. @section Pointer-Integer Conversion
  4451. @cindex pointer-integer conversion
  4452. @cindex conversion between pointers and integers
  4453. @cindex @code{uintptr_t}
  4454. On modern computers, an address is simply a number. It occupies the
  4455. same space as some size of integer. In C, you can convert a pointer
  4456. to the appropriate integer types and vice versa, without losing
  4457. information. The appropriate integer types are @code{uintptr_t} (an
  4458. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4459. in @file{stdint.h}.
  4460. For instance,
  4461. @example
  4462. #include <stdint.h>
  4463. #include <stdio.h>
  4464. void
  4465. print_pointer (void *ptr)
  4466. @{
  4467. uintptr_t converted = (uintptr_t) ptr;
  4468. printf ("Pointer value is 0x%x\n",
  4469. (unsigned int) converted);
  4470. @}
  4471. @end example
  4472. @noindent
  4473. The specification @samp{%x} in the template (the first argument) for
  4474. @code{printf} means to represent this argument using hexadecimal
  4475. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4476. printing treats the number as unsigned, but it won't actually matter:
  4477. all @code{printf} gets to see is the series of bits in the number.
  4478. @strong{Warning:} Converting pointers to integers is risky---don't do
  4479. it unless it is really necessary.
  4480. @node Printing Pointers
  4481. @section Printing Pointers
  4482. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4483. For example:
  4484. @example
  4485. void
  4486. print_pointer (void *ptr)
  4487. @{
  4488. printf ("Pointer value is %p\n", ptr);
  4489. @}
  4490. @end example
  4491. The specification @samp{%p} works with any pointer type. It prints
  4492. @samp{0x} followed by the address in hexadecimal, printed as the
  4493. appropriate unsigned integer type.
  4494. @node Structures
  4495. @chapter Structures
  4496. @cindex structures
  4497. @findex struct
  4498. @cindex fields in structures
  4499. A @dfn{structure} is a user-defined data type that holds various
  4500. @dfn{fields} of data. Each field has a name and a data type specified
  4501. in the structure's definition.
  4502. Here we define a structure suitable for storing a linked list of
  4503. integers. Each list item will hold one integer, plus a pointer
  4504. to the next item.
  4505. @example
  4506. struct intlistlink
  4507. @{
  4508. int datum;
  4509. struct intlistlink *next;
  4510. @};
  4511. @end example
  4512. The structure definition has a @dfn{type tag} so that the code can
  4513. refer to this structure. The type tag here is @code{intlistlink}.
  4514. The definition refers recursively to the same structure through that
  4515. tag.
  4516. You can define a structure without a type tag, but then you can't
  4517. refer to it again. That is useful only in some special contexts, such
  4518. as inside a @code{typedef} or a @code{union}.
  4519. The contents of the structure are specified by the @dfn{field
  4520. declarations} inside the braces. Each field in the structure needs a
  4521. declaration there. The fields in one structure definition must have
  4522. distinct names, but these names do not conflict with any other names
  4523. in the program.
  4524. A field declaration looks just like a variable declaration. You can
  4525. combine field declarations with the same beginning, just as you can
  4526. combine variable declarations.
  4527. This structure has two fields. One, named @code{datum}, has type
  4528. @code{int} and will hold one integer in the list. The other, named
  4529. @code{next}, is a pointer to another @code{struct intlistlink}
  4530. which would be the rest of the list. In the last list item, it would
  4531. be @code{NULL}.
  4532. This structure definition is recursive, since the type of the
  4533. @code{next} field refers to the structure type. Such recursion is not
  4534. a problem; in fact, you can use the type @code{struct intlistlink *}
  4535. before the definition of the type @code{struct intlistlink} itself.
  4536. That works because pointers to all kinds of structures really look the
  4537. same at the machine level.
  4538. After defining the structure, you can declare a variable of type
  4539. @code{struct intlistlink} like this:
  4540. @example
  4541. struct intlistlink foo;
  4542. @end example
  4543. The structure definition itself can serve as the beginning of a
  4544. variable declaration, so you can declare variables immediately after,
  4545. like this:
  4546. @example
  4547. struct intlistlink
  4548. @{
  4549. int datum;
  4550. struct intlistlink *next;
  4551. @} foo;
  4552. @end example
  4553. @noindent
  4554. But that is ugly. It is almost always clearer to separate the
  4555. definition of the structure from its uses.
  4556. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4557. the scope of the structure type name to that block. That means the
  4558. structure type is recognized only within that block. Declaring it in
  4559. a function parameter list, as here,
  4560. @example
  4561. int f (struct foo @{int a, b@} parm);
  4562. @end example
  4563. @noindent
  4564. (assuming that @code{struct foo} is not already defined) limits the
  4565. scope of the structure type @code{struct foo} to that parameter list;
  4566. that is basically useless, so it triggers a warning.
  4567. Standard C requires at least one field in a structure.
  4568. GNU C does not require this.
  4569. @menu
  4570. * Referencing Fields:: Accessing field values in a structure object.
  4571. * Dynamic Memory Allocation:: Allocating space for objects
  4572. while the program is running.
  4573. * Field Offset:: Memory layout of fields within a structure.
  4574. * Structure Layout:: Planning the memory layout of fields.
  4575. * Packed Structures:: Packing structure fields as close as possible.
  4576. * Bit Fields:: Dividing integer fields
  4577. into fields with fewer bits.
  4578. * Bit Field Packing:: How bit fields pack together in integers.
  4579. * const Fields:: Making structure fields immutable.
  4580. * Zero Length:: Zero-length array as a variable-length object.
  4581. * Flexible Array Fields:: Another approach to variable-length objects.
  4582. * Overlaying Structures:: Casting one structure type
  4583. over an object of another structure type.
  4584. * Structure Assignment:: Assigning values to structure objects.
  4585. * Unions:: Viewing the same object in different types.
  4586. * Packing With Unions:: Using a union type to pack various types into
  4587. the same memory space.
  4588. * Cast to Union:: Casting a value one of the union's alternative
  4589. types to the type of the union itself.
  4590. * Structure Constructors:: Building new structure objects.
  4591. * Unnamed Types as Fields:: Fields' types do not always need names.
  4592. * Incomplete Types:: Types which have not been fully defined.
  4593. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4594. * Type Tags:: Scope of structure and union type tags.
  4595. @end menu
  4596. @node Referencing Fields
  4597. @section Referencing Structure Fields
  4598. @cindex referencing structure fields
  4599. @cindex structure fields, referencing
  4600. To make a structure useful, there has to be a way to examine and store
  4601. its fields. The @samp{.} (period) operator does that; its use looks
  4602. like @code{@var{object}.@var{field}}.
  4603. Given this structure and variable,
  4604. @example
  4605. struct intlistlink
  4606. @{
  4607. int datum;
  4608. struct intlistlink *next;
  4609. @};
  4610. struct intlistlink foo;
  4611. @end example
  4612. @noindent
  4613. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4614. fields in the value of @code{foo}. These fields are lvalues, so you
  4615. can store values into them, and read the values out again.
  4616. Most often, structures are dynamically allocated (see the next
  4617. section), and we refer to the objects via pointers.
  4618. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4619. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4620. contains this declaration:
  4621. @example
  4622. struct intlistlink *ptr;
  4623. @end example
  4624. @noindent
  4625. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4626. to the two fields in the object that @code{ptr} points to.
  4627. If a unary operator precedes an expression using @samp{->},
  4628. the @samp{->} nests inside:
  4629. @example
  4630. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4631. @end example
  4632. You can intermix @samp{->} and @samp{.} without parentheses,
  4633. as shown here:
  4634. @example
  4635. struct @{ double d; struct intlistlink l; @} foo;
  4636. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4637. @end example
  4638. @node Dynamic Memory Allocation
  4639. @section Dynamic Memory Allocation
  4640. @cindex dynamic memory allocation
  4641. @cindex memory allocation, dynamic
  4642. @cindex allocating memory dynamically
  4643. To allocate an object dynamically, call the library function
  4644. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4645. Reference Manual}). Here is how to allocate an object of type
  4646. @code{struct intlistlink}. To make this code work, include the file
  4647. @file{stdlib.h}, like this:
  4648. @example
  4649. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4650. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4651. @dots{}
  4652. struct intlistlink *
  4653. alloc_intlistlink ()
  4654. @{
  4655. struct intlistlink *p;
  4656. p = malloc (sizeof (struct intlistlink));
  4657. if (p == NULL)
  4658. fatal ("Ran out of storage");
  4659. /* @r{Initialize the contents.} */
  4660. p->datum = 0;
  4661. p->next = NULL;
  4662. return p;
  4663. @}
  4664. @end example
  4665. @noindent
  4666. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4667. will automatically convert it to type @code{struct intlistlink *}.
  4668. The return value of @code{malloc} is always sufficiently aligned
  4669. (@pxref{Type Alignment}) that it is valid for any data type.
  4670. The test for @code{p == NULL} is necessary because @code{malloc}
  4671. returns a null pointer if it cannot get any storage. We assume that
  4672. the program defines the function @code{fatal} to report a fatal error
  4673. to the user.
  4674. Here's how to add one more integer to the front of such a list:
  4675. @example
  4676. struct intlistlink *my_list = NULL;
  4677. void
  4678. add_to_mylist (int my_int)
  4679. @{
  4680. struct intlistlink *p = alloc_intlistlink ();
  4681. p->datum = my_int;
  4682. p->next = mylist;
  4683. mylist = p;
  4684. @}
  4685. @end example
  4686. The way to free the objects is by calling @code{free}. Here's
  4687. a function to free all the links in one of these lists:
  4688. @example
  4689. void
  4690. free_intlist (struct intlistlink *p)
  4691. @{
  4692. while (p)
  4693. @{
  4694. struct intlistlink *q = p;
  4695. p = p->next;
  4696. free (q);
  4697. @}
  4698. @}
  4699. @end example
  4700. We must extract the @code{next} pointer from the object before freeing
  4701. it, because @code{free} can clobber the data that was in the object.
  4702. For the same reason, the program must not use the list any more after
  4703. freeing its elements. To make sure it won't, it is best to clear out
  4704. the variable where the list was stored, like this:
  4705. @example
  4706. free_intlist (mylist);
  4707. mylist = NULL;
  4708. @end example
  4709. @node Field Offset
  4710. @section Field Offset
  4711. @cindex field offset
  4712. @cindex structure field offset
  4713. @cindex offset of structure fields
  4714. To determine the offset of a given field @var{field} in a structure
  4715. type @var{type}, use the macro @code{offsetof}, which is defined in
  4716. the file @file{stddef.h}. It is used like this:
  4717. @example
  4718. offsetof (@var{type}, @var{field})
  4719. @end example
  4720. Here is an example:
  4721. @example
  4722. struct foo
  4723. @{
  4724. int element;
  4725. struct foo *next;
  4726. @};
  4727. offsetof (struct foo, next)
  4728. /* @r{On most machines that is 4. It may be 8.} */
  4729. @end example
  4730. @node Structure Layout
  4731. @section Structure Layout
  4732. @cindex structure layout
  4733. @cindex layout of structures
  4734. The rest of this chapter covers advanced topics about structures. If
  4735. you are just learning C, you can skip it.
  4736. The precise layout of a @code{struct} type is crucial when using it to
  4737. overlay hardware registers, to access data structures in shared
  4738. memory, or to assemble and disassemble packets for network
  4739. communication. It is also important for avoiding memory waste when
  4740. the program makes many objects of that type. However, the layout
  4741. depends on the target platform. Each platform has conventions for
  4742. structure layout, which compilers need to follow.
  4743. Here are the conventions used on most platforms.
  4744. The structure's fields appear in the structure layout in the order
  4745. they are declared. When possible, consecutive fields occupy
  4746. consecutive bytes within the structure. However, if a field's type
  4747. demands more alignment than it would get that way, C gives it the
  4748. alignment it requires by leaving a gap after the previous field.
  4749. Once all the fields have been laid out, it is possible to determine
  4750. the structure's alignment and size. The structure's alignment is the
  4751. maximum alignment of any of the fields in it. Then the structure's
  4752. size is rounded up to a multiple of its alignment. That may require
  4753. leaving a gap at the end of the structure.
  4754. Here are some examples, where we assume that @code{char} has size and
  4755. alignment 1 (always true), and @code{int} has size and alignment 4
  4756. (true on most kinds of computers):
  4757. @example
  4758. struct foo
  4759. @{
  4760. char a, b;
  4761. int c;
  4762. @};
  4763. @end example
  4764. @noindent
  4765. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4766. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4767. There is a gap of 2 bytes before @code{c}.
  4768. Contrast that with this structure:
  4769. @example
  4770. struct foo
  4771. @{
  4772. char a;
  4773. int c;
  4774. char b;
  4775. @};
  4776. @end example
  4777. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4778. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4779. gaps: three bytes before @code{c}, and three bytes at the end.
  4780. These two structures have the same contents at the C level, but one
  4781. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4782. fields. A reliable way to avoid this sort of wastage is to order the
  4783. fields by size, biggest fields first.
  4784. @node Packed Structures
  4785. @section Packed Structures
  4786. @cindex packed structures
  4787. @cindex @code{__attribute__((packed))}
  4788. In GNU C you can force a structure to be laid out with no gaps by
  4789. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4790. end of the structure type declaration). Here's an example:
  4791. @example
  4792. struct __attribute__((packed)) foo
  4793. @{
  4794. char a;
  4795. int c;
  4796. char b;
  4797. @};
  4798. @end example
  4799. Without @code{__attribute__((packed))}, this structure occupies 12
  4800. bytes (as described in the previous section), assuming 4-byte
  4801. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4802. only 6 bytes long---the sum of the lengths of its fields.
  4803. Use of @code{__attribute__((packed))} often results in fields that
  4804. don't have the normal alignment for their types. Taking the address
  4805. of such a field can result in an invalid pointer because of its
  4806. improper alignment. Dereferencing such a pointer can cause a
  4807. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4808. unaligned pointers.
  4809. @xref{Attributes}.
  4810. @node Bit Fields
  4811. @section Bit Fields
  4812. @cindex bit fields
  4813. A structure field declaration with an integer type can specify the
  4814. number of bits the field should occupy. We call that a @dfn{bit
  4815. field}. These are useful because consecutive bit fields are packed
  4816. into a larger storage unit. For instance,
  4817. @example
  4818. unsigned char opcode: 4;
  4819. @end example
  4820. @noindent
  4821. specifies that this field takes just 4 bits.
  4822. Since it is unsigned, its possible values range
  4823. from 0 to 15. A signed field with 4 bits, such as this,
  4824. @example
  4825. signed char small: 4;
  4826. @end example
  4827. @noindent
  4828. can hold values from -8 to 7.
  4829. You can subdivide a single byte into those two parts by writing
  4830. @example
  4831. unsigned char opcode: 4;
  4832. signed char small: 4;
  4833. @end example
  4834. @noindent
  4835. in the structure. With bit fields, these two numbers fit into
  4836. a single @code{char}.
  4837. Here's how to declare a one-bit field that can hold either 0 or 1:
  4838. @example
  4839. unsigned char special_flag: 1;
  4840. @end example
  4841. You can also use the @code{bool} type for bit fields:
  4842. @example
  4843. bool special_flag: 1;
  4844. @end example
  4845. Except when using @code{bool} (which is always unsigned,
  4846. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4847. for a bit field. There is a default, if that's not specified: the bit
  4848. field is signed if plain @code{char} is signed, except that the option
  4849. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4850. is cleaner not to depend on this default.
  4851. Bit fields are special in that you cannot take their address with
  4852. @samp{&}. They are not stored with the size and alignment appropriate
  4853. for the specified type, so they cannot be addressed through pointers
  4854. to that type.
  4855. @node Bit Field Packing
  4856. @section Bit Field Packing
  4857. Programs to communicate with low-level hardware interfaces need to
  4858. define bit fields laid out to match the hardware data. This section
  4859. explains how to do that.
  4860. Consecutive bit fields are packed together, but each bit field must
  4861. fit within a single object of its specified type. In this example,
  4862. @example
  4863. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4864. @end example
  4865. @noindent
  4866. all five fields fit consecutively into one two-byte @code{short}.
  4867. They need 15 bits, and one @code{short} provides 16. By contrast,
  4868. @example
  4869. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4870. @end example
  4871. @noindent
  4872. needs three bytes. It fits @code{a} and @code{b} into one
  4873. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4874. add up to 9 bits). So @code{c} and @code{d} go into a second
  4875. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4876. Then @code{e} needs a third @code{char}. By contrast,
  4877. @example
  4878. unsigned char a : 3, b : 3;
  4879. unsigned int c : 3;
  4880. unsigned char d : 3, e : 3;
  4881. @end example
  4882. @noindent
  4883. needs only two bytes: the type @code{unsigned int}
  4884. allows @code{c} to straddle bytes that are in the same word.
  4885. You can leave a gap of a specified number of bits by defining a
  4886. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4887. It is allocated space in the structure just as a named bit field would
  4888. be allocated.
  4889. You can force the following bit field to advance to the following
  4890. aligned memory object with @code{@var{type} : 0;}.
  4891. Both of these constructs can syntactically share @var{type} with
  4892. ordinary bit fields. This example illustrates both:
  4893. @example
  4894. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4895. @end example
  4896. @noindent
  4897. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4898. between them. Then @code{: 0} advances to the next @code{int},
  4899. so @code{c} and @code{d} fit into that one.
  4900. These rules for packing bit fields apply to most target platforms,
  4901. including all the usual real computers. A few embedded controllers
  4902. have special layout rules.
  4903. @node const Fields
  4904. @section @code{const} Fields
  4905. @cindex const fields
  4906. @cindex structure fields, constant
  4907. @c ??? Is this a C standard feature?
  4908. A structure field declared @code{const} cannot be assigned to
  4909. (@pxref{const}). For instance, let's define this modified version of
  4910. @code{struct intlistlink}:
  4911. @example
  4912. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4913. @{
  4914. const int datum;
  4915. struct intlistlink *next;
  4916. @};
  4917. @end example
  4918. This structure can be used to prevent part of the code from modifying
  4919. the @code{datum} field:
  4920. @example
  4921. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4922. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4923. struct intlistlink_ro *q
  4924. = (struct intlistlink_ro *) p;
  4925. q->datum = 5; /* @r{Error!} */
  4926. p->datum = 5; /* @r{Valid since @code{*p} is}
  4927. @r{not a @code{struct intlistlink_ro}.} */
  4928. @end example
  4929. A @code{const} field can get a value in two ways: by initialization of
  4930. the whole structure, and by making a pointer-to-structure point to an object
  4931. in which that field already has a value.
  4932. Any @code{const} field in a structure type makes assignment impossible
  4933. for structures of that type (@pxref{Structure Assignment}). That is
  4934. because structure assignment works by assigning the structure's
  4935. fields, one by one.
  4936. @node Zero Length
  4937. @section Arrays of Length Zero
  4938. @cindex array of length zero
  4939. @cindex zero-length arrays
  4940. @cindex length-zero arrays
  4941. GNU C allows zero-length arrays. They are useful as the last element
  4942. of a structure that is really a header for a variable-length object.
  4943. Here's an example, where we construct a variable-size structure
  4944. to hold a line which is @code{this_length} characters long:
  4945. @example
  4946. struct line @{
  4947. int length;
  4948. char contents[0];
  4949. @};
  4950. struct line *thisline
  4951. = ((struct line *)
  4952. malloc (sizeof (struct line)
  4953. + this_length));
  4954. thisline->length = this_length;
  4955. @end example
  4956. In ISO C90, we would have to give @code{contents} a length of 1, which
  4957. means either wasting space or complicating the argument to @code{malloc}.
  4958. @node Flexible Array Fields
  4959. @section Flexible Array Fields
  4960. @cindex flexible array fields
  4961. @cindex array fields, flexible
  4962. The C99 standard adopted a more complex equivalent of zero-length
  4963. array fields. It's called a @dfn{flexible array}, and it's indicated
  4964. by omitting the length, like this:
  4965. @example
  4966. struct line
  4967. @{
  4968. int length;
  4969. char contents[];
  4970. @};
  4971. @end example
  4972. The flexible array has to be the last field in the structure, and there
  4973. must be other fields before it.
  4974. Under the C standard, a structure with a flexible array can't be part
  4975. of another structure, and can't be an element of an array.
  4976. GNU C allows static initialization of flexible array fields. The effect
  4977. is to ``make the array long enough'' for the initializer.
  4978. @example
  4979. struct f1 @{ int x; int y[]; @} f1
  4980. = @{ 1, @{ 2, 3, 4 @} @};
  4981. @end example
  4982. @noindent
  4983. This defines a structure variable named @code{f1}
  4984. whose type is @code{struct f1}. In C, a variable name or function name
  4985. never conflicts with a structure type tag.
  4986. Omitting the flexible array field's size lets the initializer
  4987. determine it. This is allowed only when the flexible array is defined
  4988. in the outermost structure and you declare a variable of that
  4989. structure type. For example:
  4990. @example
  4991. struct foo @{ int x; int y[]; @};
  4992. struct bar @{ struct foo z; @};
  4993. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4994. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4995. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4996. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4997. @end example
  4998. @node Overlaying Structures
  4999. @section Overlaying Different Structures
  5000. @cindex overlaying structures
  5001. @cindex structures, overlaying
  5002. Be careful about using different structure types to refer to the same
  5003. memory within one function, because GNU C can optimize code assuming
  5004. it never does that. @xref{Aliasing}. Here's an example of the kind of
  5005. aliasing that can cause the problem:
  5006. @example
  5007. struct a @{ int size; char *data; @};
  5008. struct b @{ int size; char *data; @};
  5009. struct a foo;
  5010. struct b *q = (struct b *) &foo;
  5011. @end example
  5012. Here @code{q} points to the same memory that the variable @code{foo}
  5013. occupies, but they have two different types. The two types
  5014. @code{struct a} and @code{struct b} are defined alike, but they are
  5015. not the same type. Interspersing references using the two types,
  5016. like this,
  5017. @example
  5018. p->size = 0;
  5019. q->size = 1;
  5020. x = p->size;
  5021. @end example
  5022. @noindent
  5023. allows GNU C to assume that @code{p->size} is still zero when it is
  5024. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5025. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5026. Other compilers might also do this optimization. The ISO C standard
  5027. considers such code erroneous, precisely so that this optimization
  5028. will be valid.
  5029. @node Structure Assignment
  5030. @section Structure Assignment
  5031. @cindex structure assignment
  5032. @cindex assigning structures
  5033. Assignment operating on a structure type copies the structure. The
  5034. left and right operands must have the same type. Here is an example:
  5035. @example
  5036. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5037. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5038. @r{@dots{}}
  5039. struct point @{ double x, y; @};
  5040. struct point *
  5041. copy_point (struct point point)
  5042. @{
  5043. struct point *p
  5044. = (struct point *) malloc (sizeof (struct point));
  5045. if (p == NULL)
  5046. fatal ("Out of memory");
  5047. *p = point;
  5048. return p;
  5049. @}
  5050. @end example
  5051. Notionally, assignment on a structure type works by copying each of
  5052. the fields. Thus, if any of the fields has the @code{const}
  5053. qualifier, that structure type does not allow assignment:
  5054. @example
  5055. struct point @{ const double x, y; @};
  5056. struct point a, b;
  5057. a = b; /* @r{Error!} */
  5058. @end example
  5059. @xref{Assignment Expressions}.
  5060. @node Unions
  5061. @section Unions
  5062. @cindex unions
  5063. @findex union
  5064. A @dfn{union type} defines alternative ways of looking at the same
  5065. piece of memory. Each alternative view is defined with a data type,
  5066. and identified by a name. A union definition looks like this:
  5067. @example
  5068. union @var{name}
  5069. @{
  5070. @var{alternative declarations}@r{@dots{}}
  5071. @};
  5072. @end example
  5073. Each alternative declaration looks like a structure field declaration,
  5074. except that it can't be a bit field. For instance,
  5075. @example
  5076. union number
  5077. @{
  5078. long int integer;
  5079. double float;
  5080. @}
  5081. @end example
  5082. @noindent
  5083. lets you store either an integer (type @code{long int}) or a floating
  5084. point number (type @code{double}) in the same place in memory. The
  5085. length and alignment of the union type are the maximum of all the
  5086. alternatives---they do not have to be the same. In this union
  5087. example, @code{double} probably takes more space than @code{long int},
  5088. but that doesn't cause a problem in programs that use the union in the
  5089. normal way.
  5090. The members don't have to be different in data type. Sometimes
  5091. each member pertains to a way the data will be used. For instance,
  5092. @example
  5093. union datum
  5094. @{
  5095. double latitude;
  5096. double longitude;
  5097. double height;
  5098. double weight;
  5099. int continent;
  5100. @}
  5101. @end example
  5102. This union holds one of several kinds of data; most kinds are floating
  5103. points, but the value can also be a code for a continent which is an
  5104. integer. You @emph{could} use one member of type @code{double} to
  5105. access all the values which have that type, but the different member
  5106. names will make the program clearer.
  5107. The alignment of a union type is the maximum of the alignments of the
  5108. alternatives. The size of the union type is the maximum of the sizes
  5109. of the alternatives, rounded up to a multiple of the alignment
  5110. (because every type's size must be a multiple of its alignment).
  5111. All the union alternatives start at the address of the union itself.
  5112. If an alternative is shorter than the union as a whole, it occupies
  5113. the first part of the union's storage, leaving the last part unused
  5114. @emph{for that alternative}.
  5115. @strong{Warning:} if the code stores data using one union alternative
  5116. and accesses it with another, the results depend on the kind of
  5117. computer in use. Only wizards should try to do this. However, when
  5118. you need to do this, a union is a clean way to do it.
  5119. Assignment works on any union type by copying the entire value.
  5120. @node Packing With Unions
  5121. @section Packing With Unions
  5122. Sometimes we design a union with the intention of packing various
  5123. kinds of objects into a certain amount of memory space. For example.
  5124. @example
  5125. union bytes8
  5126. @{
  5127. long long big_int_elt;
  5128. double double_elt;
  5129. struct @{ int first, second; @} two_ints;
  5130. struct @{ void *first, *second; @} two_ptrs;
  5131. @};
  5132. union bytes8 *p;
  5133. @end example
  5134. This union makes it possible to look at 8 bytes of data that @code{p}
  5135. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5136. single floating-point number (@code{p->double_elt}), as a pair of
  5137. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5138. as a pair of pointers (@code{p->two_ptrs.first} and
  5139. @code{p->two_ptrs.second}).
  5140. To pack storage with such a union makes assumptions about the sizes of
  5141. all the types involved. This particular union was written expecting a
  5142. pointer to have the same size as @code{int}. On a machine where one
  5143. pointer takes 8 bytes, the code using this union probably won't work
  5144. as expected. The union, as such, will function correctly---if you
  5145. store two values through @code{two_ints} and extract them through
  5146. @code{two_ints}, you will get the same integers back---but the part of
  5147. the program that expects the union to be 8 bytes long could
  5148. malfunction, or at least use too much space.
  5149. The above example shows one case where a @code{struct} type with no
  5150. tag can be useful. Another way to get effectively the same result
  5151. is with arrays as members of the union:
  5152. @example
  5153. union eight_bytes
  5154. @{
  5155. long long big_int_elt;
  5156. double double_elt;
  5157. int two_ints[2];
  5158. void *two_ptrs[2];
  5159. @};
  5160. @end example
  5161. @node Cast to Union
  5162. @section Cast to a Union Type
  5163. @cindex cast to a union
  5164. @cindex union, casting to a
  5165. In GNU C, you can explicitly cast any of the alternative types to the
  5166. union type; for instance,
  5167. @example
  5168. (union eight_bytes) (long long) 5
  5169. @end example
  5170. @noindent
  5171. makes a value of type @code{union eight_bytes} which gets its contents
  5172. through the alternative named @code{big_int_elt}.
  5173. The value being cast must exactly match the type of the alternative,
  5174. so this is not valid:
  5175. @example
  5176. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5177. @end example
  5178. A cast to union type looks like any other cast, except that the type
  5179. specified is a union type. You can specify the type either with
  5180. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5181. Typedef Names}).
  5182. Using the cast as the right-hand side of an assignment to a variable of
  5183. union type is equivalent to storing in an alternative of the union:
  5184. @example
  5185. union foo u;
  5186. u = (union foo) x @r{means} u.i = x
  5187. u = (union foo) y @r{means} u.d = y
  5188. @end example
  5189. You can also use the union cast as a function argument:
  5190. @example
  5191. void hack (union foo);
  5192. @r{@dots{}}
  5193. hack ((union foo) x);
  5194. @end example
  5195. @node Structure Constructors
  5196. @section Structure Constructors
  5197. @cindex structure constructors
  5198. @cindex constructors, structure
  5199. You can construct a structure value by writing its type in
  5200. parentheses, followed by an initializer that would be valid in a
  5201. declaration for that type. For instance, given this declaration,
  5202. @example
  5203. struct foo @{int a; char b[2];@} structure;
  5204. @end example
  5205. @noindent
  5206. you can create a @code{struct foo} value as follows:
  5207. @example
  5208. ((struct foo) @{x + y, 'a', 0@})
  5209. @end example
  5210. @noindent
  5211. This specifies @code{x + y} for field @code{a},
  5212. the character @samp{a} for field @code{b}'s element 0,
  5213. and the null character for field @code{b}'s element 1.
  5214. The parentheses around that constructor are to necessary, but we
  5215. recommend writing them to make the nesting of the containing
  5216. expression clearer.
  5217. You can also show the nesting of the two by writing it like
  5218. this:
  5219. @example
  5220. ((struct foo) @{x + y, @{'a', 0@} @})
  5221. @end example
  5222. Each of those is equivalent to writing the following statement
  5223. expression (@pxref{Statement Exprs}):
  5224. @example
  5225. (@{
  5226. struct foo temp = @{x + y, 'a', 0@};
  5227. temp;
  5228. @})
  5229. @end example
  5230. You can also create a union value this way, but it is not especially
  5231. useful since that is equivalent to doing a cast:
  5232. @example
  5233. ((union whosis) @{@var{value}@})
  5234. @r{is equivalent to}
  5235. ((union whosis) (@var{value}))
  5236. @end example
  5237. @node Unnamed Types as Fields
  5238. @section Unnamed Types as Fields
  5239. @cindex unnamed structures
  5240. @cindex unnamed unions
  5241. @cindex structures, unnamed
  5242. @cindex unions, unnamed
  5243. A structure or a union can contain, as fields,
  5244. unnamed structures and unions. Here's an example:
  5245. @example
  5246. struct
  5247. @{
  5248. int a;
  5249. union
  5250. @{
  5251. int b;
  5252. float c;
  5253. @};
  5254. int d;
  5255. @} foo;
  5256. @end example
  5257. @noindent
  5258. You can access the fields of the unnamed union within @code{foo} as if they
  5259. were individual fields at the same level as the union definition:
  5260. @example
  5261. foo.a = 42;
  5262. foo.b = 47;
  5263. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5264. foo.d = 314;
  5265. @end example
  5266. Avoid using field names that could cause ambiguity. For example, with
  5267. this definition:
  5268. @example
  5269. struct
  5270. @{
  5271. int a;
  5272. struct
  5273. @{
  5274. int a;
  5275. float b;
  5276. @};
  5277. @} foo;
  5278. @end example
  5279. @noindent
  5280. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5281. an error when a definition is ambiguous in this way.
  5282. @node Incomplete Types
  5283. @section Incomplete Types
  5284. @cindex incomplete types
  5285. @cindex types, incomplete
  5286. A type that has not been fully defined is called an @dfn{incomplete
  5287. type}. Structure and union types are incomplete when the code makes a
  5288. forward reference, such as @code{struct foo}, before defining the
  5289. type. An array type is incomplete when its length is unspecified.
  5290. You can't use an incomplete type to declare a variable or field, or
  5291. use it for a function parameter or return type. The operators
  5292. @code{sizeof} and @code{_Alignof} give errors when used on an
  5293. incomplete type.
  5294. However, you can define a pointer to an incomplete type, and declare a
  5295. variable or field with such a pointer type. In general, you can do
  5296. everything with such pointers except dereference them. For example:
  5297. @example
  5298. extern void bar (struct mysterious_value *);
  5299. void
  5300. foo (struct mysterious_value *arg)
  5301. @{
  5302. bar (arg);
  5303. @}
  5304. @r{@dots{}}
  5305. @{
  5306. struct mysterious_value *p, **q;
  5307. p = *q;
  5308. foo (p);
  5309. @}
  5310. @end example
  5311. @noindent
  5312. These examples are valid because the code doesn't try to understand
  5313. what @code{p} points to; it just passes the pointer around.
  5314. (Presumably @code{bar} is defined in some other file that really does
  5315. have a definition for @code{struct mysterious_value}.) However,
  5316. dereferencing the pointer would get an error; that requires a
  5317. definition for the structure type.
  5318. @node Intertwined Incomplete Types
  5319. @section Intertwined Incomplete Types
  5320. When several structure types contain pointers to each other, you can
  5321. define the types in any order because pointers to types that come
  5322. later are incomplete types. Thus,
  5323. Here is an example.
  5324. @example
  5325. /* @r{An employee record points to a group.} */
  5326. struct employee
  5327. @{
  5328. char *name;
  5329. @r{@dots{}}
  5330. struct group *group; /* @r{incomplete type.} */
  5331. @r{@dots{}}
  5332. @};
  5333. /* @r{An employee list points to employees.} */
  5334. struct employee_list
  5335. @{
  5336. struct employee *this_one;
  5337. struct employee_list *next; /* @r{incomplete type.} */
  5338. @r{@dots{}}
  5339. @};
  5340. /* @r{A group points to one employee_list.} */
  5341. struct group
  5342. @{
  5343. char *name;
  5344. @r{@dots{}}
  5345. struct employee_list *employees;
  5346. @r{@dots{}}
  5347. @};
  5348. @end example
  5349. @node Type Tags
  5350. @section Type Tags
  5351. @cindex type tags
  5352. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5353. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5354. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5355. name or function name; the type tags have a separate @dfn{name space}.
  5356. Thus, there is no name conflict in this code:
  5357. @example
  5358. struct pair @{ int a, b; @};
  5359. int pair = 1;
  5360. @end example
  5361. @noindent
  5362. nor in this one:
  5363. @example
  5364. struct pair @{ int a, b; @} pair;
  5365. @end example
  5366. @noindent
  5367. where @code{pair} is both a structure type tag and a variable name.
  5368. However, @code{struct}, @code{union}, and @code{enum} share the same
  5369. name space of tags, so this is a conflict:
  5370. @example
  5371. struct pair @{ int a, b; @};
  5372. enum pair @{ c, d @};
  5373. @end example
  5374. @noindent
  5375. and so is this:
  5376. @example
  5377. struct pair @{ int a, b; @};
  5378. struct pair @{ int c, d; @};
  5379. @end example
  5380. When the code defines a type tag inside a block, the tag's scope is
  5381. limited to that block (as for local variables). Two definitions for
  5382. one type tag do not conflict if they are in different scopes; rather,
  5383. each is valid in its scope. For example,
  5384. @example
  5385. struct pair @{ int a, b; @};
  5386. void
  5387. pair_up_doubles (int len, double array[])
  5388. @{
  5389. struct pair @{ double a, b; @};
  5390. @r{@dots{}}
  5391. @}
  5392. @end example
  5393. @noindent
  5394. has two definitions for @code{struct pair} which do not conflict. The
  5395. one inside the function applies only within the definition of
  5396. @code{pair_up_doubles}. Within its scope, that definition
  5397. @dfn{shadows} the outer definition.
  5398. If @code{struct pair} appears inside the function body, before the
  5399. inner definition, it refers to the outer definition---the only one
  5400. that has been seen at that point. Thus, in this code,
  5401. @example
  5402. struct pair @{ int a, b; @};
  5403. void
  5404. pair_up_doubles (int len, double array[])
  5405. @{
  5406. struct two_pairs @{ struct pair *p, *q; @};
  5407. struct pair @{ double a, b; @};
  5408. @r{@dots{}}
  5409. @}
  5410. @end example
  5411. @noindent
  5412. the structure @code{two_pairs} has pointers to the outer definition of
  5413. @code{struct pair}, which is probably not desirable.
  5414. To prevent that, you can write @code{struct pair;} inside the function
  5415. body as a variable declaration with no variables. This is a
  5416. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5417. type tag local to the current block, with the details of the type to
  5418. come later. Here's an example:
  5419. @example
  5420. void
  5421. pair_up_doubles (int len, double array[])
  5422. @{
  5423. /* @r{Forward declaration for @code{pair}.} */
  5424. struct pair;
  5425. struct two_pairs @{ struct pair *p, *q; @};
  5426. /* @r{Give the details.} */
  5427. struct pair @{ double a, b; @};
  5428. @r{@dots{}}
  5429. @}
  5430. @end example
  5431. However, the cleanest practice is to avoid shadowing type tags.
  5432. @node Arrays
  5433. @chapter Arrays
  5434. @cindex array
  5435. @cindex elements of arrays
  5436. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5437. all of the same data type. Each element is identified by its numeric
  5438. @var{index} within the array.
  5439. We presented arrays of numbers in the sample programs early in this
  5440. manual (@pxref{Array Example}). However, arrays can have elements of
  5441. any data type, including pointers, structures, unions, and other
  5442. arrays.
  5443. If you know another programming language, you may suppose that you know all
  5444. about arrays, but C arrays have special quirks, so in this chapter we
  5445. collect all the information about arrays in C@.
  5446. The elements of a C array are allocated consecutively in memory,
  5447. with no gaps between them. Each element is aligned as required
  5448. for its data type (@pxref{Type Alignment}).
  5449. @menu
  5450. * Accessing Array Elements:: How to access individual elements of an array.
  5451. * Declaring an Array:: How to name and reserve space for a new array.
  5452. * Strings:: A string in C is a special case of array.
  5453. * Array Type Designators:: Referring to a specific array type.
  5454. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5455. * Limitations of C Arrays:: Arrays are not first-class objects.
  5456. * Multidimensional Arrays:: Arrays of arrays.
  5457. * Constructing Array Values:: Assigning values to an entire array at once.
  5458. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5459. @end menu
  5460. @node Accessing Array Elements
  5461. @section Accessing Array Elements
  5462. @cindex accessing array elements
  5463. @cindex array elements, accessing
  5464. If the variable @code{a} is an array, the @var{n}th element of
  5465. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5466. an element's value or to assign to it:
  5467. @example
  5468. x = a[5];
  5469. a[6] = 1;
  5470. @end example
  5471. @noindent
  5472. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5473. lvalue.
  5474. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5475. valid index is one less than the number of elements.
  5476. The C language does not check whether array indices are in bounds, so
  5477. if the code uses an out-of-range index, it will access memory outside the
  5478. array.
  5479. @strong{Warning:} Using only valid index values in C is the
  5480. programmer's responsibility.
  5481. Array indexing in C is not a primitive operation: it is defined in
  5482. terms of pointer arithmetic and dereferencing. Now that we know
  5483. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5484. its job.
  5485. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5486. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5487. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5488. When an expression with array type (such as @code{a}) appears as part
  5489. of a larger C expression, it is converted automatically to a pointer
  5490. to element zero of that array. For instance, @code{a} in an
  5491. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5492. computed as @code{*(&a[0]+i)}.
  5493. Now we can analyze how that expression gives us the desired element of
  5494. the array. It makes a pointer to element 0 of @code{a}, advances it
  5495. by the value of @code{i}, and dereferences that pointer.
  5496. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5497. @node Declaring an Array
  5498. @section Declaring an Array
  5499. @cindex declaring an array
  5500. @cindex array, declaring
  5501. To make an array declaration, write @code{[@var{length}]} after the
  5502. name being declared. This construct is valid in the declaration of a
  5503. variable, a function parameter, a function value type (the value can't
  5504. be an array, but it can be a pointer to one), a structure field, or a
  5505. union alternative.
  5506. The surrounding declaration specifies the element type of the array;
  5507. that can be any type of data, but not @code{void} or a function type.
  5508. For instance,
  5509. @example
  5510. double a[5];
  5511. @end example
  5512. @noindent
  5513. declares @code{a} as an array of 5 @code{double}s.
  5514. @example
  5515. struct foo bstruct[length];
  5516. @end example
  5517. @noindent
  5518. declares @code{bstruct} as an array of @code{length} objects of type
  5519. @code{struct foo}. A variable array size like this is allowed when
  5520. the array is not file-scope.
  5521. Other declaration constructs can nest within the array declaration
  5522. construct. For instance:
  5523. @example
  5524. struct foo *b[length];
  5525. @end example
  5526. @noindent
  5527. declares @code{b} as an array of @code{length} pointers to
  5528. @code{struct foo}. This shows that the length need not be a constant
  5529. (@pxref{Arrays of Variable Length}).
  5530. @example
  5531. double (*c)[5];
  5532. @end example
  5533. @noindent
  5534. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5535. @example
  5536. char *(*f (int))[5];
  5537. @end example
  5538. @noindent
  5539. declares @code{f} as a function taking an @code{int} argument and
  5540. returning a pointer to an array of 5 strings (pointers to
  5541. @code{char}s).
  5542. @example
  5543. double aa[5][10];
  5544. @end example
  5545. @noindent
  5546. declares @code{aa} as an array of 5 elements, each of which is an
  5547. array of 10 @code{double}s. This shows how to declare a
  5548. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5549. All these declarations specify the array's length, which is needed in
  5550. these cases in order to allocate storage for the array.
  5551. @node Strings
  5552. @section Strings
  5553. @cindex string
  5554. A string in C is a sequence of elements of type @code{char},
  5555. terminated with the null character, the character with code zero.
  5556. Programs often need to use strings with specific, fixed contents. To
  5557. write one in a C program, use a @dfn{string constant} such as
  5558. @code{"Take me to your leader!"}. The data type of a string constant
  5559. is @code{char *}. For the full syntactic details of writing string
  5560. constants, @ref{String Constants}.
  5561. To declare a place to store a non-constant string, declare an array of
  5562. @code{char}. Keep in mind that it must include one extra @code{char}
  5563. for the terminating null. For instance,
  5564. @example
  5565. char text[] = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5566. @end example
  5567. @noindent
  5568. declares an array named @samp{text} with six elements---five letters
  5569. and the terminating null character. An equivalent way to get the same
  5570. result is this,
  5571. @example
  5572. char text[] = "Hello";
  5573. @end example
  5574. @noindent
  5575. which copies the elements of the string constant, including @emph{its}
  5576. terminating null character.
  5577. @example
  5578. char message[200];
  5579. @end example
  5580. @noindent
  5581. declares an array long enough to hold a string of 199 ASCII characters
  5582. plus the terminating null character.
  5583. When you store a string into @code{message} be sure to check or prove
  5584. that the length does not exceed its size. For example,
  5585. @example
  5586. void
  5587. set_message (char *text)
  5588. @{
  5589. int i;
  5590. for (i = 0; i < sizeof (message); i++)
  5591. @{
  5592. message[i] = text[i];
  5593. if (text[i] == 0)
  5594. return;
  5595. @}
  5596. fatal_error ("Message is too long for `message');
  5597. @}
  5598. @end example
  5599. It's easy to do this with the standard library function
  5600. @code{strncpy}, which fills out the whole destination array (up to a
  5601. specified length) with null characters. Thus, if the last character
  5602. of the destination is not null, the string did not fit. Many system
  5603. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5604. to run faster than an explicit @code{for}-loop.
  5605. Here's what the code looks like:
  5606. @example
  5607. void
  5608. set_message (char *text)
  5609. @{
  5610. strncpy (message, text, sizeof (message));
  5611. if (message[sizeof (message) - 1] != 0)
  5612. fatal_error ("Message is too long for `message');
  5613. @}
  5614. @end example
  5615. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5616. Library Reference Manual}, for more information about the standard
  5617. library functions for operating on strings.
  5618. You can avoid putting a fixed length limit on strings you construct or
  5619. operate on by allocating the space for them dynamically.
  5620. @xref{Dynamic Memory Allocation}.
  5621. @node Array Type Designators
  5622. @section Array Type Designators
  5623. Every C type has a type designator, which you make by deleting the
  5624. variable name and the semicolon from a declaration (@pxref{Type
  5625. Designators}). The designators for array types follow this rule, but
  5626. they may appear surprising.
  5627. @example
  5628. @r{type} int a[5]; @r{designator} int [5]
  5629. @r{type} double a[5][3]; @r{designator} double [5][3]
  5630. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5631. @end example
  5632. @node Incomplete Array Types
  5633. @section Incomplete Array Types
  5634. @cindex incomplete array types
  5635. @cindex array types, incomplete
  5636. An array is equivalent, for most purposes, to a pointer to its zeroth
  5637. element. When that is true, the length of the array is irrelevant.
  5638. The length needs to be known only for allocating space for the array, or
  5639. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5640. contexts C allows
  5641. @itemize @bullet
  5642. @item
  5643. An @code{extern} declaration says how to refer to a variable allocated
  5644. elsewhere. It does not need to allocate space for the variable,
  5645. so if it is an array, you can omit the length. For example,
  5646. @example
  5647. extern int foo[];
  5648. @end example
  5649. @item
  5650. When declaring a function parameter as an array, the argument value
  5651. passed to the function is really a pointer to the array's zeroth
  5652. element. This value does not say how long the array really is, there
  5653. is no need to declare it. For example,
  5654. @example
  5655. int
  5656. func (int foo[])
  5657. @end example
  5658. @end itemize
  5659. These declarations are examples of @dfn{incomplete} array types, types
  5660. that are not fully specified. The incompleteness makes no difference
  5661. for accessing elements of the array, but it matters for some other
  5662. things. For instance, @code{sizeof} is not allowed on an incomplete
  5663. type.
  5664. With multidimensional arrays, only the first dimension can be omitted:
  5665. @example
  5666. extern struct chesspiece *funnyboard foo[][8];
  5667. @end example
  5668. In other words, the code doesn't have to say how many rows there are,
  5669. but it must state how big each row is.
  5670. @node Limitations of C Arrays
  5671. @section Limitations of C Arrays
  5672. @cindex limitations of C arrays
  5673. @cindex first-class object
  5674. Arrays have quirks in C because they are not ``first-class objects'':
  5675. there is no way in C to operate on an array as a unit.
  5676. The other composite objects in C, structures and unions, are
  5677. first-class objects: a C program can copy a structure or union value
  5678. in an assignment, or pass one as an argument to a function, or make a
  5679. function return one. You can't do those things with an array in C@.
  5680. That is because a value you can operate on never has an array type.
  5681. An expression in C can have an array type, but that doesn't produce
  5682. the array as a value. Instead it is converted automatically to a
  5683. pointer to the array's element at index zero. The code can operate
  5684. on the pointer, and through that on individual elements of the array,
  5685. but it can't get and operate on the array as a unit.
  5686. There are three exceptions to this conversion rule, but none of them
  5687. offers a way to operate on the array as a whole.
  5688. First, @samp{&} applied to an expression with array type gives you the
  5689. address of the array, as an array type. However, you can't operate on the
  5690. whole array that way---if you apply @samp{*} to get the array back,
  5691. that expression converts, as usual, to a pointer to its zeroth
  5692. element.
  5693. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5694. @code{typeof} do not convert the array to a pointer; they leave it as
  5695. an array. But they don't operate on the array's data---they only give
  5696. information about its type.
  5697. Third, a string constant used as an initializer for an array is not
  5698. converted to a pointer---rather, the declaration copies the
  5699. @emph{contents} of that string in that one special case.
  5700. You @emph{can} copy the contents of an array, just not with an
  5701. assignment operator. You can do it by calling the library function
  5702. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5703. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5704. when a structure contains just an array, you can copy that structure.
  5705. An array itself is an lvalue if it is a declared variable, or part of
  5706. a structure or union that is an lvalue. When you construct an array
  5707. from elements (@pxref{Constructing Array Values}), that array is not
  5708. an lvalue.
  5709. @node Multidimensional Arrays
  5710. @section Multidimensional Arrays
  5711. @cindex multidimensional arrays
  5712. @cindex array, multidimensional
  5713. Strictly speaking, all arrays in C are unidimensional. However, you
  5714. can create an array of arrays, which is more or less equivalent to a
  5715. multidimensional array. For example,
  5716. @example
  5717. struct chesspiece *board[8][8];
  5718. @end example
  5719. @noindent
  5720. declares an array of 8 arrays of 8 pointers to @code{struct
  5721. chesspiece}. This data type could represent the state of a chess
  5722. game. To access one square's contents requires two array index
  5723. operations, one for each dimension. For instance, you can write
  5724. @code{board[row][column]}, assuming @code{row} and @code{column}
  5725. are variables with integer values in the proper range.
  5726. How does C understand @code{board[row][column]}? First of all,
  5727. @code{board} is converted automatically to a pointer to the zeroth
  5728. element (at index zero) of @code{board}. Adding @code{row} to that
  5729. makes it point to the desired element. Thus, @code{board[row]}'s
  5730. value is an element of @code{board}---an array of 8 pointers.
  5731. However, as an expression with array type, it is converted
  5732. automatically to a pointer to the array's zeroth element. The second
  5733. array index operation, @code{[column]}, accesses the chosen element
  5734. from that array.
  5735. As this shows, pointer-to-array types are meaningful in C@.
  5736. You can declare a variable that points to a row in a chess board
  5737. like this:
  5738. @example
  5739. struct chesspiece *(*rowptr)[8];
  5740. @end example
  5741. @noindent
  5742. This points to an array of 8 pointers to @code{struct chesspiece}.
  5743. You can assign to it as follows:
  5744. @example
  5745. rowptr = &board[5];
  5746. @end example
  5747. The dimensions don't have to be equal in length. Here we declare
  5748. @code{statepop} as an array to hold the population of each state in
  5749. the United States for each year since 1900:
  5750. @example
  5751. #define NSTATES 50
  5752. @{
  5753. int nyears = current_year - 1900 + 1;
  5754. int statepop[NSTATES][nyears];
  5755. @r{@dots{}}
  5756. @}
  5757. @end example
  5758. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5759. each indexed by the year (counting from 1900). Thus, to get the
  5760. element for a particular state and year, we must subscript it first
  5761. by the number that indicates the state, and second by the index for
  5762. the year:
  5763. @example
  5764. statepop[state][year - 1900]
  5765. @end example
  5766. @cindex array, layout in memory
  5767. The subarrays within the multidimensional array are allocated
  5768. consecutively in memory, and within each subarray, its elements are
  5769. allocated consecutively in memory. The most efficient way to process
  5770. all the elements in the array is to scan the last subscript in the
  5771. innermost loop. This means consecutive accesses go to consecutive
  5772. memory locations, which optimizes use of the processor's memory cache.
  5773. For example:
  5774. @example
  5775. int total = 0;
  5776. float average;
  5777. for (int state = 0; state < NSTATES, ++state)
  5778. @{
  5779. for (int year = 0; year < nyears; ++year)
  5780. @{
  5781. total += statepop[state][year];
  5782. @}
  5783. @}
  5784. average = total / nyears;
  5785. @end example
  5786. C's layout for multidimensional arrays is different from Fortran's
  5787. layout. In Fortran, a multidimensional array is not an array of
  5788. arrays; rather, multidimensional arrays are a primitive feature, and
  5789. it is the first index that varies most rapidly between consecutive
  5790. memory locations. Thus, the memory layout of a 50x114 array in C
  5791. matches that of a 114x50 array in Fortran.
  5792. @node Constructing Array Values
  5793. @section Constructing Array Values
  5794. @cindex constructing array values
  5795. @cindex array values, constructing
  5796. You can construct an array from elements by writing them inside
  5797. braces, and preceding all that with the array type's designator in
  5798. parentheses. There is no need to specify the array length, since the
  5799. number of elements determines that. The constructor looks like this:
  5800. @example
  5801. (@var{elttype}[]) @{ @var{elements} @};
  5802. @end example
  5803. Here is an example, which constructs an array of string pointers:
  5804. @example
  5805. (char *[]) @{ "x", "y", "z" @};
  5806. @end example
  5807. That's equivalent in effect to declaring an array with the same
  5808. initializer, like this:
  5809. @example
  5810. char *array[] = @{ "x", "y", "z" @};
  5811. @end example
  5812. and then using the array.
  5813. If all the elements are simple constant expressions, or made up of
  5814. such, then the compound literal can be coerced to a pointer to its
  5815. zeroth element and used to initialize a file-scope variable
  5816. (@pxref{File-Scope Variables}), as shown here:
  5817. @example
  5818. char **foo = (char *[]) @{ "x", "y", "z" @};
  5819. @end example
  5820. @noindent
  5821. The data type of @code{foo} is @code{char **}, which is a pointer
  5822. type, not an array type. The declaration is equivalent to defining
  5823. and then using an array-type variable:
  5824. @example
  5825. char *nameless_array[] = @{ "x", "y", "z" @};
  5826. char **foo = &nameless_array[0];
  5827. @end example
  5828. @node Arrays of Variable Length
  5829. @section Arrays of Variable Length
  5830. @cindex array of variable length
  5831. @cindex variable-length arrays
  5832. In GNU C, you can declare variable-length arrays like any other
  5833. arrays, but with a length that is not a constant expression. The
  5834. storage is allocated at the point of declaration and deallocated when
  5835. the block scope containing the declaration exits. For example:
  5836. @example
  5837. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5838. #include <string.h> /* @r{Declares @code{str}.} */
  5839. FILE *
  5840. concat_fopen (char *s1, char *s2, char *mode)
  5841. @{
  5842. char str[strlen (s1) + strlen (s2) + 1];
  5843. strcpy (str, s1);
  5844. strcat (str, s2);
  5845. return fopen (str, mode);
  5846. @}
  5847. @end example
  5848. @noindent
  5849. (This uses some standard library functions; see @ref{String and Array
  5850. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5851. The length of an array is computed once when the storage is allocated
  5852. and is remembered for the scope of the array in case it is used in
  5853. @code{sizeof}.
  5854. @strong{Warning:} don't allocate a variable-length array if the size
  5855. might be very large (more than 100,000), or in a recursive function,
  5856. because that is likely to cause stack overflow. Allocate the array
  5857. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5858. Jumping or breaking out of the scope of the array name deallocates the
  5859. storage. Jumping into the scope is not allowed; that gives an error
  5860. message.
  5861. You can also use variable-length arrays as arguments to functions:
  5862. @example
  5863. struct entry
  5864. tester (int len, char data[len][len])
  5865. @{
  5866. @r{@dots{}}
  5867. @}
  5868. @end example
  5869. As usual, a function argument declared with an array type
  5870. is really a pointer to an array that already exists.
  5871. Calling the function does not allocate the array, so there's no
  5872. particular danger of stack overflow in using this construct.
  5873. To pass the array first and the length afterward, use a forward
  5874. declaration in the function's parameter list (another GNU extension).
  5875. For example,
  5876. @example
  5877. struct entry
  5878. tester (int len; char data[len][len], int len)
  5879. @{
  5880. @r{@dots{}}
  5881. @}
  5882. @end example
  5883. The @code{int len} before the semicolon is a @dfn{parameter forward
  5884. declaration}, and it serves the purpose of making the name @code{len}
  5885. known when the declaration of @code{data} is parsed.
  5886. You can write any number of such parameter forward declarations in the
  5887. parameter list. They can be separated by commas or semicolons, but
  5888. the last one must end with a semicolon, which is followed by the
  5889. ``real'' parameter declarations. Each forward declaration must match
  5890. a ``real'' declaration in parameter name and data type. ISO C11 does
  5891. not support parameter forward declarations.
  5892. @node Enumeration Types
  5893. @chapter Enumeration Types
  5894. @cindex enumeration types
  5895. @cindex types, enumeration
  5896. @cindex enumerator
  5897. An @dfn{enumeration type} represents a limited set of integer values,
  5898. each with a name. It is effectively equivalent to a primitive integer
  5899. type.
  5900. Suppose we have a list of possible emotional states to store in an
  5901. integer variable. We can give names to these alternative values with
  5902. an enumeration:
  5903. @example
  5904. enum emotion_state @{ neutral, happy, sad, worried,
  5905. calm, nervous @};
  5906. @end example
  5907. @noindent
  5908. (Never mind that this is a simplistic way to classify emotional states;
  5909. it's just a code example.)
  5910. The names inside the enumeration are called @dfn{enumerators}. The
  5911. enumeration type defines them as constants, and their values are
  5912. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5913. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5914. the enumerators explicitly like this:
  5915. @example
  5916. enum emotion_state @{ neutral = 2, happy = 5,
  5917. sad = 20, worried = 10,
  5918. calm = -5, nervous = -300 @};
  5919. @end example
  5920. Each enumerator which does not specify a value gets value zero
  5921. (if it is at the beginning) or the next consecutive integer.
  5922. @example
  5923. /* @r{@code{neutral} is 0 by default,}
  5924. @r{and @code{worried} is 21 by default.} */
  5925. enum emotion_state @{ neutral,
  5926. happy = 5, sad = 20, worried,
  5927. calm = -5, nervous = -300 @};
  5928. @end example
  5929. If an enumerator is obsolete, you can specify that using it should
  5930. cause a warning, by including an attribute in the enumerator's
  5931. declaration. Here is how @code{happy} would look with this
  5932. attribute:
  5933. @example
  5934. happy __attribute__
  5935. ((deprecated
  5936. ("impossible under plutocratic rule")))
  5937. = 5,
  5938. @end example
  5939. @xref{Attributes}.
  5940. You can declare variables with the enumeration type:
  5941. @example
  5942. enum emotion_state feelings_now;
  5943. @end example
  5944. In the C code itself, this is equivalent to declaring the variable
  5945. @code{int}. (If all the enumeration values are positive, it is
  5946. equivalent to @code{unsigned int}.) However, declaring it with the
  5947. enumeration type has an advantage in debugging, because GDB knows it
  5948. should display the current value of the variable using the
  5949. corresponding name. If the variable's type is @code{int}, GDB can
  5950. only show the value as a number.
  5951. The identifier that follows @code{enum} is called a @dfn{type tag}
  5952. since it distinguishes different enumeration types. Type tags are in
  5953. a separate name space and belong to scopes like most other names in C@.
  5954. @xref{Type Tags}, for explanation.
  5955. You can predeclare an @code{enum} type tag like a structure or union
  5956. type tag, like this:
  5957. @example
  5958. enum foo;
  5959. @end example
  5960. @noindent
  5961. The @code{enum} type is incomplete until you finish defining it.
  5962. You can optionally include a trailing comma at the end of a list of
  5963. enumeration values:
  5964. @example
  5965. enum emotion_state @{ neutral, happy, sad, worried,
  5966. calm, nervous, @};
  5967. @end example
  5968. @noindent
  5969. This is useful in some macro definitions, since it enables you to
  5970. assemble the list of enumerators without knowing which one is last.
  5971. The extra comma does not change the meaning of the enumeration in any
  5972. way.
  5973. @node Defining Typedef Names
  5974. @chapter Defining Typedef Names
  5975. @cindex typedef names
  5976. @findex typedef
  5977. You can define a data type keyword as an alias for any type, and then
  5978. use the alias syntactically like a built-in type keyword such as
  5979. @code{int}. You do this using @code{typedef}, so these aliases are
  5980. also called @dfn{typedef names}.
  5981. @code{typedef} is followed by text that looks just like a variable
  5982. declaration, but instead of declaring variables it defines data type
  5983. keywords.
  5984. Here's how to define @code{fooptr} as a typedef alias for the type
  5985. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5986. with that type:
  5987. @example
  5988. typedef struct foo *fooptr;
  5989. fooptr x, y;
  5990. @end example
  5991. @noindent
  5992. That declaration is equivalent to the following one:
  5993. @example
  5994. struct foo *x, *y;
  5995. @end example
  5996. You can define a typedef alias for any type. For instance, this makes
  5997. @code{frobcount} an alias for type @code{int}:
  5998. @example
  5999. typedef int frobcount;
  6000. @end example
  6001. @noindent
  6002. This doesn't define a new type distinct from @code{int}. Rather,
  6003. @code{frobcount} is another name for the type @code{int}. Once the
  6004. variable is declared, it makes no difference which name the
  6005. declaration used.
  6006. There is a syntactic difference, however, between @code{frobcount} and
  6007. @code{int}: A typedef name cannot be used with
  6008. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6009. to specify the type all by itself. So you can't write this:
  6010. @example
  6011. unsigned frobcount f1; /* @r{Error!} */
  6012. @end example
  6013. But you can write this:
  6014. @example
  6015. typedef unsigned int unsigned_frobcount;
  6016. unsigned_frobcount f1;
  6017. @end example
  6018. In other words, a typedef name is not an alias for @emph{a keyword}
  6019. such as @code{int}. It stands for a @emph{type}, and that could be
  6020. the type @code{int}.
  6021. Typedef names are in the same namespace as functions and variables, so
  6022. you can't use the same name for a typedef and a function, or a typedef
  6023. and a variable. When a typedef is declared inside a code block, it is
  6024. in scope only in that block.
  6025. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6026. because many of these have standard meanings.
  6027. You can redefine a typedef name to the exact same type as its first
  6028. definition, but you cannot redefine a typedef name to a
  6029. different type, even if the two types are compatible. For example, this
  6030. is valid:
  6031. @example
  6032. typedef int frobcount;
  6033. typedef int frotzcount;
  6034. typedef frotzcount frobcount;
  6035. typedef frobcount frotzcount;
  6036. @end example
  6037. @noindent
  6038. because each typedef name is always defined with the same type
  6039. (@code{int}), but this is not valid:
  6040. @example
  6041. enum foo @{f1, f2, f3@};
  6042. typedef enum foo frobcount;
  6043. typedef int frobcount;
  6044. @end example
  6045. @noindent
  6046. Even though the type @code{enum foo} is compatible with @code{int},
  6047. they are not the @emph{same} type.
  6048. @node Statements
  6049. @chapter Statements
  6050. @cindex statements
  6051. A @dfn{statement} specifies computations to be done for effect; it
  6052. does not produce a value, as an expression would. In general a
  6053. statement ends with a semicolon (@samp{;}), but blocks (which are
  6054. statements, more or less) are an exception to that rule.
  6055. @ifnottex
  6056. @xref{Blocks}.
  6057. @end ifnottex
  6058. The places to use statements are inside a block, and inside a
  6059. complex statement. A @dfn{complex statement} contains one or two
  6060. components that are nested statements. Each such component must
  6061. consist of one and only one statement. The way to put multiple
  6062. statements in such a component is to group them into a @dfn{block}
  6063. (@pxref{Blocks}), which counts as one statement.
  6064. The following sections describe the various kinds of statement.
  6065. @menu
  6066. * Expression Statement:: Evaluate an expression, as a statement,
  6067. usually done for a side effect.
  6068. * if Statement:: Basic conditional execution.
  6069. * if-else Statement:: Multiple branches for conditional execution.
  6070. * Blocks:: Grouping multiple statements together.
  6071. * return Statement:: Return a value from a function.
  6072. * Loop Statements:: Repeatedly executing a statement or block.
  6073. * switch Statement:: Multi-way conditional choices.
  6074. * switch Example:: A plausible example of using @code{switch}.
  6075. * Duffs Device:: A special way to use @code{switch}.
  6076. * Case Ranges:: Ranges of values for @code{switch} cases.
  6077. * Null Statement:: A statement that does nothing.
  6078. * goto Statement:: Jump to another point in the source code,
  6079. identified by a label.
  6080. * Local Labels:: Labels with limited scope.
  6081. * Labels as Values:: Getting the address of a label.
  6082. * Statement Exprs:: A series of statements used as an expression.
  6083. @end menu
  6084. @node Expression Statement
  6085. @section Expression Statement
  6086. @cindex expression statement
  6087. @cindex statement, expression
  6088. The most common kind of statement in C is an @dfn{expression statement}.
  6089. It consists of an expression followed by a
  6090. semicolon. The expression's value is discarded, so the expressions
  6091. that are useful are those that have side effects: assignment
  6092. expressions, increment and decrement expressions, and function calls.
  6093. Here are examples of expression statements:
  6094. @smallexample
  6095. x = 5; /* @r{Assignment expression.} */
  6096. p++; /* @r{Increment expression.} */
  6097. printf ("Done\n"); /* @r{Function call expression.} */
  6098. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6099. x + y; /* @r{Useless statement without effect.} */
  6100. @end smallexample
  6101. In very unusual circumstances we use an expression statement
  6102. whose purpose is to get a fault if an address is invalid:
  6103. @smallexample
  6104. volatile char *p;
  6105. @r{@dots{}}
  6106. *p; /* @r{Cause signal if @code{p} is null.} */
  6107. @end smallexample
  6108. If the target of @code{p} is not declared @code{volatile}, the
  6109. compiler might optimize away the memory access, since it knows that
  6110. the value isn't really used. @xref{volatile}.
  6111. @node if Statement
  6112. @section @code{if} Statement
  6113. @cindex @code{if} statement
  6114. @cindex statement, @code{if}
  6115. @findex if
  6116. An @code{if} statement computes an expression to decide
  6117. whether to execute the following statement or not.
  6118. It looks like this:
  6119. @example
  6120. if (@var{condition})
  6121. @var{execute-if-true}
  6122. @end example
  6123. The first thing this does is compute the value of @var{condition}. If
  6124. that is true (nonzero), then it executes the statement
  6125. @var{execute-if-true}. If the value of @var{condition} is false
  6126. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6127. nothing.
  6128. This is a @dfn{complex statement} because it contains a component
  6129. @var{if-true-substatement} that is a nested statement. It must be one
  6130. and only one statement. The way to put multiple statements there is
  6131. to group them into a @dfn{block} (@pxref{Blocks}).
  6132. @node if-else Statement
  6133. @section @code{if-else} Statement
  6134. @cindex @code{if}@dots{}@code{else} statement
  6135. @cindex statement, @code{if}@dots{}@code{else}
  6136. @findex else
  6137. An @code{if}-@code{else} statement computes an expression to decide
  6138. which of two nested statements to execute.
  6139. It looks like this:
  6140. @example
  6141. if (@var{condition})
  6142. @var{if-true-substatement}
  6143. else
  6144. @var{if-false-substatement}
  6145. @end example
  6146. The first thing this does is compute the value of @var{condition}. If
  6147. that is true (nonzero), then it executes the statement
  6148. @var{if-true-substatement}. If the value of @var{condition} is false
  6149. (zero), then it executes the statement @var{if-false-substatement} instead.
  6150. This is a @dfn{complex statement} because it contains components
  6151. @var{if-true-substatement} and @var{if-else-substatement} that are
  6152. nested statements. Each must be one and only one statement. The way
  6153. to put multiple statements in such a component is to group them into a
  6154. @dfn{block} (@pxref{Blocks}).
  6155. @node Blocks
  6156. @section Blocks
  6157. @cindex block
  6158. @cindex compound statement
  6159. A @dfn{block} is a construct that contains multiple statements of any
  6160. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6161. series of statements and declarations in between. Another name for
  6162. blocks is @dfn{compound statements}.
  6163. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6164. normal statement---it does not end with a semicolon. But you can
  6165. @emph{use} it like a statement; anywhere that a statement is required
  6166. or allowed, you can write a block and consider that block a statement.
  6167. So far it seems that a block is a kind of statement with an unusual
  6168. syntax. But that is not entirely true: a function body is also a
  6169. block, and that block is definitely not a statement. The text after a
  6170. function header is not treated as a statement; only a function body is
  6171. allowed there, and nothing else would be meaningful there.
  6172. In a formal grammar we would have to choose---either a block is a kind
  6173. of statement or it is not. But this manual is meant for humans, not
  6174. for parser generators. The clearest answer for humans is, ``a block
  6175. is a statement, in some ways.''
  6176. @cindex nested block
  6177. @cindex internal block
  6178. A block that isn't a function body is called an @dfn{internal block}
  6179. or a @dfn{nested block}. You can put a nested block directly inside
  6180. another block, but more often the nested block is inside some complex
  6181. statement, such as a @code{for} statement or an @code{if} statement.
  6182. There are two uses for nested blocks in C:
  6183. @itemize @bullet
  6184. @item
  6185. To specify the scope for local declarations. For instance, a local
  6186. variable's scope is the rest of the innermost containing block.
  6187. @item
  6188. To write a series of statements where, syntactically, one statement is
  6189. called for. For instance, the @var{execute-if-true} of an @code{if}
  6190. statement is one statement. To put multiple statements there, they
  6191. have to be wrapped in a block, like this:
  6192. @example
  6193. if (x < 0)
  6194. @{
  6195. printf ("x was negative\n");
  6196. x = -x;
  6197. @}
  6198. @end example
  6199. @end itemize
  6200. This example (repeated from above) shows a nested block which serves
  6201. both purposes: it includes two statements (plus a declaration) in the
  6202. body of a @code{while} statement, and it provides the scope for the
  6203. declaration of @code{q}.
  6204. @example
  6205. void
  6206. free_intlist (struct intlistlink *p)
  6207. @{
  6208. while (p)
  6209. @{
  6210. struct intlistlink *q = p;
  6211. p = p->next;
  6212. free (q);
  6213. @}
  6214. @}
  6215. @end example
  6216. @node return Statement
  6217. @section @code{return} Statement
  6218. @cindex @code{return} statement
  6219. @cindex statement, @code{return}
  6220. @findex return
  6221. The @code{return} statement makes the containing function return
  6222. immediately. It has two forms. This one specifies no value to
  6223. return:
  6224. @example
  6225. return;
  6226. @end example
  6227. @noindent
  6228. That form is meant for functions whose return type is @code{void}
  6229. (@pxref{The Void Type}). You can also use it in a function that
  6230. returns nonvoid data, but that's a bad idea, since it makes the
  6231. function return garbage.
  6232. The form that specifies a value looks like this:
  6233. @example
  6234. return @var{value};
  6235. @end example
  6236. @noindent
  6237. which computes the expression @var{value} and makes the function
  6238. return that. If necessary, the value undergoes type conversion to
  6239. the function's declared return value type, which works like
  6240. assigning the value to a variable of that type.
  6241. @node Loop Statements
  6242. @section Loop Statements
  6243. @cindex loop statements
  6244. @cindex statements, loop
  6245. @cindex iteration
  6246. You can use a loop statement when you need to execute a series of
  6247. statements repeatedly, making an @dfn{iteration}. C provides several
  6248. different kinds of loop statements, described in the following
  6249. subsections.
  6250. Every kind of loop statement is a complex statement because contains a
  6251. component, here called @var{body}, which is a nested statement.
  6252. Most often the body is a block.
  6253. @menu
  6254. * while Statement:: Loop as long as a test expression is true.
  6255. * do-while Statement:: Execute a loop once, with further looping
  6256. as long as a test expression is true.
  6257. * break Statement:: End a loop immediately.
  6258. * for Statement:: Iterative looping.
  6259. * Example of for:: An example of iterative looping.
  6260. * Omitted for-Expressions:: for-loop expression options.
  6261. * for-Index Declarations:: for-loop declaration options.
  6262. * continue Statement:: Begin the next cycle of a loop.
  6263. @end menu
  6264. @node while Statement
  6265. @subsection @code{while} Statement
  6266. @cindex @code{while} statement
  6267. @cindex statement, @code{while}
  6268. @findex while
  6269. The @code{while} statement is the simplest loop construct.
  6270. It looks like this:
  6271. @example
  6272. while (@var{test})
  6273. @var{body}
  6274. @end example
  6275. Here, @var{body} is a statement (often a nested block) to repeat, and
  6276. @var{test} is the test expression that controls whether to repeat it again.
  6277. Each iteration of the loop starts by computing @var{test} and, if it
  6278. is true (nonzero), that means the loop should execute @var{body} again
  6279. and then start over.
  6280. Here's an example of advancing to the last structure in a chain of
  6281. structures chained through the @code{next} field:
  6282. @example
  6283. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6284. @r{@dots{}}
  6285. while (chain->next != NULL)
  6286. chain = chain->next;
  6287. @end example
  6288. @noindent
  6289. This code assumes the chain isn't empty to start with; if the chain is
  6290. empty (that is, if @code{chain} is a null pointer), the code gets a
  6291. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6292. @node do-while Statement
  6293. @subsection @code{do-while} Statement
  6294. @cindex @code{do}--@code{while} statement
  6295. @cindex statement, @code{do}--@code{while}
  6296. @findex do
  6297. The @code{do}--@code{while} statement is a simple loop construct that
  6298. performs the test at the end of the iteration.
  6299. @example
  6300. do
  6301. @var{body}
  6302. while (@var{test});
  6303. @end example
  6304. Here, @var{body} is a statement (possibly a block) to repeat, and
  6305. @var{test} is an expression that controls whether to repeat it again.
  6306. Each iteration of the loop starts by executing @var{body}. Then it
  6307. computes @var{test} and, if it is true (nonzero), that means to go
  6308. back and start over with @var{body}. If @var{test} is false (zero),
  6309. then the loop stops repeating and execution moves on past it.
  6310. @node break Statement
  6311. @subsection @code{break} Statement
  6312. @cindex @code{break} statement
  6313. @cindex statement, @code{break}
  6314. @findex break
  6315. The @code{break} statement looks like @samp{break;}. Its effect is to
  6316. exit immediately from the innermost loop construct or @code{switch}
  6317. statement (@pxref{switch Statement}).
  6318. For example, this loop advances @code{p} until the next null
  6319. character or newline.
  6320. @example
  6321. while (*p)
  6322. @{
  6323. /* @r{End loop if we have reached a newline.} */
  6324. if (*p == '\n')
  6325. break;
  6326. p++
  6327. @}
  6328. @end example
  6329. When there are nested loops, the @code{break} statement exits from the
  6330. innermost loop containing it.
  6331. @example
  6332. struct list_if_tuples
  6333. @{
  6334. struct list_if_tuples next;
  6335. int length;
  6336. data *contents;
  6337. @};
  6338. void
  6339. process_all_elements (struct list_if_tuples *list)
  6340. @{
  6341. while (list)
  6342. @{
  6343. /* @r{Process all the elements in this node's vector,}
  6344. @r{stopping when we reach one that is null.} */
  6345. for (i = 0; i < list->length; i++
  6346. @{
  6347. /* @r{Null element terminates this node's vector.} */
  6348. if (list->contents[i] == NULL)
  6349. /* @r{Exit the @code{for} loop.} */
  6350. break;
  6351. /* @r{Operate on the next element.} */
  6352. process_element (list->contents[i]);
  6353. @}
  6354. list = list->next;
  6355. @}
  6356. @}
  6357. @end example
  6358. The only way in C to exit from an outer loop is with
  6359. @code{goto} (@pxref{goto Statement}).
  6360. @node for Statement
  6361. @subsection @code{for} Statement
  6362. @cindex @code{for} statement
  6363. @cindex statement, @code{for}
  6364. @findex for
  6365. A @code{for} statement uses three expressions written inside a
  6366. parenthetical group to define the repetition of the loop. The first
  6367. expression says how to prepare to start the loop. The second says how
  6368. to test, before each iteration, whether to continue looping. The
  6369. third says how to advance, at the end of an iteration, for the next
  6370. iteration. All together, it looks like this:
  6371. @example
  6372. for (@var{start}; @var{continue-test}; @var{advance})
  6373. @var{body}
  6374. @end example
  6375. The first thing the @code{for} statement does is compute @var{start}.
  6376. The next thing it does is compute the expression @var{continue-test}.
  6377. If that expression is false (zero), the @code{for} statement finishes
  6378. immediately, so @var{body} is executed zero times.
  6379. However, if @var{continue-test} is true (nonzero), the @code{for}
  6380. statement executes @var{body}, then @var{advance}. Then it loops back
  6381. to the not-quite-top to test @var{continue-test} again. But it does
  6382. not compute @var{start} again.
  6383. @node Example of for
  6384. @subsection Example of @code{for}
  6385. Here is the @code{for} statement from the iterative Fibonacci
  6386. function:
  6387. @example
  6388. int i;
  6389. for (i = 1; i < n; ++i)
  6390. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6391. /* @r{since @code{i < n} is false the first time.} */
  6392. @{
  6393. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6394. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6395. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6396. int next = prev + last;
  6397. /* @r{Shift the values down.} */
  6398. prev = last;
  6399. last = next;
  6400. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6401. @r{and @var{prev} is @code{fib (@var{i})}.}
  6402. @r{But that won't stay true for long,}
  6403. @r{because we are about to increment @var{i}.} */
  6404. @}
  6405. @end example
  6406. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6407. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6408. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6409. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6410. that contains a declaration and two statements.
  6411. @node Omitted for-Expressions
  6412. @subsection Omitted @code{for}-Expressions
  6413. A fully-fleshed @code{for} statement contains all these parts,
  6414. @example
  6415. for (@var{start}; @var{continue-test}; @var{advance})
  6416. @var{body}
  6417. @end example
  6418. @noindent
  6419. but you can omit any of the three expressions inside the parentheses.
  6420. The parentheses and the two semicolons are required syntactically, but
  6421. the expressions between them may be missing. A missing expression
  6422. means this loop doesn't use that particular feature of the @code{for}
  6423. statement.
  6424. Instead of using @var{start}, you can do the loop preparation
  6425. before the @code{for} statement: the effect is the same. So we
  6426. could have written the beginning of the previous example this way:
  6427. @example
  6428. int i = 0;
  6429. for (; i < n; ++i)
  6430. @end example
  6431. @noindent
  6432. instead of this way:
  6433. @example
  6434. int i;
  6435. for (i = 0; i < n; ++i)
  6436. @end example
  6437. Omitting @var{continue-test} means the loop runs forever (or until
  6438. something else causes exit from it). Statements inside the loop can
  6439. test conditions for termination and use @samp{break;} to exit. This
  6440. is more flexible since you can put those tests anywhere in the loop,
  6441. not solely at the beginning.
  6442. Putting an expression in @var{advance} is almost equivalent to writing
  6443. it at the end of the loop body; it does almost the same thing. The
  6444. only difference is for the @code{continue} statement (@pxref{continue
  6445. Statement}). So we could have written this:
  6446. @example
  6447. for (i = 0; i < n;)
  6448. @{
  6449. @r{@dots{}}
  6450. ++i;
  6451. @}
  6452. @end example
  6453. @noindent
  6454. instead of this:
  6455. @example
  6456. for (i = 0; i < n; ++i)
  6457. @{
  6458. @r{@dots{}}
  6459. @}
  6460. @end example
  6461. The choice is mainly a matter of what is more readable for
  6462. programmers. However, there is also a syntactic difference:
  6463. @var{advance} is an expression, not a statement. It can't include
  6464. loops, blocks, declarations, etc.
  6465. @node for-Index Declarations
  6466. @subsection @code{for}-Index Declarations
  6467. You can declare loop-index variables directly in the @var{start}
  6468. portion of the @code{for}-loop, like this:
  6469. @example
  6470. for (int i = 0; i < n; ++i)
  6471. @{
  6472. @r{@dots{}}
  6473. @}
  6474. @end example
  6475. This kind of @var{start} is limited to a single declaration; it can
  6476. declare one or more variables, separated by commas, all of which are
  6477. the same @var{basetype} (@code{int}, in this example):
  6478. @example
  6479. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6480. @{
  6481. @r{@dots{}}
  6482. @}
  6483. @end example
  6484. @noindent
  6485. The scope of these variables is the @code{for} statement as a whole.
  6486. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6487. Variables declared in @code{for} statements should have initializers.
  6488. Omitting the initialization gives the variables unpredictable initial
  6489. values, so this code is erroneous.
  6490. @example
  6491. for (int i; i < n; ++i)
  6492. @{
  6493. @r{@dots{}}
  6494. @}
  6495. @end example
  6496. @node continue Statement
  6497. @subsection @code{continue} Statement
  6498. @cindex @code{continue} statement
  6499. @cindex statement, @code{continue}
  6500. @findex continue
  6501. The @code{continue} statement looks like @samp{continue;}, and its
  6502. effect is to jump immediately to the end of the innermost loop
  6503. construct. If it is a @code{for}-loop, the next thing that happens
  6504. is to execute the loop's @var{advance} expression.
  6505. For example, this loop increments @code{p} until the next null character
  6506. or newline, and operates (in some way not shown) on all the characters
  6507. in the line except for spaces. All it does with spaces is skip them.
  6508. @example
  6509. for (;*p; ++p)
  6510. @{
  6511. /* @r{End loop if we have reached a newline.} */
  6512. if (*p == '\n')
  6513. break;
  6514. /* @r{Pay no attention to spaces.} */
  6515. if (*p == ' ')
  6516. continue;
  6517. /* @r{Operate on the next character.} */
  6518. @r{@dots{}}
  6519. @}
  6520. @end example
  6521. @noindent
  6522. Executing @samp{continue;} skips the loop body but it does not
  6523. skip the @var{advance} expression, @code{p++}.
  6524. We could also write it like this:
  6525. @example
  6526. for (;*p; ++p)
  6527. @{
  6528. /* @r{Exit if we have reached a newline.} */
  6529. if (*p == '\n')
  6530. break;
  6531. /* @r{Pay no attention to spaces.} */
  6532. if (*p != ' ')
  6533. @{
  6534. /* @r{Operate on the next character.} */
  6535. @r{@dots{}}
  6536. @}
  6537. @}
  6538. @end example
  6539. The advantage of using @code{continue} is that it reduces the
  6540. depth of nesting.
  6541. Contrast @code{continue} with the @code{break} statement. @xref{break
  6542. Statement}.
  6543. @node switch Statement
  6544. @section @code{switch} Statement
  6545. @cindex @code{switch} statement
  6546. @cindex statement, @code{switch}
  6547. @findex switch
  6548. @findex case
  6549. @findex default
  6550. The @code{switch} statement selects code to run according to the value
  6551. of an expression. The expression, in parentheses, follows the keyword
  6552. @code{switch}. After that come all the cases to select among,
  6553. inside braces. It looks like this:
  6554. @example
  6555. switch (@var{selector})
  6556. @{
  6557. @var{cases}@r{@dots{}}
  6558. @}
  6559. @end example
  6560. A case can look like this:
  6561. @example
  6562. case @var{value}:
  6563. @var{statements}
  6564. break;
  6565. @end example
  6566. @noindent
  6567. which means ``come here if @var{selector} happens to have the value
  6568. @var{value},'' or like this (a GNU C extension):
  6569. @example
  6570. case @var{rangestart} ... @var{rangeend}:
  6571. @var{statements}
  6572. break;
  6573. @end example
  6574. @noindent
  6575. which means ``come here if @var{selector} happens to have a value
  6576. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6577. Ranges}.
  6578. The values in @code{case} labels must reduce to integer constants.
  6579. They can use arithmetic, and @code{enum} constants, but they cannot
  6580. refer to data in memory, because they have to be computed at compile
  6581. time. It is an error if two @code{case} labels specify the same
  6582. value, or ranges that overlap, or if one is a range and the other is a
  6583. value in that range.
  6584. You can also define a default case to handle ``any other value,'' like
  6585. this:
  6586. @example
  6587. default:
  6588. @var{statements}
  6589. break;
  6590. @end example
  6591. If the @code{switch} statement has no @code{default:} label, then it
  6592. does nothing when the value matches none of the cases.
  6593. The brace-group inside the @code{switch} statement is a block, and you
  6594. can declare variables with that scope just as in any other block
  6595. (@pxref{Blocks}). However, initializers in these declarations won't
  6596. necessarily be executed every time the @code{switch} statement runs,
  6597. so it is best to avoid giving them initializers.
  6598. @code{break;} inside a @code{switch} statement exits immediately from
  6599. the @code{switch} statement. @xref{break Statement}.
  6600. If there is no @code{break;} at the end of the code for a case,
  6601. execution continues into the code for the following case. This
  6602. happens more often by mistake than intentionally, but since this
  6603. feature is used in real code, we cannot eliminate it.
  6604. @strong{Warning:} When one case is intended to fall through to the
  6605. next, write a comment like @samp{falls through} to say it's
  6606. intentional. That way, other programmers won't assume it was an error
  6607. and ``fix'' it erroneously.
  6608. Consecutive @code{case} statements could, pedantically, be considered
  6609. an instance of falling through, but we don't consider or treat them that
  6610. way because they won't confuse anyone.
  6611. @node switch Example
  6612. @section Example of @code{switch}
  6613. Here's an example of using the @code{switch} statement
  6614. to distinguish among characters:
  6615. @cindex counting vowels and punctuation
  6616. @example
  6617. struct vp @{ int vowels, punct; @};
  6618. struct vp
  6619. count_vowels_and_punct (char *string)
  6620. @{
  6621. int c;
  6622. int vowels = 0;
  6623. int punct = 0;
  6624. /* @r{Don't change the parameter itself.} */
  6625. /* @r{That helps in debugging.} */
  6626. char *p = string;
  6627. struct vp value;
  6628. while (c = *p++)
  6629. switch (c)
  6630. @{
  6631. case 'y':
  6632. case 'Y':
  6633. /* @r{We assume @code{y_is_consonant} will check surrounding
  6634. letters to determine whether this y is a vowel.} */
  6635. if (y_is_consonant (p - 1))
  6636. break;
  6637. /* @r{Falls through} */
  6638. case 'a':
  6639. case 'e':
  6640. case 'i':
  6641. case 'o':
  6642. case 'u':
  6643. case 'A':
  6644. case 'E':
  6645. case 'I':
  6646. case 'O':
  6647. case 'U':
  6648. vowels++;
  6649. break;
  6650. case '.':
  6651. case ',':
  6652. case ':':
  6653. case ';':
  6654. case '?':
  6655. case '!':
  6656. case '\"':
  6657. case '\'':
  6658. punct++;
  6659. break;
  6660. @}
  6661. value.vowels = vowels;
  6662. value.punct = punct;
  6663. return value;
  6664. @}
  6665. @end example
  6666. @node Duffs Device
  6667. @section Duff's Device
  6668. @cindex Duff's device
  6669. The cases in a @code{switch} statement can be inside other control
  6670. constructs. For instance, we can use a technique known as @dfn{Duff's
  6671. device} to optimize this simple function,
  6672. @example
  6673. void
  6674. copy (char *to, char *from, int count)
  6675. @{
  6676. while (count > 0)
  6677. *to++ = *from++, count--;
  6678. @}
  6679. @end example
  6680. @noindent
  6681. which copies memory starting at @var{from} to memory starting at
  6682. @var{to}.
  6683. Duff's device involves unrolling the loop so that it copies
  6684. several characters each time around, and using a @code{switch} statement
  6685. to enter the loop body at the proper point:
  6686. @example
  6687. void
  6688. copy (char *to, char *from, int count)
  6689. @{
  6690. if (count <= 0)
  6691. return;
  6692. int n = (count + 7) / 8;
  6693. switch (count % 8)
  6694. @{
  6695. do @{
  6696. case 0: *to++ = *from++;
  6697. case 7: *to++ = *from++;
  6698. case 6: *to++ = *from++;
  6699. case 5: *to++ = *from++;
  6700. case 4: *to++ = *from++;
  6701. case 3: *to++ = *from++;
  6702. case 2: *to++ = *from++;
  6703. case 1: *to++ = *from++;
  6704. @} while (--n > 0);
  6705. @}
  6706. @}
  6707. @end example
  6708. @node Case Ranges
  6709. @section Case Ranges
  6710. @cindex case ranges
  6711. @cindex ranges in case statements
  6712. You can specify a range of consecutive values in a single @code{case} label,
  6713. like this:
  6714. @example
  6715. case @var{low} ... @var{high}:
  6716. @end example
  6717. @noindent
  6718. This has the same effect as the proper number of individual @code{case}
  6719. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6720. This feature is especially useful for ranges of ASCII character codes:
  6721. @example
  6722. case 'A' ... 'Z':
  6723. @end example
  6724. @strong{Be careful:} with integers, write spaces around the @code{...}
  6725. to prevent it from being parsed wrong. For example, write this:
  6726. @example
  6727. case 1 ... 5:
  6728. @end example
  6729. @noindent
  6730. rather than this:
  6731. @example
  6732. case 1...5:
  6733. @end example
  6734. @node Null Statement
  6735. @section Null Statement
  6736. @cindex null statement
  6737. @cindex statement, null
  6738. A @dfn{null statement} is just a semicolon. It does nothing.
  6739. A null statement is a placeholder for use where a statement is
  6740. grammatically required, but there is nothing to be done. For
  6741. instance, sometimes all the work of a @code{for}-loop is done in the
  6742. @code{for}-header itself, leaving no work for the body. Here is an
  6743. example that searches for the first newline in @code{array}:
  6744. @example
  6745. for (p = array; *p != '\n'; p++)
  6746. ;
  6747. @end example
  6748. @node goto Statement
  6749. @section @code{goto} Statement and Labels
  6750. @cindex @code{goto} statement
  6751. @cindex statement, @code{goto}
  6752. @cindex label
  6753. @findex goto
  6754. The @code{goto} statement looks like this:
  6755. @example
  6756. goto @var{label};
  6757. @end example
  6758. @noindent
  6759. Its effect is to transfer control immediately to another part of the
  6760. current function---where the label named @var{label} is defined.
  6761. An ordinary label definition looks like this:
  6762. @example
  6763. @var{label}:
  6764. @end example
  6765. @noindent
  6766. and it can appear before any statement. You can't use @code{default}
  6767. as a label, since that has a special meaning for @code{switch}
  6768. statements.
  6769. An ordinary label doesn't need a separate declaration; defining it is
  6770. enough.
  6771. Here's an example of using @code{goto} to implement a loop
  6772. equivalent to @code{do}--@code{while}:
  6773. @example
  6774. @{
  6775. loop_restart:
  6776. @var{body}
  6777. if (@var{condition})
  6778. goto loop_restart;
  6779. @}
  6780. @end example
  6781. The name space of labels is separate from that of variables and functions.
  6782. Thus, there is no error in using a single name in both ways:
  6783. @example
  6784. @{
  6785. int foo; // @r{Variable @code{foo}.}
  6786. foo: // @r{Label @code{foo}.}
  6787. @var{body}
  6788. if (foo > 0) // @r{Variable @code{foo}.}
  6789. goto foo; // @r{Label @code{foo}.}
  6790. @}
  6791. @end example
  6792. Blocks have no effect on ordinary labels; each label name is defined
  6793. throughout the whole of the function it appears in. It looks strange to
  6794. jump into a block with @code{goto}, but it works. For example,
  6795. @example
  6796. if (x < 0)
  6797. goto negative;
  6798. if (y < 0)
  6799. @{
  6800. negative:
  6801. printf ("Negative\n");
  6802. return;
  6803. @}
  6804. @end example
  6805. If the goto jumps into the scope of a variable, it does not
  6806. initialize the variable. For example, if @code{x} is negative,
  6807. @example
  6808. if (x < 0)
  6809. goto negative;
  6810. if (y < 0)
  6811. @{
  6812. int i = 5;
  6813. negative:
  6814. printf ("Negative, and i is %d\n", i);
  6815. return;
  6816. @}
  6817. @end example
  6818. @noindent
  6819. prints junk because @code{i} was not initialized.
  6820. If the block declares a variable-length automatic array, jumping into
  6821. it gives a compilation error. However, jumping out of the scope of a
  6822. variable-length array works fine, and deallocates its storage.
  6823. A label can't come directly before a declaration, so the code can't
  6824. jump directly to one. For example, this is not allowed:
  6825. @example
  6826. @{
  6827. goto foo;
  6828. foo:
  6829. int x = 5;
  6830. bar(&x);
  6831. @}
  6832. @end example
  6833. @noindent
  6834. The workaround is to add a statement, even an empty statement,
  6835. directly after the label. For example:
  6836. @example
  6837. @{
  6838. goto foo;
  6839. foo:
  6840. ;
  6841. int x = 5;
  6842. bar(&x);
  6843. @}
  6844. @end example
  6845. Likewise, a label can't be the last thing in a block. The workaround
  6846. solution is the same: add a semicolon after the label.
  6847. These unnecessary restrictions on labels make no sense, and ought in
  6848. principle to be removed; but they do only a little harm since labels
  6849. and @code{goto} are rarely the best way to write a program.
  6850. These examples are all artificial; it would be more natural to
  6851. write them in other ways, without @code{goto}. For instance,
  6852. the clean way to write the example that prints @samp{Negative} is this:
  6853. @example
  6854. if (x < 0 || y < 0)
  6855. @{
  6856. printf ("Negative\n");
  6857. return;
  6858. @}
  6859. @end example
  6860. @noindent
  6861. It is hard to construct simple examples where @code{goto} is actually
  6862. the best way to write a program. Its rare good uses tend to be in
  6863. complex code, thus not apt for the purpose of explaining the meaning
  6864. of @code{goto}.
  6865. The only good time to use @code{goto} is when it makes the code
  6866. simpler than any alternative. Jumping backward is rarely desirable,
  6867. because usually the other looping and control constructs give simpler
  6868. code. Using @code{goto} to jump forward is more often desirable, for
  6869. instance when a function needs to do some processing in an error case
  6870. and errors can occur at various different places within the function.
  6871. @node Local Labels
  6872. @section Locally Declared Labels
  6873. @cindex local labels
  6874. @cindex macros, local labels
  6875. @findex __label__
  6876. In GNU C you can declare @dfn{local labels} in any nested block
  6877. scope. A local label is used in a @code{goto} statement just like an
  6878. ordinary label, but you can only reference it within the block in
  6879. which it was declared.
  6880. A local label declaration looks like this:
  6881. @example
  6882. __label__ @var{label};
  6883. @end example
  6884. @noindent
  6885. or
  6886. @example
  6887. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6888. @end example
  6889. Local label declarations must come at the beginning of the block,
  6890. before any ordinary declarations or statements.
  6891. The label declaration declares the label @emph{name}, but does not define
  6892. the label itself. That's done in the usual way, with
  6893. @code{@var{label}:}, before one of the statements in the block.
  6894. The local label feature is useful for complex macros. If a macro
  6895. contains nested loops, a @code{goto} can be useful for breaking out of
  6896. them. However, an ordinary label whose scope is the whole function
  6897. cannot be used: if the macro can be expanded several times in one
  6898. function, the label will be multiply defined in that function. A
  6899. local label avoids this problem. For example:
  6900. @example
  6901. #define SEARCH(value, array, target) \
  6902. do @{ \
  6903. __label__ found; \
  6904. __auto_type _SEARCH_target = (target); \
  6905. __auto_type _SEARCH_array = (array); \
  6906. int i, j; \
  6907. int value; \
  6908. for (i = 0; i < max; i++) \
  6909. for (j = 0; j < max; j++) \
  6910. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6911. @{ (value) = i; goto found; @} \
  6912. (value) = -1; \
  6913. found:; \
  6914. @} while (0)
  6915. @end example
  6916. This could also be written using a statement expression
  6917. (@pxref{Statement Exprs}):
  6918. @example
  6919. #define SEARCH(array, target) \
  6920. (@{ \
  6921. __label__ found; \
  6922. __auto_type _SEARCH_target = (target); \
  6923. __auto_type _SEARCH_array = (array); \
  6924. int i, j; \
  6925. int value; \
  6926. for (i = 0; i < max; i++) \
  6927. for (j = 0; j < max; j++) \
  6928. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6929. @{ value = i; goto found; @} \
  6930. value = -1; \
  6931. found: \
  6932. value; \
  6933. @})
  6934. @end example
  6935. Ordinary labels are visible throughout the function where they are
  6936. defined, and only in that function. However, explicitly declared
  6937. local labels of a block are visible in nested functions declared
  6938. within that block. @xref{Nested Functions}, for details.
  6939. @xref{goto Statement}.
  6940. @node Labels as Values
  6941. @section Labels as Values
  6942. @cindex labels as values
  6943. @cindex computed gotos
  6944. @cindex goto with computed label
  6945. @cindex address of a label
  6946. In GNU C, you can get the address of a label defined in the current
  6947. function (or a local label defined in the containing function) with
  6948. the unary operator @samp{&&}. The value has type @code{void *}. This
  6949. value is a constant and can be used wherever a constant of that type
  6950. is valid. For example:
  6951. @example
  6952. void *ptr;
  6953. @r{@dots{}}
  6954. ptr = &&foo;
  6955. @end example
  6956. To use these values requires a way to jump to one. This is done
  6957. with the computed goto statement@footnote{The analogous feature in
  6958. Fortran is called an assigned goto, but that name seems inappropriate in
  6959. C, since you can do more with label addresses than store them in special label
  6960. variables.}, @code{goto *@var{exp};}. For example,
  6961. @example
  6962. goto *ptr;
  6963. @end example
  6964. @noindent
  6965. Any expression of type @code{void *} is allowed.
  6966. @xref{goto Statement}.
  6967. @menu
  6968. * Label Value Uses:: Examples of using label values.
  6969. * Label Value Caveats:: Limitations of label values.
  6970. @end menu
  6971. @node Label Value Uses
  6972. @subsection Label Value Uses
  6973. One use for label-valued constants is to initialize a static array to
  6974. serve as a jump table:
  6975. @example
  6976. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6977. @end example
  6978. Then you can select a label with indexing, like this:
  6979. @example
  6980. goto *array[i];
  6981. @end example
  6982. @noindent
  6983. Note that this does not check whether the subscript is in bounds---array
  6984. indexing in C never checks that.
  6985. You can make the table entries offsets instead of addresses
  6986. by subtracting one label from the others. Here is an example:
  6987. @example
  6988. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6989. &&hack - &&foo @};
  6990. goto *(&&foo + array[i]);
  6991. @end example
  6992. @noindent
  6993. Using offsets is preferable in shared libraries, as it avoids the need
  6994. for dynamic relocation of the array elements; therefore, the array can
  6995. be read-only.
  6996. An array of label values or offsets serves a purpose much like that of
  6997. the @code{switch} statement. The @code{switch} statement is cleaner,
  6998. so use @code{switch} by preference when feasible.
  6999. Another use of label values is in an interpreter for threaded code.
  7000. The labels within the interpreter function can be stored in the
  7001. threaded code for super-fast dispatching.
  7002. @node Label Value Caveats
  7003. @subsection Label Value Caveats
  7004. Jumping to a label defined in another function does not work.
  7005. It can cause unpredictable results.
  7006. The best way to avoid this is to store label values only in
  7007. automatic variables, or static variables whose names are declared
  7008. within the function. Never pass them as arguments.
  7009. @cindex cloning
  7010. An optimization known as @dfn{cloning} generates multiple simplified
  7011. variants of a function's code, for use with specific fixed arguments.
  7012. Using label values in certain ways, such as saving the address in one
  7013. call to the function and using it again in another call, would make cloning
  7014. give incorrect results. These functions must disable cloning.
  7015. Inlining calls to the function would also result in multiple copies of
  7016. the code, each with its own value of the same label. Using the label
  7017. in a computed goto is no problem, because the computed goto inhibits
  7018. inlining. However, using the label value in some other way, such as
  7019. an indication of where an error occurred, would be optimized wrong.
  7020. These functions must disable inlining.
  7021. To prevent inlining or cloning of a function, specify
  7022. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7023. @xref{Attributes}.
  7024. When a function uses a label value in a static variable initializer,
  7025. that automatically prevents inlining or cloning the function.
  7026. @node Statement Exprs
  7027. @section Statements and Declarations in Expressions
  7028. @cindex statements inside expressions
  7029. @cindex declarations inside expressions
  7030. @cindex expressions containing statements
  7031. @c the above section title wrapped and causes an underfull hbox.. i
  7032. @c changed it from "within" to "in". --mew 4feb93
  7033. A block enclosed in parentheses can be used as an expression in GNU
  7034. C@. This provides a way to use local variables, loops and switches within
  7035. an expression. We call it a @dfn{statement expression}.
  7036. Recall that a block is a sequence of statements
  7037. surrounded by braces. In this construct, parentheses go around the
  7038. braces. For example:
  7039. @example
  7040. (@{ int y = foo (); int z;
  7041. if (y > 0) z = y;
  7042. else z = - y;
  7043. z; @})
  7044. @end example
  7045. @noindent
  7046. is a valid (though slightly more complex than necessary) expression
  7047. for the absolute value of @code{foo ()}.
  7048. The last statement in the block should be an expression statement; an
  7049. expression followed by a semicolon, that is. The value of this
  7050. expression serves as the value of statement expression. If the last
  7051. statement is anything else, the statement expression's value is
  7052. @code{void}.
  7053. This feature is mainly useful in making macro definitions compute each
  7054. operand exactly once. @xref{Macros and Auto Type}.
  7055. Statement expressions are not allowed in expressions that must be
  7056. constant, such as the value for an enumerator, the width of a
  7057. bit-field, or the initial value of a static variable.
  7058. Jumping into a statement expression---with @code{goto}, or using a
  7059. @code{switch} statement outside the statement expression---is an
  7060. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7061. compiler can't detect the error, but it still won't work.
  7062. Jumping out of a statement expression is permitted, but since
  7063. subexpressions in C are not computed in a strict order, it is
  7064. unpredictable which other subexpressions will have been computed by
  7065. then. For example,
  7066. @example
  7067. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7068. @end example
  7069. @noindent
  7070. calls @code{foo} and @code{bar1} before it jumps, and never
  7071. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7072. does get called, that occurs after @code{foo} and before @code{bar1}.
  7073. @node Variables
  7074. @chapter Variables
  7075. @cindex variables
  7076. Every variable used in a C program needs to be made known by a
  7077. @dfn{declaration}. It can be used only after it has been declared.
  7078. It is an error to declare a variable name more than once in the same
  7079. scope; an exception is that @code{extern} declarations and tentative
  7080. definitions can coexist with another declaration of the same
  7081. variable.
  7082. Variables can be declared anywhere within a block or file. (Older
  7083. versions of C required that all variable declarations within a block
  7084. occur before any statements.)
  7085. Variables declared within a function or block are @dfn{local} to
  7086. it. This means that the variable name is visible only until the end
  7087. of that function or block, and the memory space is allocated only
  7088. while control is within it.
  7089. Variables declared at the top level in a file are called @dfn{file-scope}.
  7090. They are assigned fixed, distinct memory locations, so they retain
  7091. their values for the whole execution of the program.
  7092. @menu
  7093. * Variable Declarations:: Name a variable and and reserve space for it.
  7094. * Initializers:: Assigning inital values to variables.
  7095. * Designated Inits:: Assigning initial values to array elements
  7096. at particular array indices.
  7097. * Auto Type:: Obtaining the type of a variable.
  7098. * Local Variables:: Variables declared in function definitions.
  7099. * File-Scope Variables:: Variables declared outside of
  7100. function definitions.
  7101. * Static Local Variables:: Variables declared within functions,
  7102. but with permanent storage allocation.
  7103. * Extern Declarations:: Declaring a variable
  7104. which is allocated somewhere else.
  7105. * Allocating File-Scope:: When is space allocated
  7106. for file-scope variables?
  7107. * auto and register:: Historically used storage directions.
  7108. * Omitting Types:: The bad practice of declaring variables
  7109. with implicit type.
  7110. @end menu
  7111. @node Variable Declarations
  7112. @section Variable Declarations
  7113. @cindex variable declarations
  7114. @cindex declaration of variables
  7115. Here's what a variable declaration looks like:
  7116. @example
  7117. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7118. @end example
  7119. The @var{keywords} specify how to handle the scope of the variable
  7120. name and the allocation of its storage. Most declarations have
  7121. no keywords because the defaults are right for them.
  7122. C allows these keywords to come before or after @var{basetype}, or
  7123. even in the middle of it as in @code{unsigned static int}, but don't
  7124. do that---it would surprise other programmers. Always write the
  7125. keywords first.
  7126. The @var{basetype} can be any of the predefined types of C, or a type
  7127. keyword defined with @code{typedef}. It can also be @code{struct
  7128. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7129. addition, it can include type qualifiers such as @code{const} and
  7130. @code{volatile} (@pxref{Type Qualifiers}).
  7131. In the simplest case, @var{decorated-variable} is just the variable
  7132. name. That declares the variable with the type specified by
  7133. @var{basetype}. For instance,
  7134. @example
  7135. int foo;
  7136. @end example
  7137. @noindent
  7138. uses @code{int} as the @var{basetype} and @code{foo} as the
  7139. @var{decorated-variable}. It declares @code{foo} with type
  7140. @code{int}.
  7141. @example
  7142. struct tree_node foo;
  7143. @end example
  7144. @noindent
  7145. declares @code{foo} with type @code{struct tree_node}.
  7146. @menu
  7147. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7148. array and pointer types.
  7149. * Combining Variable Declarations:: More than one variable declaration
  7150. in a single statement.
  7151. @end menu
  7152. @node Declaring Arrays and Pointers
  7153. @subsection Declaring Arrays and Pointers
  7154. @cindex declaring arrays and pointers
  7155. @cindex array, declaring
  7156. @cindex pointers, declaring
  7157. To declare a variable that is an array, write
  7158. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7159. @example
  7160. int foo[5];
  7161. @end example
  7162. To declare a variable that has a pointer type, write
  7163. @code{*@var{variable}} for @var{decorated-variable}:
  7164. @example
  7165. struct list_elt *foo;
  7166. @end example
  7167. These constructs nest. For instance,
  7168. @example
  7169. int foo[3][5];
  7170. @end example
  7171. @noindent
  7172. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7173. @example
  7174. struct list_elt *foo[5];
  7175. @end example
  7176. @noindent
  7177. declares @code{foo} as an array of 5 pointers to structures, and
  7178. @example
  7179. struct list_elt **foo;
  7180. @end example
  7181. @noindent
  7182. declares @code{foo} as a pointer to a pointer to a structure.
  7183. @example
  7184. int **(*foo[30])(int, double);
  7185. @end example
  7186. @noindent
  7187. declares @code{foo} as an array of 30 pointers to functions
  7188. (@pxref{Function Pointers}), each of which must accept two arguments
  7189. (one @code{int} and one @code{double}) and return type @code{int **}.
  7190. @example
  7191. void
  7192. bar (int size)
  7193. @{
  7194. int foo[size];
  7195. @r{@dots{}}
  7196. @}
  7197. @end example
  7198. @noindent
  7199. declares @code{foo} as an array of integers with a size specified at
  7200. run time when the function @code{bar} is called.
  7201. @node Combining Variable Declarations
  7202. @subsection Combining Variable Declarations
  7203. @cindex combining variable declarations
  7204. @cindex variable declarations, combining
  7205. @cindex declarations, combining
  7206. When multiple declarations have the same @var{keywords} and
  7207. @var{basetype}, you can combine them using commas. Thus,
  7208. @example
  7209. @var{keywords} @var{basetype}
  7210. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7211. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7212. @end example
  7213. @noindent
  7214. is equivalent to
  7215. @example
  7216. @var{keywords} @var{basetype}
  7217. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7218. @var{keywords} @var{basetype}
  7219. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7220. @end example
  7221. Here are some simple examples:
  7222. @example
  7223. int a, b;
  7224. int a = 1, b = 2;
  7225. int a, *p, array[5];
  7226. int a = 0, *p = &a, array[5] = @{1, 2@};
  7227. @end example
  7228. @noindent
  7229. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7230. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7231. Since the initializer for @code{array} specifies only two elements,
  7232. the other three elements are initialized to zero.
  7233. @node Initializers
  7234. @section Initializers
  7235. @cindex initializers
  7236. A variable's declaration, unless it is @code{extern}, should also
  7237. specify its initial value. For numeric and pointer-type variables,
  7238. the initializer is an expression for the value. If necessary, it is
  7239. converted to the variable's type, just as in an assignment.
  7240. You can also initialize a local structure-type (@pxref{Structures}) or
  7241. local union-type (@pxref{Unions}) variable this way, from an
  7242. expression whose value has the same type. But you can't initialize an
  7243. array this way (@pxref{Arrays}), since arrays are not first-class
  7244. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7245. assignment.
  7246. You can initialize arrays and structures componentwise,
  7247. with a list of the elements or components. You can initialize
  7248. a union with any one of its alternatives.
  7249. @itemize @bullet
  7250. @item
  7251. A component-wise initializer for an array consists of element values
  7252. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7253. don't cover all the elements in the array, the remaining elements are
  7254. initialized to zero.
  7255. You can omit the size of the array when you declare it, and let
  7256. the initializer specify the size:
  7257. @example
  7258. int array[] = @{ 3, 9, 12 @};
  7259. @end example
  7260. @item
  7261. A component-wise initializer for a structure consists of field values
  7262. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7263. order as the fields are declared in the structure. If the values in
  7264. the initializer don't cover all the fields in the structure, the
  7265. remaining fields are initialized to zero.
  7266. @item
  7267. The initializer for a union-type variable has the form @code{@{
  7268. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7269. in the union definition.
  7270. @end itemize
  7271. For an array of arrays, a structure containing arrays, an array of
  7272. structures, etc., you can nest these constructs. For example,
  7273. @example
  7274. struct point @{ double x, y; @};
  7275. struct point series[]
  7276. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7277. @end example
  7278. You can omit a pair of inner braces if they contain the right
  7279. number of elements for the sub-value they initialize, so that
  7280. no elements or fields need to be filled in with zeros.
  7281. But don't do that very much, as it gets confusing.
  7282. An array of @code{char} can be initialized using a string constant.
  7283. Recall that the string constant includes an implicit null character at
  7284. the end (@pxref{String Constants}). Using a string constant as
  7285. initializer means to use its contents as the initial values of the
  7286. array elements. Here are examples:
  7287. @example
  7288. char text[6] = "text!"; /* @r{Includes the null.} */
  7289. char text[5] = "text!"; /* @r{Excludes the null.} */
  7290. char text[] = "text!"; /* @r{Gets length 6.} */
  7291. char text[]
  7292. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7293. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7294. @end example
  7295. @noindent
  7296. and this kind of initializer can be nested inside braces to initialize
  7297. structures or arrays that contain a @code{char}-array.
  7298. In like manner, you can use a wide string constant to initialize
  7299. an array of @code{wchar_t}.
  7300. @node Designated Inits
  7301. @section Designated Initializers
  7302. @cindex initializers with labeled elements
  7303. @cindex labeled elements in initializers
  7304. @cindex case labels in initializers
  7305. @cindex designated initializers
  7306. In a complex structure or long array, it's useful to indicate
  7307. which field or element we are initializing.
  7308. To designate specific array elements during initialization, include
  7309. the array index in brackets, and an assignment operator, for each
  7310. element:
  7311. @example
  7312. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7313. @end example
  7314. @noindent
  7315. This does the same thing as:
  7316. @example
  7317. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7318. @end example
  7319. The array initialization can include non-designated element values
  7320. alongside designated indices; these follow the expected ordering
  7321. of the array initialization, so that
  7322. @example
  7323. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7324. @end example
  7325. @noindent
  7326. does the same thing as:
  7327. @example
  7328. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7329. @end example
  7330. Note that you can only use constant expressions as array index values,
  7331. not variables.
  7332. If you need to initialize a subsequence of sequential array elements to
  7333. the same value, you can specify a range:
  7334. @example
  7335. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7336. @end example
  7337. @noindent
  7338. Using a range this way is a GNU C extension.
  7339. When subsequence ranges overlap, each element is initialized by the
  7340. last specification that applies to it. Thus, this initialization is
  7341. equivalent to the previous one.
  7342. @example
  7343. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7344. @end example
  7345. @noindent
  7346. as the second overrides the first for elements 0 through 19.
  7347. The value used to initialize a range of elements is evaluated only
  7348. once, for the first element in the range. So for example, this code
  7349. @example
  7350. int random_values[100]
  7351. = @{ [0 ... 99] = get_random_number() @};
  7352. @end example
  7353. @noindent
  7354. would initialize all 100 elements of the array @code{random_values} to
  7355. the same value---probably not what is intended.
  7356. Similarly, you can initialize specific fields of a structure variable
  7357. by specifying the field name prefixed with a dot:
  7358. @example
  7359. struct point @{ int x; int y; @};
  7360. struct point foo = @{ .y = 42; @};
  7361. @end example
  7362. @noindent
  7363. The same syntax works for union variables as well:
  7364. @example
  7365. union int_double @{ int i; double d; @};
  7366. union int_double foo = @{ .d = 34 @};
  7367. @end example
  7368. @noindent
  7369. This casts the integer value 34 to a double and stores it
  7370. in the union variable @code{foo}.
  7371. You can designate both array elements and structure elements in
  7372. the same initialization; for example, here's an array of point
  7373. structures:
  7374. @example
  7375. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7376. @end example
  7377. Along with the capability to specify particular array and structure
  7378. elements to initialize comes the possibility of initializing the same
  7379. element more than once:
  7380. @example
  7381. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7382. @end example
  7383. @noindent
  7384. In such a case, the last initialization value is retained.
  7385. @node Auto Type
  7386. @section Referring to a Type with @code{__auto_type}
  7387. @findex __auto_type
  7388. @findex typeof
  7389. @cindex macros, types of arguments
  7390. You can declare a variable copying the type from
  7391. the initializer by using @code{__auto_type} instead of a particular type.
  7392. Here's an example:
  7393. @example
  7394. #define max(a,b) \
  7395. (@{ __auto_type _a = (a); \
  7396. __auto_type _b = (b); \
  7397. _a > _b ? _a : _b @})
  7398. @end example
  7399. This defines @code{_a} to be of the same type as @code{a}, and
  7400. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7401. to do in a macro that ought to be able to handle any type of data
  7402. (@pxref{Macros and Auto Type}).
  7403. The original GNU C method for obtaining the type of a value is to use
  7404. @code{typeof}, which takes as an argument either a value or the name of
  7405. a type. The previous example could also be written as:
  7406. @example
  7407. #define max(a,b) \
  7408. (@{ typeof(a) _a = (a); \
  7409. typeof(b) _b = (b); \
  7410. _a > _b ? _a : _b @})
  7411. @end example
  7412. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7413. principal use case for @code{typeof} is in variable declarations with
  7414. initialization, which is exactly what @code{__auto_type} handles.
  7415. @node Local Variables
  7416. @section Local Variables
  7417. @cindex local variables
  7418. @cindex variables, local
  7419. Declaring a variable inside a function definition (@pxref{Function
  7420. Definitions}) makes the variable name @dfn{local} to the containing
  7421. block---that is, the containing pair of braces. More precisely, the
  7422. variable's name is visible starting just after where it appears in the
  7423. declaration, and its visibility continues until the end of the block.
  7424. Local variables in C are generally @dfn{automatic} variables: each
  7425. variable's storage exists only from the declaration to the end of the
  7426. block. Execution of the declaration allocates the storage, computes
  7427. the initial value, and stores it in the variable. The end of the
  7428. block deallocates the storage.@footnote{Due to compiler optimizations,
  7429. allocation and deallocation don't necessarily really happen at
  7430. those times.}
  7431. @strong{Warning:} Two declarations for the same local variable
  7432. in the same scope are an error.
  7433. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7434. The total space for the program's stack may be limited; therefore,
  7435. in using very large arrays, it may be necessary to allocate
  7436. them in some other way to stop the program from crashing.
  7437. @strong{Warning:} If the declaration of an automatic variable does not
  7438. specify an initial value, the variable starts out containing garbage.
  7439. In this example, the value printed could be anything at all:
  7440. @example
  7441. @{
  7442. int i;
  7443. printf ("Print junk %d\n", i);
  7444. @}
  7445. @end example
  7446. In a simple test program, that statement is likely to print 0, simply
  7447. because every process starts with memory zeroed. But don't rely on it
  7448. to be zero---that is erroneous.
  7449. @strong{Note:} Make sure to store a value into each local variable (by
  7450. assignment, or by initialization) before referring to its value.
  7451. @node File-Scope Variables
  7452. @section File-Scope Variables
  7453. @cindex file-scope variables
  7454. @cindex global variables
  7455. @cindex variables, file-scope
  7456. @cindex variables, global
  7457. A variable declaration at the top level in a file (not inside a
  7458. function definition) declares a @dfn{file-scope variable}. Loading a
  7459. program allocates the storage for all the file-scope variables in it,
  7460. and initializes them too.
  7461. Each file-scope variable is either @dfn{static} (limited to one
  7462. compilation module) or @dfn{global} (shared with all compilation
  7463. modules in the program). To make the variable static, write the
  7464. keyword @code{static} at the start of the declaration. Omitting
  7465. @code{static} makes the variable global.
  7466. The initial value for a file-scope variable can't depend on the
  7467. contents of storage, and can't call any functions.
  7468. @example
  7469. int foo = 5; /* @r{Valid.} */
  7470. int bar = foo; /* @r{Invalid!} */
  7471. int bar = sin (1.0); /* @r{Invalid!} */
  7472. @end example
  7473. But it can use the address of another file-scope variable:
  7474. @example
  7475. int foo;
  7476. int *bar = &foo; /* @r{Valid.} */
  7477. int arr[5];
  7478. int *bar3 = &arr[3]; /* @r{Valid.} */
  7479. int *bar4 = arr + 4; /* @r{Valid.} */
  7480. @end example
  7481. It is valid for a module to have multiple declarations for a
  7482. file-scope variable, as long as they are all global or all static, but
  7483. at most one declaration can specify an initial value for it.
  7484. @node Static Local Variables
  7485. @section Static Local Variables
  7486. @cindex static local variables
  7487. @cindex variables, static local
  7488. @findex static
  7489. The keyword @code{static} in a local variable declaration says to
  7490. allocate the storage for the variable permanently, just like a
  7491. file-scope variable, even if the declaration is within a function.
  7492. Here's an example:
  7493. @example
  7494. int
  7495. increment_counter ()
  7496. @{
  7497. static int counter = 0;
  7498. return ++counter;
  7499. @}
  7500. @end example
  7501. The scope of the name @code{counter} runs from the declaration to the
  7502. end of the containing block, just like an automatic local variable,
  7503. but its storage is permanent, so the value persists from one call to
  7504. the next. As a result, each call to @code{increment_counter}
  7505. returns a different, unique value.
  7506. The initial value of a static local variable has the same limitations
  7507. as for file-scope variables: it can't depend on the contents of
  7508. storage or call any functions. It can use the address of a file-scope
  7509. variable or a static local variable, because those addresses are
  7510. determined before the program runs.
  7511. @node Extern Declarations
  7512. @section @code{extern} Declarations
  7513. @cindex @code{extern} declarations
  7514. @cindex declarations, @code{extern}
  7515. @findex extern
  7516. An @code{extern} declaration is used to refer to a global variable
  7517. whose principal declaration comes elsewhere---in the same module, or in
  7518. another compilation module. It looks like this:
  7519. @example
  7520. extern @var{basetype} @var{decorated-variable};
  7521. @end example
  7522. Its meaning is that, in the current scope, the variable name refers to
  7523. the file-scope variable of that name---which needs to be declared in a
  7524. non-@code{extern}, non-@code{static} way somewhere else.
  7525. For instance, if one compilation module has this global variable
  7526. declaration
  7527. @example
  7528. int error_count = 0;
  7529. @end example
  7530. @noindent
  7531. then other compilation modules can specify this
  7532. @example
  7533. extern int error_count;
  7534. @end example
  7535. @noindent
  7536. to allow reference to the same variable.
  7537. The usual place to write an @code{extern} declaration is at top level
  7538. in a source file, but you can write an @code{extern} declaration
  7539. inside a block to make a global or static file-scope variable
  7540. accessible in that block.
  7541. Since an @code{extern} declaration does not allocate space for the
  7542. variable, it can omit the size of an array:
  7543. @example
  7544. extern int array[];
  7545. @end example
  7546. You can use @code{array} normally in all contexts where it is
  7547. converted automatically to a pointer. However, to use it as the
  7548. operand of @code{sizeof} is an error, since the size is unknown.
  7549. It is valid to have multiple @code{extern} declarations for the same
  7550. variable, even in the same scope, if they give the same type. They do
  7551. not conflict---they agree. For an array, it is legitimate for some
  7552. @code{extern} declarations can specify the size while others omit it.
  7553. However, if two declarations give different sizes, that is an error.
  7554. Likewise, you can use @code{extern} declarations at file scope
  7555. (@pxref{File-Scope Variables}) followed by an ordinary global
  7556. (non-static) declaration of the same variable. They do not conflict,
  7557. because they say compatible things about the same meaning of the variable.
  7558. @node Allocating File-Scope
  7559. @section Allocating File-Scope Variables
  7560. @cindex allocation file-scope variables
  7561. @cindex file-scope variables, allocating
  7562. Some file-scope declarations allocate space for the variable, and some
  7563. don't.
  7564. A file-scope declaration with an initial value @emph{must} allocate
  7565. space for the variable; if there are two of such declarations for the
  7566. same variable, even in different compilation modules, they conflict.
  7567. An @code{extern} declaration @emph{never} allocates space for the variable.
  7568. If all the top-level declarations of a certain variable are
  7569. @code{extern}, the variable never gets memory space. If that variable
  7570. is used anywhere in the program, the use will be reported as an error,
  7571. saying that the variable is not defined.
  7572. @cindex tentative definition
  7573. A file-scope declaration without an initial value is called a
  7574. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7575. allocate space for the variable, but does not insist. So it causes no
  7576. conflict, no error, if the variable has another declaration that
  7577. allocates space for it, perhaps in another compilation module. But if
  7578. nothing else allocates space for the variable, the tentative
  7579. definition will do it. Any number of compilation modules can declare
  7580. the same variable in this way, and that is sufficient for all of them
  7581. to use the variable.
  7582. @c @opindex -fno-common
  7583. @c @opindex --warn_common
  7584. In programs that are very large or have many contributors, it may be
  7585. wise to adopt the convention of never using tentative definitions.
  7586. You can use the compilation option @option{-fno-common} to make them
  7587. an error, or @option{--warn-common} to warn about them.
  7588. If a file-scope variable gets its space through a tentative
  7589. definition, it starts out containing all zeros.
  7590. @node auto and register
  7591. @section @code{auto} and @code{register}
  7592. @cindex @code{auto} declarations
  7593. @cindex @code{register} declarations
  7594. @findex auto
  7595. @findex register
  7596. For historical reasons, you can write @code{auto} or @code{register}
  7597. before a local variable declaration. @code{auto} merely emphasizes
  7598. that the variable isn't static; it changes nothing.
  7599. @code{register} suggests to the compiler storing this variable in a
  7600. register. However, GNU C ignores this suggestion, since it can
  7601. choose the best variables to store in registers without any hints.
  7602. It is an error to take the address of a variable declared
  7603. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7604. If the variable is an array, you can't use it at all (other than as
  7605. the operand of @code{sizeof}), which makes it rather useless.
  7606. @node Omitting Types
  7607. @section Omitting Types in Declarations
  7608. @cindex omitting types in declarations
  7609. The syntax of C traditionally allows omitting the data type in a
  7610. declaration if it specifies a storage class, a type qualifier (see the
  7611. next chapter), or @code{auto} or @code{register}. Then the type
  7612. defaults to @code{int}. For example:
  7613. @example
  7614. auto foo = 42;
  7615. @end example
  7616. This is bad practice; if you see it, fix it.
  7617. @node Type Qualifiers
  7618. @chapter Type Qualifiers
  7619. A declaration can include type qualifiers to advise the compiler
  7620. about how the variable will be used. There are three different
  7621. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7622. pertain to different issues, so you can use more than one together.
  7623. For instance, @code{const volatile} describes a value that the
  7624. program is not allowed to change, but might have a different value
  7625. each time the program examines it. (This might perhaps be a special
  7626. hardware register, or part of shared memory.)
  7627. If you are just learning C, you can skip this chapter.
  7628. @menu
  7629. * const:: Variables whose values don't change.
  7630. * volatile:: Variables whose values may be accessed
  7631. or changed outside of the control of
  7632. this program.
  7633. * restrict Pointers:: Restricted pointers for code optimization.
  7634. * restrict Pointer Example:: Example of how that works.
  7635. @end menu
  7636. @node const
  7637. @section @code{const} Variables and Fields
  7638. @cindex @code{const} variables and fields
  7639. @cindex variables, @code{const}
  7640. @findex const
  7641. You can mark a variable as ``constant'' by writing @code{const} in
  7642. front of the declaration. This says to treat any assignment to that
  7643. variable as an error. It may also permit some compiler
  7644. optimizations---for instance, to fetch the value only once to satisfy
  7645. multiple references to it. The construct looks like this:
  7646. @example
  7647. const double pi = 3.14159;
  7648. @end example
  7649. After this definition, the code can use the variable @code{pi}
  7650. but cannot assign a different value to it.
  7651. @example
  7652. pi = 3.0; /* @r{Error!} */
  7653. @end example
  7654. Simple variables that are constant can be used for the same purposes
  7655. as enumeration constants, and they are not limited to integers. The
  7656. constantness of the variable propagates into pointers, too.
  7657. A pointer type can specify that the @emph{target} is constant. For
  7658. example, the pointer type @code{const double *} stands for a pointer
  7659. to a constant @code{double}. That's the typethat results from taking
  7660. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7661. left side of an assignment.
  7662. @example
  7663. *(&pi) = 3.0; /* @r{Error!} */
  7664. @end example
  7665. Nonconstant pointers can be converted automatically to constant
  7666. pointers, but not vice versa. For instance,
  7667. @example
  7668. const double *cptr;
  7669. double *ptr;
  7670. cptr = &pi; /* @r{Valid.} */
  7671. cptr = ptr; /* @r{Valid.} */
  7672. ptr = cptr; /* @r{Error!} */
  7673. ptr = &pi; /* @r{Error!} */
  7674. @end example
  7675. This is not an ironclad protection against modifying the value. You
  7676. can always cast the constant pointer to a nonconstant pointer type:
  7677. @example
  7678. ptr = (double *)cptr; /* @r{Valid.} */
  7679. ptr = (double *)&pi; /* @r{Valid.} */
  7680. @end example
  7681. However, @code{const} provides a way to show that a certain function
  7682. won't modify the data structure whose address is passed to it. Here's
  7683. an example:
  7684. @example
  7685. int
  7686. string_length (const char *string)
  7687. @{
  7688. int count = 0;
  7689. while (*string++)
  7690. count++;
  7691. return count;
  7692. @}
  7693. @end example
  7694. @noindent
  7695. Using @code{const char *} for the parameter is a way of saying this
  7696. function never modifies the memory of the string itself.
  7697. In calling @code{string_length}, you can specify an ordinary
  7698. @code{char *} since that can be converted automatically to @code{const
  7699. char *}.
  7700. @node volatile
  7701. @section @code{volatile} Variables and Fields
  7702. @cindex @code{volatile} variables and fields
  7703. @cindex variables, @code{volatile}
  7704. @findex volatile
  7705. The GNU C compiler often performs optimizations that eliminate the
  7706. need to write or read a variable. For instance,
  7707. @example
  7708. int foo;
  7709. foo = 1;
  7710. foo++;
  7711. @end example
  7712. @noindent
  7713. might simply store the value 2 into @code{foo}, without ever storing 1.
  7714. These optimizations can also apply to structure fields in some cases.
  7715. If the memory containing @code{foo} is shared with another program,
  7716. or if it is examined asynchronously by hardware, such optimizations
  7717. could confuse the communication. Using @code{volatile} is one way
  7718. to prevent them.
  7719. Writing @code{volatile} with the type in a variable or field declaration
  7720. says that the value may be examined or changed for reasons outside the
  7721. control of the program at any moment. Therefore, the program must
  7722. execute in a careful way to assure correct interaction with those
  7723. accesses, whenever they may occur.
  7724. The simplest use looks like this:
  7725. @example
  7726. volatile int lock;
  7727. @end example
  7728. This directs the compiler not to do certain common optimizations on
  7729. use of the variable @code{lock}. All the reads and writes for a volatile
  7730. variable or field are really done, and done in the order specified
  7731. by the source code. Thus, this code:
  7732. @example
  7733. lock = 1;
  7734. list = list->next;
  7735. if (lock)
  7736. lock_broken (&lock);
  7737. lock = 0;
  7738. @end example
  7739. @noindent
  7740. really stores the value 1 in @code{lock}, even though there is no
  7741. sign it is really used, and the @code{if} statement reads and
  7742. checks the value of @code{lock}, rather than assuming it is still 1.
  7743. A limited amount of optimization can be done, in principle, on
  7744. @code{volatile} variables and fields: multiple references between two
  7745. sequence points (@pxref{Sequence Points}) can be simplified together.
  7746. Use of @code{volatile} does not eliminate the flexibility in ordering
  7747. the computation of the operands of most operators. For instance, in
  7748. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7749. @code{foo} is not specified, so they may be done in either order; the
  7750. fact that @code{lock} is @code{volatile} has no effect on that.
  7751. @node restrict Pointers
  7752. @section @code{restrict}-Qualified Pointers
  7753. @cindex @code{restrict} pointers
  7754. @cindex pointers, @code{restrict}-qualified
  7755. @findex restrict
  7756. You can declare a pointer as ``restricted'' using the @code{restrict}
  7757. type qualifier, like this:
  7758. @example
  7759. int *restrict p = x;
  7760. @end example
  7761. @noindent
  7762. This enables better optimization of code that uses the pointer.
  7763. If @code{p} is declared with @code{restrict}, and then the code
  7764. references the object that @code{p} points to (using @code{*p} or
  7765. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7766. code will not access that object in any other way---only through
  7767. @code{p}.
  7768. For instance, it means the code must not use another pointer
  7769. to access the same space, as shown here:
  7770. @example
  7771. int *restrict p = @var{whatever};
  7772. int *q = p;
  7773. foo (*p, *q);
  7774. @end example
  7775. @noindent
  7776. That contradicts the @code{restrict} promise by accessing the object
  7777. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7778. Likewise, it must not do this:
  7779. @example
  7780. int *restrict p = @var{whatever};
  7781. struct @{ int *a, *b; @} s;
  7782. s.a = p;
  7783. foo (*p, *s.a);
  7784. @end example
  7785. @noindent
  7786. This example uses a structure field instead of the variable @code{q}
  7787. to hold the other pointer, and that contradicts the promise just the
  7788. same.
  7789. The keyword @code{restrict} also promises that @code{p} won't point to
  7790. the allocated space of any automatic or static variable. So the code
  7791. must not do this:
  7792. @example
  7793. int a;
  7794. int *restrict p = &a;
  7795. foo (*p, a);
  7796. @end example
  7797. @noindent
  7798. because that does direct access to the object (@code{a}) that @code{p}
  7799. points to, which bypasses @code{p}.
  7800. If the code makes such promises with @code{restrict} then breaks them,
  7801. execution is unpredictable.
  7802. @node restrict Pointer Example
  7803. @section @code{restrict} Pointer Example
  7804. Here are examples where @code{restrict} enables real optimization.
  7805. In this example, @code{restrict} assures GCC that the array @code{out}
  7806. points to does not overlap with the array @code{in} points to.
  7807. @example
  7808. void
  7809. process_data (const char *in,
  7810. char * restrict out,
  7811. size_t size)
  7812. @{
  7813. for (i = 0; i < size; i++)
  7814. out[i] = in[i] + in[i + 1];
  7815. @}
  7816. @end example
  7817. Here's a simple tree structure, where each tree node holds data of
  7818. type @code{PAYLOAD} plus two subtrees.
  7819. @example
  7820. struct foo
  7821. @{
  7822. PAYLOAD payload;
  7823. struct foo *left;
  7824. struct foo *right;
  7825. @};
  7826. @end example
  7827. Now here's a function to null out both pointers in the @code{left}
  7828. subtree.
  7829. @example
  7830. void
  7831. null_left (struct foo *a)
  7832. @{
  7833. a->left->left = NULL;
  7834. a->left->right = NULL;
  7835. @}
  7836. @end example
  7837. Since @code{*a} and @code{*a->left} have the same data type,
  7838. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7839. the compiled code for @code{null_left} must read @code{a->left}
  7840. again from memory when executing the second assignment statement.
  7841. We can enable optimization, so that it does not need to read
  7842. @code{a->left} again, by writing @code{null_left} this in a less
  7843. obvious way.
  7844. @example
  7845. void
  7846. null_left (struct foo *a)
  7847. @{
  7848. struct foo *b = a->left;
  7849. b->left = NULL;
  7850. b->right = NULL;
  7851. @}
  7852. @end example
  7853. A more elegant way to fix this is with @code{restrict}.
  7854. @example
  7855. void
  7856. null_left (struct foo *restrict a)
  7857. @{
  7858. a->left->left = NULL;
  7859. a->left->right = NULL;
  7860. @}
  7861. @end example
  7862. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7863. as @code{a->left} will not point to the same memory space as @code{a}.
  7864. Therefore, the memory location @code{a->left->left} cannot be the same
  7865. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7866. reloading @code{a->left} for the second statement.
  7867. @node Functions
  7868. @chapter Functions
  7869. @cindex functions
  7870. We have already presented many examples of functions, so if you've
  7871. read this far, you basically understand the concept of a function. It
  7872. is vital, nonetheless, to have a chapter in the manual that collects
  7873. all the information about functions.
  7874. @menu
  7875. * Function Definitions:: Writing the body of a function.
  7876. * Function Declarations:: Declaring the interface of a function.
  7877. * Function Calls:: Using functions.
  7878. * Function Call Semantics:: Call-by-value argument passing.
  7879. * Function Pointers:: Using references to functions.
  7880. * The main Function:: Where execution of a GNU C program begins.
  7881. * Advanced Definitions:: Advanced features of function definitions.
  7882. * Obsolete Definitions:: Obsolete features still used
  7883. in function definitions in old code.
  7884. @end menu
  7885. @node Function Definitions
  7886. @section Function Definitions
  7887. @cindex function definitions
  7888. @cindex defining functions
  7889. We have already presented many examples of function definitions. To
  7890. summarize the rules, a function definition looks like this:
  7891. @example
  7892. @var{returntype}
  7893. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7894. @{
  7895. @var{body}
  7896. @}
  7897. @end example
  7898. The part before the open-brace is called the @dfn{function header}.
  7899. Write @code{void} as the @var{returntype} if the function does
  7900. not return a value.
  7901. @menu
  7902. * Function Parameter Variables:: Syntax and semantics
  7903. of function parameters.
  7904. * Forward Function Declarations:: Functions can only be called after
  7905. they have been defined or declared.
  7906. * Static Functions:: Limiting visibility of a function.
  7907. * Arrays as Parameters:: Functions that accept array arguments.
  7908. * Structs as Parameters:: Functions that accept structure arguments.
  7909. @end menu
  7910. @node Function Parameter Variables
  7911. @subsection Function Parameter Variables
  7912. @cindex function parameter variables
  7913. @cindex parameter variables in functions
  7914. @cindex parameter list
  7915. A function parameter variable is a local variable (@pxref{Local
  7916. Variables}) used within the function to store the value passed as an
  7917. argument in a call to the function. Usually we say ``function
  7918. parameter'' or ``parameter'' for short, not mentioning the fact that
  7919. it's a variable.
  7920. We declare these variables in the beginning of the function
  7921. definition, in the @dfn{parameter list}. For example,
  7922. @example
  7923. fib (int n)
  7924. @end example
  7925. @noindent
  7926. has a parameter list with one function parameter @code{n}, which has
  7927. type @code{int}.
  7928. Function parameter declarations differ from ordinary variable
  7929. declarations in several ways:
  7930. @itemize @bullet
  7931. @item
  7932. Inside the function definition header, commas separate parameter
  7933. declarations, and each parameter needs a complete declaration
  7934. including the type. For instance, if a function @code{foo} has two
  7935. @code{int} parameters, write this:
  7936. @example
  7937. foo (int a, int b)
  7938. @end example
  7939. You can't share the common @code{int} between the two declarations:
  7940. @example
  7941. foo (int a, b) /* @r{Invalid!} */
  7942. @end example
  7943. @item
  7944. A function parameter variable is initialized to whatever value is
  7945. passed in the function call, so its declaration cannot specify an
  7946. initial value.
  7947. @item
  7948. Writing an array type in a function parameter declaration has the
  7949. effect of declaring it as a pointer. The size specified for the array
  7950. has no effect at all, and we normally omit the size. Thus,
  7951. @example
  7952. foo (int a[5])
  7953. foo (int a[])
  7954. foo (int *a)
  7955. @end example
  7956. @noindent
  7957. are equivalent.
  7958. @item
  7959. The scope of the parameter variables is the entire function body,
  7960. notwithstanding the fact that they are written in the function header,
  7961. which is just outside the function body.
  7962. @end itemize
  7963. If a function has no parameters, it would be most natural for the
  7964. list of parameters in its definition to be empty. But that, in C, has
  7965. a special meaning for historical reasons: ``Do not check that calls to
  7966. this function have the right number of arguments.'' Thus,
  7967. @example
  7968. int
  7969. foo ()
  7970. @{
  7971. return 5;
  7972. @}
  7973. int
  7974. bar (int x)
  7975. @{
  7976. return foo (x);
  7977. @}
  7978. @end example
  7979. @noindent
  7980. would not report a compilation error in passing @code{x} as an
  7981. argument to @code{foo}. By contrast,
  7982. @example
  7983. int
  7984. foo (void)
  7985. @{
  7986. return 5;
  7987. @}
  7988. int
  7989. bar (int x)
  7990. @{
  7991. return foo (x);
  7992. @}
  7993. @end example
  7994. @noindent
  7995. would report an error because @code{foo} is supposed to receive
  7996. no arguments.
  7997. @node Forward Function Declarations
  7998. @subsection Forward Function Declarations
  7999. @cindex forward function declarations
  8000. @cindex function declarations, forward
  8001. The order of the function definitions in the source code makes no
  8002. difference, except that each function needs to be defined or declared
  8003. before code uses it.
  8004. The definition of a function also declares its name for the rest of
  8005. the containing scope. But what if you want to call the function
  8006. before its definition? To permit that, write a compatible declaration
  8007. of the same function, before the first call. A declaration that
  8008. prefigures a subsequent definition in this way is called a
  8009. @dfn{forward declaration}. The function declaration can be at top
  8010. @c ??? file scope
  8011. level or within a block, and it applies until the end of the containing
  8012. scope.
  8013. @xref{Function Declarations}, for more information about these
  8014. declarations.
  8015. @node Static Functions
  8016. @subsection Static Functions
  8017. @cindex static functions
  8018. @cindex functions, static
  8019. @findex static
  8020. The keyword @code{static} in a function definition limits the
  8021. visibility of the name to the current compilation module. (That's the
  8022. same thing @code{static} does in variable declarations;
  8023. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8024. contains this code:
  8025. @example
  8026. static int
  8027. foo (void)
  8028. @{
  8029. @r{@dots{}}
  8030. @}
  8031. @end example
  8032. @noindent
  8033. then the code of that compilation module can call @code{foo} anywhere
  8034. after the definition, but other compilation modules cannot refer to it
  8035. at all.
  8036. @cindex forward declaration
  8037. @cindex static function, declaration
  8038. To call @code{foo} before its definition, it needs a forward
  8039. declaration, which should use @code{static} since the function
  8040. definition does. For this function, it looks like this:
  8041. @example
  8042. static int foo (void);
  8043. @end example
  8044. It is generally wise to use @code{static} on the definitions of
  8045. functions that won't be called from outside the same compilation
  8046. module. This makes sure that calls are not added in other modules.
  8047. If programmers decide to change the function's calling convention, or
  8048. understand all the consequences of its use, they will only have to
  8049. check for calls in the same compilation module.
  8050. @node Arrays as Parameters
  8051. @subsection Arrays as Parameters
  8052. @cindex array as parameters
  8053. @cindex functions with array parameters
  8054. Arrays in C are not first-class objects: it is impossible to copy
  8055. them. So they cannot be passed as arguments like other values.
  8056. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8057. a special way.
  8058. @menu
  8059. * Array Parm Pointer::
  8060. * Passing Array Args::
  8061. * Array Parm Qualifiers::
  8062. @end menu
  8063. @node Array Parm Pointer
  8064. @subsubsection Array parameters are pointers
  8065. Declaring a function parameter variable as an array really gives it a
  8066. pointer type. C does this because an expression with array type, if
  8067. used as an argument in a function call, is converted automatically to
  8068. a pointer (to the zeroth element of the array). If you declare the
  8069. corresponding parameter as an ``array'', it will work correctly with
  8070. the pointer value that really gets passed.
  8071. This relates to the fact that C does not check array bounds in access
  8072. to elements of the array (@pxref{Accessing Array Elements}).
  8073. For example, in this function,
  8074. @example
  8075. void
  8076. clobber4 (int array[20])
  8077. @{
  8078. array[4] = 0;
  8079. @}
  8080. @end example
  8081. @noindent
  8082. the parameter @code{array}'s real type is @code{int *}; the specified
  8083. length, 20, has no effect on the program. You can leave out the length
  8084. and write this:
  8085. @example
  8086. void
  8087. clobber4 (int array[])
  8088. @{
  8089. array[4] = 0;
  8090. @}
  8091. @end example
  8092. @noindent
  8093. or write the parameter declaration explicitly as a pointer:
  8094. @example
  8095. void
  8096. clobber4 (int *array)
  8097. @{
  8098. array[4] = 0;
  8099. @}
  8100. @end example
  8101. They are all equivalent.
  8102. @node Passing Array Args
  8103. @subsubsection Passing array arguments
  8104. The function call passes this pointer by
  8105. value, like all argument values in C@. However, the result is
  8106. paradoxical in that the array itself is passed by reference: its
  8107. contents are treated as shared memory---shared between the caller and
  8108. the called function, that is. When @code{clobber4} assigns to element
  8109. 4 of @code{array}, the effect is to alter element 4 of the array
  8110. specified in the call.
  8111. @example
  8112. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8113. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8114. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8115. int
  8116. main (void)
  8117. @{
  8118. int data[] = @{1, 2, 3, 4, 5, 6@};
  8119. int i;
  8120. /* @r{Show the initial value of element 4.} */
  8121. for (i = 0; i < 6; i++)
  8122. printf ("data[%d] = %d\n", i, data[i]);
  8123. printf ("\n");
  8124. clobber4 (data);
  8125. /* @r{Show that element 4 has been changed.} */
  8126. for (i = 0; i < 6; i++)
  8127. printf ("data[%d] = %d\n", i, data[i]);
  8128. printf ("\n");
  8129. return EXIT_SUCCESS;
  8130. @}
  8131. @end example
  8132. @noindent
  8133. shows that @code{data[4]} has become zero after the call to
  8134. @code{clobber4}.
  8135. The array @code{data} has 6 elements, but passing it to a function
  8136. whose argument type is written as @code{int [20]} is not an error,
  8137. because that really stands for @code{int *}. The pointer that is the
  8138. real argument carries no indication of the length of the array it
  8139. points into. It is not required to point to the beginning of the
  8140. array, either. For instance,
  8141. @example
  8142. clobber4 (data+1);
  8143. @end example
  8144. @noindent
  8145. passes an ``array'' that starts at element 1 of @code{data}, and the
  8146. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8147. If all calls to the function will provide an array of a particular
  8148. size, you can specify the size of the array to be @code{static}:
  8149. @example
  8150. void
  8151. clobber4 (int array[static 20])
  8152. @r{@dots{}}
  8153. @end example
  8154. @noindent
  8155. This is a promise to the compiler that the function will always be
  8156. called with an array of 20 elements, so that the compiler can optimize
  8157. code accordingly. If the code breaks this promise and calls the
  8158. function with, for example, a shorter array, unpredictable things may
  8159. happen.
  8160. @node Array Parm Qualifiers
  8161. @subsubsection Type qualifiers on array parameters
  8162. You can use the type qualifiers @code{const}, @code{restrict}, and
  8163. @code{volatile} with array parameters; for example:
  8164. @example
  8165. void
  8166. clobber4 (volatile int array[20])
  8167. @r{@dots{}}
  8168. @end example
  8169. @noindent
  8170. denotes that @code{array} is equivalent to a pointer to a volatile
  8171. @code{int}. Alternatively:
  8172. @example
  8173. void
  8174. clobber4 (int array[const 20])
  8175. @r{@dots{}}
  8176. @end example
  8177. @noindent
  8178. makes the array parameter equivalent to a constant pointer to an
  8179. @code{int}. If we want the @code{clobber4} function to succeed, it
  8180. would not make sense to write
  8181. @example
  8182. void
  8183. clobber4 (const int array[20])
  8184. @r{@dots{}}
  8185. @end example
  8186. @noindent
  8187. as this would tell the compiler that the parameter should point to an
  8188. array of constant @code{int} values, and then we would not be able to
  8189. store zeros in them.
  8190. In a function with multiple array parameters, you can use @code{restrict}
  8191. to tell the compiler that each array parameter passed in will be distinct:
  8192. @example
  8193. void
  8194. foo (int array1[restrict 10], int array2[restrict 10])
  8195. @r{@dots{}}
  8196. @end example
  8197. @noindent
  8198. Using @code{restrict} promises the compiler that callers will
  8199. not pass in the same array for more than one @code{restrict} array
  8200. parameter. Knowing this enables the compiler to perform better code
  8201. optimization. This is the same effect as using @code{restrict}
  8202. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8203. the code that an array of a specific size is expected.
  8204. @node Structs as Parameters
  8205. @subsection Functions That Accept Structure Arguments
  8206. Structures in GNU C are first-class objects, so using them as function
  8207. parameters and arguments works in the natural way. This function
  8208. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8209. and returns a structure of the same type but with the fields
  8210. exchanged.
  8211. @example
  8212. struct foo @{ int a, b; @};
  8213. struct foo x;
  8214. struct foo
  8215. swapfoo (struct foo inval)
  8216. @{
  8217. struct foo outval;
  8218. outval.a = inval.b;
  8219. outval.b = inval.a;
  8220. return outval;
  8221. @}
  8222. @end example
  8223. This simpler definition of @code{swapfoo} avoids using a local
  8224. variable to hold the result about to be return, by using a structure
  8225. constructor (@pxref{Structure Constructors}), like this:
  8226. @example
  8227. struct foo
  8228. swapfoo (struct foo inval)
  8229. @{
  8230. return (struct foo) @{ inval.b, inval.a @};
  8231. @}
  8232. @end example
  8233. It is valid to define a structure type in a function's parameter list,
  8234. as in
  8235. @example
  8236. int
  8237. frob_bar (struct bar @{ int a, b; @} inval)
  8238. @{
  8239. @var{body}
  8240. @}
  8241. @end example
  8242. @noindent
  8243. and @var{body} can access the fields of @var{inval} since the
  8244. structure type @code{struct bar} is defined for the whole function
  8245. body. However, there is no way to create a @code{struct bar} argument
  8246. to pass to @code{frob_bar}, except with kludges. As a result,
  8247. defining a structure type in a parameter list is useless in practice.
  8248. @node Function Declarations
  8249. @section Function Declarations
  8250. @cindex function declarations
  8251. @cindex declararing functions
  8252. To call a function, or use its name as a pointer, a @dfn{function
  8253. declaration} for the function name must be in effect at that point in
  8254. the code. The function's definition serves as a declaration of that
  8255. function for the rest of the containing scope, but to use the function
  8256. in code before the definition, or from another compilation module, a
  8257. separate function declaration must precede the use.
  8258. A function declaration looks like the start of a function definition.
  8259. It begins with the return value type (@code{void} if none) and the
  8260. function name, followed by argument declarations in parentheses
  8261. (though these can sometimes be omitted). But that's as far as the
  8262. similarity goes: instead of the function body, the declaration uses a
  8263. semicolon.
  8264. @cindex function prototype
  8265. @cindex prototype of a function
  8266. A declaration that specifies argument types is called a @dfn{function
  8267. prototype}. You can include the argument names or omit them. The
  8268. names, if included in the declaration, have no effect, but they may
  8269. serve as documentation.
  8270. This form of prototype specifies fixed argument types:
  8271. @example
  8272. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8273. @end example
  8274. @noindent
  8275. This form says the function takes no arguments:
  8276. @example
  8277. @var{rettype} @var{function} (void);
  8278. @end example
  8279. @noindent
  8280. This form declares types for some arguments, and allows additional
  8281. arguments whose types are not specified:
  8282. @example
  8283. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8284. @end example
  8285. For a parameter that's an array of variable length, you can write
  8286. its declaration with @samp{*} where the ``length'' of the array would
  8287. normally go; for example, these are all equivalent.
  8288. @example
  8289. double maximum (int n, int m, double a[n][m]);
  8290. double maximum (int n, int m, double a[*][*]);
  8291. double maximum (int n, int m, double a[ ][*]);
  8292. double maximum (int n, int m, double a[ ][m]);
  8293. @end example
  8294. @noindent
  8295. The old-fashioned form of declaration, which is not a prototype, says
  8296. nothing about the types of arguments or how many they should be:
  8297. @example
  8298. @var{rettype} @var{function} ();
  8299. @end example
  8300. @strong{Warning:} Arguments passed to a function declared without a
  8301. prototype are converted with the default argument promotions
  8302. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8303. types are unspecified.
  8304. Function declarations are usually written at the top level in a source file,
  8305. but you can also put them inside code blocks. Then the function name
  8306. is visible for the rest of the containing scope. For example:
  8307. @example
  8308. void
  8309. foo (char *file_name)
  8310. @{
  8311. void save_file (char *);
  8312. save_file (file_name);
  8313. @}
  8314. @end example
  8315. If another part of the code tries to call the function
  8316. @code{save_file}, this declaration won't be in effect there. So the
  8317. function will get an implicit declaration of the form @code{extern int
  8318. save_file ();}. That conflicts with the explicit declaration
  8319. here, and the discrepancy generates a warning.
  8320. The syntax of C traditionally allows omitting the data type in a
  8321. function declaration if it specifies a storage class or a qualifier.
  8322. Then the type defaults to @code{int}. For example:
  8323. @example
  8324. static foo (double x);
  8325. @end example
  8326. @noindent
  8327. defaults the return type to @code{int}.
  8328. This is bad practice; if you see it, fix it.
  8329. Calling a function that is undeclared has the effect of an creating
  8330. @dfn{implicit} declaration in the innermost containing scope,
  8331. equivalent to this:
  8332. @example
  8333. extern int @dfn{function} ();
  8334. @end example
  8335. @noindent
  8336. This declaration says that the function returns @code{int} but leaves
  8337. its argument types unspecified. If that does not accurately fit the
  8338. function, then the program @strong{needs} an explicit declaration of
  8339. the function with argument types in order to call it correctly.
  8340. Implicit declarations are deprecated, and a function call that creates one
  8341. causes a warning.
  8342. @node Function Calls
  8343. @section Function Calls
  8344. @cindex function calls
  8345. @cindex calling functions
  8346. Starting a program automatically calls the function named @code{main}
  8347. (@pxref{The main Function}). Aside from that, a function does nothing
  8348. except when it is @dfn{called}. That occurs during the execution of a
  8349. function-call expression specifying that function.
  8350. A function-call expression looks like this:
  8351. @example
  8352. @var{function} (@var{arguments}@r{@dots{}})
  8353. @end example
  8354. Most of the time, @var{function} is a function name. However, it can
  8355. also be an expression with a function pointer value; that way, the
  8356. program can determine at run time which function to call.
  8357. The @var{arguments} are a series of expressions separated by commas.
  8358. Each expression specifies one argument to pass to the function.
  8359. The list of arguments in a function call looks just like use of the
  8360. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8361. the parentheses of a function call gives it a different meaning.
  8362. Here's an example of a function call, taken from an example near the
  8363. beginning (@pxref{Complete Program}).
  8364. @example
  8365. printf ("Fibonacci series item %d is %d\n",
  8366. 19, fib (19));
  8367. @end example
  8368. The three arguments given to @code{printf} are a constant string, the
  8369. integer 19, and the integer returned by @code{fib (19)}.
  8370. @node Function Call Semantics
  8371. @section Function Call Semantics
  8372. @cindex function call semantics
  8373. @cindex semantics of function calls
  8374. @cindex call-by-value
  8375. The meaning of a function call is to compute the specified argument
  8376. expressions, convert their values according to the function's
  8377. declaration, then run the function giving it copies of the converted
  8378. values. (This method of argument passing is known as
  8379. @dfn{call-by-value}.) When the function finishes, the value it
  8380. returns becomes the value of the function-call expression.
  8381. Call-by-value implies that an assignment to the function argument
  8382. variable has no direct effect on the caller. For instance,
  8383. @example
  8384. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8385. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8386. void
  8387. subroutine (int x)
  8388. @{
  8389. x = 5;
  8390. @}
  8391. void
  8392. main (void)
  8393. @{
  8394. int y = 20;
  8395. subroutine (y);
  8396. printf ("y is %d\n", y);
  8397. return EXIT_SUCCESS;
  8398. @}
  8399. @end example
  8400. @noindent
  8401. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8402. from the value of @code{y}, but this does not establish any other
  8403. relationship between the two variables. Thus, the assignment to
  8404. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8405. If an argument's type is specified by the function's declaration, the
  8406. function call converts the argument expression to that type if
  8407. possible. If the conversion is impossible, that is an error.
  8408. If the function's declaration doesn't specify the type of that
  8409. argument, then the @emph{default argument promotions} apply.
  8410. @xref{Argument Promotions}.
  8411. @node Function Pointers
  8412. @section Function Pointers
  8413. @cindex function pointers
  8414. @cindex pointers to functions
  8415. A function name refers to a fixed function. Sometimes it is useful to
  8416. call a function to be determined at run time; to do this, you can use
  8417. a @dfn{function pointer value} that points to the chosen function
  8418. (@pxref{Pointers}).
  8419. Pointer-to-function types can be used to declare variables and other
  8420. data, including array elements, structure fields, and union
  8421. alternatives. They can also be used for function arguments and return
  8422. values. These types have the peculiarity that they are never
  8423. converted automatically to @code{void *} or vice versa. However, you
  8424. can do that conversion with a cast.
  8425. @menu
  8426. * Declaring Function Pointers:: How to declare a pointer to a function.
  8427. * Assigning Function Pointers:: How to assign values to function pointers.
  8428. * Calling Function Pointers:: How to call functions through pointers.
  8429. @end menu
  8430. @node Declaring Function Pointers
  8431. @subsection Declaring Function Pointers
  8432. @cindex declaring function pointers
  8433. @cindex function pointers, declaring
  8434. The declaration of a function pointer variable (or structure field)
  8435. looks almost like a function declaration, except it has an additional
  8436. @samp{*} just before the variable name. Proper nesting requires a
  8437. pair of parentheses around the two of them. For instance, @code{int
  8438. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8439. an @code{int}-returning function.''
  8440. Contrast these three declarations:
  8441. @example
  8442. /* @r{Declare a function returning @code{char *}.} */
  8443. char *a (char *);
  8444. /* @r{Declare a pointer to a function returning @code{char}.} */
  8445. char (*a) (char *);
  8446. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8447. char *(*a) (char *);
  8448. @end example
  8449. The possible argument types of the function pointed to are the same
  8450. as in a function declaration. You can write a prototype
  8451. that specifies all the argument types:
  8452. @example
  8453. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8454. @end example
  8455. @noindent
  8456. or one that specifies some and leaves the rest unspecified:
  8457. @example
  8458. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8459. @end example
  8460. @noindent
  8461. or one that says there are no arguments:
  8462. @example
  8463. @var{rettype} (*@var{function}) (void);
  8464. @end example
  8465. You can also write a non-prototype declaration that says
  8466. nothing about the argument types:
  8467. @example
  8468. @var{rettype} (*@var{function}) ();
  8469. @end example
  8470. For example, here's a declaration for a variable that should
  8471. point to some arithmetic function that operates on two @code{double}s:
  8472. @example
  8473. double (*binary_op) (double, double);
  8474. @end example
  8475. Structure fields, union alternatives, and array elements can be
  8476. function pointers; so can parameter variables. The function pointer
  8477. declaration construct can also be combined with other operators
  8478. allowed in declarations. For instance,
  8479. @example
  8480. int **(*foo)();
  8481. @end example
  8482. @noindent
  8483. declares @code{foo} as a pointer to a function that returns
  8484. type @code{int **}, and
  8485. @example
  8486. int **(*foo[30])();
  8487. @end example
  8488. @noindent
  8489. declares @code{foo} as an array of 30 pointers to functions that
  8490. return type @code{int **}.
  8491. @example
  8492. int **(**foo)();
  8493. @end example
  8494. @noindent
  8495. declares @code{foo} as a pointer to a pointer to a function that
  8496. returns type @code{int **}.
  8497. @node Assigning Function Pointers
  8498. @subsection Assigning Function Pointers
  8499. @cindex assigning function pointers
  8500. @cindex function pointers, assigning
  8501. Assuming we have declared the variable @code{binary_op} as in the
  8502. previous section, giving it a value requires a suitable function to
  8503. use. So let's define a function suitable for the variable to point
  8504. to. Here's one:
  8505. @example
  8506. double
  8507. double_add (double a, double b)
  8508. @{
  8509. return a+b;
  8510. @}
  8511. @end example
  8512. Now we can give it a value:
  8513. @example
  8514. binary_op = double_add;
  8515. @end example
  8516. The target type of the function pointer must be upward compatible with
  8517. the type of the function (@pxref{Compatible Types}).
  8518. There is no need for @samp{&} in front of @code{double_add}.
  8519. Using a function name such as @code{double_add} as an expression
  8520. automatically converts it to the function's address, with the
  8521. appropriate function pointer type. However, it is ok to use
  8522. @samp{&} if you feel that is clearer:
  8523. @example
  8524. binary_op = &double_add;
  8525. @end example
  8526. @node Calling Function Pointers
  8527. @subsection Calling Function Pointers
  8528. @cindex calling function pointers
  8529. @cindex function pointers, calling
  8530. To call the function specified by a function pointer, just write the
  8531. function pointer value in a function call. For instance, here's a
  8532. call to the function @code{binary_op} points to:
  8533. @example
  8534. binary_op (x, 5)
  8535. @end example
  8536. Since the data type of @code{binary_op} explicitly specifies type
  8537. @code{double} for the arguments, the call converts @code{x} and 5 to
  8538. @code{double}.
  8539. The call conceptually dereferences the pointer @code{binary_op} to
  8540. ``get'' the function it points to, and calls that function. If you
  8541. wish, you can explicitly represent the derefence by writing the
  8542. @code{*} operator:
  8543. @example
  8544. (*binary_op) (x, 5)
  8545. @end example
  8546. The @samp{*} reminds people reading the code that @code{binary_op} is
  8547. a function pointer rather than the name of a specific function.
  8548. @node The main Function
  8549. @section The @code{main} Function
  8550. @cindex @code{main} function
  8551. @findex main
  8552. Every complete executable program requires at least one function,
  8553. called @code{main}, which is where execution begins. You do not have
  8554. to explicitly declare @code{main}, though GNU C permits you to do so.
  8555. Conventionally, @code{main} should be defined to follow one of these
  8556. calling conventions:
  8557. @example
  8558. int main (void) @{@r{@dots{}}@}
  8559. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8560. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8561. @end example
  8562. @noindent
  8563. Using @code{void} as the parameter list means that @code{main} does
  8564. not use the arguments. You can write @code{char **argv} instead of
  8565. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8566. constructs are equivalent.
  8567. @ignore @c Not so at present
  8568. Defining @code{main} in any other way generates a warning. Your
  8569. program will still compile, but you may get unexpected results when
  8570. executing it.
  8571. @end ignore
  8572. You can call @code{main} from C code, as you can call any other
  8573. function, though that is an unusual thing to do. When you do that,
  8574. you must write the call to pass arguments that match the parameters in
  8575. the definition of @code{main}.
  8576. The @code{main} function is not actually the first code that runs when
  8577. a program starts. In fact, the first code that runs is system code
  8578. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8579. code, but in GNU we replaced it with C code. Its job is to find
  8580. the arguments for @code{main} and call that.
  8581. @menu
  8582. * Values from main:: Returning values from the main function.
  8583. * Command-line Parameters:: Accessing command-line parameters
  8584. provided to the program.
  8585. * Environment Variables:: Accessing system environment variables.
  8586. @end menu
  8587. @node Values from main
  8588. @subsection Returning Values from @code{main}
  8589. @cindex returning values from @code{main}
  8590. @cindex success
  8591. @cindex failure
  8592. @cindex exit status
  8593. When @code{main} returns, the process terminates. Whatever value
  8594. @code{main} returns becomes the exit status which is reported to the
  8595. parent process. While nominally the return value is of type
  8596. @code{int}, in fact the exit status gets truncated to eight bits; if
  8597. @code{main} returns the value 256, the exit status is 0.
  8598. Normally, programs return only one of two values: 0 for success,
  8599. and 1 for failure. For maximum portability, use the macro
  8600. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8601. @code{stdlib.h}. Here's an example:
  8602. @cindex @code{EXIT_FAILURE}
  8603. @cindex @code{EXIT_SUCCESS}
  8604. @example
  8605. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8606. /* @r{and @code{EXIT_FAILURE}.} */
  8607. int
  8608. main (void)
  8609. @{
  8610. @r{@dots{}}
  8611. if (foo)
  8612. return EXIT_SUCCESS;
  8613. else
  8614. return EXIT_FAILURE;
  8615. @}
  8616. @end example
  8617. Some types of programs maintain special conventions for various return
  8618. values; for example, comparison programs including @code{cmp} and
  8619. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8620. the comparison couldn't be performed.
  8621. @node Command-line Parameters
  8622. @subsection Accessing Command-line Parameters
  8623. @cindex command-line parameters
  8624. @cindex parameters, command-line
  8625. If the program was invoked with any command-line arguments, it can
  8626. access them through the arguments of @code{main}, @code{argc} and
  8627. @code{argv}. (You can give these arguments any names, but the names
  8628. @code{argc} and @code{argv} are customary.)
  8629. The value of @code{argv} is an array containing all of the
  8630. command-line arguments as strings, with the name of the command
  8631. invoked as the first string. @code{argc} is an integer that says how
  8632. many strings @code{argv} contains. Here is an example of accessing
  8633. the command-line parameters, retrieving the program's name and
  8634. checking for the standard @option{--version} and @option{--help} options:
  8635. @example
  8636. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8637. int
  8638. main (int argc, char *argv[])
  8639. @{
  8640. char *program_name = argv[0];
  8641. for (int i = 1; i < argc; i++)
  8642. @{
  8643. if (!strcmp (argv[i], "--version"))
  8644. @{
  8645. /* @r{Print version information and exit.} */
  8646. @r{@dots{}}
  8647. @}
  8648. else if (!strcmp (argv[i], "--help"))
  8649. @{
  8650. /* @r{Print help information and exit.} */
  8651. @r{@dots{}}
  8652. @}
  8653. @}
  8654. @r{@dots{}}
  8655. @}
  8656. @end example
  8657. @node Environment Variables
  8658. @subsection Accessing Environment Variables
  8659. @cindex environment variables
  8660. You can optionally include a third parameter to @code{main}, another
  8661. array of strings, to capture the environment variables available to
  8662. the program. Unlike what happens with @code{argv}, there is no
  8663. additional parameter for the count of environment variables; rather,
  8664. the array of environment variables concludes with a null pointer.
  8665. @example
  8666. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8667. int
  8668. main (int argc, char *argv[], char *envp[])
  8669. @{
  8670. /* @r{Print out all environment variables.} */
  8671. int i = 0;
  8672. while (envp[i])
  8673. @{
  8674. printf ("%s\n", envp[i]);
  8675. i++;
  8676. @}
  8677. @}
  8678. @end example
  8679. Another method of retrieving environment variables is to use the
  8680. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8681. Using @code{getenv} does not require defining @code{main} to accept the
  8682. @code{envp} pointer. For example, here is a program that fetches and prints
  8683. the user's home directory (if defined):
  8684. @example
  8685. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8686. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8687. int
  8688. main (void)
  8689. @{
  8690. char *home_directory = getenv ("HOME");
  8691. if (home_directory)
  8692. printf ("My home directory is: %s\n", home_directory);
  8693. else
  8694. printf ("My home directory is not defined!\n");
  8695. @}
  8696. @end example
  8697. @node Advanced Definitions
  8698. @section Advanced Function Features
  8699. This section describes some advanced or obscure features for GNU C
  8700. function definitions. If you are just learning C, you can skip the
  8701. rest of this chapter.
  8702. @menu
  8703. * Variable-Length Array Parameters:: Functions that accept arrays
  8704. of variable length.
  8705. * Variable Number of Arguments:: Variadic functions.
  8706. * Nested Functions:: Defining functions within functions.
  8707. * Inline Function Definitions:: A function call optimization technique.
  8708. @end menu
  8709. @node Variable-Length Array Parameters
  8710. @subsection Variable-Length Array Parameters
  8711. @cindex variable-length array parameters
  8712. @cindex array parameters, variable-length
  8713. @cindex functions that accept variable-length arrays
  8714. An array parameter can have variable length: simply declare the array
  8715. type with a size that isn't constant. In a nested function, the
  8716. length can refer to a variable defined in a containing scope. In any
  8717. function, it can refer to a previous parameter, like this:
  8718. @example
  8719. struct entry
  8720. tester (int len, char data[len][len])
  8721. @{
  8722. @r{@dots{}}
  8723. @}
  8724. @end example
  8725. Alternatively, in function declarations (but not in function
  8726. definitions), you can use @code{[*]} to denote that the array
  8727. parameter is of a variable length, such that these two declarations
  8728. mean the same thing:
  8729. @example
  8730. struct entry
  8731. tester (int len, char data[len][len]);
  8732. @end example
  8733. @example
  8734. struct entry
  8735. tester (int len, char data[*][*]);
  8736. @end example
  8737. @noindent
  8738. The two forms of input are equivalent in GNU C, but emphasizing that
  8739. the array parameter is variable-length may be helpful to those
  8740. studying the code.
  8741. You can also omit the length parameter, and instead use some other
  8742. in-scope variable for the length in the function definition:
  8743. @example
  8744. struct entry
  8745. tester (char data[*][*]);
  8746. @r{@dots{}}
  8747. int dataLength = 20;
  8748. @r{@dots{}}
  8749. struct entry
  8750. tester (char data[dataLength][dataLength])
  8751. @{
  8752. @r{@dots{}}
  8753. @}
  8754. @end example
  8755. @c ??? check text above
  8756. @cindex parameter forward declaration
  8757. In GNU C, to pass the array first and the length afterward, you can
  8758. use a @dfn{parameter forward declaration}, like this:
  8759. @example
  8760. struct entry
  8761. tester (int len; char data[len][len], int len)
  8762. @{
  8763. @r{@dots{}}
  8764. @}
  8765. @end example
  8766. The @samp{int len} before the semicolon is the parameter forward
  8767. declaration; it serves the purpose of making the name @code{len} known
  8768. when the declaration of @code{data} is parsed.
  8769. You can write any number of such parameter forward declarations in the
  8770. parameter list. They can be separated by commas or semicolons, but
  8771. the last one must end with a semicolon, which is followed by the
  8772. ``real'' parameter declarations. Each forward declaration must match
  8773. a subsequent ``real'' declaration in parameter name and data type.
  8774. Standard C does not support parameter forward declarations.
  8775. @node Variable Number of Arguments
  8776. @subsection Variable-Length Parameter Lists
  8777. @cindex variable-length parameter lists
  8778. @cindex parameters lists, variable length
  8779. @cindex function parameter lists, variable length
  8780. @cindex variadic function
  8781. A function that takes a variable number of arguments is called a
  8782. @dfn{variadic function}. In C, a variadic function must specify at
  8783. least one fixed argument with an explicitly declared data type.
  8784. Additional arguments can follow, and can vary in both quantity and
  8785. data type.
  8786. In the function header, declare the fixed parameters in the normal
  8787. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8788. example of a variadic function header:
  8789. @example
  8790. int add_multiple_values (int number, ...)
  8791. @end example
  8792. @cindex @code{va_list}
  8793. @cindex @code{va_start}
  8794. @cindex @code{va_end}
  8795. The function body can refer to fixed arguments by their parameter
  8796. names, but the additional arguments have no names. Accessing them in
  8797. the function body uses certain standard macros. They are defined in
  8798. the library header file @file{stdarg.h}, so the code must
  8799. @code{#include} that file.
  8800. In the body, write
  8801. @example
  8802. va_list ap;
  8803. va_start (ap, @var{last_fixed_parameter});
  8804. @end example
  8805. @noindent
  8806. This declares the variable @code{ap} (you can use any name for it)
  8807. and then sets it up to point before the first additional argument.
  8808. Then, to fetch the next consecutive additional argument, write this:
  8809. @example
  8810. va_arg (ap, @var{type})
  8811. @end example
  8812. After fetching all the additional arguments (or as many as need to be
  8813. used), write this:
  8814. @example
  8815. va_end (ap);
  8816. @end example
  8817. Here's an example of a variadic function definition that adds any
  8818. number of @code{int} arguments. The first (fixed) argument says how
  8819. many more arguments follow.
  8820. @example
  8821. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8822. @r{@dots{}}
  8823. int
  8824. add_multiple_values (int argcount, ...)
  8825. @{
  8826. int counter, total = 0;
  8827. /* @r{Declare a variable of type @code{va_list}.} */
  8828. va_list argptr;
  8829. /* @r{Initialize that variable..} */
  8830. va_start (argptr, argcount);
  8831. for (counter = 0; counter < argcount; counter++)
  8832. @{
  8833. /* @r{Get the next additional argument.} */
  8834. total += va_arg (argptr, int);
  8835. @}
  8836. /* @r{End use of the @code{argptr} variable.} */
  8837. va_end (argptr);
  8838. return total;
  8839. @}
  8840. @end example
  8841. With GNU C, @code{va_end} is superfluous, but some other compilers
  8842. might make @code{va_start} allocate memory so that calling
  8843. @code{va_end} is necessary to avoid a memory leak. Before doing
  8844. @code{va_start} again with the same variable, do @code{va_end}
  8845. first.
  8846. @cindex @code{va_copy}
  8847. Because of this possible memory allocation, it is risky (in principle)
  8848. to copy one @code{va_list} variable to another with assignment.
  8849. Instead, use @code{va_copy}, which copies the substance but allocates
  8850. separate memory in the variable you copy to. The call looks like
  8851. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8852. @var{from} should be variables of type @code{va_list}. In principle,
  8853. do @code{va_end} on each of these variables before its scope ends.
  8854. Since the additional arguments' types are not specified in the
  8855. function's definition, the default argument promotions
  8856. (@pxref{Argument Promotions}) apply to them in function calls. The
  8857. function definition must take account of this; thus, if an argument
  8858. was passed as @code{short}, the function should get it as @code{int}.
  8859. If an argument was passed as @code{float}, the function should get it
  8860. as @code{double}.
  8861. C has no mechanism to tell the variadic function how many arguments
  8862. were passed to it, so its calling convention must give it a way to
  8863. determine this. That's why @code{add_multiple_values} takes a fixed
  8864. argument that says how many more arguments follow. Thus, you can
  8865. call the function like this:
  8866. @example
  8867. sum = add_multiple_values (3, 12, 34, 190);
  8868. /* @r{Value is 12+34+190.} */
  8869. @end example
  8870. In GNU C, there is no actual need to use the @code{va_end} function.
  8871. In fact, it does nothing. It's used for compatibility with other
  8872. compilers, when that matters.
  8873. It is a mistake to access variables declared as @code{va_list} except
  8874. in the specific ways described here. Just what that type consists of
  8875. is an implementation detail, which could vary from one platform to
  8876. another.
  8877. @node Nested Functions
  8878. @subsection Nested Functions
  8879. @cindex nested functions
  8880. @cindex functions, nested
  8881. @cindex downward funargs
  8882. @cindex thunks
  8883. A @dfn{nested function} is a function defined inside another function.
  8884. The nested function's name is local to the block where it is defined.
  8885. For example, here we define a nested function named @code{square}, and
  8886. call it twice:
  8887. @example
  8888. @group
  8889. foo (double a, double b)
  8890. @{
  8891. double square (double z) @{ return z * z; @}
  8892. return square (a) + square (b);
  8893. @}
  8894. @end group
  8895. @end example
  8896. The nested function can access all the variables of the containing
  8897. function that are visible at the point of its definition. This is
  8898. called @dfn{lexical scoping}. For example, here we show a nested
  8899. function that uses an inherited variable named @code{offset}:
  8900. @example
  8901. @group
  8902. bar (int *array, int offset, int size)
  8903. @{
  8904. int access (int *array, int index)
  8905. @{ return array[index + offset]; @}
  8906. int i;
  8907. @r{@dots{}}
  8908. for (i = 0; i < size; i++)
  8909. @r{@dots{}} access (array, i) @r{@dots{}}
  8910. @}
  8911. @end group
  8912. @end example
  8913. Nested function definitions can appear wherever automatic variable
  8914. declarations are allowed; that is, in any block, interspersed with the
  8915. other declarations and statements in the block.
  8916. The nested function's name is visible only within the parent block;
  8917. the name's scope starts from its definition and continues to the end
  8918. of the containing block. If the nested function's name
  8919. is the same as the parent function's name, there wil be
  8920. no way to refer to the parent function inside the scope of the
  8921. name of the nested function.
  8922. Using @code{extern} or @code{static} on a nested function definition
  8923. is an error.
  8924. It is possible to call the nested function from outside the scope of its
  8925. name by storing its address or passing the address to another function.
  8926. You can do this safely, but you must be careful:
  8927. @example
  8928. @group
  8929. hack (int *array, int size, int addition)
  8930. @{
  8931. void store (int index, int value)
  8932. @{ array[index] = value + addition; @}
  8933. intermediate (store, size);
  8934. @}
  8935. @end group
  8936. @end example
  8937. Here, the function @code{intermediate} receives the address of
  8938. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8939. the arguments given to @code{store} are used to store into @code{array}.
  8940. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8941. It is safe for @code{intermediate} to call @code{store} because
  8942. @code{hack}'s stack frame, with its arguments and local variables,
  8943. continues to exist during the call to @code{intermediate}.
  8944. Calling the nested function through its address after the containing
  8945. function has exited is asking for trouble. If it is called after a
  8946. containing scope level has exited, and if it refers to some of the
  8947. variables that are no longer in scope, it will refer to memory
  8948. containing junk or other data. It's not wise to take the risk.
  8949. The GNU C Compiler implements taking the address of a nested function
  8950. using a technique called @dfn{trampolines}. This technique was
  8951. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8952. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8953. A nested function can jump to a label inherited from a containing
  8954. function, provided the label was explicitly declared in the containing
  8955. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8956. containing function, exiting the nested function that did the
  8957. @code{goto} and any intermediate function invocations as well. Here
  8958. is an example:
  8959. @example
  8960. @group
  8961. bar (int *array, int offset, int size)
  8962. @{
  8963. /* @r{Explicitly declare the label @code{failure}.} */
  8964. __label__ failure;
  8965. int access (int *array, int index)
  8966. @{
  8967. if (index > size)
  8968. /* @r{Exit this function,}
  8969. @r{and return to @code{bar}.} */
  8970. goto failure;
  8971. return array[index + offset];
  8972. @}
  8973. @end group
  8974. @group
  8975. int i;
  8976. @r{@dots{}}
  8977. for (i = 0; i < size; i++)
  8978. @r{@dots{}} access (array, i) @r{@dots{}}
  8979. @r{@dots{}}
  8980. return 0;
  8981. /* @r{Control comes here from @code{access}
  8982. if it does the @code{goto}.} */
  8983. failure:
  8984. return -1;
  8985. @}
  8986. @end group
  8987. @end example
  8988. To declare the nested function before its definition, use
  8989. @code{auto} (which is otherwise meaningless for function declarations;
  8990. @pxref{auto and register}). For example,
  8991. @example
  8992. bar (int *array, int offset, int size)
  8993. @{
  8994. auto int access (int *, int);
  8995. @r{@dots{}}
  8996. @r{@dots{}} access (array, i) @r{@dots{}}
  8997. @r{@dots{}}
  8998. int access (int *array, int index)
  8999. @{
  9000. @r{@dots{}}
  9001. @}
  9002. @r{@dots{}}
  9003. @}
  9004. @end example
  9005. @node Inline Function Definitions
  9006. @subsection Inline Function Definitions
  9007. @cindex inline function definitions
  9008. @cindex function definitions, inline
  9009. @findex inline
  9010. To declare a function inline, use the @code{inline} keyword in its
  9011. definition. Here's a simple function that takes a pointer-to-@code{int}
  9012. and increments the integer stored there---declared inline.
  9013. @example
  9014. struct list
  9015. @{
  9016. struct list *first, *second;
  9017. @};
  9018. inline struct list *
  9019. list_first (struct list *p)
  9020. @{
  9021. return p->first;
  9022. @}
  9023. inline struct list *
  9024. list_second (struct list *p)
  9025. @{
  9026. return p->second;
  9027. @}
  9028. @end example
  9029. optimized compilation can substitute the inline function's body for
  9030. any call to it. This is called @emph{inlining} the function. It
  9031. makes the code that contains the call run faster, significantly so if
  9032. the inline function is small.
  9033. Here's a function that uses @code{pair_second}:
  9034. @example
  9035. int
  9036. pairlist_length (struct list *l)
  9037. @{
  9038. int length = 0;
  9039. while (l)
  9040. @{
  9041. length++;
  9042. l = pair_second (l);
  9043. @}
  9044. return length;
  9045. @}
  9046. @end example
  9047. Substituting the code of @code{pair_second} into the definition of
  9048. @code{pairlist_length} results in this code, in effect:
  9049. @example
  9050. int
  9051. pairlist_length (struct list *l)
  9052. @{
  9053. int length = 0;
  9054. while (l)
  9055. @{
  9056. length++;
  9057. l = l->second;
  9058. @}
  9059. return length;
  9060. @}
  9061. @end example
  9062. Since the definition of @code{pair_second} does not say @code{extern}
  9063. or @code{static}, that definition is used only for inlining. It
  9064. doesn't generate code that can be called at run time. If not all the
  9065. calls to the function are inlined, there must be a definition of the
  9066. same function name in another module for them to call.
  9067. @cindex inline functions, omission of
  9068. @c @opindex fkeep-inline-functions
  9069. Adding @code{static} to an inline function definition means the
  9070. function definition is limited to this compilation module. Also, it
  9071. generates run-time code if necessary for the sake of any calls that
  9072. were not inlined. If all calls are inlined then the function
  9073. definition does not generate run-time code, but you can force
  9074. generation of run-time code with the option
  9075. @option{-fkeep-inline-functions}.
  9076. @cindex extern inline function
  9077. Specifying @code{extern} along with @code{inline} means the function is
  9078. external and generates run-time code to be called from other
  9079. separately compiled modules, as well as inlined. You can define the
  9080. function as @code{inline} without @code{extern} in other modules so as
  9081. to inline calls to the same function in those modules.
  9082. Why are some calls not inlined? First of all, inlining is an
  9083. optimization, so non-optimized compilation does not inline.
  9084. Some calls cannot be inlined for technical reasons. Also, certain
  9085. usages in a function definition can make it unsuitable for inline
  9086. substitution. Among these usages are: variadic functions, use of
  9087. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9088. use of nonlocal goto. The option @option{-Winline} requests a warning
  9089. when a function marked @code{inline} is unsuitable to be inlined. The
  9090. warning explains what obstacle makes it unsuitable.
  9091. Just because a call @emph{can} be inlined does not mean it
  9092. @emph{should} be inlined. The GNU C compiler weighs costs and
  9093. benefits to decide whether inlining a particular call is advantageous.
  9094. You can force inlining of all calls to a given function that can be
  9095. inlined, even in a non-optimized compilation. by specifying the
  9096. @samp{always_inline} attribute for the function, like this:
  9097. @example
  9098. /* @r{Prototype.} */
  9099. inline void foo (const char) __attribute__((always_inline));
  9100. @end example
  9101. @noindent
  9102. This is a GNU C extension. @xref{Attributes}.
  9103. A function call may be inlined even if not declared @code{inline} in
  9104. special cases where the compiler can determine this is correct and
  9105. desirable. For instance, when a static function is called only once,
  9106. it will very likely be inlined. With @option{-flto}, link-time
  9107. optimization, any function might be inlined. To absolutely prevent
  9108. inlining of a specific function, specify
  9109. @code{__attribute__((__noinline__))} in the function's definition.
  9110. @node Obsolete Definitions
  9111. @section Obsolete Function Features
  9112. These features of function definitions are still used in old
  9113. programs, but you shouldn't write code this way today.
  9114. If you are just learning C, you can skip this section.
  9115. @menu
  9116. * Old GNU Inlining:: An older inlining technique.
  9117. * Old-Style Function Definitions:: Original K&R style functions.
  9118. @end menu
  9119. @node Old GNU Inlining
  9120. @subsection Older GNU C Inlining
  9121. The GNU C spec for inline functions, before GCC version 5, defined
  9122. @code{extern inline} on a function definition to mean to inline calls
  9123. to it but @emph{not} generate code for the function that could be
  9124. called at run time. By contrast, @code{inline} without @code{extern}
  9125. specified to generate run-time code for the function. In effect, ISO
  9126. incompatibly flipped the meanings of these two cases. We changed GCC
  9127. in version 5 to adopt the ISO specification.
  9128. Many programs still use these cases with the previous GNU C meanings.
  9129. You can specify use of those meanings with the option
  9130. @option{-fgnu89-inline}. You can also specify this for a single
  9131. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9132. @example
  9133. inline __attribute__ ((gnu_inline))
  9134. int
  9135. inc (int *a)
  9136. @{
  9137. (*a)++;
  9138. @}
  9139. @end example
  9140. @node Old-Style Function Definitions
  9141. @subsection Old-Style Function Definitions
  9142. @cindex old-style function definitions
  9143. @cindex function definitions, old-style
  9144. @cindex K&R-style function definitions
  9145. The syntax of C traditionally allows omitting the data type in a
  9146. function declaration if it specifies a storage class or a qualifier.
  9147. Then the type defaults to @code{int}. For example:
  9148. @example
  9149. static foo (double x);
  9150. @end example
  9151. @noindent
  9152. defaults the return type to @code{int}. This is bad practice; if you
  9153. see it, fix it.
  9154. An @dfn{old-style} (or ``K&R'') function definition is the way
  9155. function definitions were written in the 1980s. It looks like this:
  9156. @example
  9157. @var{rettype}
  9158. @var{function} (@var{parmnames})
  9159. @var{parm_declarations}
  9160. @{
  9161. @var{body}
  9162. @}
  9163. @end example
  9164. In @var{parmnames}, only the parameter names are listed, separated by
  9165. commas. Then @var{parm_declarations} declares their data types; these
  9166. declarations look just like variable declarations. If a parameter is
  9167. listed in @var{parmnames} but has no declaration, it is implicitly
  9168. declared @code{int}.
  9169. There is no reason to write a definition this way nowadays, but they
  9170. can still be seen in older GNU programs.
  9171. An old-style variadic function definition looks like this:
  9172. @example
  9173. #include <varargs.h>
  9174. int
  9175. add_multiple_values (va_alist)
  9176. va_dcl
  9177. @{
  9178. int argcount;
  9179. int counter, total = 0;
  9180. /* @r{Declare a variable of type @code{va_list}.} */
  9181. va_list argptr;
  9182. /* @r{Initialize that variable.} */
  9183. va_start (argptr);
  9184. /* @r{Get the first argument (fixed).} */
  9185. argcount = va_arg (int);
  9186. for (counter = 0; counter < argcount; counter++)
  9187. @{
  9188. /* @r{Get the next additional argument.} */
  9189. total += va_arg (argptr, int);
  9190. @}
  9191. /* @r{End use of the @code{argptr} variable.} */
  9192. va_end (argptr);
  9193. return total;
  9194. @}
  9195. @end example
  9196. Note that the old-style variadic function definition has no fixed
  9197. parameter variables; all arguments must be obtained with
  9198. @code{va_arg}.
  9199. @node Compatible Types
  9200. @chapter Compatible Types
  9201. @cindex compatible types
  9202. @cindex types, compatible
  9203. Declaring a function or variable twice is valid in C only if the two
  9204. declarations specify @dfn{compatible} types. In addition, some
  9205. operations on pointers require operands to have compatible target
  9206. types.
  9207. In C, two different primitive types are never compatible. Likewise for
  9208. the defined types @code{struct}, @code{union} and @code{enum}: two
  9209. separately defined types are incompatible unless they are defined
  9210. exactly the same way.
  9211. However, there are a few cases where different types can be
  9212. compatible:
  9213. @itemize @bullet
  9214. @item
  9215. Every enumeration type is compatible with some integer type. In GNU
  9216. C, the choice of integer type depends on the largest enumeration
  9217. value.
  9218. @c ??? Which one, in GCC?
  9219. @c ??? ... it varies, depending on the enum values. Testing on
  9220. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9221. @c ??? then moves on to an 8-byte signed integer. These details
  9222. @c ??? might be platform-dependent, as the C standard says that even
  9223. @c ??? char could be used as an enum type, but it's at least true
  9224. @c ??? that GCC chooses a type that is at least large enough to
  9225. @c ??? hold the largest enum value.
  9226. @item
  9227. Array types are compatible if the element types are compatible
  9228. and the sizes (when specified) match.
  9229. @item
  9230. Pointer types are compatible if the pointer target types are
  9231. compatible.
  9232. @item
  9233. Function types that specify argument types are compatible if the
  9234. return types are compatible and the argument types are compatible,
  9235. argument by argument. In addition, they must all agree in whether
  9236. they use @code{...} to allow additional arguments.
  9237. @item
  9238. Function types that don't specify argument types are compatible if the
  9239. return types are.
  9240. @item
  9241. Function types that specify the argument types are compatible with
  9242. function types that omit them, if the return types are compatible and
  9243. the specified argument types are unaltered by the argument promotions
  9244. (@pxref{Argument Promotions}).
  9245. @end itemize
  9246. In order for types to be compatible, they must agree in their type
  9247. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9248. It follows that @code{const int *} and @code{int *} are incompatible
  9249. too (they are pointers to types that are not compatible).
  9250. If two types are compatible ignoring the qualifiers, we call them
  9251. @dfn{nearly compatible}. (If they are array types, we ignore
  9252. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9253. Comparison of pointers is valid if the pointers' target types are
  9254. nearly compatible. Likewise, the two branches of a conditional
  9255. expression may be pointers to nearly compatible target types.
  9256. If two types are compatible ignoring the qualifiers, and the first
  9257. type has all the qualifiers of the second type, we say the first is
  9258. @dfn{upward compatible} with the second. Assignment of pointers
  9259. requires the assigned pointer's target type to be upward compatible
  9260. with the right operand (the new value)'s target type.
  9261. @node Type Conversions
  9262. @chapter Type Conversions
  9263. @cindex type conversions
  9264. @cindex conversions, type
  9265. C converts between data types automatically when that seems clearly
  9266. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9267. @menu
  9268. * Explicit Type Conversion:: Casting a value from one type to another.
  9269. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9270. * Argument Promotions:: Automatic conversion of function parameters.
  9271. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9272. * Common Type:: When operand types differ, which one is used?
  9273. @end menu
  9274. @node Explicit Type Conversion
  9275. @section Explicit Type Conversion
  9276. @cindex cast
  9277. @cindex explicit type conversion
  9278. You can do explicit conversions using the unary @dfn{cast} operator,
  9279. which is written as a type designator (@pxref{Type Designators}) in
  9280. parentheses. For example, @code{(int)} is the operator to cast to
  9281. type @code{int}. Here's an example of using it:
  9282. @example
  9283. @{
  9284. double d = 5.5;
  9285. printf ("Floating point value: %f\n", d);
  9286. printf ("Rounded to integer: %d\n", (int) d);
  9287. @}
  9288. @end example
  9289. Using @code{(int) d} passes an @code{int} value as argument to
  9290. @code{printf}, so you can print it with @samp{%d}. Using just
  9291. @code{d} without the cast would pass the value as @code{double}.
  9292. That won't work at all with @samp{%d}; the results would be gibberish.
  9293. To divide one integer by another without rounding,
  9294. cast either of the integers to @code{double} first:
  9295. @example
  9296. (double) @var{dividend} / @var{divisor}
  9297. @var{dividend} / (double) @var{divisor}
  9298. @end example
  9299. It is enough to cast one of them, because that forces the common type
  9300. to @code{double} so the other will be converted automatically.
  9301. The valid cast conversions are:
  9302. @itemize @bullet
  9303. @item
  9304. One numerical type to another.
  9305. @item
  9306. One pointer type to another.
  9307. (Converting between pointers that point to functions
  9308. and pointers that point to data is not standard C.)
  9309. @item
  9310. A pointer type to an integer type.
  9311. @item
  9312. An integer type to a pointer type.
  9313. @item
  9314. To a union type, from the type of any alternative in the union
  9315. (@pxref{Unions}). (This is a GNU extension.)
  9316. @item
  9317. Anything, to @code{void}.
  9318. @end itemize
  9319. @node Assignment Type Conversions
  9320. @section Assignment Type Conversions
  9321. @cindex assignment type conversions
  9322. Certain type conversions occur automatically in assignments
  9323. and certain other contexts. These are the conversions
  9324. assignments can do:
  9325. @itemize @bullet
  9326. @item
  9327. Converting any numeric type to any other numeric type.
  9328. @item
  9329. Converting @code{void *} to any other pointer type
  9330. (except pointer-to-function types).
  9331. @item
  9332. Converting any other pointer type to @code{void *}.
  9333. (except pointer-to-function types).
  9334. @item
  9335. Converting 0 (a null pointer constant) to any pointer type.
  9336. @item
  9337. Converting any pointer type to @code{bool}. (The result is
  9338. 1 if the pointer is not null.)
  9339. @item
  9340. Converting between pointer types when the left-hand target type is
  9341. upward compatible with the right-hand target type. @xref{Compatible
  9342. Types}.
  9343. @end itemize
  9344. These type conversions occur automatically in certain contexts,
  9345. which are:
  9346. @itemize @bullet
  9347. @item
  9348. An assignment converts the type of the right-hand expression
  9349. to the type wanted by the left-hand expression. For example,
  9350. @example
  9351. double i;
  9352. i = 5;
  9353. @end example
  9354. @noindent
  9355. converts 5 to @code{double}.
  9356. @item
  9357. A function call, when the function specifies the type for that
  9358. argument, converts the argument value to that type. For example,
  9359. @example
  9360. void foo (double);
  9361. foo (5);
  9362. @end example
  9363. @noindent
  9364. converts 5 to @code{double}.
  9365. @item
  9366. A @code{return} statement converts the specified value to the type
  9367. that the function is declared to return. For example,
  9368. @example
  9369. double
  9370. foo ()
  9371. @{
  9372. return 5;
  9373. @}
  9374. @end example
  9375. @noindent
  9376. also converts 5 to @code{double}.
  9377. @end itemize
  9378. In all three contexts, if the conversion is impossible, that
  9379. constitutes an error.
  9380. @node Argument Promotions
  9381. @section Argument Promotions
  9382. @cindex argument promotions
  9383. @cindex promotion of arguments
  9384. When a function's definition or declaration does not specify the type
  9385. of an argument, that argument is passed without conversion in whatever
  9386. type it has, with these exceptions:
  9387. @itemize @bullet
  9388. @item
  9389. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9390. expression is a narrow integer, such as @code{char} or @code{short},
  9391. the call converts it automatically to @code{int} (@pxref{Integer
  9392. Types}).@footnote{On an embedded controller where @code{char}
  9393. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9394. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9395. never occurs in GNU C on real computers.}
  9396. In this example, the expression @code{c} is passed as an @code{int}:
  9397. @example
  9398. char c = '$';
  9399. printf ("Character c is '%c'\n", c);
  9400. @end example
  9401. @item
  9402. If the expression
  9403. has type @code{float}, the call converts it automatically to
  9404. @code{double}.
  9405. @item
  9406. An array as argument is converted to a pointer to its zeroth element.
  9407. @item
  9408. A function name as argument is converted to a pointer to that function.
  9409. @end itemize
  9410. @node Operand Promotions
  9411. @section Operand Promotions
  9412. @cindex operand promotions
  9413. The operands in arithmetic operations undergo type conversion automatically.
  9414. These @dfn{operand promotions} are the same as the argument promotions
  9415. except without converting @code{float} to @code{double}. In other words,
  9416. the operand promotions convert
  9417. @itemize @bullet
  9418. @item
  9419. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9420. @item
  9421. an array to a pointer to its zeroth element, and
  9422. @item
  9423. a function name to a pointer to that function.
  9424. @end itemize
  9425. @node Common Type
  9426. @section Common Type
  9427. @cindex common type
  9428. Arithmetic binary operators (except the shift operators) convert their
  9429. operands to the @dfn{common type} before operating on them.
  9430. Conditional expressions also convert the two possible results to their
  9431. common type. Here are the rules for determining the common type.
  9432. If one of the numbers has a floating-point type and the other is an
  9433. integer, the common type is that floating-point type. For instance,
  9434. @example
  9435. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9436. @end example
  9437. If both are floating point, the type with the larger range is the
  9438. common type.
  9439. If both are integers but of different widths, the common type
  9440. is the wider of the two.
  9441. If they are integer types of the same width, the common type is
  9442. unsigned if either operand is unsigned, and it's @code{long} if either
  9443. operand is @code{long}. It's @code{long long} if either operand is
  9444. @code{long long}.
  9445. These rules apply to addition, subtraction, multiplication, division,
  9446. remainder, comparisons, and bitwise operations. They also apply to
  9447. the two branches of a conditional expression, and to the arithmetic
  9448. done in a modifying assignment operation.
  9449. @node Scope
  9450. @chapter Scope
  9451. @cindex scope
  9452. @cindex block scope
  9453. @cindex function scope
  9454. @cindex function prototype scope
  9455. Each definition or declaration of an identifier is visible
  9456. in certain parts of the program, which is typically less than the whole
  9457. of the program. The parts where it is visible are called its @dfn{scope}.
  9458. Normally, declarations made at the top-level in the source -- that is,
  9459. not within any blocks and function definitions -- are visible for the
  9460. entire contents of the source file after that point. This is called
  9461. @dfn{file scope} (@pxref{File-Scope Variables}).
  9462. Declarations made within blocks of code, including within function
  9463. definitions, are visible only within those blocks. This is called
  9464. @dfn{block scope}. Here is an example:
  9465. @example
  9466. @group
  9467. void
  9468. foo (void)
  9469. @{
  9470. int x = 42;
  9471. @}
  9472. @end group
  9473. @end example
  9474. @noindent
  9475. In this example, the variable @code{x} has block scope; it is visible
  9476. only within the @code{foo} function definition block. Thus, other
  9477. blocks could have their own variables, also named @code{x}, without
  9478. any conflict between those variables.
  9479. A variable declared inside a subblock has a scope limited to
  9480. that subblock,
  9481. @example
  9482. @group
  9483. void
  9484. foo (void)
  9485. @{
  9486. @{
  9487. int x = 42;
  9488. @}
  9489. // @r{@code{x} is out of scope here.}
  9490. @}
  9491. @end group
  9492. @end example
  9493. If a variable declared within a block has the same name as a variable
  9494. declared outside of that block, the definition within the block
  9495. takes precedence during its scope:
  9496. @example
  9497. @group
  9498. int x = 42;
  9499. void
  9500. foo (void)
  9501. @{
  9502. int x = 17;
  9503. printf ("%d\n", x);
  9504. @}
  9505. @end group
  9506. @end example
  9507. @noindent
  9508. This prints 17, the value of the variable @code{x} declared in the
  9509. function body block, rather than the value of the variable @code{x} at
  9510. file scope. We say that the inner declaration of @code{x}
  9511. @dfn{shadows} the outer declaration, for the extent of the inner
  9512. declaration's scope.
  9513. A declaration with block scope can be shadowed by another declaration
  9514. with the same name in a subblock.
  9515. @example
  9516. @group
  9517. void
  9518. foo (void)
  9519. @{
  9520. char *x = "foo";
  9521. @{
  9522. int x = 42;
  9523. @r{@dots{}}
  9524. exit (x / 6);
  9525. @}
  9526. @}
  9527. @end group
  9528. @end example
  9529. A function parameter's scope is the entire function body, but it can
  9530. be shadowed. For example:
  9531. @example
  9532. @group
  9533. int x = 42;
  9534. void
  9535. foo (int x)
  9536. @{
  9537. printf ("%d\n", x);
  9538. @}
  9539. @end group
  9540. @end example
  9541. @noindent
  9542. This prints the value of @code{x} the function parameter, rather than
  9543. the value of the file-scope variable @code{x}. However,
  9544. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9545. is visible for the whole of the containing function body, both before
  9546. and after the label declaration:
  9547. @example
  9548. @group
  9549. void
  9550. foo (void)
  9551. @{
  9552. @r{@dots{}}
  9553. goto bar;
  9554. @r{@dots{}}
  9555. @{ // @r{Subblock does not affect labels.}
  9556. bar:
  9557. @r{@dots{}}
  9558. @}
  9559. goto bar;
  9560. @}
  9561. @end group
  9562. @end example
  9563. Except for labels, a declared identifier is not
  9564. visible to code before its declaration. For example:
  9565. @example
  9566. @group
  9567. int x = 5;
  9568. int y = x + 10;
  9569. @end group
  9570. @end example
  9571. @noindent
  9572. will work, but:
  9573. @example
  9574. @group
  9575. int x = y + 10;
  9576. int y = 5;
  9577. @end group
  9578. @end example
  9579. @noindent
  9580. cannot refer to the variable @code{y} before its declaration.
  9581. @include cpp.texi
  9582. @node Integers in Depth
  9583. @chapter Integers in Depth
  9584. This chapter explains the machine-level details of integer types: how
  9585. they are represented as bits in memory, and the range of possible
  9586. values for each integer type.
  9587. @menu
  9588. * Integer Representations:: How integer values appear in memory.
  9589. * Maximum and Minimum Values:: Value ranges of integer types.
  9590. @end menu
  9591. @node Integer Representations
  9592. @section Integer Representations
  9593. @cindex integer representations
  9594. @cindex representation of integers
  9595. Modern computers store integer values as binary (base-2) numbers that
  9596. occupy a single unit of storage, typically either as an 8-bit
  9597. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9598. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9599. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9600. any of these types could have some other size, bit it's not worth even
  9601. a minute to cater to that possibility. It never happens on
  9602. GNU/Linux.}
  9603. @cindex @code{CHAR_BIT}
  9604. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9605. of bits in type @code{char}. On any real operating system, the value
  9606. is 8.
  9607. The fixed sizes of numeric types necessarily limits their @dfn{range
  9608. of values}, and the particular encoding of integers decides what that
  9609. range is.
  9610. @cindex two's-complement representation
  9611. For unsigned integers, the entire space is used to represent a
  9612. nonnegative value. Signed integers are stored using
  9613. @dfn{two's-complement representation}: a signed integer with @var{n}
  9614. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9615. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9616. high-order, bit is called the @dfn{sign bit}.
  9617. @c ??? Needs correcting
  9618. There is only one value that means zero, and the most negative number
  9619. lacks a positive counterpart. As a result, negating that number
  9620. causes overflow; in practice, its result is that number back again.
  9621. For example, a two's-complement signed 8-bit integer can represent all
  9622. decimal numbers from @minus{}128 to +127. We will revisit that
  9623. peculiarity shortly.
  9624. Decades ago, there were computers that didn't use two's-complement
  9625. representation for integers (@pxref{Integers in Depth}), but they are
  9626. long gone and not worth any effort to support.
  9627. @c ??? Is this duplicate?
  9628. When an arithmetic operation produces a value that is too big to
  9629. represent, the operation is said to @dfn{overflow}. In C, integer
  9630. overflow does not interrupt the control flow or signal an error.
  9631. What it does depends on signedness.
  9632. For unsigned arithmetic, the result of an operation that overflows is
  9633. the @var{n} low-order bits of the correct value. If the correct value
  9634. is representable in @var{n} bits, that is always the result;
  9635. thus we often say that ``integer arithmetic is exact,'' omitting the
  9636. crucial qualifying phrase ``as long as the exact result is
  9637. representable.''
  9638. In principle, a C program should be written so that overflow never
  9639. occurs for signed integers, but in GNU C you can specify various ways
  9640. of handling such overflow (@pxref{Integer Overflow}).
  9641. Integer representations are best understood by looking at a table for
  9642. a tiny integer size; here are the possible values for an integer with
  9643. three bits:
  9644. @multitable @columnfractions .25 .25 .25 .25
  9645. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9646. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9647. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9648. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9649. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9650. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9651. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9652. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9653. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9654. @end multitable
  9655. The parenthesized decimal numbers in the last column represent the
  9656. signed meanings of the two's-complement of the line's value. Recall
  9657. that, in two's-complement encoding, the high-order bit is 0 when
  9658. the number is nonnegative.
  9659. We can now understand the peculiar behavior of negation of the
  9660. most negative two's-complement integer: start with 0b100,
  9661. invert the bits to get 0b011, and add 1: we get
  9662. 0b100, the value we started with.
  9663. We can also see overflow behavior in two's-complement:
  9664. @example
  9665. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9666. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9667. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9668. @end example
  9669. @noindent
  9670. A sum of two nonnegative signed values that overflows has a 1 in the
  9671. sign bit, so the exact positive result is truncated to a negative
  9672. value.
  9673. @c =====================================================================
  9674. @node Maximum and Minimum Values
  9675. @section Maximum and Minimum Values
  9676. @cindex maximum integer values
  9677. @cindex minimum integer values
  9678. @cindex integer ranges
  9679. @cindex ranges of integer types
  9680. @findex INT_MAX
  9681. @findex UINT_MAX
  9682. @findex SHRT_MAX
  9683. @findex LONG_MAX
  9684. @findex LLONG_MAX
  9685. @findex USHRT_MAX
  9686. @findex ULONG_MAX
  9687. @findex ULLONG_MAX
  9688. @findex CHAR_MAX
  9689. @findex SCHAR_MAX
  9690. @findex UCHAR_MAX
  9691. For each primitive integer type, there is a standard macro defined in
  9692. @file{limits.h} that gives the largest value that type can hold. For
  9693. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9694. On a 32-bit computer, that is equal to 2,147,483,647. The
  9695. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9696. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9697. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9698. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9699. @code{ULLONG_MAX}.
  9700. Since there are three ways to specify a @code{char} type, there are
  9701. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9702. @code{UCHAR_MAX}.
  9703. For each type that is or might be signed, there is another symbol that
  9704. gives the minimum value it can hold. (Just replace @code{MAX} with
  9705. @code{MIN} in the names listed above.) There is no minimum limit
  9706. symbol for types specified with @code{unsigned} because the
  9707. minimum for them is universally zero.
  9708. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9709. two's-complement representation, the most negative number is 1 less
  9710. than the negative of the most positive number. Thus, @code{INT_MIN}
  9711. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9712. actually write the value that way in C, since it would overflow.
  9713. That's a good reason to use @code{INT_MIN} to specify
  9714. that value. Its definition is written to avoid overflow.
  9715. @include fp.texi
  9716. @node Compilation
  9717. @chapter Compilation
  9718. @cindex object file
  9719. @cindex compilation module
  9720. @cindex make rules
  9721. Early in the manual we explained how to compile a simple C program
  9722. that consists of a single source file (@pxref{Compile Example}).
  9723. However, we handle only short programs that way. A typical C program
  9724. consists of many source files, each of which is a separate
  9725. @dfn{compilation module}---meaning that it has to be compiled
  9726. separately.
  9727. The full details of how to compile with GCC are documented in xxxx.
  9728. @c ??? ref
  9729. Here we give only a simple introduction.
  9730. These are the commands to compile two compilation modules,
  9731. @file{foo.c} and @file{bar.c}, with a command for each module:
  9732. @example
  9733. gcc -c -O -g foo.c
  9734. gcc -c -O -g bar.c
  9735. @end example
  9736. @noindent
  9737. In these commands, @option{-g} says to generate debugging information,
  9738. @option{-O} says to do some optimization, and @option{-c} says to put
  9739. the compiled code for that module into a corresponding @dfn{object
  9740. file} and go no further. The object file for @file{foo.c} is called
  9741. @file{foo.o}, and so on.
  9742. If you wish, you can specify the additional options @option{-Wformat
  9743. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9744. One reason to divide a large program into multiple compilation modules
  9745. is to control how each module can access the internals of the others.
  9746. When a module declares a function or variable @code{extern}, other
  9747. modules can access it. The other functions and variables in
  9748. a module can't be accessed from outside that module.
  9749. The other reason for using multiple modules is so that changing
  9750. one source file does not require recompiling all of them in order
  9751. to try the modified program. Dividing a large program into many
  9752. substantial modules in this way typically makes recompilation much faster.
  9753. @cindex linking object files
  9754. After you compile all the program's modules, in order to run the
  9755. program you must @dfn{link} the object files into a combined
  9756. executable, like this:
  9757. @example
  9758. gcc -o foo foo.o bar.o
  9759. @end example
  9760. @noindent
  9761. In this command, @option{-o foo} species the file name for the
  9762. executable file, and the other arguments are the object files to link.
  9763. Always specify the executable file name in a command that generates
  9764. one.
  9765. Normally we don't run any of these commands directly. Instead we
  9766. write a set of @dfn{make rules} for the program, then use the
  9767. @command{make} program to recompile only the source files that need to
  9768. be recompiled.
  9769. @c ??? ref to make manual
  9770. @node Directing Compilation
  9771. @chapter Directing Compilation
  9772. This chapter describes C constructs that don't alter the program's
  9773. meaning @emph{as such}, but rather direct the compiler how to treat
  9774. some aspects of the program.
  9775. @menu
  9776. * Pragmas:: Controling compilation of some constructs.
  9777. * Static Assertions:: Compile-time tests for conditions.
  9778. @end menu
  9779. @node Pragmas
  9780. @section Pragmas
  9781. A @dfn{pragma} is an annotation in a program that gives direction to
  9782. the compiler.
  9783. @menu
  9784. * Pragma Basics:: Pragma syntax and usage.
  9785. * Severity Pragmas:: Settings for compile-time pragma output.
  9786. * Optimization Pragmas:: Controlling optimizations.
  9787. @end menu
  9788. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9789. @node Pragma Basics
  9790. @subsection Pragma Basics
  9791. C defines two syntactical forms for pragmas, the line form and the
  9792. token form. You can write any pragma in either form, with the same
  9793. meaning.
  9794. The line form is a line in the source code, like this:
  9795. @example
  9796. #pragma @var{line}
  9797. @end example
  9798. @noindent
  9799. The line pragma has no effect on the parsing of the lines around it.
  9800. This form has the drawback that it can't be generated by a macro expansion.
  9801. The token form is a series of tokens; it can appear anywhere in the
  9802. program between the other tokens.
  9803. @example
  9804. _Pragma (@var{stringconstant})
  9805. @end example
  9806. @noindent
  9807. The pragma has no effect on the syntax of the tokens that surround it;
  9808. thus, here's a pragma in the middle of an @code{if} statement:
  9809. @example
  9810. if _Pragma ("hello") (x > 1)
  9811. @end example
  9812. @noindent
  9813. However, that's an unclear thing to do; for the sake of
  9814. understandability, it is better to put a pragma on a line by itself
  9815. and not embedded in the middle of another construct.
  9816. Both forms of pragma have a textual argument. In a line pragma, the
  9817. text is the rest of the line. The textual argument to @code{_Pragma}
  9818. uses the same syntax as a C string constant: surround the text with
  9819. two @samp{"} characters, and add a backslash before each @samp{"} or
  9820. @samp{\} character in it.
  9821. With either syntax, the textual argument specifies what to do.
  9822. It begins with one or several words that specify the operation.
  9823. If the compiler does not recognize them, it ignores the pragma.
  9824. Here are the pragma operations supported in GNU C@.
  9825. @c ??? Verify font for []
  9826. @table @code
  9827. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9828. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9829. Declares that the current source file depends on @var{file}, so GNU C
  9830. compares the file times and gives a warning if @var{file} is newer
  9831. than the current source file.
  9832. This directive searches for @var{file} the way @code{#include}
  9833. searches for a non-system header file.
  9834. If @var{message} is given, the warning message includes that text.
  9835. Examples:
  9836. @example
  9837. #pragma GCC dependency "parse.y"
  9838. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9839. rerun fixincludes")
  9840. @end example
  9841. @item #pragma GCC poison @var{identifiers}
  9842. @itemx _Pragma ("GCC poison @var{identifiers}")
  9843. Poisons the identifiers listed in @var{identifiers}.
  9844. This is useful to make sure all mention of @var{identifiers} has been
  9845. deleted from the program and that no reference to them creeps back in.
  9846. If any of those identifiers appears anywhere in the source after the
  9847. directive, it causes a compilation error. For example,
  9848. @example
  9849. #pragma GCC poison printf sprintf fprintf
  9850. sprintf(some_string, "hello");
  9851. @end example
  9852. @noindent
  9853. generates an error.
  9854. If a poisoned identifier appears as part of the expansion of a macro
  9855. that was defined before the identifier was poisoned, it will @emph{not}
  9856. cause an error. Thus, system headers that define macros that use
  9857. the identifier will not cause errors.
  9858. For example,
  9859. @example
  9860. #define strrchr rindex
  9861. _Pragma ("GCC poison rindex")
  9862. strrchr(some_string, 'h');
  9863. @end example
  9864. @noindent
  9865. does not cause a compilation error.
  9866. @item #pragma GCC system_header
  9867. @itemx _Pragma ("GCC system_header")
  9868. Specify treating the rest of the current source file as if it came
  9869. from a system header file. @xref{System Headers, System Headers,
  9870. System Headers, gcc, Using the GNU Compiler Collection}.
  9871. @item #pragma GCC warning @var{message}
  9872. @itemx _Pragma ("GCC warning @var{message}")
  9873. Equivalent to @code{#warning}. Its advantage is that the
  9874. @code{_Pragma} form can be included in a macro definition.
  9875. @item #pragma GCC error @var{message}
  9876. @itemx _Pragma ("GCC error @var{message}")
  9877. Equivalent to @code{#error}. Its advantage is that the
  9878. @code{_Pragma} form can be included in a macro definition.
  9879. @item #pragma GCC message @var{message}
  9880. @itemx _Pragma ("GCC message @var{message}")
  9881. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9882. informational message, and could be used to include additional warning
  9883. or error text without triggering more warnings or errors. (Note that
  9884. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9885. @samp{GCC} as part of the pragma.)
  9886. @end table
  9887. @node Severity Pragmas
  9888. @subsection Severity Pragmas
  9889. These pragmas control the severity of classes of diagnostics.
  9890. You can specify the class of diagnostic with the GCC option that causes
  9891. those diagnostics to be generated.
  9892. @table @code
  9893. @item #pragma GCC diagnostic error @var{option}
  9894. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9895. For code following this pragma, treat diagnostics of the variety
  9896. specified by @var{option} as errors. For example:
  9897. @example
  9898. _Pragma ("GCC diagnostic error -Wformat")
  9899. @end example
  9900. @noindent
  9901. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9902. as errors rather than warnings.
  9903. @item #pragma GCC diagnostic warning @var{option}
  9904. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9905. For code following this pragma, treat diagnostics of the variety
  9906. specified by @var{option} as warnings. This overrides the
  9907. @var{-Werror} option which says to treat warnings as errors.
  9908. @item #pragma GCC diagnostic ignore @var{option}
  9909. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9910. For code following this pragma, refrain from reporting any diagnostics
  9911. of the variety specified by @var{option}.
  9912. @item #pragma GCC diagnostic push
  9913. @itemx _Pragma ("GCC diagnostic push")
  9914. @itemx #pragma GCC diagnostic pop
  9915. @itemx _Pragma ("GCC diagnostic pop")
  9916. These pragmas maintain a stack of states for severity settings.
  9917. @samp{GCC diagnostic push} saves the current settings on the stack,
  9918. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9919. the current settings from that.
  9920. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9921. restores the settings to what they were at the start of compilation.
  9922. Here is an example:
  9923. @example
  9924. _Pragma ("GCC diagnostic error -Wformat")
  9925. /* @r{@option{-Wformat} messages treated as errors. } */
  9926. _Pragma ("GCC diagnostic push")
  9927. _Pragma ("GCC diagnostic warning -Wformat")
  9928. /* @r{@option{-Wformat} messages treated as warnings. } */
  9929. _Pragma ("GCC diagnostic push")
  9930. _Pragma ("GCC diagnostic ignored -Wformat")
  9931. /* @r{@option{-Wformat} messages suppressed. } */
  9932. _Pragma ("GCC diagnostic pop")
  9933. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9934. _Pragma ("GCC diagnostic pop")
  9935. /* @r{@option{-Wformat} messages treated as errors again. } */
  9936. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9937. _Pragma ("GCC diagnostic pop")
  9938. /* @r{@option{-Wformat} messages treated once again}
  9939. @r{as specified by the GCC command-line options.} */
  9940. @end example
  9941. @end table
  9942. @node Optimization Pragmas
  9943. @subsection Optimization Pragmas
  9944. These pragmas enable a particular optimization for specific function
  9945. definitions. The settings take effect at the end of a function
  9946. definition, so the clean place to use these pragmas is between
  9947. function definitions.
  9948. @table @code
  9949. @item #pragma GCC optimize @var{optimization}
  9950. @itemx _Pragma ("GCC optimize @var{optimization}")
  9951. These pragmas enable the optimization @var{optimization} for the
  9952. following functions. For example,
  9953. @example
  9954. _Pragma ("GCC optimize -fforward-propagate")
  9955. @end example
  9956. @noindent
  9957. says to apply the @samp{forward-propagate} optimization to all
  9958. following function definitions. Specifying optimizations for
  9959. individual functions, rather than for the entire program, is rare but
  9960. can be useful for getting around a bug in the compiler.
  9961. If @var{optimization} does not correspond to a defined optimization
  9962. option, the pragma is erroneous. To turn off an optimization, use the
  9963. corresponding @samp{-fno-} option, such as
  9964. @samp{-fno-forward-propagate}.
  9965. @item #pragma GCC target @var{optimizations}
  9966. @itemx _Pragma ("GCC target @var{optimizations}")
  9967. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9968. used for platform-specific optimizations. Thus,
  9969. @example
  9970. _Pragma ("GCC target popcnt")
  9971. @end example
  9972. @noindent
  9973. activates the optimization @samp{popcnt} for all
  9974. following function definitions. This optimization is supported
  9975. on a few common targets but not on others.
  9976. @item #pragma GCC push_options
  9977. @itemx _Pragma ("GCC push_options")
  9978. The @samp{push_options} pragma saves on a stack the current settings
  9979. specified with the @samp{target} and @samp{optimize} pragmas.
  9980. @item #pragma GCC pop_options
  9981. @itemx _Pragma ("GCC pop_options")
  9982. The @samp{pop_options} pragma pops saved settings from that stack.
  9983. Here's an example of using this stack.
  9984. @example
  9985. _Pragma ("GCC push_options")
  9986. _Pragma ("GCC optimize forward-propagate")
  9987. /* @r{Functions to compile}
  9988. @r{with the @code{forward-propagate} optimization.} */
  9989. _Pragma ("GCC pop_options")
  9990. /* @r{Ends enablement of @code{forward-propagate}.} */
  9991. @end example
  9992. @item #pragma GCC reset_options
  9993. @itemx _Pragma ("GCC reset_options")
  9994. Clears all pragma-defined @samp{target} and @samp{optimize}
  9995. optimization settings.
  9996. @end table
  9997. @node Static Assertions
  9998. @section Static Assertions
  9999. @cindex static assertions
  10000. @findex _Static_assert
  10001. You can add compiler-time tests for necessary conditions into your
  10002. code using @code{_Static_assert}. This can be useful, for example, to
  10003. check that the compilation target platform supports the type sizes
  10004. that the code expects. For example,
  10005. @example
  10006. _Static_assert ((sizeof (long int) >= 8),
  10007. "long int needs to be at least 8 bytes");
  10008. @end example
  10009. @noindent
  10010. reports a compile-time error if compiled on a system with long
  10011. integers smaller than 8 bytes, with @samp{long int needs to be at
  10012. least 8 bytes} as the error message.
  10013. Since calls @code{_Static_assert} are processed at compile time, the
  10014. expression must be computable at compile time and the error message
  10015. must be a literal string. The expression can refer to the sizes of
  10016. variables, but can't refer to their values. For example, the
  10017. following static assertion is invalid for two reasons:
  10018. @example
  10019. char *error_message
  10020. = "long int needs to be at least 8 bytes";
  10021. int size_of_long_int = sizeof (long int);
  10022. _Static_assert (size_of_long_int == 8, error_message);
  10023. @end example
  10024. @noindent
  10025. The expression @code{size_of_long_int == 8} isn't computable at
  10026. compile time, and the error message isn't a literal string.
  10027. You can, though, use preprocessor definition values with
  10028. @code{_Static_assert}:
  10029. @example
  10030. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10031. at least 8 bytes"
  10032. _Static_assert ((sizeof (long int) == 8),
  10033. LONG_INT_ERROR_MESSAGE);
  10034. @end example
  10035. Static assertions are permitted wherever a statement or declaration is
  10036. permitted, including at top level in the file, and also inside the
  10037. definition of a type.
  10038. @example
  10039. union y
  10040. @{
  10041. int i;
  10042. int *ptr;
  10043. _Static_assert (sizeof (int *) == sizeof (int),
  10044. "Pointer and int not same size");
  10045. @};
  10046. @end example
  10047. @node Type Alignment
  10048. @appendix Type Alignment
  10049. @cindex type alignment
  10050. @cindex alignment of type
  10051. @findex _Alignof
  10052. @findex __alignof__
  10053. Code for device drivers and other communication with low-level
  10054. hardware sometimes needs to be concerned with the alignment of
  10055. data objects in memory.
  10056. Each data type has a required @dfn{alignment}, always a power of 2,
  10057. that says at which memory addresses an object of that type can validly
  10058. start. A valid address for the type must be a multiple of its
  10059. alignment. If a type's alignment is 1, that means it can validly
  10060. start at any address. If a type's alignment is 2, that means it can
  10061. only start at an even address. If a type's alignment is 4, that means
  10062. it can only start at an address that is a multiple of 4.
  10063. The alignment of a type (except @code{char}) can vary depending on the
  10064. kind of computer in use. To refer to the alignment of a type in a C
  10065. program, use @code{_Alignof}, whose syntax parallels that of
  10066. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10067. operation, and it doesn't compute the value of the expression used
  10068. as its argument.
  10069. Nominally, each integer and floating-point type has an alignment equal to
  10070. the largest power of 2 that divides its size. Thus, @code{int} with
  10071. size 4 has a nominal alignment of 4, and @code{long long int} with
  10072. size 8 has a nominal alignment of 8.
  10073. However, each kind of computer generally has a maximum alignment, and
  10074. no type needs more alignment than that. If the computer's maximum
  10075. alignment is 4 (which is common), then no type's alignment is more
  10076. than 4.
  10077. The size of any type is always a multiple of its alignment; that way,
  10078. in an array whose elements have that type, all the elements are
  10079. properly aligned if the first one is.
  10080. These rules apply to all real computers today, but some embedded
  10081. controllers have odd exceptions. We don't have references to cite for
  10082. them.
  10083. @c We can't cite a nonfree manual as documentation.
  10084. Ordinary C code guarantees that every object of a given type is in
  10085. fact aligned as that type requires.
  10086. If the operand of @code{_Alignof} is a structure field, the value
  10087. is the alignment it requires. It may have a greater alignment by
  10088. coincidence, due to the other fields, but @code{_Alignof} is not
  10089. concerned about that. @xref{Structures}.
  10090. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10091. but now that the feature has been standardized, it is better
  10092. to use the standard keyword @code{_Alignof}.
  10093. @findex _Alignas
  10094. @findex __aligned__
  10095. You can explicitly specify an alignment requirement for a particular
  10096. variable or structure field by adding @code{_Alignas
  10097. (@var{alignment})} to the declaration, where @var{alignment} is a
  10098. power of 2 or a type name. For instance:
  10099. @example
  10100. char _Alignas (8) x;
  10101. @end example
  10102. @noindent
  10103. or
  10104. @example
  10105. char _Alignas (double) x;
  10106. @end example
  10107. @noindent
  10108. specifies that @code{x} must start on an address that is a multiple of
  10109. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10110. machine, that maximum is how much alignment @code{x} will get.
  10111. The older GNU C syntax for this feature looked like
  10112. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10113. declaration, and was added after the variable. For instance:
  10114. @example
  10115. char x __attribute__ ((__aligned__ 8));
  10116. @end example
  10117. @xref{Attributes}.
  10118. @node Aliasing
  10119. @appendix Aliasing
  10120. @cindex aliasing (of storage)
  10121. @cindex pointer type conversion
  10122. @cindex type conversion, pointer
  10123. We have already presented examples of casting a @code{void *} pointer
  10124. to another pointer type, and casting another pointer type to
  10125. @code{void *}.
  10126. One common kind of pointer cast is guaranteed safe: casting the value
  10127. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10128. Allocation}). It is safe because these functions do not save the
  10129. pointer anywhere else; the only way the program will access the newly
  10130. allocated memory is via the pointer just returned.
  10131. In fact, C allows casting any pointer type to any other pointer type.
  10132. Using this to access the same place in memory using two
  10133. different data types is called @dfn{aliasing}.
  10134. Aliasing is necessary in some programs that do sophisticated memory
  10135. management, such as GNU Emacs, but most C programs don't need to do
  10136. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10137. aliasing correctly requires following the rules stated below.
  10138. Otherwise, the aliasing may result in malfunctions when the program
  10139. runs.
  10140. The rest of this appendix explains the pitfalls and rules of aliasing.
  10141. @menu
  10142. * Aliasing Alignment:: Memory alignment considerations for
  10143. casting between pointer types.
  10144. * Aliasing Length:: Type size considerations for
  10145. casting between pointer types.
  10146. * Aliasing Type Rules:: Even when type alignment and size matches,
  10147. aliasing can still have surprising results.
  10148. @end menu
  10149. @node Aliasing Alignment
  10150. @appendixsection Aliasing and Alignment
  10151. In order for a type-converted pointer to be valid, it must have the
  10152. alignment that the new pointer type requires. For instance, on most
  10153. computers, @code{int} has alignment 4; the address of an @code{int}
  10154. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10155. address of a @code{char} is usually not a multiple of 4. Taking the
  10156. address of such a @code{char} and casting it to @code{int *} probably
  10157. results in an invalid pointer. Trying to dereference it may cause a
  10158. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10159. @example
  10160. foo ()
  10161. @{
  10162. char i[4];
  10163. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10164. return *p; /* @r{Crash!} */
  10165. @}
  10166. @end example
  10167. This requirement is never a problem when casting the return value
  10168. of @code{malloc} because that function always returns a pointer
  10169. with as much alignment as any type can require.
  10170. @node Aliasing Length
  10171. @appendixsection Aliasing and Length
  10172. When converting a pointer to a different pointer type, make sure the
  10173. object it really points to is at least as long as the target of the
  10174. converted pointer. For instance, suppose @code{p} has type @code{int
  10175. *} and it's cast as follows:
  10176. @example
  10177. int *p;
  10178. struct
  10179. @{
  10180. double d, e, f;
  10181. @} foo;
  10182. struct foo *q = (struct foo *)p;
  10183. q->f = 5.14159;
  10184. @end example
  10185. @noindent
  10186. the value @code{q->f} will run past the end of the @code{int} that
  10187. @code{p} points to. If @code{p} was initialized to the start of an
  10188. array of type @code{int[6]}, the object is long enough for three
  10189. @code{double}s. But if @code{p} points to something shorter,
  10190. @code{q->f} will run on beyond the end of that, overlaying some other
  10191. data. Storing that will garble that other data. Or it could extend
  10192. past the end of memory space and cause a @code{SIGSEGV} signal
  10193. (@pxref{Signals}).
  10194. @node Aliasing Type Rules
  10195. @appendixsection Type Rules for Aliasing
  10196. C code that converts a pointer to a different pointer type can use the
  10197. pointers to access the same memory locations with two different data
  10198. types. If the same address is accessed with different types in a
  10199. single control thread, optimization can make the code do surprising
  10200. things (in effect, make it malfunction).
  10201. Here's a concrete example where aliasing that can change the code's
  10202. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10203. long, like @code{int}, and so is every pointer. Thus, the structures
  10204. @code{struct a} and @code{struct b} are both 8 bytes.
  10205. @example
  10206. #include <stdio.h>
  10207. struct a @{ int size; char *data; @};
  10208. struct b @{ float size; char *data; @};
  10209. void sub (struct a *p, struct b *q)
  10210. @{
  10211.   int x;
  10212.   p->size = 0;
  10213.   q->size = 1;
  10214.   x = p->size;
  10215.   printf("x       =%d\n", x);
  10216.   printf("p->size =%d\n", (int)p->size);
  10217.   printf("q->size =%d\n", (int)q->size);
  10218. @}
  10219. int main(void)
  10220. @{
  10221.   struct a foo;
  10222.   struct a *p = &foo;
  10223.   struct b *q = (struct b *) &foo;
  10224.   sub (p, q);
  10225. @}
  10226. @end example
  10227. This code works as intended when compiled without optimization. All
  10228. the operations are carried out sequentially as written. The code
  10229. sets @code{x} to @code{p->size}, but what it actually gets is the
  10230. bits of the floating point number 1, as type @code{int}.
  10231. However, when optimizing, the compiler is allowed to assume
  10232. (mistakenly, here) that @code{q} does not point to the same storage as
  10233. @code{p}, because their data types are not allowed to alias.
  10234. From this assumption, the compiler can deduce (falsely, here) that the
  10235. assignment into @code{q->size} has no effect on the value of
  10236. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10237. be set to 0.
  10238. GNU C, following the C standard, @emph{defines} this optimization as
  10239. legitimate. Code that misbehaves when optimized following these rules
  10240. is, by definition, incorrect C code.
  10241. The rules for storage aliasing in C are based on the two data types:
  10242. the type of the object, and the type it is accessed through. The
  10243. rules permit accessing part of a storage object of type @var{t} using
  10244. only these types:
  10245. @itemize @bullet
  10246. @item
  10247. @var{t}.
  10248. @item
  10249. A type compatible with @var{t}. @xref{Compatible Types}.
  10250. @item
  10251. A signed or unsigned version of one of the above.
  10252. @item
  10253. A qualifed version of one of the above.
  10254. @xref{Type Qualifiers}.
  10255. @item
  10256. An array, structure (@pxref{Structures}), or union type
  10257. (@code{Unions}) that contains one of the above, either directly as a
  10258. field or through multiple levels of fields. If @var{t} is
  10259. @code{double}, this would include @code{struct s @{ union @{ double
  10260. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10261. inside it somewhere.
  10262. @item
  10263. A character type.
  10264. @end itemize
  10265. What do these rules say about the example in this subsection?
  10266. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10267. @code{int}. The type @code{float} is not allowed as an aliasing type
  10268. by those rules, so @code{b->size} is not supposed to alias with
  10269. elements of @code{j}. Based on that assumption, GNU C makes a
  10270. permitted optimization that was not, in this case, consistent with
  10271. what the programmer intended the program to do.
  10272. Whether GCC actually performs type-based aliasing analysis depends on
  10273. the details of the code. GCC has other ways to determine (in some cases)
  10274. whether objects alias, and if it gets a reliable answer that way, it won't
  10275. fall back on type-based heuristics.
  10276. @c @opindex -fno-strict-aliasing
  10277. The importance of knowing the type-based aliasing rules is not so as
  10278. to ensure that the optimization is done where it would be safe, but so
  10279. as to ensure it is @emph{not} done in a way that would break the
  10280. program. You can turn off type-based aliasing analysis by giving GCC
  10281. the option @option{-fno-strict-aliasing}.
  10282. @node Digraphs
  10283. @appendix Digraphs
  10284. @cindex digraphs
  10285. C accepts aliases for certain characters. Apparently in the 1990s
  10286. some computer systems had trouble inputting these characters, or
  10287. trouble displaying them. These digraphs almost never appear in C
  10288. programs nowadays, but we mention them for completeness.
  10289. @table @samp
  10290. @item <:
  10291. An alias for @samp{[}.
  10292. @item :>
  10293. An alias for @samp{]}.
  10294. @item <%
  10295. An alias for @samp{@{}.
  10296. @item %>
  10297. An alias for @samp{@}}.
  10298. @item %:
  10299. An alias for @samp{#},
  10300. used for preprocessing directives (@pxref{Directives}) and
  10301. macros (@pxref{Macros}).
  10302. @end table
  10303. @node Attributes
  10304. @appendix Attributes in Declarations
  10305. @cindex attributes
  10306. @findex __attribute__
  10307. You can specify certain additional requirements in a declaration, to
  10308. get fine-grained control over code generation, and helpful
  10309. informational messages during compilation. We use a few attributes in
  10310. code examples throughout this manual, including
  10311. @table @code
  10312. @item aligned
  10313. The @code{aligned} attribute specifies a minimum alignment for a
  10314. variable or structure field, measured in bytes:
  10315. @example
  10316. int foo __attribute__ ((aligned (8))) = 0;
  10317. @end example
  10318. @noindent
  10319. This directs GNU C to allocate @code{foo} at an address that is a
  10320. multiple of 8 bytes. However, you can't force an alignment bigger
  10321. than the computer's maximum meaningful alignment.
  10322. @item packed
  10323. The @code{packed} attribute specifies to compact the fields of a
  10324. structure by not leaving gaps between fields. For example,
  10325. @example
  10326. struct __attribute__ ((packed)) bar
  10327. @{
  10328. char a;
  10329. int b;
  10330. @};
  10331. @end example
  10332. @noindent
  10333. allocates the integer field @code{b} at byte 1 in the structure,
  10334. immediately after the character field @code{a}. The packed structure
  10335. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10336. alignment is 1, that of @code{char}.
  10337. @item deprecated
  10338. Applicable to both variables and functions, the @code{deprecated}
  10339. attribute tells the compiler to issue a warning if the variable or
  10340. function is ever used in the source file.
  10341. @example
  10342. int old_foo __attribute__ ((deprecated));
  10343. int old_quux () __attribute__ ((deprecated));
  10344. @end example
  10345. @item __noinline__
  10346. The @code{__noinline__} attribute, in a function's declaration or
  10347. definition, specifies never to inline calls to that function. All
  10348. calls to that function, in a compilation unit where it has this
  10349. attribute, will be compiled to invoke the separately compiled
  10350. function. @xref{Inline Function Definitions}.
  10351. @item __noclone__
  10352. The @code{__noclone__} attribute, in a function's declaration or
  10353. definition, specifies never to clone that function. Thus, there will
  10354. be only one compiled version of the function. @xref{Label Value
  10355. Caveats}, for more information about cloning.
  10356. @item always_inline
  10357. The @code{always_inline} attribute, in a function's declaration or
  10358. definition, specifies to inline all calls to that function (unless
  10359. something about the function makes inlining impossible). This applies
  10360. to all calls to that function in a compilation unit where it has this
  10361. attribute. @xref{Inline Function Definitions}.
  10362. @item gnu_inline
  10363. The @code{gnu_inline} attribute, in a function's declaration or
  10364. definition, specifies to handle the @code{inline} keywprd the way GNU
  10365. C originally implemented it, many years before ISO C said anything
  10366. about inlining. @xref{Inline Function Definitions}.
  10367. @end table
  10368. For full documentation of attributes, see the GCC manual.
  10369. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10370. the GNU Compiler Collection}.
  10371. @node Signals
  10372. @appendix Signals
  10373. @cindex signal
  10374. @cindex handler (for signal)
  10375. @cindex @code{SIGSEGV}
  10376. @cindex @code{SIGFPE}
  10377. @cindex @code{SIGBUS}
  10378. Some program operations bring about an error condition called a
  10379. @dfn{signal}. These signals terminate the program, by default.
  10380. There are various different kinds of signals, each with a name. We
  10381. have seen several such error conditions through this manual:
  10382. @table @code
  10383. @item SIGSEGV
  10384. This signal is generated when a program tries to read or write outside
  10385. the memory that is allocated for it, or to write memory that can only
  10386. be read. The name is an abbreviation for ``segmentation violation''.
  10387. @item SIGFPE
  10388. This signal indicates a fatal arithmetic error. The name is an
  10389. abbreviation for ``floating-point exception'', but covers all types of
  10390. arithmetic errors, including division by zero and overflow.
  10391. @item SIGBUS
  10392. This signal is generated when an invalid pointer is dereferenced,
  10393. typically the result of dereferencing an uninintalized pointer. It is
  10394. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10395. invalid access to valid memory, while @code{SIGBUS} indicates an
  10396. attempt to access an invalid address.
  10397. @end table
  10398. These kinds of signal allow the program to specify a function as a
  10399. @dfn{signal handler}. When a signal has a handler, it doesn't
  10400. terminate the program; instead it calls the handler.
  10401. There are many other kinds of signal; here we list only those that
  10402. come from run-time errors in C operations. The rest have to do with
  10403. the functioning of the operating system. The GNU C Library Reference
  10404. Manual gives more explanation about signals (@pxref{Program Signal
  10405. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10406. Manual}).
  10407. @node GNU Free Documentation License
  10408. @appendix GNU Free Documentation License
  10409. @include fdl.texi
  10410. @node Symbol Index
  10411. @unnumbered Index of Symbols and Keywords
  10412. @printindex fn
  10413. @node Concept Index
  10414. @unnumbered Concept Index
  10415. @printindex cp
  10416. @bye