c.texi 419 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007
  1. \input texinfo
  2. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  3. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  4. licensed to the FSF.)
  5. @c move alignment later?
  6. @setfilename ./c
  7. @settitle GNU C Language Manual
  8. @documentencoding UTF-8
  9. @synindex vr fn
  10. @copying
  11. Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  12. (The work of Trevis Rothwell and Nelson Beebe has been assigned or
  13. licensed to the FSF.)
  14. @quotation
  15. Permission is granted to copy, distribute and/or modify this document
  16. under the terms of the GNU Free Documentation License, Version 1.3 or
  17. any later version published by the Free Software Foundation; with the
  18. Invariant Sections being ``GNU General Public License,'' with the
  19. Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover
  20. Texts as in (a) below. A copy of the license is included in the
  21. section entitled ``GNU Free Documentation License.''
  22. (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
  23. modify this GNU manual. Buying copies from the FSF supports it in
  24. developing GNU and promoting software freedom.''
  25. @end quotation
  26. @end copying
  27. @dircategory Programming
  28. @direntry
  29. * C: (c). GNU C Language Intro and Reference Manual
  30. @end direntry
  31. @documentencoding UTF-8
  32. @titlepage
  33. @sp 6
  34. @center @titlefont{GNU C Language Intro 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. WILL BE Published by the Free Software Foundation @*
  48. 51 Franklin Street, Fifth Floor @*
  49. Boston, MA 02110-1301 USA @*
  50. ISBN ?-??????-??-?
  51. @ignore
  52. @sp 1
  53. Cover art by J. Random Artist
  54. @end ignore
  55. @end titlepage
  56. @summarycontents
  57. @contents
  58. @node Top
  59. @ifnottex
  60. @top GNU C Manual
  61. @end ifnottex
  62. @iftex
  63. @top Preface
  64. @end iftex
  65. This manual explains the C language for use with the GNU Compiler
  66. Collection (GCC) on the GNU/Linux system and other systems. We refer
  67. to this dialect as GNU C. If you already know C, you can use this as
  68. a reference manual.
  69. If you understand basic concepts of programming but know nothing about
  70. C, you can read this manual sequentially from the beginning to learn
  71. the C language.
  72. If you are a beginner to programming, we recommend you first learn a
  73. language with automatic garbage collection and no explicit pointers,
  74. rather than starting with C@. Good choices include Lisp, Scheme,
  75. Python and Java. C's explicit pointers mean that programmers must be
  76. careful to avoid certain kinds of errors.
  77. C is a venerable language; it was first used in 1973. The GNU C
  78. Compiler, which was subsequently extended into the GNU Compiler
  79. Collection, was first released in 1987. Other important languages
  80. were designed based on C: once you know C, it gives you a useful base
  81. for learning C@t{++}, C#, Java, Scala, D, Go, and more.
  82. The special advantage of C is that it is fairly simple while allowing
  83. close access to the computer's hardware, which previously required
  84. writing in assembler language to describe the individual machine
  85. instructions. Some have called C a ``high-level assembler language''
  86. because of its explicit pointers and lack of automatic management of
  87. storage. As one wag put it, ``C combines the power of assembler
  88. language with the convenience of assembler language.'' However, C is
  89. far more portable, and much easier to read and write, than assembler
  90. language.
  91. This manual focuses on the GNU C language supported by the GNU
  92. Compiler Collection, version ???. When a construct may be absent or
  93. work differently in other C compilers, we say so. When it is not part
  94. of ISO standard C, we say it is a ``GNU C extension,'' because it is
  95. useful to know that; however, other dialects and standards are not the
  96. focus of this manual. We keep those notes short, unless it is vital
  97. to say more. For the same reason, we hardly mention C@t{++} or other
  98. languages that the GNU Compiler Collection supports.
  99. Some aspects of the meaning of C programs depend on the target
  100. platform: which computer, and which operating system, the compiled
  101. code will run on. Where this is the case, we say so.
  102. The C language provides no built-in facilities for performing such
  103. common operations as input/output, memory management, string
  104. manipulation, and the like. Instead, these facilities are defined in
  105. a standard library, which is automatically available in every C
  106. program. @xref{Top, The GNU C Library, , libc, The GNU C Library
  107. Reference Manual}.
  108. This manual incorporates the former GNU C Preprocessor Manual, which
  109. was among the earliest GNU Manuals. It also uses some text from the
  110. earlier GNU C Manual that was written by Trevis Rothwell and James
  111. Youngman.
  112. GNU C has many obscure features, each one either for historical
  113. compatibility or meant for very special situations. We have left them
  114. to a companion manual, the GNU C Obscurities Manual, which will be
  115. published digitally later.
  116. @menu
  117. * The First Example:: Getting started with basic C code.
  118. * Complete Program:: A whole example program
  119. that can be compiled and run.
  120. * Storage:: Basic layout of storage; bytes.
  121. * Beyond Integers:: Exploring different numeric types.
  122. * Lexical Syntax:: The various lexical components of C programs.
  123. * Arithmetic:: Numeric computations.
  124. * Assignment Expressions:: Storing values in variables.
  125. * Execution Control Expressions:: Expressions combining values in various ways.
  126. * Binary Operator Grammar:: An overview of operator precedence.
  127. * Order of Execution:: The order of program execution.
  128. * Primitive Types:: More details about primitive data types.
  129. * Constants:: Explicit constant values:
  130. details and examples.
  131. * Type Size:: The memory space occupied by a type.
  132. * Pointers:: Creating and manipulating memory pointers.
  133. * Structures:: Compound data types built
  134. by grouping other types.
  135. * Arrays:: Creating and manipulating arrays.
  136. * Enumeration Types:: Sets of integers with named values.
  137. * Defining Typedef Names:: Using @code{typedef} to define type names.
  138. * Statements:: Controling program flow.
  139. * Variables:: Details about declaring, initializing,
  140. and using variables.
  141. * Type Qualifiers:: Mark variables for certain intended uses.
  142. * Functions:: Declaring, defining, and calling functions.
  143. * Compatible Types:: How to tell if two types are compatible
  144. with each other.
  145. * Type Conversions:: Converting between types.
  146. * Scope:: Different categories of identifier scope.
  147. * Preprocessing:: Using the GNU C preprocessor.
  148. * Integers in Depth:: How integer numbers are represented.
  149. * Floating Point in Depth:: How floating-point numbers are represented.
  150. * Compilation:: How to compile multi-file programs.
  151. * Directing Compilation:: Operations that affect compilation
  152. but don't change the program.
  153. Appendices
  154. * Type Alignment:: Where in memory a type can validly start.
  155. * Aliasing:: Accessing the same data in two types.
  156. * Digraphs:: Two-character aliases for some characters.
  157. * Attributes:: Specifying additional information
  158. in a declaration.
  159. * Signals:: Fatal errors triggered in various scenarios.
  160. * GNU Free Documentation License:: The license for this manual.
  161. * Symbol Index:: Keyword and symbol index.
  162. * Concept Index:: Detailed topical index.
  163. @detailmenu
  164. --- The Detailed Node Listing ---
  165. * Recursive Fibonacci:: Writing a simple function recursively.
  166. * Stack:: Each function call uses space in the stack.
  167. * Iterative Fibonacci:: Writing the same function iteratively.
  168. * Complete Example:: Turn the simple function into a full program.
  169. * Complete Explanation:: Explanation of each part of the example.
  170. * Complete Line-by-Line:: Explaining each line of the example.
  171. * Compile Example:: Using GCC to compile the example.
  172. * Float Example:: A function that uses floating-point numbers.
  173. * Array Example:: A function that works with arrays.
  174. * Array Example Call:: How to call that function.
  175. * Array Example Variations:: Different ways to write the call example.
  176. Lexical Syntax
  177. * English:: Write programs in English!
  178. * Characters:: The characters allowed in C programs.
  179. * Whitespace:: The particulars of whitespace characters.
  180. * Comments:: How to include comments in C code.
  181. * Identifiers:: How to form identifiers (names).
  182. * Operators/Punctuation:: Characters used as operators or punctuation.
  183. * Line Continuation:: Splitting one line into multiple lines.
  184. * Digraphs:: Two-character substitutes for some characters.
  185. Arithmetic
  186. * Basic Arithmetic:: Addition, subtraction, multiplication,
  187. and division.
  188. * Integer Arithmetic:: How C performs arithmetic with integer values.
  189. * Integer Overflow:: When an integer value exceeds the range
  190. of its type.
  191. * Mixed Mode:: Calculating with both integer values
  192. and floating-point values.
  193. * Division and Remainder:: How integer division works.
  194. * Numeric Comparisons:: Comparing numeric values for
  195. equality or order.
  196. * Shift Operations:: Shift integer bits left or right.
  197. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  198. Assignment Expressions
  199. * Simple Assignment:: The basics of storing a value.
  200. * Lvalues:: Expressions into which a value can be stored.
  201. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  202. * Increment/Decrement:: Shorthand for incrementing and decrementing
  203. an lvalue's contents.
  204. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  205. * Assignment in Subexpressions:: How to avoid ambiguity.
  206. * Write Assignments Separately:: Write assignments as separate statements.
  207. Execution Control Expressions
  208. * Logical Operators:: Logical conjunction, disjunction, negation.
  209. * Logicals and Comparison:: Logical operators with comparison operators.
  210. * Logicals and Assignments:: Assignments with logical operators.
  211. * Conditional Expression:: An if/else construct inside expressions.
  212. * Comma Operator:: Build a sequence of subexpressions.
  213. Order of Execution
  214. * Reordering of Operands:: Operations in C are not necessarily computed
  215. in the order they are written.
  216. * Associativity and Ordering:: Some associative operations are performed
  217. in a particular order; others are not.
  218. * Sequence Points:: Some guarantees about the order of operations.
  219. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  220. * Ordering of Operands:: Evaluation order of operands
  221. and function arguments.
  222. * Optimization and Ordering:: Compiler optimizations can reorder operations
  223. only if it has no impact on program results.
  224. Primitive Data Types
  225. * Integer Types:: Description of integer types.
  226. * Floating-Point Data Types:: Description of floating-point types.
  227. * Complex Data Types:: Description of complex number types.
  228. * The Void Type:: A type indicating no value at all.
  229. * Other Data Types:: A brief summary of other types.
  230. Constants
  231. * Integer Constants:: Literal integer values.
  232. * Integer Const Type:: Types of literal integer values.
  233. * Floating Constants:: Literal floating-point values.
  234. * Imaginary Constants:: Literal imaginary number values.
  235. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  236. * Character Constants:: Literal character values.
  237. * Unicode Character Codes:: Unicode characters represented
  238. in either UTF-16 or UTF-32.
  239. * Wide Character Constants:: Literal characters values larger than 8 bits.
  240. * String Constants:: Literal string values.
  241. * UTF-8 String Constants:: Literal UTF-8 string values.
  242. * Wide String Constants:: Literal string values made up of
  243. 16- or 32-bit characters.
  244. Pointers
  245. * Address of Data:: Using the ``address-of'' operator.
  246. * Pointer Types:: For each type, there is a pointer type.
  247. * Pointer Declarations:: Declaring variables with pointer types.
  248. * Pointer Type Designators:: Designators for pointer types.
  249. * Pointer Dereference:: Accessing what a pointer points at.
  250. * Null Pointers:: Pointers which do not point to any object.
  251. * Invalid Dereference:: Dereferencing null or invalid pointers.
  252. * Void Pointers:: Totally generic pointers, can cast to any.
  253. * Pointer Comparison:: Comparing memory address values.
  254. * Pointer Arithmetic:: Computing memory address values.
  255. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  256. * Pointer Arithmetic Low Level:: More about computing memory address values.
  257. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  258. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  259. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  260. * Printing Pointers:: Using @code{printf} for a pointer's value.
  261. Structures
  262. * Referencing Fields:: Accessing field values in a structure object.
  263. * Dynamic Memory Allocation:: Allocating space for objects
  264. while the program is running.
  265. * Field Offset:: Memory layout of fields within a structure.
  266. * Structure Layout:: Planning the memory layout of fields.
  267. * Packed Structures:: Packing structure fields as close as possible.
  268. * Bit Fields:: Dividing integer fields
  269. into fields with fewer bits.
  270. * Bit Field Packing:: How bit fields pack together in integers.
  271. * const Fields:: Making structure fields immutable.
  272. * Zero Length:: Zero-length array as a variable-length object.
  273. * Flexible Array Fields:: Another approach to variable-length objects.
  274. * Overlaying Structures:: Casting one structure type
  275. over an object of another structure type.
  276. * Structure Assignment:: Assigning values to structure objects.
  277. * Unions:: Viewing the same object in different types.
  278. * Packing With Unions:: Using a union type to pack various types into
  279. the same memory space.
  280. * Cast to Union:: Casting a value one of the union's alternative
  281. types to the type of the union itself.
  282. * Structure Constructors:: Building new structure objects.
  283. * Unnamed Types as Fields:: Fields' types do not always need names.
  284. * Incomplete Types:: Types which have not been fully defined.
  285. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  286. * Type Tags:: Scope of structure and union type tags.
  287. Arrays
  288. * Accessing Array Elements:: How to access individual elements of an array.
  289. * Declaring an Array:: How to name and reserve space for a new array.
  290. * Strings:: A string in C is a special case of array.
  291. * Incomplete Array Types:: Naming, but not allocating, a new array.
  292. * Limitations of C Arrays:: Arrays are not first-class objects.
  293. * Multidimensional Arrays:: Arrays of arrays.
  294. * Constructing Array Values:: Assigning values to an entire array at once.
  295. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  296. Statements
  297. * Expression Statement:: Evaluate an expression, as a statement,
  298. usually done for a side effect.
  299. * if Statement:: Basic conditional execution.
  300. * if-else Statement:: Multiple branches for conditional execution.
  301. * Blocks:: Grouping multiple statements together.
  302. * return Statement:: Return a value from a function.
  303. * Loop Statements:: Repeatedly executing a statement or block.
  304. * switch Statement:: Multi-way conditional choices.
  305. * switch Example:: A plausible example of using @code{switch}.
  306. * Duffs Device:: A special way to use @code{switch}.
  307. * Case Ranges:: Ranges of values for @code{switch} cases.
  308. * Null Statement:: A statement that does nothing.
  309. * goto Statement:: Jump to another point in the source code,
  310. identified by a label.
  311. * Local Labels:: Labels with limited scope.
  312. * Labels as Values:: Getting the address of a label.
  313. * Statement Exprs:: A series of statements used as an expression.
  314. Variables
  315. * Variable Declarations:: Name a variable and and reserve space for it.
  316. * Initializers:: Assigning inital values to variables.
  317. * Designated Inits:: Assigning initial values to array elements
  318. at particular array indices.
  319. * Auto Type:: Obtaining the type of a variable.
  320. * Local Variables:: Variables declared in function definitions.
  321. * File-Scope Variables:: Variables declared outside of
  322. function definitions.
  323. * Static Local Variables:: Variables declared within functions,
  324. but with permanent storage allocation.
  325. * Extern Declarations:: Declaring a variable
  326. which is allocated somewhere else.
  327. * Allocating File-Scope:: When is space allocated
  328. for file-scope variables?
  329. * auto and register:: Historically used storage directions.
  330. * Omitting Types:: The bad practice of declaring variables
  331. with implicit type.
  332. Type Qualifiers
  333. * const:: Variables whose values don't change.
  334. * volatile:: Variables whose values may be accessed
  335. or changed outside of the control of
  336. this program.
  337. * restrict Pointers:: Restricted pointers for code optimization.
  338. * restrict Pointer Example:: Example of how that works.
  339. Functions
  340. * Function Definitions:: Writing the body of a function.
  341. * Function Declarations:: Declaring the interface of a function.
  342. * Function Calls:: Using functions.
  343. * Function Call Semantics:: Call-by-value argument passing.
  344. * Function Pointers:: Using references to functions.
  345. * The main Function:: Where execution of a GNU C program begins.
  346. Type Conversions
  347. * Explicit Type Conversion:: Casting a value from one type to another.
  348. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  349. * Argument Promotions:: Automatic conversion of function parameters.
  350. * Operand Promotions:: Automatic conversion of arithmetic operands.
  351. * Common Type:: When operand types differ, which one is used?
  352. Scope
  353. * Scope:: Different categories of identifier scope.
  354. Preprocessing
  355. * Preproc Overview:: Introduction to the C preprocessor.
  356. * Directives:: The form of preprocessor directives.
  357. * Preprocessing Tokens:: The lexical elements of preprocessing.
  358. * Header Files:: Including one source file in another.
  359. * Macros:: Macro expansion by the preprocessor.
  360. * Conditionals:: Controling whether to compile some lines
  361. or ignore them.
  362. * Diagnostics:: Reporting warnings and errors.
  363. * Line Control:: Reporting source line numbers.
  364. * Null Directive:: A preprocessing no-op.
  365. Integers in Depth
  366. * Integer Representations:: How integer values appear in memory.
  367. * Maximum and Minimum Values:: Value ranges of integer types.
  368. Floating Point in Depth
  369. * Floating Representations:: How floating-point values appear in memory.
  370. * Floating Type Specs:: Precise details of memory representations.
  371. * Special Float Values:: Infinity, Not a Number, and Subnormal Numbers.
  372. * Invalid Optimizations:: Don't mess up non-numbers and signed zeros.
  373. * Exception Flags:: Handling certain conditions in floating point.
  374. * Exact Floating-Point:: Not all floating calculations lose precision.
  375. * Rounding:: When a floating result can't be represented
  376. exactly in the floating-point type in use.
  377. * Rounding Issues:: Avoid magnifying rounding errors.
  378. * Significance Loss:: Subtracting numbers that are almost equal.
  379. * Fused Multiply-Add:: Taking advantage of a special floating-point
  380. instruction for faster execution.
  381. * Error Recovery:: Determining rounding errors.
  382. * Exact Floating Constants:: Precisely specified floating-point numbers.
  383. * Handling Infinity:: When floating calculation is out of range.
  384. * Handling NaN:: What floating calculation is undefined.
  385. * Signed Zeros:: Positive zero vs. negative zero.
  386. * Scaling by the Base:: A useful exact floating-point operation.
  387. * Rounding Control:: Specifying some rounding behaviors.
  388. * Machine Epsilon:: The smallest number you can add to 1.0
  389. and get a sum which is larger than 1.0.
  390. * Complex Arithmetic:: Details of arithmetic with complex numbers.
  391. * Round-Trip Base Conversion:: What happens between base-2 and base-10.
  392. * Further Reading:: References for floating-point numbers.
  393. Directing Compilation
  394. * Pragmas:: Controling compilation of some constructs.
  395. * Static Assertions:: Compile-time tests for conditions.
  396. @end detailmenu
  397. @end menu
  398. @node The First Example
  399. @chapter The First Example
  400. This chapter presents the source code for a very simple C program and
  401. uses it to explain a few features of the language. If you already
  402. know the basic points of C presented in this chapter, you can skim it
  403. or skip it.
  404. @menu
  405. * Recursive Fibonacci:: Writing a simple function recursively.
  406. * Stack:: Each function call uses space in the stack.
  407. * Iterative Fibonacci:: Writing the same function iteratively.
  408. @end menu
  409. @node Recursive Fibonacci
  410. @section Example: Recursive Fibonacci
  411. @cindex recursive Fibonacci function
  412. @cindex Fibonacci function, recursive
  413. To introduce the most basic features of C, let's look at code for a
  414. simple mathematical function that does calculations on integers. This
  415. function calculates the @var{n}th number in the Fibonacci series, in
  416. which each number is the sum of the previous two: 1, 1, 2, 3, 5, 8,
  417. 13, 21, 34, 55, @dots{}.
  418. @example
  419. int
  420. fib (int n)
  421. @{
  422. if (n <= 2) /* @r{This avoids infinite recursion.} */
  423. return 1;
  424. else
  425. return fib (n - 1) + fib (n - 2);
  426. @}
  427. @end example
  428. This very simple program illustrates several features of C:
  429. @itemize @bullet
  430. @item
  431. A function definition, whose first two lines constitute the function
  432. header. @xref{Function Definitions}.
  433. @item
  434. A function parameter @code{n}, referred to as the variable @code{n}
  435. inside the function body. @xref{Function Parameter Variables}.
  436. A function definition uses parameters to refer to the argument
  437. values provided in a call to that function.
  438. @item
  439. Arithmetic. C programs add with @samp{+} and subtract with
  440. @samp{-}. @xref{Arithmetic}.
  441. @item
  442. Numeric comparisons. The operator @samp{<=} tests for ``less than or
  443. equal.'' @xref{Numeric Comparisons}.
  444. @item
  445. Integer constants written in base 10.
  446. @xref{Integer Constants}.
  447. @item
  448. A function call. The function call @code{fib (n - 1)} calls the
  449. function @code{fib}, passing as its argument the value @code{n - 1}.
  450. @xref{Function Calls}.
  451. @item
  452. A comment, which starts with @samp{/*} and ends with @samp{*/}. The
  453. comment has no effect on the execution of the program. Its purpose is
  454. to provide explanations to people reading the source code. Including
  455. comments in the code is tremendously important---they provide
  456. background information so others can understand the code more quickly.
  457. @xref{Comments}.
  458. @item
  459. Two kinds of statements, the @code{return} statement and the
  460. @code{if}@dots{}@code{else} statement. @xref{Statements}.
  461. @item
  462. Recursion. The function @code{fib} calls itself; that is called a
  463. @dfn{recursive call}. These are valid in C, and quite common.
  464. The @code{fib} function would not be useful if it didn't return.
  465. Thus, recursive definitions, to be of any use, must avoid infinite
  466. recursion.
  467. This function definition prevents infinite recursion by specially
  468. handling the case where @code{n} is two or less. Thus the maximum
  469. depth of recursive calls is less than @code{n}.
  470. @end itemize
  471. @menu
  472. * Function Header:: The function's name and how it is called.
  473. * Function Body:: Declarations and statements that implement the function.
  474. @end menu
  475. @node Function Header
  476. @subsection Function Header
  477. @cindex function header
  478. In our example, the first two lines of the function definition are the
  479. @dfn{header}. Its purpose is to state the function's name and say how
  480. it is called:
  481. @example
  482. int
  483. fib (int n)
  484. @end example
  485. @noindent
  486. says that the function returns an integer (type @code{int}), its name is
  487. @code{fib}, and it takes one argument named @code{n} which is also an
  488. integer. (Data types will be explained later, in @ref{Primitive Types}.)
  489. @node Function Body
  490. @subsection Function Body
  491. @cindex function body
  492. @cindex recursion
  493. The rest of the function definition is called the @dfn{function body}.
  494. Like every function body, this one starts with @samp{@{}, ends with
  495. @samp{@}}, and contains zero or more @dfn{statements} and
  496. @dfn{declarations}. Statements specify actions to take, whereas
  497. declarations define names of variables, functions, and so on. Each
  498. statement and each declaration ends with a semicolon (@samp{;}).
  499. Statements and declarations often contain @dfn{expressions}; an
  500. expression is a construct whose execution produces a @dfn{value} of
  501. some data type, but may also take actions through ``side effects''
  502. that alter subsequent execution. A statement, by contrast, does not
  503. have a value; it affects further execution of the program only through
  504. the actions it takes.
  505. This function body contains no declarations, and just one statement,
  506. but that one is a complex statement in that it contains nested
  507. statements. This function uses two kinds of statements:
  508. @table @code
  509. @item return
  510. The @code{return} statement makes the function return immediately.
  511. It looks like this:
  512. @example
  513. return @var{value};
  514. @end example
  515. Its meaning is to compute the expression @var{value} and exit the
  516. function, making it return whatever value that expression produced.
  517. For instance,
  518. @example
  519. return 1;
  520. @end example
  521. @noindent
  522. returns the integer 1 from the function, and
  523. @example
  524. return fib (n - 1) + fib (n - 2);
  525. @end example
  526. @noindent
  527. returns a value computed by performing two function calls
  528. as specified and adding their results.
  529. @item @code{if}@dots{}@code{else}
  530. The @code{if}@dots{}@code{else} statement is a @dfn{conditional}.
  531. Each time it executes, it chooses one of its two substatements to execute
  532. and ignores the other. It looks like this:
  533. @example
  534. if (@var{condition})
  535. @var{if-true-statement}
  536. else
  537. @var{if-false-statement}
  538. @end example
  539. Its meaning is to compute the expression @var{condition} and, if it's
  540. ``true,'' execute @var{if-true-statement}. Otherwise, execute
  541. @var{if-false-statement}. @xref{if-else Statement}.
  542. Inside the @code{if}@dots{}@code{else} statement, @var{condition} is
  543. simply an expression. It's considered ``true'' if its value is
  544. nonzero. (A comparison operation, such as @code{n <= 2}, produces the
  545. value 1 if it's ``true'' and 0 if it's ``false.'' @xref{Numeric
  546. Comparisons}.) Thus,
  547. @example
  548. if (n <= 2)
  549. return 1;
  550. else
  551. return fib (n - 1) + fib (n - 2);
  552. @end example
  553. @noindent
  554. first tests whether the value of @code{n} is less than or equal to 2.
  555. If so, the expression @code{n <= 2} has the value 1. So execution
  556. continues with the statement
  557. @example
  558. return 1;
  559. @end example
  560. @noindent
  561. Otherwise, execution continues with this statement:
  562. @example
  563. return fib (n - 1) + fib (n - 2);
  564. @end example
  565. Each of these statements ends the execution of the function and
  566. provides a value for it to return. @xref{return Statement}.
  567. @end table
  568. Calculating @code{fib} using ordinary integers in C works only for
  569. @var{n} < 47, because the value of @code{fib (47)} is too large to fit
  570. in type @code{int}. The addition operation that tries to add
  571. @code{fib (46)} and @code{fib (45)} cannot deliver the correct result.
  572. This occurrence is called @dfn{integer overflow}.
  573. Overflow can manifest itself in various ways, but one thing that can't
  574. possibly happen is to produce the correct value, since that can't fit
  575. in the space for the value. @xref{Integer Overflow}.
  576. @xref{Functions}, for a full explanation about functions.
  577. @node Stack
  578. @section The Stack, And Stack Overflow
  579. @cindex stack
  580. @cindex stack frame
  581. @cindex stack overflow
  582. @cindex recursion, drawbacks of
  583. @cindex stack frame
  584. Recursion has a drawback: there are limits to how many nested function
  585. calls a program can make. In C, each function call allocates a block
  586. of memory which it uses until the call returns. C allocates these
  587. blocks consecutively within a large area of memory known as the
  588. @dfn{stack}, so we refer to the blocks as @dfn{stack frames}.
  589. The size of the stack is limited; if the program tries to use too
  590. much, that causes the program to fail because the stack is full. This
  591. is called @dfn{stack overflow}.
  592. @cindex crash
  593. @cindex segmentation fault
  594. Stack overflow on GNU/Linux typically manifests itself as the
  595. @dfn{signal} named @code{SIGSEGV}, also known as a ``segmentation
  596. fault.'' By default, this signal terminates the program immediately,
  597. rather than letting the program try to recover, or reach an expected
  598. ending point. (We commonly say in this case that the program
  599. ``crashes''). @xref{Signals}.
  600. It is inconvenient to observe a crash by passing too large
  601. an argument to recursive Fibonacci, because the program would run a
  602. long time before it crashes. This algorithm is simple but
  603. ridiculously slow: in calculating @code{fib (@var{n})}, the number of
  604. (recursive) calls @code{fib (1)} or @code{fib (2)} that it makes equals
  605. the final result.
  606. However, you can observe stack overflow very quickly if you use
  607. this function instead:
  608. @example
  609. int
  610. fill_stack (int n)
  611. @{
  612. if (n <= 1) /* @r{This limits the depth of recursion.} */
  613. return 1;
  614. else
  615. return fill_stack (n - 1);
  616. @}
  617. @end example
  618. Under gNewSense GNU/Linux on the Lemote Yeeloong, without optimization
  619. and using the default configuration, an experiment showed there is
  620. enough stack space to do 261906 nested calls to that function. One
  621. more, and the stack overflows and the program crashes. On another
  622. platform, with a different configuration, or with a different
  623. function, the limit might be bigger or smaller.
  624. @node Iterative Fibonacci
  625. @section Example: Iterative Fibonacci
  626. @cindex iterative Fibonacci function
  627. @cindex Fibonacci function, iterative
  628. Here's a much faster algorithm for computing the same Fibonacci
  629. series. It is faster for two reasons. First, it uses @dfn{iteration}
  630. (that is, repetition or looping) rather than recursion, so it doesn't
  631. take time for a large number of function calls. But mainly, it is
  632. faster because the number of repetitions is small---only @code{@var{n}}.
  633. @c If you change this, change the duplicate in node Example of for.
  634. @example
  635. int
  636. fib (int n)
  637. @{
  638. int last = 1; /* @r{Initial value is @code{fib (1)}.} */
  639. int prev = 0; /* @r{Initial value controls @code{fib (2)}.} */
  640. int i;
  641. for (i = 1; i < n; ++i)
  642. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  643. /* @r{since @code{i < n} is false the first time.} */
  644. @{
  645. /* @r{Now @code{last} is @code{fib (@code{i})}}
  646. @r{and @code{prev} is @code{fib (@code{i} @minus{} 1)}.} */
  647. /* @r{Compute @code{fib (@code{i} + 1)}.} */
  648. int next = prev + last;
  649. /* @r{Shift the values down.} */
  650. prev = last;
  651. last = next;
  652. /* @r{Now @code{last} is @code{fib (@code{i} + 1)}}
  653. @r{and @code{prev} is @code{fib (@code{i})}.}
  654. @r{But that won't stay true for long,}
  655. @r{because we are about to increment @code{i}.} */
  656. @}
  657. return last;
  658. @}
  659. @end example
  660. This definition computes @code{fib (@var{n})} in a time proportional
  661. to @code{@var{n}}. The comments in the definition explain how it works: it
  662. advances through the series, always keeps the last two values in
  663. @code{last} and @code{prev}, and adds them to get the next value.
  664. Here are the additional C features that this definition uses:
  665. @table @asis
  666. @item Internal blocks
  667. Within a function, wherever a statement is called for, you can write a
  668. @dfn{block}. It looks like @code{@{ @r{@dots{}} @}} and contains zero or
  669. more statements and declarations. (You can also use additional
  670. blocks as statements in a block.)
  671. The function body also counts as a block, which is why it can contain
  672. statements and declarations.
  673. @xref{Blocks}.
  674. @item Declarations of local variables
  675. This function body contains declarations as well as statements. There
  676. are three declarations directly in the function body, as well as a
  677. fourth declaration in an internal block. Each starts with @code{int}
  678. because it declares a variable whose type is integer. One declaration
  679. can declare several variables, but each of these declarations is
  680. simple and declares just one variable.
  681. Variables declared inside a block (either a function body or an
  682. internal block) are @dfn{local variables}. These variables exist only
  683. within that block; their names are not defined outside the block, and
  684. exiting the block deallocates their storage. This example declares
  685. four local variables: @code{last}, @code{prev}, @code{i}, and
  686. @code{next}.
  687. The most basic local variable declaration looks like this:
  688. @example
  689. @var{type} @var{variablename};
  690. @end example
  691. For instance,
  692. @example
  693. int i;
  694. @end example
  695. @noindent
  696. declares the local variable @code{i} as an integer.
  697. @xref{Variable Declarations}.
  698. @item Initializers
  699. When you declare a variable, you can also specify its initial value,
  700. like this:
  701. @example
  702. @var{type} @var{variablename} = @var{value};
  703. @end example
  704. For instance,
  705. @example
  706. int last = 1;
  707. @end example
  708. @noindent
  709. declares the local variable @code{last} as an integer (type
  710. @code{int}) and starts it off with the value 1. @xref{Initializers}.
  711. @item Assignment
  712. Assignment: a specific kind of expression, written with the @samp{=}
  713. operator, that stores a new value in a variable or other place. Thus,
  714. @example
  715. @var{variable} = @var{value}
  716. @end example
  717. @noindent
  718. is an expression that computes @code{@var{value}} and stores the value in
  719. @code{@var{variable}}. @xref{Assignment Expressions}.
  720. @item Expression statements
  721. An expression statement is an expression followed by a semicolon.
  722. That computes the value of the expression, then ignores the value.
  723. An expression statement is useful when the expression changes some
  724. data or has other side effects---for instance, with function calls, or
  725. with assignments as in this example. @xref{Expression Statement}.
  726. Using an expression with no side effects in an expression statement is
  727. pointless except in very special cases. For instance, the expression
  728. statement @code{x;} would examine the value of @code{x} and ignore it.
  729. That is not useful.
  730. @item Increment operator
  731. The increment operator is @samp{++}. @code{++i} is an
  732. expression that is short for @code{i = i + 1}.
  733. @xref{Increment/Decrement}.
  734. @item @code{for} statements
  735. A @code{for} statement is a clean way of executing a statement
  736. repeatedly---a @dfn{loop} (@pxref{Loop Statements}). Specifically,
  737. @example
  738. for (i = 1; i < n; ++i)
  739. @var{body}
  740. @end example
  741. @noindent
  742. means to start by doing @code{i = 1} (set @code{i} to one) to prepare
  743. for the loop. The loop itself consists of
  744. @itemize @bullet
  745. @item
  746. Testing @code{i < n} and exiting the loop if that's false.
  747. @item
  748. Executing @var{body}.
  749. @item
  750. Advancing the loop (executing @code{++i}, which increments @code{i}).
  751. @end itemize
  752. The net result is to execute @var{body} with 0 in @code{i},
  753. then with 1 in @code{i}, and so on, stopping just before the repetition
  754. where @code{i} would equal @code{n}.
  755. The body of the @code{for} statement must be one and only one
  756. statement. You can't write two statements in a row there; if you try
  757. to, only the first of them will be treated as part of the loop.
  758. The way to put multiple statements in those places is to group them
  759. with a block, and that's what we do in this example.
  760. @end table
  761. @node Complete Program
  762. @chapter A Complete Program
  763. @cindex complete example program
  764. @cindex example program, complete
  765. It's all very well to write a Fibonacci function, but you cannot run
  766. it by itself. It is a useful program, but it is not a complete
  767. program.
  768. In this chapter we present a complete program that contains the
  769. @code{fib} function. This example shows how to make the program
  770. start, how to make it finish, how to do computation, and how to print
  771. a result.
  772. @menu
  773. * Complete Example:: Turn the simple function into a full program.
  774. * Complete Explanation:: Explanation of each part of the example.
  775. * Complete Line-by-Line:: Explaining each line of the example.
  776. * Compile Example:: Using GCC to compile the example.
  777. @end menu
  778. @node Complete Example
  779. @section Complete Program Example
  780. Here is the complete program that uses the simple, recursive version
  781. of the @code{fib} function (@pxref{Recursive Fibonacci}):
  782. @example
  783. #include <stdio.h>
  784. int
  785. fib (int n)
  786. @{
  787. if (n <= 2) /* @r{This avoids infinite recursion.} */
  788. return 1;
  789. else
  790. return fib (n - 1) + fib (n - 2);
  791. @}
  792. int
  793. main (void)
  794. @{
  795. printf ("Fibonacci series item %d is %d\n",
  796. 20, fib (20));
  797. return 0;
  798. @}
  799. @end example
  800. @noindent
  801. This program prints a message that shows the value of @code{fib (20)}.
  802. Now for an explanation of what that code means.
  803. @node Complete Explanation
  804. @section Complete Program Explanation
  805. @ifnottex
  806. Here's the explanation of the code of the example in the
  807. previous section.
  808. @end ifnottex
  809. This sample program prints a message that shows the value of @code{fib
  810. (20)}, and exits with code 0 (which stands for successful execution).
  811. Every C program is started by running the function named @code{main}.
  812. Therefore, the example program defines a function named @code{main} to
  813. provide a way to start it. Whatever that function does is what the
  814. program does. @xref{The main Function}.
  815. The @code{main} function is the first one called when the program
  816. runs, but it doesn't come first in the example code. The order of the
  817. function definitions in the source code makes no difference to the
  818. program's meaning.
  819. The initial call to @code{main} always passes certain arguments, but
  820. @code{main} does not have to pay attention to them. To ignore those
  821. arguments, define @code{main} with @code{void} as the parameter list.
  822. (@code{void} as a function's parameter list normally means ``call with
  823. no arguments,'' but @code{main} is a special case.)
  824. The function @code{main} returns 0 because that is
  825. the conventional way for @code{main} to indicate successful execution.
  826. It could instead return a positive integer to indicate failure, and
  827. some utility programs have specific conventions for the meaning of
  828. certain numeric @dfn{failure codes}. @xref{Values from main}.
  829. @cindex @code{printf}
  830. The simplest way to print text in C is by calling the @code{printf}
  831. function, so here we explain what that does.
  832. @cindex standard output
  833. The first argument to @code{printf} is a @dfn{string constant}
  834. (@pxref{String Constants}) that is a template for output. The
  835. function @code{printf} copies most of that string directly as output,
  836. including the newline character at the end of the string, which is
  837. written as @samp{\n}. The output goes to the program's @dfn{standard
  838. output} destination, which in the usual case is the terminal.
  839. @samp{%} in the template introduces a code that substitutes other text
  840. into the output. Specifically, @samp{%d} means to take the next
  841. argument to @code{printf} and substitute it into the text as a decimal
  842. number. (The argument for @samp{%d} must be of type @code{int}; if it
  843. isn't, @code{printf} will malfunction.) So the output is a line that
  844. looks like this:
  845. @example
  846. Fibonacci series item 20 is 6765
  847. @end example
  848. This program does not contain a definition for @code{printf} because
  849. it is defined by the C library, which makes it available in all C
  850. programs. However, each program does need to @dfn{declare}
  851. @code{printf} so it will be called correctly. The @code{#include}
  852. line takes care of that; it includes a @dfn{header file} called
  853. @file{stdio.h} into the program's code. That file is provided by the
  854. operating system and it contains declarations for the many standard
  855. input/output functions in the C library, one of which is
  856. @code{printf}.
  857. Don't worry about header files for now; we'll explain them later in
  858. @ref{Header Files}.
  859. The first argument of @code{printf} does not have to be a string
  860. constant; it can be any string (@pxref{Strings}). However, using a
  861. constant is the most common case.
  862. To learn more about @code{printf} and other facilities of the C
  863. library, see @ref{Top, The GNU C Library, , libc, The GNU C Library
  864. Reference Manual}.
  865. @node Complete Line-by-Line
  866. @section Complete Program, Line by Line
  867. Here's the same example, explained line by line.
  868. @strong{Beginners, do you find this helpful or not?
  869. Would you prefer a different layout for the example?
  870. Please tell rms@@gnu.org.}
  871. @example
  872. #include <stdio.h> /* @r{Include declaration of usual} */
  873. /* @r{I/O functions such as @code{printf}.} */
  874. /* @r{Most programs need these.} */
  875. int /* @r{This function returns an @code{int}.} */
  876. fib (int n) /* @r{Its name is @code{fib};} */
  877. /* @r{its argument is called @code{n}.} */
  878. @{ /* @r{Start of function body.} */
  879. /* @r{This stops the recursion from being infinite.} */
  880. if (n <= 2) /* @r{If @code{n} is 1 or 2,} */
  881. return 1; /* @r{make @code{fib} return 1.} */
  882. else /* @r{otherwise, add the two previous} */
  883. /* @r{fibonacci numbers.} */
  884. return fib (n - 1) + fib (n - 2);
  885. @}
  886. int /* @r{This function returns an @code{int}.} */
  887. main (void) /* @r{Start here; ignore arguments.} */
  888. @{ /* @r{Print message with numbers in it.} */
  889. printf ("Fibonacci series item %d is %d\n",
  890. 20, fib (20));
  891. return 0; /* @r{Terminate program, report success.} */
  892. @}
  893. @end example
  894. @node Compile Example
  895. @section Compiling the Example Program
  896. @cindex compiling
  897. @cindex executable file
  898. To run a C program requires converting the source code into an
  899. @dfn{executable file}. This is called @dfn{compiling} the program,
  900. and the command to do that using GNU C is @command{gcc}.
  901. This example program consists of a single source file. If we
  902. call that file @file{fib1.c}, the complete command to compile it is
  903. this:
  904. @example
  905. gcc -g -O -o fib1 fib1.c
  906. @end example
  907. @noindent
  908. Here, @option{-g} says to generate debugging information, @option{-O}
  909. says to optimize at the basic level, and @option{-o fib1} says to put
  910. the executable program in the file @file{fib1}.
  911. To run the program, use its file name as a shell command.
  912. For instance,
  913. @example
  914. ./fib1
  915. @end example
  916. @noindent
  917. However, unless you are sure the program is correct, you should
  918. expect to need to debug it. So use this command,
  919. @example
  920. gdb fib1
  921. @end example
  922. @noindent
  923. which starts the GDB debugger (@pxref{Sample Session, Sample Session,
  924. A Sample GDB Session, gdb, Debugging with GDB}) so you can run and
  925. debug the executable program @code{fib1}.
  926. @xref{Compilation}, for an introduction to compiling more complex
  927. programs which consist of more than one source file.
  928. @node Storage
  929. @chapter Storage and Data
  930. @cindex bytes
  931. @cindex storage organization
  932. @cindex memory organization
  933. Storage in C programs is made up of units called @dfn{bytes}. On
  934. nearly all computers, a byte consists of 8 bits, but there are a few
  935. peculiar computers (mostly ``embedded controllers'' for very small
  936. systems) where a byte is longer than that. This manual does not try
  937. to explain the peculiarity of those computers; we assume that a byte
  938. is 8 bits.
  939. Every C data type is made up of a certain number of bytes; that number
  940. is the data type's @dfn{size}. @xref{Type Size}, for details. The
  941. types @code{signed char} and @code{unsigned char} are one byte long;
  942. use those types to operate on data byte by byte. @xref{Signed and
  943. Unsigned Types}. You can refer to a series of consecutive bytes as an
  944. array of @code{char} elements; that's what an ASCII string looks like
  945. in memory. @xref{String Constants}.
  946. @node Beyond Integers
  947. @chapter Beyond Integers
  948. So far we've presented programs that operate on integers. In this
  949. chapter we'll present examples of handling non-integral numbers and
  950. arrays of numbers.
  951. @menu
  952. * Float Example:: A function that uses floating-point numbers.
  953. * Array Example:: A function that works with arrays.
  954. * Array Example Call:: How to call that function.
  955. * Array Example Variations:: Different ways to write the call example.
  956. @end menu
  957. @node Float Example
  958. @section An Example with Non-Integer Numbers
  959. @cindex floating point example
  960. Here's a function that operates on and returns @dfn{floating point}
  961. numbers that don't have to be integers. Floating point represents a
  962. number as a fraction together with a power of 2. (For more detail,
  963. @pxref{Floating-Point Data Types}.) This example calculates the
  964. average of three floating point numbers that are passed to it as
  965. arguments:
  966. @example
  967. double
  968. average_of_three (double a, double b, double c)
  969. @{
  970. return (a + b + c) / 3;
  971. @}
  972. @end example
  973. The values of the parameter @var{a}, @var{b} and @var{c} do not have to be
  974. integers, and even when they happen to be integers, most likely their
  975. average is not an integer.
  976. @code{double} is the usual data type in C for calculations on
  977. floating-point numbers.
  978. To print a @code{double} with @code{printf}, we must use @samp{%f}
  979. instead of @samp{%d}:
  980. @example
  981. printf ("Average is %f\n",
  982. average_of_three (1.1, 9.8, 3.62));
  983. @end example
  984. The code that calls @code{printf} must pass a @code{double} for
  985. printing with @samp{%f} and an @code{int} for printing with @samp{%d}.
  986. If the argument has the wrong type, @code{printf} will produce garbage
  987. output.
  988. Here's a complete program that computes the average of three
  989. specific numbers and prints the result:
  990. @example
  991. double
  992. average_of_three (double a, double b, double c)
  993. @{
  994. return (a + b + c) / 3;
  995. @}
  996. int
  997. main (void)
  998. @{
  999. printf ("Average is %f\n",
  1000. average_of_three (1.1, 9.8, 3.62));
  1001. return 0;
  1002. @}
  1003. @end example
  1004. From now on we will not present examples of calls to @code{main}.
  1005. Instead we encourage you to write them for yourself when you want
  1006. to test executing some code.
  1007. @node Array Example
  1008. @section An Example with Arrays
  1009. @cindex array example
  1010. A function to take the average of three numbers is very specific and
  1011. limited. A more general function would take the average of any number
  1012. of numbers. That requires passing the numbers in an array. An array
  1013. is an object in memory that contains a series of values of the same
  1014. data type. This chapter presents the basic concepts and use of arrays
  1015. through an example; for the full explanation, see @ref{Arrays}.
  1016. Here's a function definition to take the average of several
  1017. floating-point numbers, passed as type @code{double}. The first
  1018. parameter, @code{length}, specifies how many numbers are passed. The
  1019. second parameter, @code{input_data}, is an array that holds those
  1020. numbers.
  1021. @example
  1022. double
  1023. avg_of_double (int length, double input_data[])
  1024. @{
  1025. double sum = 0;
  1026. int i;
  1027. for (i = 0; i < length; i++)
  1028. sum = sum + input_data[i];
  1029. return sum / length;
  1030. @}
  1031. @end example
  1032. This introduces the expression to refer to an element of an array:
  1033. @code{input_data[i]} means the element at index @code{i} in
  1034. @code{input_data}. The index of the element can be any expression
  1035. with an integer value; in this case, the expression is @code{i}.
  1036. @xref{Accessing Array Elements}.
  1037. @cindex zero-origin indexing
  1038. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  1039. valid index is one less than the number of elements. (This is known
  1040. as @dfn{zero-origin indexing}.)
  1041. This example also introduces the way to declare that a function
  1042. parameter is an array. Such declarations are modeled after the syntax
  1043. for an element of the array. Just as @code{double foo} declares that
  1044. @code{foo} is of type @code{double}, @code{double input_data[]}
  1045. declares that each element of @code{input_data} is of type
  1046. @code{double}. Therefore, @code{input_data} itself has type ``array
  1047. of @code{double}.''
  1048. When declaring an array parameter, it's not necessary to say how long
  1049. the array is. In this case, the parameter @code{input_data} has no
  1050. length information. That's why the function needs another parameter,
  1051. @code{length}, for the caller to provide that information to the
  1052. function @code{avg_of_double}.
  1053. @node Array Example Call
  1054. @section Calling the Array Example
  1055. To call the function @code{avg_of_double} requires making an
  1056. array and then passing it as an argument. Here is an example.
  1057. @example
  1058. @{
  1059. /* @r{The array of values to average.} */
  1060. double nums_to_average[5];
  1061. /* @r{The average, once we compute it.} */
  1062. double average;
  1063. /* @r{Fill in elements of @code{nums_to_average}.} */
  1064. nums_to_average[0] = 58.7;
  1065. nums_to_average[1] = 5.1;
  1066. nums_to_average[2] = 7.7;
  1067. nums_to_average[3] = 105.2;
  1068. nums_to_average[4] = -3.14159;
  1069. average = avg_of_double (5, nums_to_average);
  1070. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1071. @}
  1072. @end example
  1073. This shows an array subscripting expression again, this time
  1074. on the left side of an assignment, storing a value into an
  1075. element of an array.
  1076. It also shows how to declare a local variable that is an array:
  1077. @code{double nums_to_average[5];}. Since this declaration allocates the
  1078. space for the array, it needs to know the array's length. You can
  1079. specify the length with any expression whose value is an integer, but
  1080. in this declaration the length is a constant, the integer 5.
  1081. The name of the array, when used by itself as an expression, stands
  1082. for the address of the array's data, and that's what gets passed to
  1083. the function @code{avg_of_double} in @code{avg_of_double (5,
  1084. nums_to_average)}.
  1085. We can make the code easier to maintain by avoiding the need to write
  1086. 5, the array length, when calling @code{avg_of_double}. That way, if
  1087. we change the array to include more elements, we won't have to change
  1088. that call. One way to do this is with the @code{sizeof} operator:
  1089. @example
  1090. average = avg_of_double ((sizeof (nums_to_average)
  1091. / sizeof (nums_to_average[0])),
  1092. nums_to_average);
  1093. @end example
  1094. This computes the number of elements in @code{nums_to_average} by dividing
  1095. its total size by the size of one element. @xref{Type Size}, for more
  1096. details of using @code{sizeof}.
  1097. We don't show in this example what happens after storing the result of
  1098. @code{avg_of_double} in the variable @code{average}. Presumably
  1099. more code would follow that uses that result somehow. (Why compute
  1100. the average and not use it?) But that isn't part of this topic.
  1101. @node Array Example Variations
  1102. @section Variations for Array Example
  1103. The code to call @code{avg_of_double} has two declarations that
  1104. start with the same data type:
  1105. @example
  1106. /* @r{The array of values to average.} */
  1107. double nums_to_average[5];
  1108. /* @r{The average, once we compute it.} */
  1109. double average;
  1110. @end example
  1111. In C, you can combine the two, like this:
  1112. @example
  1113. double nums_to_average[5], average;
  1114. @end example
  1115. This declares @code{nums_to_average} so each of its elements is a
  1116. @code{double}, and @code{average} so that it simply is a
  1117. @code{double}.
  1118. However, while you @emph{can} combine them, that doesn't mean you
  1119. @emph{should}. If it is useful to write comments about the variables,
  1120. and usually it is, then it's clearer to keep the declarations separate
  1121. so you can put a comment on each one.
  1122. We set all of the elements of the array @code{nums_to_average} with
  1123. assignments, but it is more convenient to use an initializer in the
  1124. declaration:
  1125. @example
  1126. @{
  1127. /* @r{The array of values to average.} */
  1128. double nums_to_average[]
  1129. = @{ 58.7, 5.1, 7.7, 105.2, -3.14159 @};
  1130. /* @r{The average, once we compute it.} */
  1131. average = avg_of_double ((sizeof (nums_to_average)
  1132. / sizeof (nums_to_average[0])),
  1133. nums_to_average);
  1134. /* @r{@dots{}now make use of @code{average}@dots{}} */
  1135. @}
  1136. @end example
  1137. The array initializer is a comma-separated list of values, delimited
  1138. by braces. @xref{Initializers}.
  1139. Note that the declaration does not specify a size for
  1140. @code{nums_to_average}, so the size is determined from the
  1141. initializer. There are five values in the initializer, so
  1142. @code{nums_to_average} gets length 5. If we add another element to
  1143. the initializer, @code{nums_to_average} will have six elements.
  1144. Because the code computes the number of elements from the size of
  1145. the array, using @code{sizeof}, the program will operate on all the
  1146. elements in the initializer, regardless of how many those are.
  1147. @node Lexical Syntax
  1148. @chapter Lexical Syntax
  1149. @cindex lexical syntax
  1150. @cindex token
  1151. To start the full description of the C language, we explain the
  1152. lexical syntax and lexical units of C code. The lexical units of a
  1153. programming language are known as @dfn{tokens}. This chapter covers
  1154. all the tokens of C except for constants, which are covered in a later
  1155. chapter (@pxref{Constants}). One vital kind of token is the
  1156. @dfn{identifier} (@pxref{Identifiers}), which is used for names of any
  1157. kind.
  1158. @menu
  1159. * English:: Write programs in English!
  1160. * Characters:: The characters allowed in C programs.
  1161. * Whitespace:: The particulars of whitespace characters.
  1162. * Comments:: How to include comments in C code.
  1163. * Identifiers:: How to form identifiers (names).
  1164. * Operators/Punctuation:: Characters used as operators or punctuation.
  1165. * Line Continuation:: Splitting one line into multiple lines.
  1166. @end menu
  1167. @node English
  1168. @section Write Programs in English!
  1169. In principle, you can write the function and variable names in a
  1170. program, and the comments, in any human language. C allows any kinds
  1171. of characters in comments, and you can put non-ASCII characters into
  1172. identifiers with a special prefix. However, to enable programmers in
  1173. all countries to understand and develop the program, it is best given
  1174. today's circumstances to write identifiers and comments in
  1175. English.
  1176. English is the one language that programmers in all countries
  1177. generally study. If a program's names are in English, most
  1178. programmers in Bangladesh, Belgium, Bolivia, Brazil, and Bulgaria can
  1179. understand them. Most programmers in those countries can speak
  1180. English, or at least read it, but they do not read each other's
  1181. languages at all. In India, with so many languages, two programmers
  1182. may have no common language other than English.
  1183. If you don't feel confident in writing English, do the best you can,
  1184. and follow each English comment with a version in a language you
  1185. write better; add a note asking others to translate that to English.
  1186. Someone will eventually do that.
  1187. The program's user interface is a different matter. We don't need to
  1188. choose one language for that; it is easy to support multiple languages
  1189. and let each user choose the language to use. This requires writing
  1190. the program to support localization of its interface. (The
  1191. @code{gettext} package exists to support this; @pxref{Message
  1192. Translation, The GNU C Library, , libc, The GNU C Library Reference
  1193. Manual}.) Then a community-based translation effort can provide
  1194. support for all the languages users want to use.
  1195. @node Characters
  1196. @section Characters
  1197. @cindex character set
  1198. @cindex Unicode
  1199. @c ??? How to express ¶?
  1200. GNU C source files are usually written in the
  1201. @url{https://en.wikipedia.org/wiki/ASCII,,ASCII} character set, which
  1202. was defined in the 1960s for English. However, they can also include
  1203. Unicode characters represented in the
  1204. @url{https://en.wikipedia.org/wiki/UTF-8,,UTF-8} multibyte encoding.
  1205. This makes it possible to represent accented letters such as @samp{á},
  1206. as well as other scripts such as Arabic, Chinese, Cyrillic, Hebrew,
  1207. Japanese, and Korean.@footnote{On some obscure systems, GNU C uses
  1208. UTF-EBCDIC instead of UTF-8, but that is not worth describing in this
  1209. manual.}
  1210. In C source code, non-ASCII characters are valid in comments, in wide
  1211. character constants (@pxref{Wide Character Constants}), and in string
  1212. constants (@pxref{String Constants}).
  1213. @c ??? valid in identifiers?
  1214. Another way to specify non-ASCII characters in constants (character or
  1215. string) and identifiers is with an escape sequence starting with
  1216. backslash, specifying the intended Unicode character. (@xref{Unicode
  1217. Character Codes}.) This specifies non-ASCII characters without
  1218. putting a real non-ASCII character in the source file itself.
  1219. C accepts two-character aliases called @dfn{digraphs} for certain
  1220. characters. @xref{Digraphs}.
  1221. @node Whitespace
  1222. @section Whitespace
  1223. @cindex whitespace characters in source files
  1224. @cindex space character in source
  1225. @cindex tab character in source
  1226. @cindex formfeed in source
  1227. @cindex linefeed in source
  1228. @cindex newline in source
  1229. @cindex carriage return in source
  1230. @cindex vertical tab in source
  1231. Whitespace means characters that exist in a file but appear blank in a
  1232. printed listing of a file (or traditionally did appear blank, several
  1233. decades ago). The C language requires whitespace in order to separate
  1234. two consecutive identifiers, or to separate an identifier from a
  1235. numeric constant. Other than that, and a few special situations
  1236. described later, whitespace is optional; you can put it in when you
  1237. wish, to make the code easier to read.
  1238. Space and tab in C code are treated as whitespace characters. So are
  1239. line breaks. You can represent a line break with the newline
  1240. character (also called @dfn{linefeed} or LF), CR (carriage return), or
  1241. the CRLF sequence (two characters: carriage return followed by a
  1242. newline character).
  1243. The @dfn{formfeed} character, Control-L, was traditionally used to
  1244. divide a file into pages. It is still used this way in source code,
  1245. and the tools that generate nice printouts of source code still start
  1246. a new page after each ``formfeed'' character. Dividing code into
  1247. pages separated by formfeed characters is a good way to break it up
  1248. into comprehensible pieces and show other programmers where they start
  1249. and end.
  1250. The @dfn{vertical tab} character, Control-K, was traditionally used to
  1251. make printing advance down to the next section of a page. We know of
  1252. no particular reason to use it in source code, but it is still
  1253. accepted as whitespace in C.
  1254. Comments are also syntactically equivalent to whitespace.
  1255. @ifinfo
  1256. @xref{Comments}.
  1257. @end ifinfo
  1258. @node Comments
  1259. @section Comments
  1260. @cindex comments
  1261. A comment encapsulates text that has no effect on the program's
  1262. execution or meaning.
  1263. The purpose of comments is to explain the code to people that read it.
  1264. Writing good comments for your code is tremendously important---they
  1265. should provide background information that helps programmers
  1266. understand the reasons why the code is written the way it is. You,
  1267. returning to the code six months from now, will need the help of these
  1268. comments to remember why you wrote it this way.
  1269. Outdated comments that become incorrect are counterproductive, so part
  1270. of the software developer's responsibility is to update comments as
  1271. needed to correspond with changes to the program code.
  1272. C allows two kinds of comment syntax, the traditional style and the
  1273. C@t{++} style. A traditional C comment starts with @samp{/*} and ends
  1274. with @samp{*/}. For instance,
  1275. @example
  1276. /* @r{This is a comment in traditional C syntax.} */
  1277. @end example
  1278. A traditional comment can contain @samp{/*}, but these delimiters do
  1279. not nest as pairs. The first @samp{*/} ends the comment regardless of
  1280. whether it contains @samp{/*} sequences.
  1281. @example
  1282. /* @r{This} /* @r{is a comment} */ But this is not! */
  1283. @end example
  1284. A @dfn{line comment} starts with @samp{//} and ends at the end of the line.
  1285. For instance,
  1286. @example
  1287. // @r{This is a comment in C@t{++} style.}
  1288. @end example
  1289. Line comments do nest, in effect, because @samp{//} inside a line
  1290. comment is part of that comment:
  1291. @example
  1292. // @r{this whole line is} // @r{one comment}
  1293. This is code, not comment.
  1294. @end example
  1295. It is safe to put line comments inside block comments, or vice versa.
  1296. @example
  1297. @group
  1298. /* @r{traditional comment}
  1299. // @r{contains line comment}
  1300. @r{more traditional comment}
  1301. */ text here is not a comment
  1302. // @r{line comment} /* @r{contains traditional comment} */
  1303. @end group
  1304. @end example
  1305. But beware of commenting out one end of a traditional comment with a line
  1306. comment. The delimiter @samp{/*} doesn't start a comment if it occurs
  1307. inside an already-started comment.
  1308. @example
  1309. @group
  1310. // @r{line comment} /* @r{That would ordinarily begin a block comment.}
  1311. Oops! The line comment has ended;
  1312. this isn't a comment any more. */
  1313. @end group
  1314. @end example
  1315. Comments are not recognized within string constants. @t{@w{"/* blah
  1316. */"}} is the string constant @samp{@w{/* blah */}}, not an empty
  1317. string.
  1318. In this manual we show the text in comments in a variable-width font,
  1319. for readability, but this font distinction does not exist in source
  1320. files.
  1321. A comment is syntactically equivalent to whitespace, so it always
  1322. separates tokens. Thus,
  1323. @example
  1324. @group
  1325. int/* @r{comment} */foo;
  1326. @r{is equivalent to}
  1327. int foo;
  1328. @end group
  1329. @end example
  1330. @noindent
  1331. but clean code always uses real whitespace to separate the comment
  1332. visually from surrounding code.
  1333. @node Identifiers
  1334. @section Identifiers
  1335. @cindex identifiers
  1336. An @dfn{identifier} (name) in C is a sequence of letters and digits,
  1337. as well as @samp{_}, that does not start with a digit. Most compilers
  1338. also allow @samp{$}. An identifier can be as long as you like; for
  1339. example,
  1340. @example
  1341. int anti_dis_establishment_arian_ism;
  1342. @end example
  1343. @cindex case of letters in identifiers
  1344. Letters in identifiers are case-sensitive in C; thus, @code{a}
  1345. and @code{A} are two different identifiers.
  1346. @cindex keyword
  1347. @cindex reserved words
  1348. Identifiers in C are used as variable names, function names, typedef
  1349. names, enumeration constants, type tags, field names, and labels.
  1350. Certain identifiers in C are @dfn{keywords}, which means they have
  1351. specific syntactic meanings. Keywords in C are @dfn{reserved words},
  1352. meaning you cannot use them in any other way. For instance, you can't
  1353. define a variable or function named @code{return} or @code{if}.
  1354. You can also include other characters, even non-ASCII characters, in
  1355. identifiers by writing their Unicode character names, which start with
  1356. @samp{\u} or @samp{\U}, in the identifier name. @xref{Unicode
  1357. Character Codes}. However, it is usually a bad idea to use non-ASCII
  1358. characters in identifiers, and when they are written in English, they
  1359. never need non-ASCII characters. @xref{English}.
  1360. Whitespace is required to separate two consecutive identifiers, or to
  1361. separate an identifier from a preceding or following numeric
  1362. constant.
  1363. @node Operators/Punctuation
  1364. @section Operators and Punctuation
  1365. @cindex operators
  1366. @cindex punctuation
  1367. Here we describe the lexical syntax of operators and punctuation in C.
  1368. The specific operators of C and their meanings are presented in
  1369. subsequent chapters.
  1370. Most operators in C consist of one or two characters that can't be
  1371. used in identifiers. The characters used for operators in C are
  1372. @samp{!~^&|*/%+-=<>,.?:}.
  1373. Some operators are a single character. For instance, @samp{-} is the
  1374. operator for negation (with one operand) and the operator for
  1375. subtraction (with two operands).
  1376. Some operators are two characters. For example, @samp{++} is the
  1377. increment operator. Recognition of multicharacter operators works by
  1378. grouping together as many consecutive characters as can constitute one
  1379. operator.
  1380. For instance, the character sequence @samp{++} is always interpreted
  1381. as the increment operator; therefore, if we want to write two
  1382. consecutive instances of the operator @samp{+}, we must separate them
  1383. with a space so that they do not combine as one token. Applying the
  1384. same rule, @code{a+++++b} is always tokenized as @code{@w{a++ ++ +
  1385. b}}, not as @code{@w{a++ + ++b}}, even though the latter could be part
  1386. of a valid C program and the former could not (since @code{a++}
  1387. is not an lvalue and thus can't be the operand of @code{++}).
  1388. A few C operators are keywords rather than special characters. They
  1389. include @code{sizeof} (@pxref{Type Size}) and @code{_Alignof}
  1390. (@pxref{Type Alignment}).
  1391. The characters @samp{;@{@}[]()} are used for punctuation and grouping.
  1392. Semicolon (@samp{;}) ends a statement. Braces (@samp{@{} and
  1393. @samp{@}}) begin and end a block at the statement level
  1394. (@pxref{Blocks}), and surround the initializer (@pxref{Initializers})
  1395. for a variable with multiple elements or components (such as arrays or
  1396. structures).
  1397. Square brackets (@samp{[} and @samp{]}) do array indexing, as in
  1398. @code{array[5]}.
  1399. Parentheses are used in expressions for explicit nesting of
  1400. expressions (@pxref{Basic Arithmetic}), around the parameter
  1401. declarations in a function declaration or definition, and around the
  1402. arguments in a function call, as in @code{printf ("Foo %d\n", i)}
  1403. (@pxref{Function Calls}). Several kinds of statements also use
  1404. parentheses as part of their syntax---for instance, @code{if}
  1405. statements, @code{for} statements, @code{while} statements, and
  1406. @code{switch} statements. @xref{if Statement}, and following
  1407. sections.
  1408. Parentheses are also required around the operand of the operator
  1409. keywords @code{sizeof} and @code{_Alignof} when the operand is a data
  1410. type rather than a value. @xref{Type Size}.
  1411. @node Line Continuation
  1412. @section Line Continuation
  1413. @cindex line continuation
  1414. @cindex continuation of lines
  1415. The sequence of a backslash and a newline is ignored absolutely
  1416. anywhere in a C program. This makes it possible to split a single
  1417. source line into multiple lines in the source file. GNU C tolerates
  1418. and ignores other whitespace between the backslash and the newline.
  1419. In particular, it always ignores a CR (carriage return) character
  1420. there, in case some text editor decided to end the line with the CRLF
  1421. sequence.
  1422. The main use of line continuation in C is for macro definitions that
  1423. would be inconveniently long for a single line (@pxref{Macros}).
  1424. It is possible to continue a line comment onto another line with
  1425. backslash-newline. You can put backslash-newline in the middle of an
  1426. identifier, even a keyword, or an operator. You can even split
  1427. @samp{/*}, @samp{*/}, and @samp{//} onto multiple lines with
  1428. backslash-newline. Here's an ugly example:
  1429. @example
  1430. @group
  1431. /\
  1432. *
  1433. */ fo\
  1434. o +\
  1435. = 1\
  1436. 0;
  1437. @end group
  1438. @end example
  1439. @noindent
  1440. That's equivalent to @samp{/* */ foo += 10;}.
  1441. Don't do those things in real programs, since they make code hard to
  1442. read.
  1443. @strong{Note:} For the sake of using certain tools on the source code, it is
  1444. wise to end every source file with a newline character which is not
  1445. preceded by a backslash, so that it really ends the last line.
  1446. @node Arithmetic
  1447. @chapter Arithmetic
  1448. @cindex arithmetic operators
  1449. @cindex operators, arithmetic
  1450. @c ??? Duplication with other sections -- get rid of that?
  1451. Arithmetic operators in C attempt to be as similar as possible to the
  1452. abstract arithmetic operations, but it is impossible to do this
  1453. perfectly. Numbers in a computer have a finite range of possible
  1454. values, and non-integer values have a limit on their possible
  1455. accuracy. Nonetheless, in most cases you will encounter no surprises
  1456. in using @samp{+} for addition, @samp{-} for subtraction, and @samp{*}
  1457. for multiplication.
  1458. Each C operator has a @dfn{precedence}, which is its rank in the
  1459. grammatical order of the various operators. The operators with the
  1460. highest precedence grab adjoining operands first; these expressions
  1461. then become operands for operators of lower precedence. We give some
  1462. information about precedence of operators in this chapter where we
  1463. describe the operators; for the full explanation, see @ref{Binary
  1464. Operator Grammar}.
  1465. The arithmetic operators always @dfn{promote} their operands before
  1466. operating on them. This means converting narrow integer data types to
  1467. a wider data type (@pxref{Operand Promotions}). If you are just
  1468. learning C, don't worry about this yet.
  1469. Given two operands that have different types, most arithmetic
  1470. operations convert them both to their @dfn{common type}. For
  1471. instance, if one is @code{int} and the other is @code{double}, the
  1472. common type is @code{double}. (That's because @code{double} can
  1473. represent all the values that an @code{int} can hold, but not vice
  1474. versa.) For the full details, see @ref{Common Type}.
  1475. @menu
  1476. * Basic Arithmetic:: Addition, subtraction, multiplication,
  1477. and division.
  1478. * Integer Arithmetic:: How C performs arithmetic with integer values.
  1479. * Integer Overflow:: When an integer value exceeds the range
  1480. of its type.
  1481. * Mixed Mode:: Calculating with both integer values
  1482. and floating-point values.
  1483. * Division and Remainder:: How integer division works.
  1484. * Numeric Comparisons:: Comparing numeric values for equality or order.
  1485. * Shift Operations:: Shift integer bits left or right.
  1486. * Bitwise Operations:: Bitwise conjunction, disjunction, negation.
  1487. @end menu
  1488. @node Basic Arithmetic
  1489. @section Basic Arithmetic
  1490. @cindex addition operator
  1491. @cindex subtraction operator
  1492. @cindex multiplication operator
  1493. @cindex division operator
  1494. @cindex negation operator
  1495. @cindex operator, addition
  1496. @cindex operator, subtraction
  1497. @cindex operator, multiplication
  1498. @cindex operator, division
  1499. @cindex operator, negation
  1500. Basic arithmetic in C is done with the usual binary operators of
  1501. algebra: addition (@samp{+}), subtraction (@samp{-}), multiplication
  1502. (@samp{*}) and division (@samp{/}). The unary operator @samp{-} is
  1503. used to change the sign of a number. The unary @code{+} operator also
  1504. exists; it yields its operand unaltered.
  1505. @samp{/} is the division operator, but dividing integers may not give
  1506. the result you expect. Its value is an integer, which is not equal to
  1507. the mathematical quotient when that is a fraction. Use @samp{%} to
  1508. get the corresponding integer remainder when necessary.
  1509. @xref{Division and Remainder}. Floating point division yields value
  1510. as close as possible to the mathematical quotient.
  1511. These operators use algebraic syntax with the usual algebraic
  1512. precedence rule (@pxref{Binary Operator Grammar}) that multiplication
  1513. and division are done before addition and subtraction, but you can use
  1514. parentheses to explicitly specify how the operators nest. They are
  1515. left-associative (@pxref{Associativity and Ordering}). Thus,
  1516. @example
  1517. -a + b - c + d * e / f
  1518. @end example
  1519. @noindent
  1520. is equivalent to
  1521. @example
  1522. (((-a) + b) - c) + ((d * e) / f)
  1523. @end example
  1524. @node Integer Arithmetic
  1525. @section Integer Arithmetic
  1526. @cindex integer arithmetic
  1527. Each of the basic arithmetic operations in C has two variants for
  1528. integers: @dfn{signed} and @dfn{unsigned}. The choice is determined
  1529. by the data types of their operands.
  1530. Each integer data type in C is either @dfn{signed} or @dfn{unsigned}.
  1531. A signed type can hold a range of positive and negative numbers, with
  1532. zero near the middle of the range. An unsigned type can hold only
  1533. nonnegative numbers; its range starts with zero and runs upward.
  1534. The most basic integer types are @code{int}, which normally can hold
  1535. numbers from @minus{}2,147,483,648 to 2,147,483,647, and @code{unsigned
  1536. int}, which normally can hold numbers from 0 to 4,294.967,295. (This
  1537. assumes @code{int} is 32 bits wide, always true for GNU C on real
  1538. computers but not always on embedded controllers.) @xref{Integer
  1539. Types}, for full information about integer types.
  1540. When a basic arithmetic operation is given two signed operands, it
  1541. does signed arithmetic. Given two unsigned operands, it does
  1542. unsigned arithmetic.
  1543. If one operand is @code{unsigned int} and the other is @code{int}, the
  1544. operator treats them both as unsigned. More generally, the common
  1545. type of the operands determines whether the operation is signed or
  1546. not. @xref{Common Type}.
  1547. Printing the results of unsigned arithmetic with @code{printf} using
  1548. @samp{%d} can produce surprising results for values far away from
  1549. zero. Even though the rules above say that the computation was done
  1550. with unsigned arithmetic, the printed result may appear to be signed!
  1551. The explanation is that the bit pattern resulting from addition,
  1552. subtraction or multiplication is actually the same for signed and
  1553. unsigned operations. The difference is only in the data type of the
  1554. result, which affects the @emph{interpretation} of the result bit pattern,
  1555. and whether the arithmetic operation can overflow (see the next section).
  1556. But @samp{%d} doesn't know its argument's data type. It sees only the
  1557. value's bit pattern, and it is defined to interpret that as
  1558. @code{signed int}. To print it as unsigned requires using @samp{%u}
  1559. instead of @samp{%d}. @xref{Formatted Output, The GNU C Library, ,
  1560. libc, The GNU C Library Reference Manual}.
  1561. Arithmetic in C never operates directly on narrow integer types (those
  1562. with fewer bits than @code{int}; @ref{Narrow Integers}). Instead it
  1563. ``promotes'' them to @code{int}. @xref{Operand Promotions}.
  1564. @node Integer Overflow
  1565. @section Integer Overflow
  1566. @cindex integer overflow
  1567. @cindex overflow, integer
  1568. When the mathematical value of an arithmetic operation doesn't fit in
  1569. the range of the data type in use, that's called @dfn{overflow}.
  1570. When it happens in integer arithmetic, it is @dfn{integer overflow}.
  1571. Integer overflow happens only in arithmetic operations. Type conversion
  1572. operations, by definition, do not cause overflow, not even when the
  1573. result can't fit in its new type. @xref{Integer Conversion}.
  1574. Signed numbers use two's-complement representation, in which the most
  1575. negative number lacks a positive counterpart (@pxref{Integers in
  1576. Depth}). Thus, the unary @samp{-} operator on a signed integer can
  1577. overflow.
  1578. @menu
  1579. * Unsigned Overflow:: Overlow in unsigned integer arithmetic.
  1580. * Signed Overflow:: Overlow in signed integer arithmetic.
  1581. @end menu
  1582. @node Unsigned Overflow
  1583. @subsection Overflow with Unsigned Integers
  1584. Unsigned arithmetic in C ignores overflow; it produces the true result
  1585. modulo the @var{n}th power of 2, where @var{n} is the number of bits
  1586. in the data type. We say it ``truncates'' the true result to the
  1587. lowest @var{n} bits.
  1588. A true result that is negative, when taken modulo the @var{n}th power
  1589. of 2, yields a positive number. For instance,
  1590. @example
  1591. unsigned int x = 1;
  1592. unsigned int y;
  1593. y = -x;
  1594. @end example
  1595. @noindent
  1596. causes overflow because the negative number @minus{}1 can't be stored
  1597. in an unsigned type. The actual result, which is @minus{}1 modulo the
  1598. @var{n}th power of 2, is one less than the @var{n}th power of 2. That
  1599. is the largest value that the unsigned data type can store. For a
  1600. 32-bit @code{unsigned int}, the value is 4,294,967,295. @xref{Maximum
  1601. and Minimum Values}.
  1602. Adding that number to itself, as here,
  1603. @example
  1604. unsigned int z;
  1605. z = y + y;
  1606. @end example
  1607. @noindent
  1608. ought to yield 8,489,934,590; however, that is again too large to fit,
  1609. so overflow truncates the value to 4,294,967,294. If that were a
  1610. signed integer, it would mean @minus{}2, which (not by coincidence)
  1611. equals @minus{}1 + @minus{}1.
  1612. @node Signed Overflow
  1613. @subsection Overflow with Signed Integers
  1614. @cindex compiler options for integer overflow
  1615. @cindex integer overflow, compiler options
  1616. @cindex overflow, compiler options
  1617. For signed integers, the result of overflow in C is @emph{in
  1618. principle} undefined, meaning that anything whatsoever could happen.
  1619. Therefore, C compilers can do optimizations that treat the overflow
  1620. case with total unconcern. (Since the result of overflow is undefined
  1621. in principle, one cannot claim that these optimizations are
  1622. erroneous.)
  1623. @strong{Watch out:} These optimizations can do surprising things. For
  1624. instance,
  1625. @example
  1626. int i;
  1627. @r{@dots{}}
  1628. if (i < i + 1)
  1629. x = 5;
  1630. @end example
  1631. @noindent
  1632. could be optimized to do the assignment unconditionally, because the
  1633. @code{if}-condition is always true if @code{i + 1} does not overflow.
  1634. GCC offers compiler options to control handling signed integer
  1635. overflow. These options operate per module; that is, each module
  1636. behaves according to the options it was compiled with.
  1637. These two options specify particular ways to handle signed integer
  1638. overflow, other than the default way:
  1639. @table @option
  1640. @item -fwrapv
  1641. Make signed integer operations well-defined, like unsigned integer
  1642. operations: they produce the @var{n} low-order bits of the true
  1643. result. The highest of those @var{n} bits is the sign bit of the
  1644. result. With @option{-fwrapv}, these out-of-range operations are not
  1645. considered overflow, so (strictly speaking) integer overflow never
  1646. happens.
  1647. The option @option{-fwrapv} enables some optimizations based on the
  1648. defined values of out-of-range results. In GCC 8, it disables
  1649. optimizations that are based on assuming signed integer operations
  1650. will not overflow.
  1651. @item -ftrapv
  1652. Generate a signal @code{SIGFPE} when signed integer overflow occurs.
  1653. This terminates the program unless the program handles the signal.
  1654. @xref{Signals}.
  1655. @end table
  1656. One other option is useful for finding where overflow occurs:
  1657. @ignore
  1658. @item -fno-strict-overflow
  1659. Disable optimizations that are based on assuming signed integer
  1660. operations will not overflow.
  1661. @end ignore
  1662. @table @option
  1663. @item -fsanitize=signed-integer-overflow
  1664. Output a warning message at run time when signed integer overflow
  1665. occurs. This checks the @samp{+}, @samp{*}, and @samp{-} operators.
  1666. This takes priority over @option{-ftrapv}.
  1667. @end table
  1668. @node Mixed Mode
  1669. @section Mixed-Mode Arithmetic
  1670. Mixing integers and floating-point numbers in a basic arithmetic
  1671. operation converts the integers automatically to floating point.
  1672. In most cases, this gives exactly the desired results.
  1673. But sometimes it matters precisely where the conversion occurs.
  1674. If @code{i} and @code{j} are integers, @code{(i + j) * 2.0} adds them
  1675. as an integer, then converts the sum to floating point for the
  1676. multiplication. If the addition gets an overflow, that is not
  1677. equivalent to converting both integers to floating point and then
  1678. adding them. You can get the latter result by explicitly converting
  1679. the integers, as in @code{((double) i + (double) j) * 2.0}.
  1680. @xref{Explicit Type Conversion}.
  1681. @c Eggert's report
  1682. Adding or multiplying several values, including some integers and some
  1683. floating point, does the operations left to right. Thus, @code{3.0 +
  1684. i + j} converts @code{i} to floating point, then adds 3.0, then
  1685. converts @code{j} to floating point and adds that. You can specify a
  1686. different order using parentheses: @code{3.0 + (i + j)} adds @code{i}
  1687. and @code{j} first and then adds that result (converting to floating
  1688. point) to 3.0. In this respect, C differs from other languages, such
  1689. as Fortran.
  1690. @node Division and Remainder
  1691. @section Division and Remainder
  1692. @cindex remainder operator
  1693. @cindex modulus
  1694. @cindex operator, remainder
  1695. Division of integers in C rounds the result to an integer. The result
  1696. is always rounded towards zero.
  1697. @example
  1698. 16 / 3 @result{} 5
  1699. -16 / 3 @result{} -5
  1700. 16 / -3 @result{} -5
  1701. -16 / -3 @result{} 5
  1702. @end example
  1703. @noindent
  1704. To get the corresponding remainder, use the @samp{%} operator:
  1705. @example
  1706. 16 % 3 @result{} 1
  1707. -16 % 3 @result{} -1
  1708. 16 % -3 @result{} 1
  1709. -16 % -3 @result{} -1
  1710. @end example
  1711. @noindent
  1712. @samp{%} has the same operator precedence as @samp{/} and @samp{*}.
  1713. From the rounded quotient and the remainder, you can reconstruct
  1714. the dividend, like this:
  1715. @example
  1716. int
  1717. original_dividend (int divisor, int quotient, int remainder)
  1718. @{
  1719. return divisor * quotient + remainder;
  1720. @}
  1721. @end example
  1722. To do unrounded division, use floating point. If only one operand is
  1723. floating point, @samp{/} converts the other operand to floating
  1724. point.
  1725. @example
  1726. 16.0 / 3 @result{} 5.333333333333333
  1727. 16 / 3.0 @result{} 5.333333333333333
  1728. 16.0 / 3.0 @result{} 5.333333333333333
  1729. 16 / 3 @result{} 5
  1730. @end example
  1731. The remainder operator @samp{%} is not allowed for floating-point
  1732. operands, because it is not needed. The concept of remainder makes
  1733. sense for integers because the result of division of integers has to
  1734. be an integer. For floating point, the result of division is a
  1735. floating-point number, in other words a fraction, which will differ
  1736. from the exact result only by a very small amount.
  1737. There are functions in the standard C library to calculate remainders
  1738. from integral-values division of floating-point numbers.
  1739. @xref{Remainder Functions, The GNU C Library, , libc, The GNU C Library
  1740. Reference Manual}.
  1741. Integer division overflows in one specific case: dividing the smallest
  1742. negative value for the data type (@pxref{Maximum and Minimum Values})
  1743. by @minus{}1. That's because the correct result, which is the
  1744. corresponding positive number, does not fit (@pxref{Integer Overflow})
  1745. in the same number of bits. On some computers now in use, this always
  1746. causes a signal @code{SIGFPE} (@pxref{Signals}), the same behavior
  1747. that the option @option{-ftrapv} specifies (@pxref{Signed Overflow}).
  1748. Division by zero leads to unpredictable results---depending on the
  1749. type of computer, it might cause a signal @code{SIGFPE}, or it might
  1750. produce a numeric result.
  1751. @cindex division by zero
  1752. @cindex zero, division by
  1753. @strong{Watch out:} Make sure the program does not divide by zero. If
  1754. you can't prove that the divisor is not zero, test whether it is zero,
  1755. and skip the division if so.
  1756. @node Numeric Comparisons
  1757. @section Numeric Comparisons
  1758. @cindex numeric comparisons
  1759. @cindex comparisons
  1760. @cindex operators, comparison
  1761. @cindex equal operator
  1762. @cindex not-equal operator
  1763. @cindex less-than operator
  1764. @cindex greater-than operator
  1765. @cindex less-or-equal operator
  1766. @cindex greater-or-equal operator
  1767. @cindex operator, equal
  1768. @cindex operator, not-equal
  1769. @cindex operator, less-than
  1770. @cindex operator, greater-than
  1771. @cindex operator, less-or-equal
  1772. @cindex operator, greater-or-equal
  1773. @cindex truth value
  1774. There are two kinds of comparison operators: @dfn{equality} and
  1775. @dfn{ordering}. Equality comparisons test whether two expressions
  1776. have the same value. The result is a @dfn{truth value}: a number that
  1777. is 1 for ``true'' and 0 for ``false.''
  1778. @example
  1779. a == b /* @r{Test for equal.} */
  1780. a != b /* @r{Test for not equal.} */
  1781. @end example
  1782. The equality comparison is written @code{==} because plain @code{=}
  1783. is the assignment operator.
  1784. Ordering comparisons test which operand is greater or less. Their
  1785. results are truth values. These are the ordering comparisons of C:
  1786. @example
  1787. a < b /* @r{Test for less-than.} */
  1788. a > b /* @r{Test for greater-than.} */
  1789. a <= b /* @r{Test for less-than-or-equal.} */
  1790. a >= b /* @r{Test for greater-than-or-equal.} */
  1791. @end example
  1792. For any integers @code{a} and @code{b}, exactly one of the comparisons
  1793. @code{a < b}, @code{a == b} and @code{a > b} is true, just as in
  1794. mathematics. However, if @code{a} and @code{b} are special floating
  1795. point values (not ordinary numbers), all three can be false.
  1796. @xref{Special Float Values}, and @ref{Invalid Optimizations}.
  1797. @node Shift Operations
  1798. @section Shift Operations
  1799. @cindex shift operators
  1800. @cindex operators, shift
  1801. @cindex operators, shift
  1802. @cindex shift count
  1803. @dfn{Shifting} an integer means moving the bit values to the left or
  1804. right within the bits of the data type. Shifting is defined only for
  1805. integers. Here's the way to write it:
  1806. @example
  1807. /* @r{Left shift.} */
  1808. 5 << 2 @result{} 20
  1809. /* @r{Right shift.} */
  1810. 5 >> 2 @result{} 1
  1811. @end example
  1812. @noindent
  1813. The left operand is the value to be shifted, and the right operand
  1814. says how many bits to shift it (the @dfn{shift count}). The left
  1815. operand is promoted (@pxref{Operand Promotions}), so shifting never
  1816. operates on a narrow integer type; it's always either @code{int} or
  1817. wider. The value of the shift operator has the same type as the
  1818. promoted left operand.
  1819. @menu
  1820. * Bits Shifted In:: How shifting makes new bits to shift in.
  1821. * Shift Caveats:: Caveats of shift operations.
  1822. * Shift Hacks:: Clever tricks with shift operations.
  1823. @end menu
  1824. @node Bits Shifted In
  1825. @subsection Shifting Makes New Bits
  1826. A shift operation shifts towards one end of the number and has to
  1827. generate new bits at the other end.
  1828. Shifting left one bit must generate a new least significant bit. It
  1829. always brings in zero there. It is equivalent to multiplying by the
  1830. appropriate power of 2. For example,
  1831. @example
  1832. 5 << 3 @r{is equivalent to} 5 * 2*2*2
  1833. -10 << 4 @r{is equivalent to} -10 * 2*2*2*2
  1834. @end example
  1835. The meaning of shifting right depends on whether the data type is
  1836. signed or unsigned (@pxref{Signed and Unsigned Types}). For a signed
  1837. data type, it performs ``arithmetic shift,'' which keeps the number's
  1838. sign unchanged by duplicating the sign bit. For an unsigned data
  1839. type, it performs ``logical shift,'' which always shifts in zeros at
  1840. the most significant bit.
  1841. In both cases, shifting right one bit is division by two, rounding
  1842. towards negative infinity. For example,
  1843. @example
  1844. (unsigned) 19 >> 2 @result{} 4
  1845. (unsigned) 20 >> 2 @result{} 5
  1846. (unsigned) 21 >> 2 @result{} 5
  1847. @end example
  1848. For negative left operand @code{a}, @code{a >> 1} is not equivalent to
  1849. @code{a / 2}. They both divide by 2, but @samp{/} rounds toward
  1850. zero.
  1851. The shift count must be zero or greater. Shifting by a negative
  1852. number of bits gives machine-dependent results.
  1853. @node Shift Caveats
  1854. @subsection Caveats for Shift Operations
  1855. @strong{Warning:} If the shift count is greater than or equal to the
  1856. width in bits of the first operand, the results are machine-dependent.
  1857. Logically speaking, the ``correct'' value would be either -1 (for
  1858. right shift of a negative number) or 0 (in all other cases), but what
  1859. it really generates is whatever the machine's shift instruction does in
  1860. that case. So unless you can prove that the second operand is not too
  1861. large, write code to check it at run time.
  1862. @strong{Warning:} Never rely on how the shift operators relate in
  1863. precedence to other arithmetic binary operators. Programmers don't
  1864. remember these precedences, and won't understand the code. Always use
  1865. parentheses to explicitly specify the nesting, like this:
  1866. @example
  1867. a + (b << 5) /* @r{Shift first, then add.} */
  1868. (a + b) << 5 /* @r{Add first, then shift.} */
  1869. @end example
  1870. Note: according to the C standard, shifting of signed values isn't
  1871. guaranteed to work properly when the value shifted is negative, or
  1872. becomes negative during the operation of shifting left. However, only
  1873. pedants have a reason to be concerned about this; only computers with
  1874. strange shift instructions could plausibly do this wrong. In GNU C,
  1875. the operation always works as expected,
  1876. @node Shift Hacks
  1877. @subsection Shift Hacks
  1878. You can use the shift operators for various useful hacks. For
  1879. example, given a date specified by day of the month @code{d}, month
  1880. @code{m}, and year @code{y}, you can store the entire date in a single
  1881. integer @code{date}:
  1882. @example
  1883. unsigned int d = 12;
  1884. unsigned int m = 6;
  1885. unsigned int y = 1983;
  1886. unsigned int date = ((y << 4) + m) << 5) + d;
  1887. @end example
  1888. @noindent
  1889. To extract the original day, month, and year out of
  1890. @code{date}, use a combination of shift and remainder.
  1891. @example
  1892. d = date % 32;
  1893. m = (date >> 5) % 16;
  1894. y = date >> 9;
  1895. @end example
  1896. @code{-1 << LOWBITS} is a clever way to make an integer whose
  1897. @code{LOWBITS} lowest bits are all 0 and the rest are all 1.
  1898. @code{-(1 << LOWBITS)} is equivalent to that, due to associativity of
  1899. multiplication, since negating a value is equivalent to multiplying it
  1900. by @minus{}1.
  1901. @node Bitwise Operations
  1902. @section Bitwise Operations
  1903. @cindex bitwise operators
  1904. @cindex operators, bitwise
  1905. @cindex negation, bitwise
  1906. @cindex conjunction, bitwise
  1907. @cindex disjunction, bitwise
  1908. Bitwise operators operate on integers, treating each bit independently.
  1909. They are not allowed for floating-point types.
  1910. The examples in this section use binary constants, starting with
  1911. @samp{0b} (@pxref{Integer Constants}). They stand for 32-bit integers
  1912. of type @code{int}.
  1913. @table @code
  1914. @item ~@code{a}
  1915. Unary operator for bitwise negation; this changes each bit of
  1916. @code{a} from 1 to 0 or from 0 to 1.
  1917. @example
  1918. ~0b10101000 @result{} 0b11111111111111111111111101010111
  1919. ~0 @result{} 0b11111111111111111111111111111111
  1920. ~0b11111111111111111111111111111111 @result{} 0
  1921. ~ (-1) @result{} 0
  1922. @end example
  1923. It is useful to remember that @code{~@var{x} + 1} equals
  1924. @code{-@var{x}}, for integers, and @code{~@var{x}} equals
  1925. @code{-@var{x} - 1}. The last example above shows this with @minus{}1
  1926. as @var{x}.
  1927. @item @code{a} & @code{b}
  1928. Binary operator for bitwise ``and'' or ``conjunction.'' Each bit in
  1929. the result is 1 if that bit is 1 in both @code{a} and @code{b}.
  1930. @example
  1931. 0b10101010 & 0b11001100 @result{} 0b10001000
  1932. @end example
  1933. @item @code{a} | @code{b}
  1934. Binary operator for bitwise ``or'' (``inclusive or'' or
  1935. ``disjunction''). Each bit in the result is 1 if that bit is 1 in
  1936. either @code{a} or @code{b}.
  1937. @example
  1938. 0b10101010 | 0b11001100 @result{} 0b11101110
  1939. @end example
  1940. @item @code{a} ^ @code{b}
  1941. Binary operator for bitwise ``xor'' (``exclusive or''). Each bit in
  1942. the result is 1 if that bit is 1 in exactly one of @code{a} and @code{b}.
  1943. @example
  1944. 0b10101010 ^ 0b11001100 @result{} 0b01100110
  1945. @end example
  1946. @end table
  1947. To understand the effect of these operators on signed integers, keep
  1948. in mind that all modern computers use two's-complement representation
  1949. (@pxref{Integer Representations}) for negative integers. This means
  1950. that the highest bit of the number indicates the sign; it is 1 for a
  1951. negative number and 0 for a positive number. In a negative number,
  1952. the value in the other bits @emph{increases} as the number gets closer
  1953. to zero, so that @code{0b111@r{@dots{}}111} is @minus{}1 and
  1954. @code{0b100@r{@dots{}}000} is the most negative possible integer.
  1955. @strong{Warning:} C defines a precedence ordering for the bitwise
  1956. binary operators, but you should never rely on it. You should
  1957. never rely on how bitwise binary operators relate in precedence to the
  1958. arithmetic and shift binary operators. Other programmers don't
  1959. remember this precedence ordering, so always use parentheses to
  1960. explicitly specify the nesting.
  1961. For example, suppose @code{offset} is an integer that specifies
  1962. the offset within shared memory of a table, except that its bottom few
  1963. bits (@code{LOWBITS} says how many) are special flags. Here's
  1964. how to get just that offset and add it to the base address.
  1965. @example
  1966. shared_mem_base + (offset & (-1 << LOWBITS))
  1967. @end example
  1968. Thanks to the outer set of parentheses, we don't need to know whether
  1969. @samp{&} has higher precedence than @samp{+}. Thanks to the inner
  1970. set, we don't need to know whether @samp{&} has higher precedence than
  1971. @samp{<<}. But we can rely on all unary operators to have higher
  1972. precedence than any binary operator, so we don't need parentheses
  1973. around the left operand of @samp{<<}.
  1974. @node Assignment Expressions
  1975. @chapter Assignment Expressions
  1976. @cindex assignment expressions
  1977. @cindex operators, assignment
  1978. As a general concept in programming, an @dfn{assignment} is a
  1979. construct that stores a new value into a place where values can be
  1980. stored---for instance, in a variable. Such places are called
  1981. @dfn{lvalues} (@pxref{Lvalues}) because they are locations that hold a value.
  1982. An assignment in C is an expression because it has a value; we call
  1983. it an @dfn{assignment expression}. A simple assignment looks like
  1984. @example
  1985. @var{lvalue} = @var{value-to-store}
  1986. @end example
  1987. @noindent
  1988. We say it assigns the value of the expression @var{value-to-store} to
  1989. the location @var{lvalue}, or that it stores @var{value-to-store}
  1990. there. You can think of the ``l'' in ``lvalue'' as standing for
  1991. ``left,'' since that's what you put on the left side of the assignment
  1992. operator.
  1993. However, that's not the only way to use an lvalue, and not all lvalues
  1994. can be assigned to. To use the lvalue in the left side of an
  1995. assignment, it has to be @dfn{modifiable}. In C, that means it was
  1996. not declared with the type qualifier @code{const} (@pxref{const}).
  1997. The value of the assignment expression is that of @var{lvalue} after
  1998. the new value is stored in it. This means you can use an assignment
  1999. inside other expressions. Assignment operators are right-associative
  2000. so that
  2001. @example
  2002. x = y = z = 0;
  2003. @end example
  2004. @noindent
  2005. is equivalent to
  2006. @example
  2007. x = (y = (z = 0));
  2008. @end example
  2009. This is the only useful way for them to associate;
  2010. the other way,
  2011. @example
  2012. ((x = y) = z) = 0;
  2013. @end example
  2014. @noindent
  2015. would be invalid since an assignment expression such as @code{x = y}
  2016. is not valid as an lvalue.
  2017. @strong{Warning:} Write parentheses around an assignment if you nest
  2018. it inside another expression, unless that is a conditional expression,
  2019. or comma-separated series, or another assignment.
  2020. @menu
  2021. * Simple Assignment:: The basics of storing a value.
  2022. * Lvalues:: Expressions into which a value can be stored.
  2023. * Modifying Assignment:: Shorthand for changing an lvalue's contents.
  2024. * Increment/Decrement:: Shorthand for incrementing and decrementing
  2025. an lvalue's contents.
  2026. * Postincrement/Postdecrement:: Accessing then incrementing or decrementing.
  2027. * Assignment in Subexpressions:: How to avoid ambiguity.
  2028. * Write Assignments Separately:: Write assignments as separate statements.
  2029. @end menu
  2030. @node Simple Assignment
  2031. @section Simple Assignment
  2032. @cindex simple assignment
  2033. @cindex assignment, simple
  2034. A @dfn{simple assignment expression} computes the value of the right
  2035. operand and stores it into the lvalue on the left. Here is a simple
  2036. assignment expression that stores 5 in @code{i}:
  2037. @example
  2038. i = 5
  2039. @end example
  2040. @noindent
  2041. We say that this is an @dfn{assignment to} the variable @code{i} and
  2042. that it @dfn{assigns} @code{i} the value 5. It has no semicolon
  2043. because it is an expression (so it has a value). Adding a semicolon
  2044. at the end would make it a statement (@pxref{Expression Statement}).
  2045. Here is another example of a simple assignment expression. Its
  2046. operands are not simple, but the kind of assignment done here is
  2047. simple assignment.
  2048. @example
  2049. x[foo ()] = y + 6
  2050. @end example
  2051. A simple assignment with two different numeric data types converts the
  2052. right operand value to the lvalue's type, if possible. It can convert
  2053. any numeric type to any other numeric type.
  2054. Simple assignment is also allowed on some non-numeric types: pointers
  2055. (@pxref{Pointers}), structures (@pxref{Structure Assignment}), and
  2056. unions (@pxref{Unions}).
  2057. @strong{Warning:} Assignment is not allowed on arrays because
  2058. there are no array values in C; C variables can be arrays, but these
  2059. arrays cannot be manipulated as wholes. @xref{Limitations of C
  2060. Arrays}.
  2061. @xref{Assignment Type Conversions}, for the complete rules about data
  2062. types used in assignments.
  2063. @node Lvalues
  2064. @section Lvalues
  2065. @cindex lvalues
  2066. An expression that identifies a memory space that holds a value is
  2067. called an @dfn{lvalue}, because it is a location that can hold a value.
  2068. The standard kinds of lvalues are:
  2069. @itemize @bullet
  2070. @item
  2071. A variable.
  2072. @item
  2073. A pointer-dereference expression (@pxref{Pointer Dereference}) using
  2074. unary @samp{*}.
  2075. @item
  2076. A structure field reference (@pxref{Structures}) using @samp{.}, if
  2077. the structure value is an lvalue.
  2078. @item
  2079. A structure field reference using @samp{->}. This is always an lvalue
  2080. since @samp{->} implies pointer dereference.
  2081. @item
  2082. A union alternative reference (@pxref{Unions}), on the same conditions
  2083. as for structure fields.
  2084. @item
  2085. An array-element reference using @samp{[@r{@dots{}}]}, if the array
  2086. is an lvalue.
  2087. @end itemize
  2088. If an expression's outermost operation is any other operator, that
  2089. expression is not an lvalue. Thus, the variable @code{x} is an
  2090. lvalue, but @code{x + 0} is not, even though these two expressions
  2091. compute the same value (assuming @code{x} is a number).
  2092. An array can be an lvalue (the rules above determine whether it is
  2093. one), but using the array in an expression converts it automatically
  2094. to a pointer to the first element. The result of this conversion is
  2095. not an lvalue. Thus, if the variable @code{a} is an array, you can't
  2096. use @code{a} by itself as the left operand of an assignment. But you
  2097. can assign to an element of @code{a}, such as @code{a[0]}. That is an
  2098. lvalue since @code{a} is an lvalue.
  2099. @node Modifying Assignment
  2100. @section Modifying Assignment
  2101. @cindex modifying assignment
  2102. @cindex assignment, modifying
  2103. You can abbreviate the common construct
  2104. @example
  2105. @var{lvalue} = @var{lvalue} + @var{expression}
  2106. @end example
  2107. @noindent
  2108. as
  2109. @example
  2110. @var{lvalue} += @var{expression}
  2111. @end example
  2112. This is known as a @dfn{modifying assignment}. For instance,
  2113. @example
  2114. i = i + 5;
  2115. i += 5;
  2116. @end example
  2117. @noindent
  2118. shows two statements that are equivalent. The first uses
  2119. simple assignment; the second uses modifying assignment.
  2120. Modifying assignment works with any binary arithmetic operator. For
  2121. instance, you can subtract something from an lvalue like this,
  2122. @example
  2123. @var{lvalue} -= @var{expression}
  2124. @end example
  2125. @noindent
  2126. or multiply it by a certain amount like this,
  2127. @example
  2128. @var{lvalue} *= @var{expression}
  2129. @end example
  2130. @noindent
  2131. or shift it by a certain amount like this.
  2132. @example
  2133. @var{lvalue} <<= @var{expression}
  2134. @var{lvalue} >>= @var{expression}
  2135. @end example
  2136. In most cases, this feature adds no power to the language, but it
  2137. provides substantial convenience. Also, when @var{lvalue} contains
  2138. code that has side effects, the simple assignment performs those side
  2139. effects twice, while the modifying assignment performs them once. For
  2140. instance,
  2141. @example
  2142. x[foo ()] = x[foo ()] + 5;
  2143. @end example
  2144. @noindent
  2145. calls @code{foo} twice, and it could return different values each
  2146. time. If @code{foo ()} returns 1 the first time and 3 the second
  2147. time, then the effect could be to add @code{x[3]} and 5 and store the
  2148. result in @code{x[1]}, or to add @code{x[1]} and 5 and store the
  2149. result in @code{x[3]}. We don't know which of the two it will do,
  2150. because C does not specify which call to @code{foo} is computed first.
  2151. Such a statement is not well defined, and shouldn't be used.
  2152. By contrast,
  2153. @example
  2154. x[foo ()] += 5;
  2155. @end example
  2156. @noindent
  2157. is well defined: it calls @code{foo} only once to determine which
  2158. element of @code{x} to adjust, and it adjusts that element by adding 5
  2159. to it.
  2160. @node Increment/Decrement
  2161. @section Increment and Decrement Operators
  2162. @cindex increment operator
  2163. @cindex decrement operator
  2164. @cindex operator, increment
  2165. @cindex operator, decrement
  2166. @cindex preincrement expression
  2167. @cindex predecrement expression
  2168. The operators @samp{++} and @samp{--} are the @dfn{increment} and
  2169. @dfn{decrement} operators. When used on a numeric value, they add or
  2170. subtract 1. We don't consider them assignments, but they are
  2171. equivalent to assignments.
  2172. Using @samp{++} or @samp{--} as a prefix, before an lvalue, is called
  2173. @dfn{preincrement} or @dfn{predecrement}. This adds or subtracts 1
  2174. and the result becomes the expression's value. For instance,
  2175. @example
  2176. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2177. int
  2178. main (void)
  2179. @{
  2180. int i = 5;
  2181. printf ("%d\n", i);
  2182. printf ("%d\n", ++i);
  2183. printf ("%d\n", i);
  2184. return 0;
  2185. @}
  2186. @end example
  2187. @noindent
  2188. prints lines containing 5, 6, and 6 again. The expression @code{++i}
  2189. increments @code{i} from 5 to 6, and has the value 6, so the output
  2190. from @code{printf} on that line says @samp{6}.
  2191. Using @samp{--} instead, for predecrement,
  2192. @example
  2193. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2194. int
  2195. main (void)
  2196. @{
  2197. int i = 5;
  2198. printf ("%d\n", i);
  2199. printf ("%d\n", --i);
  2200. printf ("%d\n", i);
  2201. return 0;
  2202. @}
  2203. @end example
  2204. @noindent
  2205. prints three lines that contain (respectively) @samp{5}, @samp{4}, and
  2206. again @samp{4}.
  2207. @node Postincrement/Postdecrement
  2208. @section Postincrement and Postdecrement
  2209. @cindex postincrement expression
  2210. @cindex postdecrement expression
  2211. @cindex operator, postincrement
  2212. @cindex operator, postdecrement
  2213. Using @samp{++} or @samp{--} @emph{after} an lvalue does something
  2214. peculiar: it gets the value directly out of the lvalue and @emph{then}
  2215. increments or decrement it. Thus, the value of @code{i++} is the same
  2216. as the value of @code{i}, but @code{i++} also increments @code{i} ``a
  2217. little later.'' This is called @dfn{postincrement} or
  2218. @dfn{postdecrement}.
  2219. For example,
  2220. @example
  2221. #include <stdio.h> /* @r{Declares @code{printf}.} */
  2222. int
  2223. main (void)
  2224. @{
  2225. int i = 5;
  2226. printf ("%d\n", i);
  2227. printf ("%d\n", i++);
  2228. printf ("%d\n", i);
  2229. return 0;
  2230. @}
  2231. @end example
  2232. @noindent
  2233. prints lines containing 5, again 5, and 6. The expression @code{i++}
  2234. has the value 5, which is the value of @code{i} at the time,
  2235. but it increments @code{i} from 5 to 6 just a little later.
  2236. How much later is ``just a little later''? That is flexible. The
  2237. increment has to happen by the next @dfn{sequence point}. In simple cases,
  2238. that means by the end of the statement. @xref{Sequence Points}.
  2239. If a unary operator precedes a postincrement or postincrement expression,
  2240. the increment nests inside:
  2241. @example
  2242. -a++ @r{is equivalent to} -(a++)
  2243. @end example
  2244. That's the only order that makes sense; @code{-a} is not an lvalue, so
  2245. it can't be incremented.
  2246. @node Assignment in Subexpressions
  2247. @section Pitfall: Assignment in Subexpressions
  2248. @cindex assignment in subexpressions
  2249. @cindex subexpressions, assignment in
  2250. In C, the order of computing parts of an expression is not fixed.
  2251. Aside from a few special cases, the operations can be computed in any
  2252. order. If one part of the expression has an assignment to @code{x}
  2253. and another part of the expression uses @code{x}, the result is
  2254. unpredictable because that use might be computed before or after the
  2255. assignment.
  2256. Here's an example of ambiguous code:
  2257. @example
  2258. x = 20;
  2259. printf ("%d %d\n", x, x = 4);
  2260. @end example
  2261. @noindent
  2262. If the second argument, @code{x}, is computed before the third argument,
  2263. @code{x = 4}, the second argument's value will be 20. If they are
  2264. computed in the other order, the second argument's value will be 4.
  2265. Here's one way to make that code unambiguous:
  2266. @example
  2267. y = 20;
  2268. printf ("%d %d\n", y, x = 4);
  2269. @end example
  2270. Here's another way, with the other meaning:
  2271. @example
  2272. x = 4;
  2273. printf ("%d %d\n", x, x);
  2274. @end example
  2275. This issue applies to all kinds of assignments, and to the increment
  2276. and decrement operators, which are equivalent to assignments.
  2277. @xref{Order of Execution}, for more information about this.
  2278. However, it can be useful to write assignments inside an
  2279. @code{if}-condition or @code{while}-test along with logical operators.
  2280. @xref{Logicals and Assignments}.
  2281. @node Write Assignments Separately
  2282. @section Write Assignments in Separate Statements
  2283. It is often convenient to write an assignment inside an
  2284. @code{if}-condition, but that can reduce the readability of the
  2285. program. Here's an example of what to avoid:
  2286. @example
  2287. if (x = advance (x))
  2288. @r{@dots{}}
  2289. @end example
  2290. The idea here is to advance @code{x} and test if the value is nonzero.
  2291. However, readers might miss the fact that it uses @samp{=} and not
  2292. @samp{==}. In fact, writing @samp{=} where @samp{==} was intended
  2293. inside a condition is a common error, so GNU C can give warnings when
  2294. @samp{=} appears in a way that suggests it's an error.
  2295. It is much clearer to write the assignment as a separate statement, like this:
  2296. @example
  2297. x = advance (x);
  2298. if (x != 0)
  2299. @r{@dots{}}
  2300. @end example
  2301. @noindent
  2302. This makes it unmistakably clear that @code{x} is assigned a new value.
  2303. Another method is to use the comma operator (@pxref{Comma Operator}),
  2304. like this:
  2305. @example
  2306. if (x = advance (x), x != 0)
  2307. @r{@dots{}}
  2308. @end example
  2309. @noindent
  2310. However, putting the assignment in a separate statement is usually clearer
  2311. unless the assignment is very short, because it reduces nesting.
  2312. @node Execution Control Expressions
  2313. @chapter Execution Control Expressions
  2314. @cindex execution control expressions
  2315. @cindex expressions, execution control
  2316. This chapter describes the C operators that combine expressions to
  2317. control which of those expressions execute, or in which order.
  2318. @menu
  2319. * Logical Operators:: Logical conjunction, disjunction, negation.
  2320. * Logicals and Comparison:: Logical operators with comparison operators.
  2321. * Logicals and Assignments:: Assignments with logical operators.
  2322. * Conditional Expression:: An if/else construct inside expressions.
  2323. * Comma Operator:: Build a sequence of subexpressions.
  2324. @end menu
  2325. @node Logical Operators
  2326. @section Logical Operators
  2327. @cindex logical operators
  2328. @cindex operators, logical
  2329. @cindex conjunction operator
  2330. @cindex disjunction operator
  2331. @cindex negation operator, logical
  2332. The @dfn{logical operators} combine truth values, which are normally
  2333. represented in C as numbers. Any expression with a numeric value is a
  2334. valid truth value: zero means false, and any other value means true.
  2335. A pointer type is also meaningful as a truth value; a null pointer
  2336. (which is zero) means false, and a non-null pointer means true
  2337. (@pxref{Pointer Types}). The value of a logical operator is always 1
  2338. or 0 and has type @code{int} (@pxref{Integer Types}).
  2339. The logical operators are used mainly in the condition of an @code{if}
  2340. statement, or in the end test in a @code{for} statement or
  2341. @code{while} statement (@pxref{Statements}). However, they are valid
  2342. in any context where an integer-valued expression is allowed.
  2343. @table @samp
  2344. @item ! @var{exp}
  2345. Unary operator for logical ``not.'' The value is 1 (true) if
  2346. @var{exp} is 0 (false), and 0 (false) if @var{exp} is nonzero (true).
  2347. @strong{Warning:} if @code{exp} is anything but an lvalue or a
  2348. function call, you should write parentheses around it.
  2349. @item @var{left} && @var{right}
  2350. The logical ``and'' binary operator computes @var{left} and, if necessary,
  2351. @var{right}. If both of the operands are true, the @samp{&&} expression
  2352. gives the value 1 (which is true). Otherwise, the @samp{&&} expression
  2353. gives the value 0 (false). If @var{left} yields a false value,
  2354. that determines the overall result, so @var{right} is not computed.
  2355. @item @var{left} || @var{right}
  2356. The logical ``or'' binary operator computes @var{left} and, if necessary,
  2357. @var{right}. If at least one of the operands is true, the @samp{||} expression
  2358. gives the value 1 (which is true). Otherwise, the @samp{||} expression
  2359. gives the value 0 (false). If @var{left} yields a true value,
  2360. that determines the overall result, so @var{right} is not computed.
  2361. @end table
  2362. @strong{Warning:} never rely on the relative precedence of @samp{&&}
  2363. and @samp{||}. When you use them together, always use parentheses to
  2364. specify explicitly how they nest, as shown here:
  2365. @example
  2366. if ((r != 0 && x % r == 0)
  2367. ||
  2368. (s != 0 && x % s == 0))
  2369. @end example
  2370. @node Logicals and Comparison
  2371. @section Logical Operators and Comparisons
  2372. The most common thing to use inside the logical operators is a
  2373. comparison. Conveniently, @samp{&&} and @samp{||} have lower
  2374. precedence than comparison operators and arithmetic operators, so we
  2375. can write expressions like this without parentheses and get the
  2376. nesting that is natural: two comparison operations that must both be
  2377. true.
  2378. @example
  2379. if (r != 0 && x % r == 0)
  2380. @end example
  2381. @noindent
  2382. This example also shows how it is useful that @samp{&&} guarantees to
  2383. skip the right operand if the left one turns out false. Because of
  2384. that, this code never tries to divide by zero.
  2385. This is equivalent:
  2386. @example
  2387. if (r && x % r == 0)
  2388. @end example
  2389. @noindent
  2390. A truth value is simply a number, so @code{r}
  2391. as a truth value tests whether it is nonzero.
  2392. But @code{r}'s meaning is not a truth value---it is a number to divide by.
  2393. So it is better style to write the explicit @code{!= 0}.
  2394. Here's another equivalent way to write it:
  2395. @example
  2396. if (!(r == 0) && x % r == 0)
  2397. @end example
  2398. @noindent
  2399. This illustrates the unary @samp{!} operator, and the need to
  2400. write parentheses around its operand.
  2401. @node Logicals and Assignments
  2402. @section Logical Operators and Assignments
  2403. There are cases where assignments nested inside the condition can
  2404. actually make a program @emph{easier} to read. Here is an example
  2405. using a hypothetical type @code{list} which represents a list; it
  2406. tests whether the list has at least two links, using hypothetical
  2407. functions, @code{nonempty} which is true of the argument is a nonempty
  2408. list, and @code{list_next} which advances from one list link to the
  2409. next. We assume that a list is never a null pointer, so that the
  2410. assignment expressions are always ``true.''
  2411. @example
  2412. if (nonempty (list)
  2413. && (temp1 = list_next (list))
  2414. && nonempty (temp1)
  2415. && (temp2 = list_next (temp1)))
  2416. @r{@dots{}} /* @r{use @code{temp1} and @code{temp2}} */
  2417. @end example
  2418. @noindent
  2419. Here we get the benefit of the @samp{&&} operator, to avoid executing
  2420. the rest of the code if a call to @code{nonempty} says ``false.'' The
  2421. only natural place to put the assignments is among those calls.
  2422. It would be possible to rewrite this as several statements, but that
  2423. could make it much more cumbersome. On the other hand, when the test
  2424. is even more complex than this one, splitting it into multiple
  2425. statements might be necessary for clarity.
  2426. If an empty list is a null pointer, we can dispense with calling
  2427. @code{nonempty}:
  2428. @example
  2429. if ((temp1 = list_next (list))
  2430. && (temp2 = list_next (temp1)))
  2431. @r{@dots{}}
  2432. @end example
  2433. @node Conditional Expression
  2434. @section Conditional Expression
  2435. @cindex conditional expression
  2436. @cindex expression, conditional
  2437. C has a conditional expression that selects one of two expressions
  2438. to compute and get the value from. It looks like this:
  2439. @example
  2440. @var{condition} ? @var{iftrue} : @var{iffalse}
  2441. @end example
  2442. @menu
  2443. * Conditional Rules:: Rules for the conditional operator.
  2444. * Conditional Branches:: About the two branches in a conditional.
  2445. @end menu
  2446. @node Conditional Rules
  2447. @subsection Rules for Conditional Operator
  2448. The first operand, @var{condition}, should be a value that can be
  2449. compared with zero---a number or a pointer. If it is true (nonzero),
  2450. then the conditional expression computes @var{iftrue} and its value
  2451. becomes the value of the conditional expression. Otherwise the
  2452. conditional expression computes @var{iffalse} and its value becomes
  2453. the value of the conditional expression. The conditional expression
  2454. always computes just one of @var{iftrue} and @var{iffalse}, never both
  2455. of them.
  2456. Here's an example: the absolute value of a number @code{x}
  2457. can be written as @code{(x >= 0 ? x : -x)}.
  2458. @strong{Warning:} The conditional expression operators have rather low
  2459. syntactic precedence. Except when the conditional expression is used
  2460. as an argument in a function call, write parentheses around it. For
  2461. clarity, always write parentheses around it if it extends across more
  2462. than one line.
  2463. Assignment operators and the comma operator (@pxref{Comma Operator})
  2464. have lower precedence than conditional expression operators, so write
  2465. parentheses around those when they appear inside a conditional
  2466. expression. @xref{Order of Execution}.
  2467. @node Conditional Branches
  2468. @subsection Conditional Operator Branches
  2469. @cindex branches of conditional expression
  2470. We call @var{iftrue} and @var{iffalse} the @dfn{branches} of the
  2471. conditional.
  2472. The two branches should normally have the same type, but a few
  2473. exceptions are allowed. If they are both numeric types, the
  2474. conditional converts both to their common type (@pxref{Common Type}).
  2475. With pointers (@pxref{Pointers}), the two values can be pointers to
  2476. nearly compatible types (@pxref{Compatible Types}). In this case, the
  2477. result type is a similar pointer whose target type combines all the
  2478. type qualifiers (@pxref{Type Qualifiers}) of both branches.
  2479. If one branch has type @code{void *} and the other is a pointer to an
  2480. object (not to a function), the conditional converts the @code{void *}
  2481. branch to the type of the other.
  2482. If one branch is an integer constant with value zero and the other is
  2483. a pointer, the conditional converts zero to the pointer's type.
  2484. In GNU C, you can omit @var{iftrue} in a conditional expression. In
  2485. that case, if @var{condition} is nonzero, its value becomes the value of
  2486. the conditional expression, after conversion to the common type.
  2487. Thus,
  2488. @example
  2489. x ? : y
  2490. @end example
  2491. @noindent
  2492. has the value of @code{x} if that is nonzero; otherwise, the value of
  2493. @code{y}.
  2494. @cindex side effect in ?:
  2495. @cindex ?: side effect
  2496. Omitting @var{iftrue} is useful when @var{condition} has side effects.
  2497. In that case, writing that expression twice would carry out the side
  2498. effects twice, but writing it once does them just once. For example,
  2499. if we suppose that the function @code{next_element} advances a pointer
  2500. variable to point to the next element in a list and returns the new
  2501. pointer,
  2502. @example
  2503. next_element () ? : default_pointer
  2504. @end example
  2505. @noindent
  2506. is a way to advance the pointer and use its new value if it isn't
  2507. null, but use @code{default_pointer} if that is null. We must not do
  2508. it this way,
  2509. @example
  2510. next_element () ? next_element () : default_pointer
  2511. @end example
  2512. @noindent
  2513. because it would advance the pointer a second time.
  2514. @node Comma Operator
  2515. @section Comma Operator
  2516. @cindex comma operator
  2517. @cindex operator, comma
  2518. The comma operator stands for sequential execution of expressions.
  2519. The value of the comma expression comes from the last expression in
  2520. the sequence; the previous expressions are computed only for their
  2521. side effects. It looks like this:
  2522. @example
  2523. @var{exp1}, @var{exp2} @r{@dots{}}
  2524. @end example
  2525. @noindent
  2526. You can bundle any number of expressions together this way, by putting
  2527. commas between them.
  2528. @menu
  2529. * Uses of Comma:: When to use the comma operator.
  2530. * Clean Comma:: Clean use of the comma operator.
  2531. * Avoid Comma:: When to not use the comma operator.
  2532. @end menu
  2533. @node Uses of Comma
  2534. @subsection The Uses of the Comma Operator
  2535. With commas, you can put several expressions into a place that
  2536. requires just one expression---for example, in the header of a
  2537. @code{for} statement. This statement
  2538. @example
  2539. for (i = 0, j = 10, k = 20; i < n; i++)
  2540. @end example
  2541. @noindent
  2542. contains three assignment expressions, to initialize @code{i}, @code{j}
  2543. and @code{k}. The syntax of @code{for} requires just one expression
  2544. for initialization; to include three assignments, we use commas to
  2545. bundle them into a single larger expression, @code{i = 0, j = 10, k =
  2546. 20}. This technique is also useful in the loop-advance expression,
  2547. the last of the three inside the @code{for} parentheses.
  2548. In the @code{for} statement and the @code{while} statement
  2549. (@pxref{Loop Statements}), a comma provides a way to perform some side
  2550. effect before the loop-exit test. For example,
  2551. @example
  2552. while (printf ("At the test, x = %d\n", x), x != 0)
  2553. @end example
  2554. @node Clean Comma
  2555. @subsection Clean Use of the Comma Operator
  2556. Always write parentheses around a series of comma operators, except
  2557. when it is at top level in an expression statement, or within the
  2558. parentheses of an @code{if}, @code{for}, @code{while}, or @code{switch}
  2559. statement (@pxref{Statements}). For instance, in
  2560. @example
  2561. for (i = 0, j = 10, k = 20; i < n; i++)
  2562. @end example
  2563. @noindent
  2564. the commas between the assignments are clear because they are between
  2565. a parenthesis and a semicolon.
  2566. The arguments in a function call are also separated by commas, but that is
  2567. not an instance of the comma operator. Note the difference between
  2568. @example
  2569. foo (4, 5, 6)
  2570. @end example
  2571. @noindent
  2572. which passes three arguments to @code{foo} and
  2573. @example
  2574. foo ((4, 5, 6))
  2575. @end example
  2576. @noindent
  2577. which uses the comma operator and passes just one argument
  2578. (with value 6).
  2579. @strong{Warning:} don't use the comma operator around an argument
  2580. of a function unless it helps understand the code. When you do so,
  2581. don't put part of another argument on the same line. Instead, add a
  2582. line break to make the parentheses around the comma operator easier to
  2583. see, like this.
  2584. @example
  2585. foo ((mumble (x, y), frob (z)),
  2586. *p)
  2587. @end example
  2588. @node Avoid Comma
  2589. @subsection When Not to Use the Comma Operator
  2590. You can use a comma in any subexpression, but in most cases it only
  2591. makes the code confusing, and it is clearer to raise all but the last
  2592. of the comma-separated expressions to a higher level. Thus, instead
  2593. of this:
  2594. @example
  2595. x = (y += 4, 8);
  2596. @end example
  2597. @noindent
  2598. it is much clearer to write this:
  2599. @example
  2600. y += 4, x = 8;
  2601. @end example
  2602. @noindent
  2603. or this:
  2604. @example
  2605. y += 4;
  2606. x = 8;
  2607. @end example
  2608. Use commas only in the cases where there is no clearer alternative
  2609. involving multiple statements.
  2610. By contrast, don't hesitate to use commas in the expansion in a macro
  2611. definition. The trade-offs of code clarity are different in that
  2612. case, because the @emph{use} of the macro may improve overall clarity
  2613. so much that the ugliness of the macro's @emph{definition} is a small
  2614. price to pay. @xref{Macros}.
  2615. @node Binary Operator Grammar
  2616. @chapter Binary Operator Grammar
  2617. @cindex binary operator grammar
  2618. @cindex grammar, binary operator
  2619. @cindex operator precedence
  2620. @cindex precedence, operator
  2621. @cindex left-associative
  2622. @dfn{Binary operators} are those that take two operands, one
  2623. on the left and one on the right.
  2624. All the binary operators in C are syntactically left-associative.
  2625. This means that @w{@code{a @var{op} b @var{op} c}} means @w{@code{(a
  2626. @var{op} b) @var{op} c}}. However, you should only write repeated
  2627. operators without parentheses using @samp{+}, @samp{-}, @samp{*} and
  2628. @samp{/}, because those cases are clear from algebra. So it is ok to
  2629. write @code{a + b + c} or @code{a - b - c}, but never @code{a == b ==
  2630. c} or @code{a % b % c}.
  2631. Each C operator has a @dfn{precedence}, which is its rank in the
  2632. grammatical order of the various operators. The operators with the
  2633. highest precedence grab adjoining operands first; these expressions
  2634. then become operands for operators of lower precedence.
  2635. The precedence order of operators in C is fully specified, so any
  2636. combination of operations leads to a well-defined nesting. We state
  2637. only part of the full precedence ordering here because it is bad
  2638. practice for C code to depend on the other cases. For cases not
  2639. specified in this chapter, always use parentheses to make the nesting
  2640. explicit.@footnote{Personal note from Richard Stallman: I wrote GCC without
  2641. remembering anything about the C precedence order beyond what's stated
  2642. here. I studied the full precedence table to write the parser, and
  2643. promptly forgot it again. If you need to look up the full precedence order
  2644. to understand some C code, fix the code with parentheses so nobody else
  2645. needs to do that.}
  2646. You can depend on this subsequence of the precedence ordering
  2647. (stated from highest precedence to lowest):
  2648. @enumerate
  2649. @item
  2650. Component access (@samp{.} and @samp{->}).
  2651. @item
  2652. Unary prefix operators.
  2653. @item
  2654. Unary postfix operators.
  2655. @item
  2656. Multiplication, division, and remainder (they have the same precedence).
  2657. @item
  2658. Addition and subtraction (they have the same precedence).
  2659. @item
  2660. Comparisons---but watch out!
  2661. @item
  2662. Logical operators @samp{&&} and @samp{||}---but watch out!
  2663. @item
  2664. Conditional expression with @samp{?} and @samp{:}.
  2665. @item
  2666. Assignments.
  2667. @item
  2668. Sequential execution (the comma operator, @samp{,}).
  2669. @end enumerate
  2670. Two of the lines in the above list say ``but watch out!'' That means
  2671. that the line covers operators with subtly different precedence.
  2672. Never depend on the grammar of C to decide how two comparisons nest;
  2673. instead, always use parentheses to specify their nesting.
  2674. You can let several @samp{&&} operators associate, or several
  2675. @samp{||} operators, but always use parentheses to show how @samp{&&}
  2676. and @samp{||} nest with each other. @xref{Logical Operators}.
  2677. There is one other precedence ordering that code can depend on:
  2678. @enumerate
  2679. @item
  2680. Unary postfix operators.
  2681. @item
  2682. Bitwise and shift operators---but watch out!
  2683. @item
  2684. Conditional expression with @samp{?} and @samp{:}.
  2685. @end enumerate
  2686. The caveat for bitwise and shift operators is like that for logical
  2687. operators: you can let multiple uses of one bitwise operator
  2688. associate, but always use parentheses to control nesting of dissimilar
  2689. operators.
  2690. These lists do not specify any precedence ordering between the bitwise
  2691. and shift operators of the second list and the binary operators above
  2692. conditional expressions in the first list. When they come together,
  2693. parenthesize them. @xref{Bitwise Operations}.
  2694. @node Order of Execution
  2695. @chapter Order of Execution
  2696. @cindex order of execution
  2697. The order of execution of a C program is not always obvious, and not
  2698. necessarily predictable. This chapter describes what you can count on.
  2699. @menu
  2700. * Reordering of Operands:: Operations in C are not necessarily computed
  2701. in the order they are written.
  2702. * Associativity and Ordering:: Some associative operations are performed
  2703. in a particular order; others are not.
  2704. * Sequence Points:: Some guarantees about the order of operations.
  2705. * Postincrement and Ordering:: Ambiguous excution order with postincrement.
  2706. * Ordering of Operands:: Evaluation order of operands
  2707. and function arguments.
  2708. * Optimization and Ordering:: Compiler optimizations can reorder operations
  2709. only if it has no impact on program results.
  2710. @end menu
  2711. @node Reordering of Operands
  2712. @section Reordering of Operands
  2713. @cindex ordering of operands
  2714. @cindex reordering of operands
  2715. @cindex operand execution ordering
  2716. The C language does not necessarily carry out operations within an
  2717. expression in the order they appear in the code. For instance, in
  2718. this expression,
  2719. @example
  2720. foo () + bar ()
  2721. @end example
  2722. @noindent
  2723. @code{foo} might be called first or @code{bar} might be called first.
  2724. If @code{foo} updates a datum and @code{bar} uses that datum, the
  2725. results can be unpredictable.
  2726. The unpredictable order of computation of subexpressions also makes a
  2727. difference when one of them contains an assignment. We already saw
  2728. this example of bad code,
  2729. @example
  2730. x = 20;
  2731. printf ("%d %d\n", x, x = 4);
  2732. @end example
  2733. @noindent
  2734. in which the second argument, @code{x}, has a different value
  2735. depending on whether it is computed before or after the assignment in
  2736. the third argument.
  2737. @node Associativity and Ordering
  2738. @section Associativity and Ordering
  2739. @cindex associativity and ordering
  2740. An associative binary operator, such as @code{+}, when used repeatedly
  2741. can combine any number of operands. The operands' values may be
  2742. computed in any order.
  2743. If the values are integers and overflow can be ignored, they may be
  2744. combined in any order. Thus, given four functions that return
  2745. @code{unsigned int}, calling them and adding their results as here
  2746. @example
  2747. (foo () + bar ()) + (baz () + quux ())
  2748. @end example
  2749. @noindent
  2750. may add up the results in any order.
  2751. By contrast, arithmetic on signed integers, with overflow significant,
  2752. is not really associative (@pxref{Integer Overflow}). Thus, the
  2753. additions must be done in the order specified, obeying parentheses and
  2754. left-association. That means computing @code{(foo () + bar ())} and
  2755. @code{(baz () + quux ())} first (in either order), then adding the
  2756. two.
  2757. The same applies to arithmetic on floating-point values, since that
  2758. too is not really associative. However, the GCC option
  2759. @option{-funsafe-math-optimizations} allows the compiler to change the
  2760. order of calculation when an associative operation (associative in
  2761. exact mathematics) combines several operands. The option takes effect
  2762. when compiling a module (@pxref{Compilation}). Changing the order
  2763. of association can enable the program to pipeline the floating point
  2764. operations.
  2765. In all these cases, the four function calls can be done in any order.
  2766. There is no right or wrong about that.
  2767. @node Sequence Points
  2768. @section Sequence Points
  2769. @cindex sequence points
  2770. @cindex full expression
  2771. There are some points in the code where C makes limited guarantees
  2772. about the order of operations. These are called @dfn{sequence
  2773. points}. Here is where they occur:
  2774. @itemize @bullet
  2775. @item
  2776. At the end of a @dfn{full expression}; that is to say, an expression
  2777. that is not part of a larger expression. All side effects specified
  2778. by that expression are carried out before execution moves
  2779. on to subsequent code.
  2780. @item
  2781. At the end of the first operand of certain operators: @samp{,},
  2782. @samp{&&}, @samp{||}, and @samp{?:}. All side effects specified by
  2783. that expression are carried out before any execution of the
  2784. next operand.
  2785. The commas that separate arguments in a function call are @emph{not}
  2786. comma operators, and they do not create sequence points. The rule
  2787. for function arguments and the rule for operands are different
  2788. (@pxref{Ordering of Operands}).
  2789. @item
  2790. Just before calling a function. All side effects specified by the
  2791. argument expressions are carried out before calling the function.
  2792. If the function to be called is not constant---that is, if it is
  2793. computed by an expression---all side effects in that expression are
  2794. carried out before calling the function.
  2795. @end itemize
  2796. The ordering imposed by a sequence point applies locally to a limited
  2797. range of code, as stated above in each case. For instance, the
  2798. ordering imposed by the comma operator does not apply to code outside
  2799. that comma operator. Thus, in this code,
  2800. @example
  2801. (x = 5, foo (x)) + x * x
  2802. @end example
  2803. @noindent
  2804. the sequence point of the comma operator orders @code{x = 5} before
  2805. @code{foo (x)}, but @code{x * x} could be computed before or after
  2806. them.
  2807. @node Postincrement and Ordering
  2808. @section Postincrement and Ordering
  2809. @cindex postincrement and ordering
  2810. @cindex ordering and postincrement
  2811. Ordering requirements are loose with the postincrement and
  2812. postdecrement operations (@pxref{Postincrement/Postdecrement}), which
  2813. specify side effects to happen ``a little later.'' They must happen
  2814. before the next sequence point, but that still leaves room for various
  2815. meanings. In this expression,
  2816. @example
  2817. z = x++ - foo ()
  2818. @end example
  2819. @noindent
  2820. it's unpredictable whether @code{x} gets incremented before or after
  2821. calling the function @code{foo}. If @code{foo} refers to @code{x},
  2822. it might see the old value or it might see the incremented value.
  2823. In this perverse expression,
  2824. @example
  2825. x = x++
  2826. @end example
  2827. @noindent
  2828. @code{x} will certainly be incremented but the incremented value may
  2829. not stick. If the incrementation of @code{x} happens after the
  2830. assignment to @code{x}, the incremented value will remain in place.
  2831. But if the incrementation happens first, the assignment will overwrite
  2832. that with the not-yet-incremented value, so the expression as a whole
  2833. will leave @code{x} unchanged.
  2834. @node Ordering of Operands
  2835. @section Ordering of Operands
  2836. @cindex ordering of operands
  2837. @cindex operand ordering
  2838. Operands and arguments can be computed in any order, but there are limits to
  2839. this intermixing in GNU C:
  2840. @itemize @bullet
  2841. @item
  2842. The operands of a binary arithmetic operator can be computed in either
  2843. order, but they can't be intermixed: one of them has to come first,
  2844. followed by the other. Any side effects in the operand that's computed
  2845. first are executed before the other operand is computed.
  2846. @item
  2847. That applies to assignment operators too, except that in simple assignment
  2848. the previous value of the left operand is unused.
  2849. @item
  2850. The arguments in a function call can be computed in any order, but
  2851. they can't be intermixed. Thus, one argument is fully computed, then
  2852. another, and so on until they are all done. Any side effects in one argument
  2853. are executed before computation of another argument begins.
  2854. @end itemize
  2855. These rules don't cover side effects caused by postincrement and
  2856. postdecrement operators---those can be deferred up to the next
  2857. sequence point.
  2858. If you want to get pedantic, the fact is that GCC can reorder the
  2859. computations in many other ways provided that doesn't alter the result
  2860. of running the program. However, because they don't alter the result
  2861. of running the program, they are negligible, unless you are concerned
  2862. with the values in certain variables at various times as seen by other
  2863. processes. In those cases, you can use @code{volatile} to prevent
  2864. optimizations that would make them behave strangely. @xref{volatile}.
  2865. @node Optimization and Ordering
  2866. @section Optimization and Ordering
  2867. @cindex optimization and ordering
  2868. @cindex ordering and optimization
  2869. Sequence points limit the compiler's freedom to reorder operations
  2870. arbitrarily, but optimizations can still reorder them if the compiler
  2871. concludes that this won't alter the results. Thus, in this code,
  2872. @example
  2873. x++;
  2874. y = z;
  2875. x++;
  2876. @end example
  2877. @noindent
  2878. there is a sequence point after each statement, so the code is
  2879. supposed to increment @code{x} once before the assignment to @code{y}
  2880. and once after. However, incrementing @code{x} has no effect on
  2881. @code{y} or @code{z}, and setting @code{y} can't affect @code{x}, so
  2882. the code could be optimized into this:
  2883. @example
  2884. y = z;
  2885. x += 2;
  2886. @end example
  2887. Normally that has no effect except to make the program faster. But
  2888. there are special situations where it can cause trouble due to things
  2889. that the compiler cannot know about, such as shared memory. To limit
  2890. optimization in those places, use the @code{volatile} type qualifier
  2891. (@pxref{volatile}).
  2892. @node Primitive Types
  2893. @chapter Primitive Data Types
  2894. @cindex primitive types
  2895. @cindex types, primitive
  2896. This chapter describes all the primitive data types of C---that is,
  2897. all the data types that aren't built up from other types. They
  2898. include the types @code{int} and @code{double} that we've already covered.
  2899. @menu
  2900. * Integer Types:: Description of integer types.
  2901. * Floating-Point Data Types:: Description of floating-point types.
  2902. * Complex Data Types:: Description of complex number types.
  2903. * The Void Type:: A type indicating no value at all.
  2904. * Other Data Types:: A brief summary of other types.
  2905. * Type Designators:: Referring to a data type abstractly.
  2906. @end menu
  2907. These types are all made up of bytes (@pxref{Storage}).
  2908. @node Integer Types
  2909. @section Integer Data Types
  2910. @cindex integer types
  2911. @cindex types, integer
  2912. Here we describe all the integer types and their basic
  2913. characteristics. @xref{Integers in Depth}, for more information about
  2914. the bit-level integer data representations and arithmetic.
  2915. @menu
  2916. * Basic Integers:: Overview of the various kinds of integers.
  2917. * Signed and Unsigned Types:: Integers can either hold both negative and
  2918. non-negative values, or only non-negative.
  2919. * Narrow Integers:: When to use smaller integer types.
  2920. * Integer Conversion:: Casting a value from one integer type
  2921. to another.
  2922. * Boolean Type:: An integer type for boolean values.
  2923. * Integer Variations:: Sizes of integer types can vary
  2924. across platforms.
  2925. @end menu
  2926. @node Basic Integers
  2927. @subsection Basic Integers
  2928. @findex char
  2929. @findex int
  2930. @findex short int
  2931. @findex long int
  2932. @findex long long int
  2933. Integer data types in C can be signed or unsigned. An unsigned type
  2934. can represent only positive numbers and zero. A signed type can
  2935. represent both positive and negative numbers, in a range spread almost
  2936. equally on both sides of zero.
  2937. Aside from signedness, the integer data types vary in size: how many
  2938. bytes long they are. The size determines how many different integer
  2939. values the type can hold.
  2940. Here's a list of the signed integer data types, with the sizes they
  2941. have on most computers. Each has a corresponding unsigned type; see
  2942. @ref{Signed and Unsigned Types}.
  2943. @table @code
  2944. @item signed char
  2945. One byte (8 bits). This integer type is used mainly for integers that
  2946. represent characters, as part of arrays or other data structures.
  2947. @item short
  2948. @itemx short int
  2949. Two bytes (16 bits).
  2950. @item int
  2951. Four bytes (32 bits).
  2952. @item long
  2953. @itemx long int
  2954. Four bytes (32 bits) or eight bytes (64 bits), depending on the
  2955. platform. Typically it is 32 bits on 32-bit computers
  2956. and 64 bits on 64-bit computers, but there are exceptions.
  2957. @item long long
  2958. @itemx long long int
  2959. Eight bytes (64 bits). Supported in GNU C in the 1980s, and
  2960. incorporated into standard C as of ISO C99.
  2961. @end table
  2962. You can omit @code{int} when you use @code{long} or @code{short}.
  2963. This is harmless and customary.
  2964. @node Signed and Unsigned Types
  2965. @subsection Signed and Unsigned Types
  2966. @cindex signed types
  2967. @cindex unsigned types
  2968. @cindex types, signed
  2969. @cindex types, unsigned
  2970. @findex signed
  2971. @findex unsigned
  2972. An unsigned integer type can represent only positive numbers and zero.
  2973. A signed type can represent both positive and negative number, in a
  2974. range spread almost equally on both sides of zero. For instance,
  2975. @code{unsigned char} holds numbers from 0 to 255 (on most computers),
  2976. while @code{signed char} holds numbers from @minus{}128 to 127. Each of
  2977. these types holds 256 different possible values, since they are both 8
  2978. bits wide.
  2979. Write @code{signed} or @code{unsigned} before the type keyword to
  2980. specify a signed or an unsigned type. However, the integer types
  2981. other than @code{char} are signed by default; with them, @code{signed}
  2982. is a no-op.
  2983. Plain @code{char} may be signed or unsigned; this depends on the
  2984. compiler, the machine in use, and its operating system.
  2985. In many programs, it makes no difference whether @code{char} is
  2986. signed. When it does matter, don't leave it to chance; write
  2987. @code{signed char} or @code{unsigned char}.@footnote{Personal note from
  2988. Richard Stallman: Eating with hackers at a fish restaurant, I ordered
  2989. Arctic Char. When my meal arrived, I noted that the chef had not
  2990. signed it. So I complained, ``This char is unsigned---I wanted a
  2991. signed char!'' Or rather, I would have said this if I had thought of
  2992. it fast enough.}
  2993. @node Narrow Integers
  2994. @subsection Narrow Integers
  2995. The types that are narrower than @code{int} are rarely used for
  2996. ordinary variables---we declare them @code{int} instead. This is
  2997. because C converts those narrower types to @code{int} for any
  2998. arithmetic. There is literally no reason to declare a local variable
  2999. @code{char}, for instance.
  3000. In particular, if the value is really a character, you should declare
  3001. the variable @code{int}. Not @code{char}! Using that narrow type can
  3002. force the compiler to truncate values for conversion, which is a
  3003. waste. Furthermore, some functions return either a character value,
  3004. or @minus{}1 for ``no character.'' Using @code{int} keeps those
  3005. values distinct.
  3006. The narrow integer types are useful as parts of other objects, such as
  3007. arrays and structures. Compare these array declarations, whose sizes
  3008. on 32-bit processors are shown:
  3009. @example
  3010. signed char ac[1000]; /* @r{1000 bytes} */
  3011. short as[1000]; /* @r{2000 bytes} */
  3012. int ai[1000]; /* @r{4000 bytes} */
  3013. long long all[1000]; /* @r{8000 bytes} */
  3014. @end example
  3015. In addition, character strings must be made up of @code{char}s,
  3016. because that's what all the standard library string functions expect.
  3017. Thus, array @code{ac} could be used as a character string, but the
  3018. others could not be.
  3019. @node Integer Conversion
  3020. @subsection Conversion among Integer Types
  3021. C converts between integer types implicitly in many situations. It
  3022. converts the narrow integer types, @code{char} and @code{short}, to
  3023. @code{int} whenever they are used in arithmetic. Assigning a new
  3024. value to an integer variable (or other lvalue) converts the value to
  3025. the variable's type.
  3026. You can also convert one integer type to another explicitly with a
  3027. @dfn{cast} operator. @xref{Explicit Type Conversion}.
  3028. The process of conversion to a wider type is straightforward: the
  3029. value is unchanged. The only exception is when converting a negative
  3030. value (in a signed type, obviously) to a wider unsigned type. In that
  3031. case, the result is a positive value with the same bits
  3032. (@pxref{Integers in Depth}).
  3033. @cindex truncation
  3034. Converting to a narrower type, also called @dfn{truncation}, involves
  3035. discarding some of the value's bits. This is not considered overflow
  3036. (@pxref{Integer Overflow}) because loss of significant bits is a
  3037. normal consequence of truncation. Likewise for conversion between
  3038. signed and unsigned types of the same width.
  3039. More information about conversion for assignment is in
  3040. @ref{Assignment Type Conversions}. For conversion for arithmetic,
  3041. see @ref{Argument Promotions}.
  3042. @node Boolean Type
  3043. @subsection Boolean Type
  3044. @cindex boolean type
  3045. @cindex type, boolean
  3046. @findex bool
  3047. The unsigned integer type @code{bool} holds truth values: its possible
  3048. values are 0 and 1. Converting any nonzero value to @code{bool}
  3049. results in 1. For example:
  3050. @example
  3051. bool a = 0;
  3052. bool b = 1;
  3053. bool c = 4; /* @r{Stores the value 1 in @code{c}.} */
  3054. @end example
  3055. Unlike @code{int}, @code{bool} is not a keyword. It is defined in
  3056. the header file @file{stdbool.h}.
  3057. @node Integer Variations
  3058. @subsection Integer Variations
  3059. The integer types of C have standard @emph{names}, but what they
  3060. @emph{mean} varies depending on the kind of platform in use:
  3061. which kind of computer, which operating system, and which compiler.
  3062. It may even depend on the compiler options used.
  3063. Plain @code{char} may be signed or unsigned; this depends on the
  3064. platform, too. Even for GNU C, there is no general rule.
  3065. In theory, all of the integer types' sizes can vary. @code{char} is
  3066. always considered one ``byte'' for C, but it is not necessarily an
  3067. 8-bit byte; on some platforms it may be more than 8 bits. ISO C
  3068. specifies only that none of these types is narrower than the ones
  3069. above it in the list in @ref{Basic Integers}, and that @code{short}
  3070. has at least 16 bits.
  3071. It is possible that in the future GNU C will support platforms where
  3072. @code{int} is 64 bits long. In practice, however, on today's real
  3073. computers, there is little variation; you can rely on the table
  3074. given previously (@pxref{Basic Integers}).
  3075. To be completely sure of the size of an integer type,
  3076. use the types @code{int16_t}, @code{int32_t} and @code{int64_t}.
  3077. Their corresponding unsigned types add @samp{u} at the front.
  3078. To define these, include the header file @file{stdint.h}.
  3079. The GNU C Compiler compiles for some embedded controllers that use two
  3080. bytes for @code{int}. On some, @code{int} is just one ``byte,'' and
  3081. so is @code{short int}---but that ``byte'' may contain 16 bits or even
  3082. 32 bits. These processors can't support an ordinary operating system
  3083. (they may have their own specialized operating systems), and most C
  3084. programs do not try to support them.
  3085. @node Floating-Point Data Types
  3086. @section Floating-Point Data Types
  3087. @cindex floating-point types
  3088. @cindex types, floating-point
  3089. @findex double
  3090. @findex float
  3091. @findex long double
  3092. @dfn{Floating point} is the binary analogue of scientific notation:
  3093. internally it represents a number as a fraction and a binary exponent; the
  3094. value is that fraction multiplied by the specified power of 2.
  3095. For instance, to represent 6, the fraction would be 0.75 and the
  3096. exponent would be 3; together they stand for the value @math{0.75 * 2@sup{3}},
  3097. meaning 0.75 * 8. The value 1.5 would use 0.75 as the fraction and 1
  3098. as the exponent. The value 0.75 would use 0.75 as the fraction and 0
  3099. as the exponent. The value 0.375 would use 0.75 as the fraction and
  3100. -1 as the exponent.
  3101. These binary exponents are used by machine instructions. You can
  3102. write a floating-point constant this way if you wish, using
  3103. hexadecimal; but normally we write floating-point numbers in decimal.
  3104. @xref{Floating Constants}.
  3105. C has three floating-point data types:
  3106. @table @code
  3107. @item double
  3108. ``Double-precision'' floating point, which uses 64 bits. This is the
  3109. normal floating-point type, and modern computers normally do
  3110. their floating-point computations in this type, or some wider type.
  3111. Except when there is a special reason to do otherwise, this is the
  3112. type to use for floating-point values.
  3113. @item float
  3114. ``Single-precision'' floating point, which uses 32 bits. It is useful
  3115. for floating-point values stored in structures and arrays, to save
  3116. space when the full precision of @code{double} is not needed. In
  3117. addition, single-precision arithmetic is faster on some computers, and
  3118. occasionally that is useful. But not often---most programs don't use
  3119. the type @code{float}.
  3120. C would be cleaner if @code{float} were the name of the type we
  3121. use for most floating-point values; however, for historical reasons,
  3122. that's not so.
  3123. @item long double
  3124. ``Extended-precision'' floating point is either 80-bit or 128-bit
  3125. precision, depending on the machine in use. On some machines, which
  3126. have no floating-point format wider than @code{double}, this is
  3127. equivalent to @code{double}.
  3128. @end table
  3129. Floating-point arithmetic raises many subtle issues. @xref{Floating
  3130. Point in Depth}, for more information.
  3131. @node Complex Data Types
  3132. @section Complex Data Types
  3133. @cindex complex numbers
  3134. @cindex types, complex
  3135. @cindex @code{_Complex} keyword
  3136. @cindex @code{__complex__} keyword
  3137. @findex _Complex
  3138. @findex __complex__
  3139. Complex numbers can include both a real part and an imaginary part.
  3140. The numeric constants covered above have real-numbered values. An
  3141. imaginary-valued constant is an ordinary real-valued constant followed
  3142. by @samp{i}.
  3143. To declare numeric variables as complex, use the @code{_Complex}
  3144. keyword.@footnote{For compatibility with older versions of GNU C, the
  3145. keyword @code{__complex__} is also allowed. Going forward, however,
  3146. use the new @code{_Complex} keyword as defined in ISO C11.} The
  3147. standard C complex data types are floating point,
  3148. @example
  3149. _Complex float foo;
  3150. _Complex double bar;
  3151. _Complex long double quux;
  3152. @end example
  3153. @noindent
  3154. but GNU C supports integer complex types as well.
  3155. Since @code{_Complex} is a keyword just like @code{float} and
  3156. @code{double} and @code{long}, the keywords can appear in any order,
  3157. but the order shown above seems most logical.
  3158. GNU C supports constants for complex values; for instance, @code{4.0 +
  3159. 3.0i} has the value 4 + 3i as type @code{_Complex double}.
  3160. @xref{Imaginary Constants}.
  3161. To pull the real and imaginary parts of the number back out, GNU C
  3162. provides the keywords @code{__real__} and @code{__imag__}:
  3163. @example
  3164. _Complex double foo = 4.0 + 3.0i;
  3165. double a = __real__ foo; /* @r{@code{a} is now 4.0.} */
  3166. double b = __imag__ foo; /* @r{@code{b} is now 3.0.} */
  3167. @end example
  3168. @noindent
  3169. Standard C does not include these keywords, and instead relies on
  3170. functions defined in @code{complex.h} for accessing the real and
  3171. imaginary parts of a complex number: @code{crealf}, @code{creal}, and
  3172. @code{creall} extract the real part of a float, double, or long double
  3173. complex number, respectively; @code{cimagf}, @code{cimag}, and
  3174. @code{cimagl} extract the imaginary part.
  3175. @cindex complex conjugation
  3176. GNU C also defines @samp{~} as an operator for complex conjugation,
  3177. which means negating the imaginary part of a complex number:
  3178. @example
  3179. _Complex double foo = 4.0 + 3.0i;
  3180. _Complex double bar = ~foo; /* @r{@code{bar} is now 4 @minus{} 3i.} */
  3181. @end example
  3182. @noindent
  3183. For standard C compatibility, you can use the appropriate library
  3184. function: @code{conjf}, @code{conj}, or @code{confl}.
  3185. @node The Void Type
  3186. @section The Void Type
  3187. @cindex void type
  3188. @cindex type, void
  3189. @findex void
  3190. The data type @code{void} is a dummy---it allows no operations. It
  3191. really means ``no value at all.'' When a function is meant to return
  3192. no value, we write @code{void} for its return type. Then
  3193. @code{return} statements in that function should not specify a value
  3194. (@pxref{return Statement}). Here's an example:
  3195. @example
  3196. void
  3197. print_if_positive (double x, double y)
  3198. @{
  3199. if (x <= 0)
  3200. return;
  3201. if (y <= 0)
  3202. return;
  3203. printf ("Next point is (%f,%f)\n", x, y);
  3204. @}
  3205. @end example
  3206. A @code{void}-returning function is comparable to what some other languages
  3207. call a ``procedure'' instead of a ``function.''
  3208. @c ??? Already presented
  3209. @c @samp{%f} in an output template specifies to format a @code{double} value
  3210. @c as a decimal number, using a decimal point if needed.
  3211. @node Other Data Types
  3212. @section Other Data Types
  3213. Beyond the primitive types, C provides several ways to construct new
  3214. data types. For instance, you can define @dfn{pointers}, values that
  3215. represent the addresses of other data (@pxref{Pointers}). You can
  3216. define @dfn{structures}, as in many other languages
  3217. (@pxref{Structures}), and @dfn{unions}, which specify multiple ways
  3218. to look at the same memory space (@pxref{Unions}). @dfn{Enumerations}
  3219. are collections of named integer codes (@pxref{Enumeration Types}).
  3220. @dfn{Array types} in C are used for allocating space for objects,
  3221. but C does not permit operating on an array value as a whole. @xref{Arrays}.
  3222. @node Type Designators
  3223. @section Type Designators
  3224. @cindex type designator
  3225. Some C constructs require a way to designate a specific data type
  3226. independent of any particular variable or expression which has that
  3227. type. The way to do this is with a @dfn{type designator}. The
  3228. constucts that need one include casts (@pxref{Explicit Type
  3229. Conversion}) and @code{sizeof} (@pxref{Type Size}).
  3230. We also use type designators to talk about the type of a value in C,
  3231. so you will see many type designators in this manual. When we say,
  3232. ``The value has type @code{int},'' @code{int} is a type designator.
  3233. To make the designator for any type, imagine a variable declaration
  3234. for a variable of that type and delete the variable name and the final
  3235. semicolon.
  3236. For example, to designate the type of full-word integers, we start
  3237. with the declaration for a variable @code{foo} with that type,
  3238. which is this:
  3239. @example
  3240. int foo;
  3241. @end example
  3242. @noindent
  3243. Then we delete the variable name @code{foo} and the semicolon, leaving
  3244. @code{int}---exactly the keyword used in such a declaration.
  3245. Therefore, the type designator for this type is @code{int}.
  3246. What about long unsigned integers? From the declaration
  3247. @example
  3248. unsigned long int foo;
  3249. @end example
  3250. @noindent
  3251. we determine that the designator is @code{unsigned long int}.
  3252. Following this procedure, the designator for any primitive type is
  3253. simply the set of keywords which specifies that type in a declaration.
  3254. The same is true for compound types such as structures, unions, and
  3255. enumerations.
  3256. Designators for pointer types do follow the rule of deleting the
  3257. variable name and semicolon, but the result is not so simple.
  3258. @xref{Pointer Type Designators}, as part of the chapter about
  3259. pointers. @xref{Array Type Designators}), for designators for array
  3260. types.
  3261. To understand what type a designator stands for, imagine a variable
  3262. name inserted into the right place in the designator to make a valid
  3263. declaration. What type would that variable be declared as? That is the
  3264. type the designator designates.
  3265. @node Constants
  3266. @chapter Constants
  3267. @cindex constants
  3268. A @dfn{constant} is an expression that stands for a specific value by
  3269. explicitly representing the desired value. C allows constants for
  3270. numbers, characters, and strings. We have already seen numeric and
  3271. string constants in the examples.
  3272. @menu
  3273. * Integer Constants:: Literal integer values.
  3274. * Integer Const Type:: Types of literal integer values.
  3275. * Floating Constants:: Literal floating-point values.
  3276. * Imaginary Constants:: Literal imaginary number values.
  3277. * Invalid Numbers:: Avoiding preprocessing number misconceptions.
  3278. * Character Constants:: Literal character values.
  3279. * String Constants:: Literal string values.
  3280. * UTF-8 String Constants:: Literal UTF-8 string values.
  3281. * Unicode Character Codes:: Unicode characters represented
  3282. in either UTF-16 or UTF-32.
  3283. * Wide Character Constants:: Literal characters values larger than 8 bits.
  3284. * Wide String Constants:: Literal string values made up of
  3285. 16- or 32-bit characters.
  3286. @end menu
  3287. @node Integer Constants
  3288. @section Integer Constants
  3289. @cindex integer constants
  3290. @cindex constants, integer
  3291. An integer constant consists of a number to specify the value,
  3292. followed optionally by suffix letters to specify the data type.
  3293. The simplest integer constants are numbers written in base 10
  3294. (decimal), such as @code{5}, @code{77}, and @code{403}. A decimal
  3295. constant cannot start with the character @samp{0} (zero) because
  3296. that makes the constant octal.
  3297. You can get the effect of a negative integer constant by putting a
  3298. minus sign at the beginning. Grammatically speaking, that is an
  3299. arithmetic expression rather than a constant, but it behaves just like
  3300. a true constant.
  3301. Integer constants can also be written in octal (base 8), hexadecimal
  3302. (base 16), or binary (base 2). An octal constant starts with the
  3303. character @samp{0} (zero), followed by any number of octal digits
  3304. (@samp{0} to @samp{7}):
  3305. @example
  3306. 0 // @r{zero}
  3307. 077 // @r{63}
  3308. 0403 // @r{259}
  3309. @end example
  3310. @noindent
  3311. Pedantically speaking, the constant @code{0} is an octal constant, but
  3312. we can think of it as decimal; it has the same value either way.
  3313. A hexadecimal constant starts with @samp{0x} (upper or lower case)
  3314. followed by hex digits (@samp{0} to @samp{9}, as well as @samp{a}
  3315. through @samp{f} in upper or lower case):
  3316. @example
  3317. 0xff // @r{255}
  3318. 0XA0 // @r{160}
  3319. 0xffFF // @r{65535}
  3320. @end example
  3321. @cindex binary integer constants
  3322. A binary constant starts with @samp{0b} (upper or lower case) followed
  3323. by bits (each represented by the characters @samp{0} or @samp{1}):
  3324. @example
  3325. 0b101 // @r{5}
  3326. @end example
  3327. Binary constants are a GNU C extension, not part of the C standard.
  3328. Sometimes a space is needed after an integer constant to avoid
  3329. lexical confusion with the following tokens. @xref{Invalid Numbers}.
  3330. @node Integer Const Type
  3331. @section Integer Constant Data Types
  3332. @cindex integer constant data types
  3333. @cindex constant data types, integer
  3334. @cindex types of integer constants
  3335. The type of an integer constant is normally @code{int}, if the value
  3336. fits in that type, but here are the complete rules. The type
  3337. of an integer constant is the first one in this sequence that can
  3338. properly represent the value,
  3339. @enumerate
  3340. @item
  3341. @code{int}
  3342. @item
  3343. @code{unsigned int}
  3344. @item
  3345. @code{long int}
  3346. @item
  3347. @code{unsigned long int}
  3348. @item
  3349. @code{long long int}
  3350. @item
  3351. @code{unsigned long long int}
  3352. @end enumerate
  3353. @noindent
  3354. and that isn't excluded by the following rules.
  3355. If the constant has @samp{l} or @samp{L} as a suffix, that excludes the
  3356. first two types (non-@code{long}).
  3357. If the constant has @samp{ll} or @samp{LL} as a suffix, that excludes
  3358. first four types (non-@code{long long}).
  3359. If the constant has @samp{u} or @samp{U} as a suffix, that excludes
  3360. the signed types.
  3361. Otherwise, if the constant is decimal, that excludes the unsigned
  3362. types.
  3363. @c ### This said @code{unsigned int} is excluded.
  3364. @c ### See 17 April 2016
  3365. Here are some examples of the suffixes.
  3366. @example
  3367. 3000000000u // @r{three billion as @code{unsigned int}.}
  3368. 0LL // @r{zero as a @code{long long int}.}
  3369. 0403l // @r{259 as a @code{long int}.}
  3370. @end example
  3371. Suffixes in integer constants are rarely used. When the precise type
  3372. is important, it is cleaner to convert explicitly (@pxref{Explicit
  3373. Type Conversion}).
  3374. @xref{Integer Types}.
  3375. @node Floating Constants
  3376. @section Floating-Point Constants
  3377. @cindex floating-point constants
  3378. @cindex constants, floating-point
  3379. A floating-point constant must have either a decimal point, an
  3380. exponent-of-ten, or both; they distinguish it from an integer
  3381. constant.
  3382. To indicate an exponent, write @samp{e} or @samp{E}. The exponent
  3383. value follows. It is always written as a decimal number; it can
  3384. optionally start with a sign. The exponent @var{n} means to multiply
  3385. the constant's value by ten to the @var{n}th power.
  3386. Thus, @samp{1500.0}, @samp{15e2}, @samp{15e+2}, @samp{15.0e2},
  3387. @samp{1.5e+3}, @samp{.15e4}, and @samp{15000e-1} are six ways of
  3388. writing a floating-point number whose value is 1500. They are all
  3389. equivalent.
  3390. Here are more examples with decimal points:
  3391. @example
  3392. 1.0
  3393. 1000.
  3394. 3.14159
  3395. .05
  3396. .0005
  3397. @end example
  3398. For each of them, here are some equivalent constants written with
  3399. exponents:
  3400. @example
  3401. 1e0, 1.0000e0
  3402. 100e1, 100e+1, 100E+1, 1e3, 10000e-1
  3403. 3.14159e0
  3404. 5e-2, .0005e+2, 5E-2, .0005E2
  3405. .05e-2
  3406. @end example
  3407. A floating-point constant normally has type @code{double}. You can
  3408. force it to type @code{float} by adding @samp{f} or @samp{F}
  3409. at the end. For example,
  3410. @example
  3411. 3.14159f
  3412. 3.14159e0f
  3413. 1000.f
  3414. 100E1F
  3415. .0005f
  3416. .05e-2f
  3417. @end example
  3418. Likewise, @samp{l} or @samp{L} at the end forces the constant
  3419. to type @code{long double}.
  3420. You can use exponents in hexadecimal floating constants, but since
  3421. @samp{e} would be interpreted as a hexadecimal digit, the character
  3422. @samp{p} or @samp{P} (for ``power'') indicates an exponent.
  3423. The exponent in a hexadecimal floating constant is a possibly-signed
  3424. decimal integer that specifies a power of 2 (@emph{not} 10 or 16) to
  3425. multiply into the number.
  3426. Here are some examples:
  3427. @example
  3428. @group
  3429. 0xAp2 // @r{40 in decimal}
  3430. 0xAp-1 // @r{5 in decimal}
  3431. 0x2.0Bp4 // @r{16.75 decimal}
  3432. 0xE.2p3 // @r{121 decimal}
  3433. 0x123.ABCp0 // @r{291.6708984375 in decimal}
  3434. 0x123.ABCp4 // @r{4666.734375 in decimal}
  3435. 0x100p-8 // @r{1}
  3436. 0x10p-4 // @r{1}
  3437. 0x1p+4 // @r{16}
  3438. 0x1p+8 // @r{256}
  3439. @end group
  3440. @end example
  3441. @xref{Floating-Point Data Types}.
  3442. @node Imaginary Constants
  3443. @section Imaginary Constants
  3444. @cindex imaginary constants
  3445. @cindex complex constants
  3446. @cindex constants, imaginary
  3447. A complex number consists of a real part plus an imaginary part.
  3448. (Either or both parts may be zero.) This section explains how to
  3449. write numeric constants with imaginary values. By adding these to
  3450. ordinary real-valued numeric constants, we can make constants with
  3451. complex values.
  3452. The simple way to write an imaginary-number constant is to attach the
  3453. suffix @samp{i} or @samp{I}, or @samp{j} or @samp{J}, to an integer or
  3454. floating-point constant. For example, @code{2.5fi} has type
  3455. @code{_Complex float} and @code{3i} has type @code{_Complex int}.
  3456. The four alternative suffix letters are all equivalent.
  3457. @cindex _Complex_I
  3458. The other way to write an imaginary constant is to multiply a real
  3459. constant by @code{_Complex_I}, which represents the imaginary number
  3460. i. Standard C doesn't support suffixing with @samp{i} or @samp{j}, so
  3461. this clunky way is needed.
  3462. To write a complex constant with a nonzero real part and a nonzero
  3463. imaginary part, write the two separately and add them, like this:
  3464. @example
  3465. 4.0 + 3.0i
  3466. @end example
  3467. @noindent
  3468. That gives the value 4 + 3i, with type @code{_Complex double}.
  3469. Such a sum can include multiple real constants, or none. Likewise, it
  3470. can include multiple imaginary constants, or none. For example:
  3471. @example
  3472. _Complex double foo, bar, quux;
  3473. foo = 2.0i + 4.0 + 3.0i; /* @r{Imaginary part is 5.0.} */
  3474. bar = 4.0 + 12.0; /* @r{Imaginary part is 0.0.} */
  3475. quux = 3.0i + 15.0i; /* @r{Real part is 0.0.} */
  3476. @end example
  3477. @xref{Complex Data Types}.
  3478. @node Invalid Numbers
  3479. @section Invalid Numbers
  3480. Some number-like constructs which are not really valid as numeric
  3481. constants are treated as numbers in preprocessing directives. If
  3482. these constructs appear outside of preprocessing, they are erroneous.
  3483. @xref{Preprocessing Tokens}.
  3484. Sometimes we need to insert spaces to separate tokens so that they
  3485. won't be combined into a single number-like construct. For example,
  3486. @code{0xE+12} is a preprocessing number that is not a valid numeric
  3487. constant, so it is a syntax error. If what we want is the three
  3488. tokens @code{@w{0xE + 12}}, we have to use those spaces as separators.
  3489. @node Character Constants
  3490. @section Character Constants
  3491. @cindex character constants
  3492. @cindex constants, character
  3493. @cindex escape sequence
  3494. A @dfn{character constant} is written with single quotes, as in
  3495. @code{'@var{c}'}. In the simplest case, @var{c} is a single ASCII
  3496. character that the constant should represent. The constant has type
  3497. @code{int}, and its value is the character code of that character.
  3498. For instance, @code{'a'} represents the character code for the letter
  3499. @samp{a}: 97, that is.
  3500. To put the @samp{'} character (single quote) in the character
  3501. constant, @dfn{quote} it with a backslash (@samp{\}). This character
  3502. constant looks like @code{'\''}. This sort of sequence, starting with
  3503. @samp{\}, is called an @dfn{escape sequence}---the backslash character
  3504. here functions as a kind of @dfn{escape character}.
  3505. To put the @samp{\} character (backslash) in the character constant,
  3506. quote it likewise with @samp{\} (another backslash). This character
  3507. constant looks like @code{'\\'}.
  3508. @cindex bell character
  3509. @cindex @samp{\a}
  3510. @cindex backspace
  3511. @cindex @samp{\b}
  3512. @cindex tab (ASCII character)
  3513. @cindex @samp{\t}
  3514. @cindex vertical tab
  3515. @cindex @samp{\v}
  3516. @cindex formfeed
  3517. @cindex @samp{\f}
  3518. @cindex newline
  3519. @cindex @samp{\n}
  3520. @cindex return (ASCII character)
  3521. @cindex @samp{\r}
  3522. @cindex escape (ASCII character)
  3523. @cindex @samp{\e}
  3524. Here are all the escape sequences that represent specific
  3525. characters in a character constant. The numeric values shown are
  3526. the corresponding ASCII character codes, as decimal numbers.
  3527. @example
  3528. '\a' @result{} 7 /* @r{alarm, @kbd{CTRL-g}} */
  3529. '\b' @result{} 8 /* @r{backspace, @key{BS}, @kbd{CTRL-h}} */
  3530. '\t' @result{} 9 /* @r{tab, @key{TAB}, @kbd{CTRL-i}} */
  3531. '\n' @result{} 10 /* @r{newline, @kbd{CTRL-j}} */
  3532. '\v' @result{} 11 /* @r{vertical tab, @kbd{CTRL-k}} */
  3533. '\f' @result{} 12 /* @r{formfeed, @kbd{CTRL-l}} */
  3534. '\r' @result{} 13 /* @r{carriage return, @key{RET}, @kbd{CTRL-m}} */
  3535. '\e' @result{} 27 /* @r{escape character, @key{ESC}, @kbd{CTRL-[}} */
  3536. '\\' @result{} 92 /* @r{backslash character, @kbd{\}} */
  3537. '\'' @result{} 39 /* @r{singlequote character, @kbd{'}} */
  3538. '\"' @result{} 34 /* @r{doublequote character, @kbd{"}} */
  3539. '\?' @result{} 63 /* @r{question mark, @kbd{?}} */
  3540. @end example
  3541. @samp{\e} is a GNU C extension; to stick to standard C, write @samp{\33}.
  3542. You can also write octal and hex character codes as
  3543. @samp{\@var{octalcode}} or @samp{\x@var{hexcode}}. Decimal is not an
  3544. option here, so octal codes do not need to start with @samp{0}.
  3545. The character constant's value has type @code{int}. However, the
  3546. character code is treated initially as a @code{char} value, which is
  3547. then converted to @code{int}. If the character code is greater than
  3548. 127 (@code{0177} in octal), the resulting @code{int} may be negative
  3549. on a platform where the type @code{char} is 8 bits long and signed.
  3550. @node String Constants
  3551. @section String Constants
  3552. @cindex string constants
  3553. @cindex constants, string
  3554. A @dfn{string constant} represents a series of characters. It starts
  3555. with @samp{"} and ends with @samp{"}; in between are the contents of
  3556. the string. Quoting special characters such as @samp{"}, @samp{\} and
  3557. newline in the contents works in string constants as in character
  3558. constants. In a string constant, @samp{'} does not need to be quoted.
  3559. A string constant defines an array of characters which contains the
  3560. specified characters followed by the null character (code 0). Using
  3561. the string constant is equivalent to using the name of an array with
  3562. those contents. In simple cases, the length in bytes of the string
  3563. constant is one greater than the number of characters written in it.
  3564. As with any array in C, using the string constant in an expression
  3565. converts the array to a pointer (@pxref{Pointers}) to the array's
  3566. first element (@pxref{Accessing Array Elements}). This pointer will
  3567. have type @code{char *} because it points to an element of type
  3568. @code{char}. @code{char *} is an example of a type designator for a
  3569. pointer type (@pxref{Pointer Type Designators}). That type is used
  3570. for strings generally, not just the strings expressed as constants
  3571. in a program.
  3572. Thus, the string constant @code{"Foo!"} is almost
  3573. equivalent to declaring an array like this
  3574. @example
  3575. char string_array_1[] = @{'F', 'o', 'o', '!', '\0' @};
  3576. @end example
  3577. @noindent
  3578. and then using @code{string_array_1} in the program. There
  3579. are two differences, however:
  3580. @itemize @bullet
  3581. @item
  3582. The string constant doesn't define a name for the array.
  3583. @item
  3584. The string constant is probably stored in a read-only area of memory.
  3585. @end itemize
  3586. Newlines are not allowed in the text of a string constant. The motive
  3587. for this prohibition is to catch the error of omitting the closing
  3588. @samp{"}. To put a newline in a constant string, write it as
  3589. @samp{\n} in the string constant.
  3590. A real null character in the source code inside a string constant
  3591. causes a warning. To put a null character in the middle of a string
  3592. constant, write @samp{\0} or @samp{\000}.
  3593. Consecutive string constants are effectively concatenated. Thus,
  3594. @example
  3595. "Fo" "o!" @r{is equivalent to} "Foo!"
  3596. @end example
  3597. This is useful for writing a string containing multiple lines,
  3598. like this:
  3599. @example
  3600. "This message is so long that it needs more than\n"
  3601. "a single line of text. C does not allow a newline\n"
  3602. "to represent itself in a string constant, so we have to\n"
  3603. "write \\n to put it in the string. For readability of\n"
  3604. "the source code, it is advisable to put line breaks in\n"
  3605. "the source where they occur in the contents of the\n"
  3606. "constant.\n"
  3607. @end example
  3608. The sequence of a backslash and a newline is ignored anywhere
  3609. in a C program, and that includes inside a string constant.
  3610. Thus, you can write multi-line string constants this way:
  3611. @example
  3612. "This is another way to put newlines in a string constant\n\
  3613. and break the line after them in the source code."
  3614. @end example
  3615. @noindent
  3616. However, concatenation is the recommended way to do this.
  3617. You can also write perverse string constants like this,
  3618. @example
  3619. "Fo\
  3620. o!"
  3621. @end example
  3622. @noindent
  3623. but don't do that---write it like this instead:
  3624. @example
  3625. "Foo!"
  3626. @end example
  3627. Be careful to avoid passing a string constant to a function that
  3628. modifies the string it receives. The memory where the string constant
  3629. is stored may be read-only, which would cause a fatal @code{SIGSEGV}
  3630. signal that normally terminates the function (@pxref{Signals}. Even
  3631. worse, the memory may not be read-only. Then the function might
  3632. modify the string constant, thus spoiling the contents of other string
  3633. constants that are supposed to contain the same value and are unified
  3634. by the compiler.
  3635. @node UTF-8 String Constants
  3636. @section UTF-8 String Constants
  3637. @cindex UTF-8 String Constants
  3638. Writing @samp{u8} immediately before a string constant, with no
  3639. intervening space, means to represent that string in UTF-8 encoding as
  3640. a sequence of bytes. UTF-8 represents ASCII characters with a single
  3641. byte, and represents non-ASCII Unicode characters (codes 128 and up)
  3642. as multibyte sequences. Here is an example of a UTF-8 constant:
  3643. @example
  3644. u8"A cónstàñt"
  3645. @end example
  3646. This constant occupies 13 bytes plus the terminating null,
  3647. because each of the accented letters is a two-byte sequence.
  3648. Concatenating an ordinary string with a UTF-8 string conceptually
  3649. produces another UTF-8 string. However, if the ordinary string
  3650. contains character codes 128 and up, the results cannot be relied on.
  3651. @node Unicode Character Codes
  3652. @section Unicode Character Codes
  3653. @cindex Unicode character codes
  3654. @cindex universal character names
  3655. You can specify Unicode characters, for individual character constants
  3656. or as part of string constants (@pxref{String Constants}), using
  3657. escape sequences. Use the @samp{\u} escape sequence with a 16-bit
  3658. hexadecimal Unicode character code. If the code value is too big for
  3659. 16 bits, use the @samp{\U} escape sequence with a 32-bit hexadecimal
  3660. Unicode character code. (These codes are called @dfn{universal
  3661. character names}.) For example,
  3662. @example
  3663. \u6C34 /* @r{16-bit code (UTF-16)} */
  3664. \U0010ABCD /* @r{32-bit code (UTF-32)} */
  3665. @end example
  3666. @noindent
  3667. One way to use these is in UTF-8 string constants (@pxref{UTF-8 String
  3668. Constants}). For instance,
  3669. @example
  3670. u8"fóó \u6C34 \U0010ABCD"
  3671. @end example
  3672. You can also use them in wide character constants (@pxref{Wide
  3673. Character Constants}), like this:
  3674. @example
  3675. u'\u6C34' /* @r{16-bit code} */
  3676. U'\U0010ABCD' /* @r{32-bit code} */
  3677. @end example
  3678. @noindent
  3679. and in wide string constants (@pxref{Wide String Constants}), like
  3680. this:
  3681. @example
  3682. u"\u6C34\u6C33" /* @r{16-bit code} */
  3683. U"\U0010ABCD" /* @r{32-bit code} */
  3684. @end example
  3685. Codes in the range of @code{D800} through @code{DFFF} are not valid
  3686. in Unicode. Codes less than @code{00A0} are also forbidden, except for
  3687. @code{0024}, @code{0040}, and @code{0060}; these characters are
  3688. actually ASCII control characters, and you can specify them with other
  3689. escape sequences (@pxref{Character Constants}).
  3690. @node Wide Character Constants
  3691. @section Wide Character Constants
  3692. @cindex wide character constants
  3693. @cindex constants, wide character
  3694. A @dfn{wide character constant} represents characters with more than 8
  3695. bits of character code. This is an obscure feature that we need to
  3696. document but that you probably won't ever use. If you're just
  3697. learning C, you may as well skip this section.
  3698. The original C wide character constant looks like @samp{L} (upper
  3699. case!) followed immediately by an ordinary character constant (with no
  3700. intervening space). Its data type is @code{wchar_t}, which is an
  3701. alias defined in @file{stddef.h} for one of the standard integer
  3702. types. Depending on the platform, it could be 16 bits or 32 bits. If
  3703. it is 16 bits, these character constants use the UTF-16 form of
  3704. Unicode; if 32 bits, UTF-32.
  3705. There are also Unicode wide character constants which explicitly
  3706. specify the width. These constants start with @samp{u} or @samp{U}
  3707. instead of @samp{L}. @samp{u} specifies a 16-bit Unicode wide
  3708. character constant, and @samp{U} a 32-bit Unicode wide character
  3709. constant. Their types are, respectively, @code{char16_t} and
  3710. @w{@code{char32_t}}; they are declared in the header file
  3711. @file{uchar.h}. These character constants are valid even if
  3712. @file{uchar.h} is not included, but some uses of them may be
  3713. inconvenient without including it to declare those type names.
  3714. The character represented in a wide character constant can be an
  3715. ordinary ASCII character. @code{L'a'}, @code{u'a'} and @code{U'a'}
  3716. are all valid, and they are all equal to @code{'a'}.
  3717. In all three kinds of wide character constants, you can write a
  3718. non-ASCII Unicode character in the constant itself; the constant's
  3719. value is the character's Unicode character code. Or you can specify
  3720. the Unicode character with an escape sequence (@pxref{Unicode
  3721. Character Codes}).
  3722. @node Wide String Constants
  3723. @section Wide String Constants
  3724. @cindex wide string constants
  3725. @cindex constants, wide string
  3726. A @dfn{wide string constant} stands for an array of 16-bit or 32-bit
  3727. characters. They are rarely used; if you're just
  3728. learning C, you may as well skip this section.
  3729. There are three kinds of wide string constants, which differ in the
  3730. data type used for each character in the string. Each wide string
  3731. constant is equivalent to an array of integers, but the data type of
  3732. those integers depends on the kind of wide string. Using the constant
  3733. in an expression will convert the array to a pointer to its first
  3734. element, as usual for arrays in C (@pxref{Accessing Array Elements}).
  3735. For each kind of wide string constant, we state here what type that
  3736. pointer will be.
  3737. @table @code
  3738. @item char16_t
  3739. This is a 16-bit Unicode wide string constant: each element is a
  3740. 16-bit Unicode character code with type @code{char16_t}, so the string
  3741. has the pointer type @code{char16_t@ *}. (That is a type designator;
  3742. @pxref{Pointer Type Designators}.) The constant is written as
  3743. @samp{u} (which must be lower case) followed (with no intervening
  3744. space) by a string constant with the usual syntax.
  3745. @item char32_t
  3746. This is a 32-bit Unicode wide string constant: each element is a
  3747. 32-bit Unicode character code, and the string has type @code{char32_t@ *}.
  3748. It's written as @samp{U} (which must be upper case) followed (with no
  3749. intervening space) by a string constant with the usual syntax.
  3750. @item wchar_t
  3751. This is the original kind of wide string constant. It's written as
  3752. @samp{L} (which must be upper case) followed (with no intervening
  3753. space) by a string constant with the usual syntax, and the string has
  3754. type @code{wchar_t@ *}.
  3755. The width of the data type @code{wchar_t} depends on the target
  3756. platform, which makes this kind of wide string somewhat less useful
  3757. than the newer kinds.
  3758. @end table
  3759. @code{char16_t} and @code{char32_t} are declared in the header file
  3760. @file{uchar.h}. @code{wchar_t} is declared in @file{stddef.h}.
  3761. Consecutive wide string constants of the same kind concatenate, just
  3762. like ordinary string constants. A wide string constant concatenated
  3763. with an ordinary string constant results in a wide string constant.
  3764. You can't concatenate two wide string constants of different kinds.
  3765. You also can't concatenate a wide string constant (of any kind) with a
  3766. UTF-8 string constant.
  3767. @node Type Size
  3768. @chapter Type Size
  3769. @cindex type size
  3770. @cindex size of type
  3771. @findex sizeof
  3772. Each data type has a @dfn{size}, which is the number of bytes
  3773. (@pxref{Storage}) that it occupies in memory. To refer to the size in
  3774. a C program, use @code{sizeof}. There are two ways to use it:
  3775. @table @code
  3776. @item sizeof @var{expression}
  3777. This gives the size of @var{expression}, based on its data type. It
  3778. does not calculate the value of @var{expression}, only its size, so if
  3779. @var{expression} includes side effects or function calls, they do not
  3780. happen. Therefore, @code{sizeof} is always a compile-time operation
  3781. that has zero run-time cost.
  3782. A value that is a bit field (@pxref{Bit Fields}) is not allowed as an
  3783. operand of @code{sizeof}.
  3784. For example,
  3785. @example
  3786. double a;
  3787. i = sizeof a + 10;
  3788. @end example
  3789. @noindent
  3790. sets @code{i} to 18 on most computers because @code{a} occupies 8 bytes.
  3791. Here's how to determine the number of elements in an array
  3792. @code{array}:
  3793. @example
  3794. (sizeof array / sizeof array[0])
  3795. @end example
  3796. @noindent
  3797. The expression @code{sizeof array} gives the size of the array, not
  3798. the size of a pointer to an element. However, if @var{expression} is
  3799. a function parameter that was declared as an array, that
  3800. variable really has a pointer type (@pxref{Array Parm Pointer}), so
  3801. the result is the size of that pointer.
  3802. @item sizeof (@var{type})
  3803. This gives the size of @var{type}.
  3804. For example,
  3805. @example
  3806. i = sizeof (double) + 10;
  3807. @end example
  3808. @noindent
  3809. is equivalent to the previous example.
  3810. You can't apply @code{sizeof} to an incomplete type (@pxref{Incomplete
  3811. Types}), nor @code{void}. Using it on a function type gives 1 in GNU
  3812. C, which makes adding an integer to a function pointer work as desired
  3813. (@pxref{Pointer Arithmetic}).
  3814. @end table
  3815. @strong{Warning}: When you use @code{sizeof} with a type
  3816. instead of an expression, you must write parentheses around the type.
  3817. @strong{Warning}: When applying @code{sizeof} to the result of a cast
  3818. (@pxref{Explicit Type Conversion}), you must write parentheses around
  3819. the cast expression to avoid an ambiguity in the grammar of C@.
  3820. Specifically,
  3821. @example
  3822. sizeof (int) -x
  3823. @end example
  3824. @noindent
  3825. parses as
  3826. @example
  3827. (sizeof (int)) - x
  3828. @end example
  3829. @noindent
  3830. If what you want is
  3831. @example
  3832. sizeof ((int) -x)
  3833. @end example
  3834. @noindent
  3835. you must write it that way, with parentheses.
  3836. The data type of the value of the @code{sizeof} operator is always one
  3837. of the unsigned integer types; which one of those types depends on the
  3838. machine. The header file @code{stddef.h} defines the typedef name
  3839. @code{size_t} as an alias for this type. @xref{Defining Typedef
  3840. Names}.
  3841. @node Pointers
  3842. @chapter Pointers
  3843. @cindex pointers
  3844. Among high-level languages, C is rather low level, close to the
  3845. machine. This is mainly because it has explicit @dfn{pointers}. A
  3846. pointer value is the numeric address of data in memory. The type of
  3847. data to be found at that address is specified by the data type of the
  3848. pointer itself. The unary operator @samp{*} gets the data that a
  3849. pointer points to---this is called @dfn{dereferencing the pointer}.
  3850. C also allows pointers to functions, but since there are some
  3851. differences in how they work, we treat them later. @xref{Function
  3852. Pointers}.
  3853. @menu
  3854. * Address of Data:: Using the ``address-of'' operator.
  3855. * Pointer Types:: For each type, there is a pointer type.
  3856. * Pointer Declarations:: Declaring variables with pointer types.
  3857. * Pointer Type Designators:: Designators for pointer types.
  3858. * Pointer Dereference:: Accessing what a pointer points at.
  3859. * Null Pointers:: Pointers which do not point to any object.
  3860. * Invalid Dereference:: Dereferencing null or invalid pointers.
  3861. * Void Pointers:: Totally generic pointers, can cast to any.
  3862. * Pointer Comparison:: Comparing memory address values.
  3863. * Pointer Arithmetic:: Computing memory address values.
  3864. * Pointers and Arrays:: Using pointer syntax instead of array syntax.
  3865. * Pointer Arithmetic Low Level:: More about computing memory address values.
  3866. * Pointer Increment/Decrement:: Incrementing and decrementing pointers.
  3867. * Pointer Arithmetic Drawbacks:: A common pointer bug to watch out for.
  3868. * Pointer-Integer Conversion:: Converting pointer types to integer types.
  3869. * Printing Pointers:: Using @code{printf} for a pointer's value.
  3870. @end menu
  3871. @node Address of Data
  3872. @section Address of Data
  3873. @cindex address-of operator
  3874. The most basic way to make a pointer is with the ``address-of''
  3875. operator, @samp{&}. Let's suppose we have these variables available:
  3876. @example
  3877. int i;
  3878. double a[5];
  3879. @end example
  3880. Now, @code{&i} gives the address of the variable @code{i}---a pointer
  3881. value that points to @code{i}'s location---and @code{&a[3]} gives the
  3882. address of the element 3 of @code{a}. (It is actually the fourth
  3883. element in the array, since the first element has index 0.)
  3884. The address-of operator is unusual because it operates on a place to
  3885. store a value (an lvalue, @pxref{Lvalues}), not on the value currently
  3886. stored there. (The left argument of a simple assignment is unusual in
  3887. the same way.) You can use it on any lvalue except a bit field
  3888. (@pxref{Bit Fields}) or a constructor (@pxref{Structure
  3889. Constructors}).
  3890. @node Pointer Types
  3891. @section Pointer Types
  3892. For each data type @var{t}, there is a type for pointers to type
  3893. @var{t}. For these variables,
  3894. @example
  3895. int i;
  3896. double a[5];
  3897. @end example
  3898. @itemize @bullet
  3899. @item
  3900. @code{i} has type @code{int}; we say
  3901. @code{&i} is a ``pointer to @code{int}.''
  3902. @item
  3903. @code{a} has type @code{double[5]}; we say @code{&a} is a ``pointer to
  3904. arrays of five @code{double}s.''
  3905. @item
  3906. @code{a[3]} has type @code{double}; we say @code{&a[3]} is a ``pointer
  3907. to @code{double}.''
  3908. @end itemize
  3909. @node Pointer Declarations
  3910. @section Pointer-Variable Declarations
  3911. The way to declare that a variable @code{foo} points to type @var{t} is
  3912. @example
  3913. @var{t} *foo;
  3914. @end example
  3915. To remember this syntax, think ``if you dereference @code{foo}, using
  3916. the @samp{*} operator, what you get is type @var{t}. Thus, @code{foo}
  3917. points to type @var{t}.''
  3918. Thus, we can declare variables that hold pointers to these three
  3919. types, like this:
  3920. @example
  3921. int *ptri; /* @r{Pointer to @code{int}.} */
  3922. double *ptrd; /* @r{Pointer to @code{double}.} */
  3923. double (*ptrda)[5]; /* @r{Pointer to @code{double[5]}.} */
  3924. @end example
  3925. @samp{int *ptri;} means, ``if you dereference @code{ptri}, you get an
  3926. @code{int}.'' @samp{double (*ptrda)[5];} means, ``if you dereference
  3927. @code{ptrda}, then subscript it by an integer less than 5, you get a
  3928. @code{double}.'' The parentheses express the point that you would
  3929. dereference it first, then subscript it.
  3930. Contrast the last one with this:
  3931. @example
  3932. double *aptrd[5]; /* @r{Array of five pointers to @code{double}.} */
  3933. @end example
  3934. @noindent
  3935. Because @samp{*} has higher syntactic precedence than subscripting,
  3936. you would subscript @code{aptrd} then dereference it. Therefore, it
  3937. declares an array of pointers, not a pointer.
  3938. @node Pointer Type Designators
  3939. @section Pointer-Type Designators
  3940. Every type in C has a designator; you make it by deleting the variable
  3941. name and the semicolon from a declaration (@pxref{Type
  3942. Designators}). Here are the designators for the pointer
  3943. types of the example declarations in the previous section:
  3944. @example
  3945. int * /* @r{Pointer to @code{int}.} */
  3946. double * /* @r{Pointer to @code{double}.} */
  3947. double (*)[5] /* @r{Pointer to @code{double[5]}.} */
  3948. @end example
  3949. Remember, to understand what type a designator stands for, imagine the
  3950. variable name that would be in the declaration, and figure out what
  3951. type it would declare that variable with. @code{double (*)[5]} can
  3952. only come from @code{double (*@var{variable})[5]}, so it's a pointer
  3953. which, when dereferenced, gives an array of 5 @code{double}s.
  3954. @node Pointer Dereference
  3955. @section Dereferencing Pointers
  3956. @cindex dereferencing pointers
  3957. @cindex pointer dereferencing
  3958. The main use of a pointer value is to @dfn{dereference it} (access the
  3959. data it points at) with the unary @samp{*} operator. For instance,
  3960. @code{*&i} is the value at @code{i}'s address---which is just
  3961. @code{i}. The two expressions are equivalent, provided @code{&i} is
  3962. valid.
  3963. A pointer-dereference expression whose type is data (not a function)
  3964. is an lvalue.
  3965. Pointers become really useful when we store them somewhere and use
  3966. them later. Here's a simple example to illustrate the practice:
  3967. @example
  3968. @{
  3969. int i;
  3970. int *ptr;
  3971. ptr = &i;
  3972. i = 5;
  3973. @r{@dots{}}
  3974. return *ptr; /* @r{Returns 5, fetched from @code{i}.} */
  3975. @}
  3976. @end example
  3977. This shows how to declare the variable @code{ptr} as type
  3978. @code{int *} (pointer to @code{int}), store a pointer value into it
  3979. (pointing at @code{i}), and use it later to get the value of the
  3980. object it points at (the value in @code{i}).
  3981. If anyone can provide a useful example which is this basic,
  3982. I would be grateful.
  3983. @node Null Pointers
  3984. @section Null Pointers
  3985. @cindex null pointers
  3986. @cindex pointers, null
  3987. @c ???stdio loads sttddef
  3988. A pointer value can be @dfn{null}, which means it does not point to
  3989. any object. The cleanest way to get a null pointer is by writing
  3990. @code{NULL}, a standard macro defined in @file{stddef.h}. You can
  3991. also do it by casting 0 to the desired pointer type, as in
  3992. @code{(char *) 0}. (The cast operator performs explicit type conversion;
  3993. @xref{Explicit Type Conversion}.)
  3994. You can store a null pointer in any lvalue whose data type
  3995. is a pointer type:
  3996. @example
  3997. char *foo;
  3998. foo = NULL;
  3999. @end example
  4000. These two, if consecutive, can be combined into a declaration with
  4001. initializer,
  4002. @example
  4003. char *foo = NULL;
  4004. @end example
  4005. You can also explicitly cast @code{NULL} to the specific pointer type
  4006. you want---it makes no difference.
  4007. @example
  4008. char *foo;
  4009. foo = (char *) NULL;
  4010. @end example
  4011. To test whether a pointer is null, compare it with zero or
  4012. @code{NULL}, as shown here:
  4013. @example
  4014. if (p != NULL)
  4015. /* @r{@code{p} is not null.} */
  4016. operate (p);
  4017. @end example
  4018. Since testing a pointer for not being null is basic and frequent, all
  4019. but beginners in C will understand the conditional without need for
  4020. @code{!= NULL}:
  4021. @example
  4022. if (p)
  4023. /* @r{@code{p} is not null.} */
  4024. operate (p);
  4025. @end example
  4026. @node Invalid Dereference
  4027. @section Dereferencing Null or Invalid Pointers
  4028. Trying to dereference a null pointer is an error. On most platforms,
  4029. it generally causes a signal, usually @code{SIGSEGV}
  4030. (@pxref{Signals}).
  4031. @example
  4032. char *foo = NULL;
  4033. c = *foo; /* @r{This causes a signal and terminates.} */
  4034. @end example
  4035. @noindent
  4036. Likewise a pointer that has the wrong alignment for the target data type
  4037. (on most types of computer), or points to a part of memory that has
  4038. not been allocated in the process's address space.
  4039. The signal terminates the program, unless the program has arranged to
  4040. handle the signal (@pxref{Signal Handling, The GNU C Library, , libc,
  4041. The GNU C Library Reference Manual}).
  4042. However, the signal might not happen if the dereference is optimized
  4043. away. In the example above, if you don't subsequently use the value
  4044. of @code{c}, GCC might optimize away the code for @code{*foo}. You
  4045. can prevent such optimization using the @code{volatile} qualifier, as
  4046. shown here:
  4047. @example
  4048. volatile char *p;
  4049. volatile char c;
  4050. c = *p;
  4051. @end example
  4052. You can use this to test whether @code{p} points to unallocated
  4053. memory. Set up a signal handler first, so the signal won't terminate
  4054. the program.
  4055. @node Void Pointers
  4056. @section Void Pointers
  4057. @cindex void pointers
  4058. @cindex pointers, void
  4059. The peculiar type @code{void *}, a pointer whose target type is
  4060. @code{void}, is used often in C@. It represents a pointer to
  4061. we-don't-say-what. Thus,
  4062. @example
  4063. void *numbered_slot_pointer (int);
  4064. @end example
  4065. @noindent
  4066. declares a function @code{numbered_slot_pointer} that takes an
  4067. integer parameter and returns a pointer, but we don't say what type of
  4068. data it points to.
  4069. With type @code{void *}, you can pass the pointer around and test
  4070. whether it is null. However, dereferencing it gives a @code{void}
  4071. value that can't be used (@pxref{The Void Type}). To dereference the
  4072. pointer, first convert it to some other pointer type.
  4073. Assignments convert @code{void *} automatically to any other pointer
  4074. type, if the left operand has a pointer type; for instance,
  4075. @example
  4076. @{
  4077. int *p;
  4078. /* @r{Converts return value to @code{int *}.} */
  4079. p = numbered_slot_pointer (5);
  4080. @r{@dots{}}
  4081. @}
  4082. @end example
  4083. Passing an argument of type @code{void *} for a parameter that has a
  4084. pointer type also converts. For example, supposing the function
  4085. @code{hack} is declared to require type @code{float *} for its
  4086. argument, this will convert the null pointer to that type.
  4087. @example
  4088. /* @r{Declare @code{hack} that way.}
  4089. @r{We assume it is defined somewhere else.} */
  4090. void hack (float *);
  4091. @dots{}
  4092. /* @r{Now call @code{hack}.} */
  4093. @{
  4094. /* @r{Converts return value of @code{numbered_slot_pointer}}
  4095. @r{to @code{float *} to pass it to @code{hack}.} */
  4096. hack (numbered_slot_pointer (5));
  4097. @r{@dots{}}
  4098. @}
  4099. @end example
  4100. You can also convert to another pointer type with an explicit cast
  4101. (@pxref{Explicit Type Conversion}), like this:
  4102. @example
  4103. (int *) numbered_slot_pointer (5)
  4104. @end example
  4105. Here is an example which decides at run time which pointer
  4106. type to convert to:
  4107. @example
  4108. void
  4109. extract_int_or_double (void *ptr, bool its_an_int)
  4110. @{
  4111. if (its_an_int)
  4112. handle_an_int (*(int *)ptr);
  4113. else
  4114. handle_a_double (*(double *)ptr);
  4115. @}
  4116. @end example
  4117. The expression @code{*(int *)ptr} means to convert @code{ptr}
  4118. to type @code{int *}, then dereference it.
  4119. @node Pointer Comparison
  4120. @section Pointer Comparison
  4121. @cindex pointer comparison
  4122. @cindex comparison, pointer
  4123. Two pointer values are equal if they point to the same location, or if
  4124. they are both null. You can test for this with @code{==} and
  4125. @code{!=}. Here's a trivial example:
  4126. @example
  4127. @{
  4128. int i;
  4129. int *p, *q;
  4130. p = &i;
  4131. q = &i;
  4132. if (p == q)
  4133. printf ("This will be printed.\n");
  4134. if (p != q)
  4135. printf ("This won't be printed.\n");
  4136. @}
  4137. @end example
  4138. Ordering comparisons such as @code{>} and @code{>=} operate on
  4139. pointers by converting them to unsigned integers. The C standard says
  4140. the two pointers must point within the same object in memory, but on
  4141. GNU/Linux systems these operations simply compare the numeric values
  4142. of the pointers.
  4143. The pointer values to be compared should in principle have the same type, but
  4144. they are allowed to differ in limited cases. First of all, if the two
  4145. pointers' target types are nearly compatible (@pxref{Compatible
  4146. Types}), the comparison is allowed.
  4147. If one of the operands is @code{void *} (@pxref{Void Pointers}) and
  4148. the other is another pointer type, the comparison operator converts
  4149. the @code{void *} pointer to the other type so as to compare them.
  4150. (In standard C, this is not allowed if the other type is a function
  4151. pointer type, but that works in GNU C@.)
  4152. Comparison operators also allow comparing the integer 0 with a pointer
  4153. value. Thus works by converting 0 to a null pointer of the same type
  4154. as the other operand.
  4155. @node Pointer Arithmetic
  4156. @section Pointer Arithmetic
  4157. @cindex pointer arithmetic
  4158. @cindex arithmetic, pointer
  4159. Adding an integer (positive or negative) to a pointer is valid in C@.
  4160. It assumes that the pointer points to an element in an array, and
  4161. advances or retracts the pointer across as many array elements as the
  4162. integer specifies. Here is an example, in which adding a positive
  4163. integer advances the pointer to a later element in the same array.
  4164. @example
  4165. void
  4166. incrementing_pointers ()
  4167. @{
  4168. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4169. int elt0, elt1, elt4;
  4170. int *p = &array[0];
  4171. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4172. elt0 = *p;
  4173. ++p;
  4174. /* @r{Now @code{p} points at element 1. Fetch it.} */
  4175. elt1 = *p;
  4176. p += 3;
  4177. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4178. elt4 = *p;
  4179. printf ("elt0 %d elt1 %d elt4 %d.\n",
  4180. elt0, elt1, elt4);
  4181. /* @r{Prints elt0 45 elt1 29 elt4 123456.} */
  4182. @}
  4183. @end example
  4184. Here's an example where adding a negative integer retracts the pointer
  4185. to an earlier element in the same array.
  4186. @example
  4187. void
  4188. decrementing_pointers ()
  4189. @{
  4190. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4191. int elt0, elt3, elt4;
  4192. int *p = &array[4];
  4193. /* @r{Now @code{p} points at element 4 (the last). Fetch it.} */
  4194. elt4 = *p;
  4195. --p;
  4196. /* @r{Now @code{p} points at element 3. Fetch it.} */
  4197. elt3 = *p;
  4198. p -= 3;
  4199. /* @r{Now @code{p} points at element 0. Fetch it.} */
  4200. elt0 = *p;
  4201. printf ("elt0 %d elt3 %d elt4 %d.\n",
  4202. elt0, elt3, elt4);
  4203. /* @r{Prints elt0 45 elt3 -3 elt4 123456.} */
  4204. @}
  4205. @end example
  4206. If one pointer value was made by adding an integer to another
  4207. pointer value, it should be possible to subtract the pointer values
  4208. and recover that integer. That works too in C@.
  4209. @example
  4210. void
  4211. subtract_pointers ()
  4212. @{
  4213. int array[5] = @{ 45, 29, 104, -3, 123456 @};
  4214. int *p0, *p3, *p4;
  4215. int *p = &array[4];
  4216. /* @r{Now @code{p} points at element 4 (the last). Save the value.} */
  4217. p4 = p;
  4218. --p;
  4219. /* @r{Now @code{p} points at element 3. Save the value.} */
  4220. p3 = p;
  4221. p -= 3;
  4222. /* @r{Now @code{p} points at element 0. Save the value.} */
  4223. p0 = p;
  4224. printf ("%d, %d, %d, %d\n",
  4225. p4 - p0, p0 - p0, p3 - p0, p0 - p3);
  4226. /* @r{Prints 4, 0, 3, -3.} */
  4227. @}
  4228. @end example
  4229. The addition operation does not know where arrays are. All it does is
  4230. add the integer (multiplied by object size) to the value of the
  4231. pointer. When the initial pointer and the result point into a single
  4232. array, the result is well-defined.
  4233. @strong{Warning:} Only experts should do pointer arithmetic involving pointers
  4234. into different memory objects.
  4235. The difference between two pointers has type @code{int}, or
  4236. @code{long} if necessary (@pxref{Integer Types}). The clean way to
  4237. declare it is to use the typedef name @code{ptrdiff_t} defined in the
  4238. file @file{stddef.h}.
  4239. This definition of pointer subtraction is consistent with
  4240. pointer-integer addition, in that @code{(p3 - p1) + p1} equals
  4241. @code{p3}, as in ordinary algebra.
  4242. In standard C, addition and subtraction are not allowed on @code{void
  4243. *}, since the target type's size is not defined in that case.
  4244. Likewise, they are not allowed on pointers to function types.
  4245. However, these operations work in GNU C, and the ``size of the target
  4246. type'' is taken as 1.
  4247. @node Pointers and Arrays
  4248. @section Pointers and Arrays
  4249. @cindex pointers and arrays
  4250. @cindex arrays and pointers
  4251. The clean way to refer to an array element is
  4252. @code{@var{array}[@var{index}]}. Another, complicated way to do the
  4253. same job is to get the address of that element as a pointer, then
  4254. dereference it: @code{* (&@var{array}[0] + @var{index})} (or
  4255. equivalently @code{* (@var{array} + @var{index})}). This first gets a
  4256. pointer to element zero, then increments it with @code{+} to point to
  4257. the desired element, then gets the value from there.
  4258. That pointer-arithmetic construct is the @emph{definition} of square
  4259. brackets in C@. @code{@var{a}[@var{b}]} means, by definition,
  4260. @code{*(@var{a} + @var{b})}. This definition uses @var{a} and @var{b}
  4261. symmetrically, so one must be a pointer and the other an integer; it
  4262. does not matter which comes first.
  4263. Since indexing with square brackets is defined in terms of addition
  4264. and dereference, that too is symmetrical. Thus, you can write
  4265. @code{3[array]} and it is equivalent to @code{array[3]}. However, it
  4266. would be foolish to write @code{3[array]}, since it has no advantage
  4267. and could confuse people who read the code.
  4268. It may seem like a discrepancy that the definition @code{*(@var{a} +
  4269. @var{b})} requires a pointer, but @code{array[3]} uses an array value
  4270. instead. Why is this valid? The name of the array, when used by
  4271. itself as an expression (other than in @code{sizeof}), stands for a
  4272. pointer to the arrays's zeroth element. Thus, @code{array + 3}
  4273. converts @code{array} implicitly to @code{&array[0]}, and the result
  4274. is a pointer to element 3, equivalent to @code{&array[3]}.
  4275. Since square brackets are defined in terms of such addition,
  4276. @code{array[3]} first converts @code{array} to a pointer. That's why
  4277. it works to use an array directly in that construct.
  4278. @node Pointer Arithmetic Low Level
  4279. @section Pointer Arithmetic at Low Level
  4280. @cindex pointer arithmetic, low level
  4281. @cindex low level pointer arithmetic
  4282. The behavior of pointer arithmetic is theoretically defined only when
  4283. the pointer values all point within one object allocated in memory.
  4284. But the addition and subtraction operators can't tell whether the
  4285. pointer values are all within one object. They don't know where
  4286. objects start and end. So what do they really do?
  4287. Adding pointer @var{p} to integer @var{i} treats @var{p} as a memory
  4288. address, which is in fact an integer---call it @var{pint}. It treats
  4289. @var{i} as a number of elements of the type that @var{p} points to.
  4290. These elements' sizes add up to @code{@var{i} * sizeof (*@var{p})}.
  4291. So the sum, as an integer, is @code{@var{pint} + @var{i} * sizeof
  4292. (*@var{p})}. This value is reinterpreted as a pointer like @var{p}.
  4293. If the starting pointer value @var{p} and the result do not point at
  4294. parts of the same object, the operation is not officially legitimate,
  4295. and C code is not ``supposed'' to do it. But you can do it anyway,
  4296. and it gives precisely the results described by the procedure above.
  4297. In some special situations it can do something useful, but non-wizards
  4298. should avoid it.
  4299. Here's a function to offset a pointer value @emph{as if} it pointed to
  4300. an object of any given size, by explicitly performing that calculation:
  4301. @example
  4302. #include <stdint.h>
  4303. void *
  4304. ptr_add (void *p, int i, int objsize)
  4305. @{
  4306. intptr_t p_address = (long) p;
  4307. intptr_t totalsize = i * objsize;
  4308. intptr_t new_address = p_address + totalsize;
  4309. return (void *) new_address;
  4310. @}
  4311. @end example
  4312. @noindent
  4313. @cindex @code{intptr_t}
  4314. This does the same job as @code{@var{p} + @var{i}} with the proper
  4315. pointer type for @var{p}. It uses the type @code{intptr_t}, which is
  4316. defined in the header file @file{stdint.h}. (In practice, @code{long
  4317. long} would always work, but it is cleaner to use @code{intptr_t}.)
  4318. @node Pointer Increment/Decrement
  4319. @section Pointer Increment and Decrement
  4320. @cindex pointer increment and decrement
  4321. @cindex incrementing pointers
  4322. @cindex decrementing pointers
  4323. The @samp{++} operator adds 1 to a variable. We have seen it for
  4324. integers (@pxref{Increment/Decrement}), but it works for pointers too.
  4325. For instance, suppose we have a series of positive integers,
  4326. terminated by a zero, and we want to add them all up.
  4327. @example
  4328. int
  4329. sum_array_till_0 (int *p)
  4330. @{
  4331. int sum = 0;
  4332. for (;;)
  4333. @{
  4334. /* @r{Fetch the next integer.} */
  4335. int next = *p++;
  4336. /* @r{Exit the loop if it's 0.} */
  4337. if (next == 0)
  4338. break;
  4339. /* @r{Add it into running total.} */
  4340. sum += next;
  4341. @}
  4342. return sum;
  4343. @}
  4344. @end example
  4345. @noindent
  4346. The statement @samp{break;} will be explained further on (@pxref{break
  4347. Statement}). Used in this way, it immediately exits the surrounding
  4348. @code{for} statement.
  4349. @code{*p++} parses as @code{*(p++)}, because a postfix operator always
  4350. takes precedence over a prefix operator. Therefore, it dereferences
  4351. @code{p}, and increments @code{p} afterwards. Incrementing a variable
  4352. means adding 1 to it, as in @code{p = p + 1}. Since @code{p} is a
  4353. pointer, adding 1 to it advances it by the width of the datum it
  4354. points to---in this case, one @code{int}. Therefore, each iteration
  4355. of the loop picks up the next integer from the series and puts it into
  4356. @code{next}.
  4357. This @code{for}-loop has no initialization expression since @code{p}
  4358. and @code{sum} are already initialized, it has no end-test since the
  4359. @samp{break;} statement will exit it, and needs no expression to
  4360. advance it since that's done within the loop by incrementing @code{p}
  4361. and @code{sum}. Thus, those three expressions after @code{for} are
  4362. left empty.
  4363. Another way to write this function is by keeping the parameter value unchanged
  4364. and using indexing to access the integers in the table.
  4365. @example
  4366. int
  4367. sum_array_till_0_indexing (int *p)
  4368. @{
  4369. int i;
  4370. int sum = 0;
  4371. for (i = 0; ; i++)
  4372. @{
  4373. /* @r{Fetch the next integer.} */
  4374. int next = p[i];
  4375. /* @r{Exit the loop if it's 0.} */
  4376. if (next == 0)
  4377. break;
  4378. /* @r{Add it into running total.} */
  4379. sum += next;
  4380. @}
  4381. return sum;
  4382. @}
  4383. @end example
  4384. In this program, instead of advancing @code{p}, we advance @code{i}
  4385. and add it to @code{p}. (Recall that @code{p[i]} means @code{*(p +
  4386. i)}.) Either way, it uses the same address to get the next integer.
  4387. It makes no difference in this program whether we write @code{i++} or
  4388. @code{++i}, because the value is not used. All that matters is the
  4389. effect, to increment @code{i}.
  4390. The @samp{--} operator also works on pointers; it can be used
  4391. to scan backwards through an array, like this:
  4392. @example
  4393. int
  4394. after_last_nonzero (int *p, int len)
  4395. @{
  4396. /* @r{Set up @code{q} to point just after the last array element.} */
  4397. int *q = p + len;
  4398. while (q != p)
  4399. /* @r{Step @code{q} back until it reaches a nonzero element.} */
  4400. if (*--q != 0)
  4401. /* @r{Return the index of the element after that nonzero.} */
  4402. return q - p + 1;
  4403. return 0;
  4404. @}
  4405. @end example
  4406. That function returns the length of the nonzero part of the
  4407. array specified by its arguments; that is, the index of the
  4408. first zero of the run of zeros at the end.
  4409. @node Pointer Arithmetic Drawbacks
  4410. @section Drawbacks of Pointer Arithmetic
  4411. @cindex drawbacks of pointer arithmetic
  4412. @cindex pointer arithmetic, drawbacks
  4413. Pointer arithmetic is clean and elegant, but it is also the cause of a
  4414. major security flaw in the C language. Theoretically, it is only
  4415. valid to adjust a pointer within one object allocated as a unit in
  4416. memory. However, if you unintentionally adjust a pointer across the
  4417. bounds of the object and into some other object, the system has no way
  4418. to detect this error.
  4419. A bug which does that can easily result in clobbering part of another
  4420. object. For example, with @code{array[-1]} you can read or write the
  4421. nonexistent element before the beginning of an array---probably part
  4422. of some other data.
  4423. Combining pointer arithmetic with casts between pointer types, you can
  4424. create a pointer that fails to be properly aligned for its type. For
  4425. example,
  4426. @example
  4427. int a[2];
  4428. char *pa = (char *)a;
  4429. int *p = (int *)(pa + 1);
  4430. @end example
  4431. @noindent
  4432. gives @code{p} a value pointing to an ``integer'' that includes part
  4433. of @code{a[0]} and part of @code{a[1]}. Dereferencing that with
  4434. @code{*p} can cause a fatal @code{SIGSEGV} signal or it can return the
  4435. contents of that badly aligned @code{int} (@pxref{Signals}. If it
  4436. ``works,'' it may be quite slow. It can also cause aliasing
  4437. confusions (@pxref{Aliasing}).
  4438. @strong{Warning:} Using improperly aligned pointers is risky---don't do it
  4439. unless it is really necessary.
  4440. @node Pointer-Integer Conversion
  4441. @section Pointer-Integer Conversion
  4442. @cindex pointer-integer conversion
  4443. @cindex conversion between pointers and integers
  4444. @cindex @code{uintptr_t}
  4445. On modern computers, an address is simply a number. It occupies the
  4446. same space as some size of integer. In C, you can convert a pointer
  4447. to the appropriate integer types and vice versa, without losing
  4448. information. The appropriate integer types are @code{uintptr_t} (an
  4449. unsigned type) and @code{intptr_t} (a signed type). Both are defined
  4450. in @file{stdint.h}.
  4451. For instance,
  4452. @example
  4453. #include <stdint.h>
  4454. #include <stdio.h>
  4455. void
  4456. print_pointer (void *ptr)
  4457. @{
  4458. uintptr_t converted = (uintptr_t) ptr;
  4459. printf ("Pointer value is 0x%x\n",
  4460. (unsigned int) converted);
  4461. @}
  4462. @end example
  4463. @noindent
  4464. The specification @samp{%x} in the template (the first argument) for
  4465. @code{printf} means to represent this argument using hexadecimal
  4466. notation. It's cleaner to use @code{uintptr_t}, since hexadecimal
  4467. printing treats the number as unsigned, but it won't actually matter:
  4468. all @code{printf} gets to see is the series of bits in the number.
  4469. @strong{Warning:} Converting pointers to integers is risky---don't do
  4470. it unless it is really necessary.
  4471. @node Printing Pointers
  4472. @section Printing Pointers
  4473. To print the numeric value of a pointer, use the @samp{%p} specifier.
  4474. For example:
  4475. @example
  4476. void
  4477. print_pointer (void *ptr)
  4478. @{
  4479. printf ("Pointer value is %p\n", ptr);
  4480. @}
  4481. @end example
  4482. The specification @samp{%p} works with any pointer type. It prints
  4483. @samp{0x} followed by the address in hexadecimal, printed as the
  4484. appropriate unsigned integer type.
  4485. @node Structures
  4486. @chapter Structures
  4487. @cindex structures
  4488. @findex struct
  4489. @cindex fields in structures
  4490. A @dfn{structure} is a user-defined data type that holds various
  4491. @dfn{fields} of data. Each field has a name and a data type specified
  4492. in the structure's definition.
  4493. Here we define a structure suitable for storing a linked list of
  4494. integers. Each list item will hold one integer, plus a pointer
  4495. to the next item.
  4496. @example
  4497. struct intlistlink
  4498. @{
  4499. int datum;
  4500. struct intlistlink *next;
  4501. @};
  4502. @end example
  4503. The structure definition has a @dfn{type tag} so that the code can
  4504. refer to this structure. The type tag here is @code{intlistlink}.
  4505. The definition refers recursively to the same structure through that
  4506. tag.
  4507. You can define a structure without a type tag, but then you can't
  4508. refer to it again. That is useful only in some special contexts, such
  4509. as inside a @code{typedef} or a @code{union}.
  4510. The contents of the structure are specified by the @dfn{field
  4511. declarations} inside the braces. Each field in the structure needs a
  4512. declaration there. The fields in one structure definition must have
  4513. distinct names, but these names do not conflict with any other names
  4514. in the program.
  4515. A field declaration looks just like a variable declaration. You can
  4516. combine field declarations with the same beginning, just as you can
  4517. combine variable declarations.
  4518. This structure has two fields. One, named @code{datum}, has type
  4519. @code{int} and will hold one integer in the list. The other, named
  4520. @code{next}, is a pointer to another @code{struct intlistlink}
  4521. which would be the rest of the list. In the last list item, it would
  4522. be @code{NULL}.
  4523. This structure definition is recursive, since the type of the
  4524. @code{next} field refers to the structure type. Such recursion is not
  4525. a problem; in fact, you can use the type @code{struct intlistlink *}
  4526. before the definition of the type @code{struct intlistlink} itself.
  4527. That works because pointers to all kinds of structures really look the
  4528. same at the machine level.
  4529. After defining the structure, you can declare a variable of type
  4530. @code{struct intlistlink} like this:
  4531. @example
  4532. struct intlistlink foo;
  4533. @end example
  4534. The structure definition itself can serve as the beginning of a
  4535. variable declaration, so you can declare variables immediately after,
  4536. like this:
  4537. @example
  4538. struct intlistlink
  4539. @{
  4540. int datum;
  4541. struct intlistlink *next;
  4542. @} foo;
  4543. @end example
  4544. @noindent
  4545. But that is ugly. It is almost always clearer to separate the
  4546. definition of the structure from its uses.
  4547. Declaring a structure type inside a block (@pxref{Blocks}) limits
  4548. the scope of the structure type name to that block. That means the
  4549. structure type is recognized only within that block. Declaring it in
  4550. a function parameter list, as here,
  4551. @example
  4552. int f (struct foo @{int a, b@} parm);
  4553. @end example
  4554. @noindent
  4555. (assuming that @code{struct foo} is not already defined) limits the
  4556. scope of the structure type @code{struct foo} to that parameter list;
  4557. that is basically useless, so it triggers a warning.
  4558. Standard C requires at least one field in a structure.
  4559. GNU C does not require this.
  4560. @menu
  4561. * Referencing Fields:: Accessing field values in a structure object.
  4562. * Dynamic Memory Allocation:: Allocating space for objects
  4563. while the program is running.
  4564. * Field Offset:: Memory layout of fields within a structure.
  4565. * Structure Layout:: Planning the memory layout of fields.
  4566. * Packed Structures:: Packing structure fields as close as possible.
  4567. * Bit Fields:: Dividing integer fields
  4568. into fields with fewer bits.
  4569. * Bit Field Packing:: How bit fields pack together in integers.
  4570. * const Fields:: Making structure fields immutable.
  4571. * Zero Length:: Zero-length array as a variable-length object.
  4572. * Flexible Array Fields:: Another approach to variable-length objects.
  4573. * Overlaying Structures:: Casting one structure type
  4574. over an object of another structure type.
  4575. * Structure Assignment:: Assigning values to structure objects.
  4576. * Unions:: Viewing the same object in different types.
  4577. * Packing With Unions:: Using a union type to pack various types into
  4578. the same memory space.
  4579. * Cast to Union:: Casting a value one of the union's alternative
  4580. types to the type of the union itself.
  4581. * Structure Constructors:: Building new structure objects.
  4582. * Unnamed Types as Fields:: Fields' types do not always need names.
  4583. * Incomplete Types:: Types which have not been fully defined.
  4584. * Intertwined Incomplete Types:: Defining mutually-recursive structue types.
  4585. * Type Tags:: Scope of structure and union type tags.
  4586. @end menu
  4587. @node Referencing Fields
  4588. @section Referencing Structure Fields
  4589. @cindex referencing structure fields
  4590. @cindex structure fields, referencing
  4591. To make a structure useful, there has to be a way to examine and store
  4592. its fields. The @samp{.} (period) operator does that; its use looks
  4593. like @code{@var{object}.@var{field}}.
  4594. Given this structure and variable,
  4595. @example
  4596. struct intlistlink
  4597. @{
  4598. int datum;
  4599. struct intlistlink *next;
  4600. @};
  4601. struct intlistlink foo;
  4602. @end example
  4603. @noindent
  4604. you can write @code{foo.datum} and @code{foo.next} to refer to the two
  4605. fields in the value of @code{foo}. These fields are lvalues, so you
  4606. can store values into them, and read the values out again.
  4607. Most often, structures are dynamically allocated (see the next
  4608. section), and we refer to the objects via pointers.
  4609. @code{(*p).@var{field}} is somewhat cumbersome, so there is an
  4610. abbreviation: @code{p->@var{field}}. For instance, assume the program
  4611. contains this declaration:
  4612. @example
  4613. struct intlistlink *ptr;
  4614. @end example
  4615. @noindent
  4616. You can write @code{ptr->datum} and @code{ptr->next} to refer
  4617. to the two fields in the object that @code{ptr} points to.
  4618. If a unary operator precedes an expression using @samp{->},
  4619. the @samp{->} nests inside:
  4620. @example
  4621. -ptr->datum @r{is equivalent to} -(ptr->datum)
  4622. @end example
  4623. You can intermix @samp{->} and @samp{.} without parentheses,
  4624. as shown here:
  4625. @example
  4626. struct @{ double d; struct intlistlink l; @} foo;
  4627. @r{@dots{}}foo.l.next->next->datum@r{@dots{}}
  4628. @end example
  4629. @node Dynamic Memory Allocation
  4630. @section Dynamic Memory Allocation
  4631. @cindex dynamic memory allocation
  4632. @cindex memory allocation, dynamic
  4633. @cindex allocating memory dynamically
  4634. To allocate an object dynamically, call the library function
  4635. @code{malloc} (@pxref{Basic Allocation, The GNU C Library,, libc, The GNU C Library
  4636. Reference Manual}). Here is how to allocate an object of type
  4637. @code{struct intlistlink}. To make this code work, include the file
  4638. @file{stdlib.h}, like this:
  4639. @example
  4640. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  4641. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  4642. @dots{}
  4643. struct intlistlink *
  4644. alloc_intlistlink ()
  4645. @{
  4646. struct intlistlink *p;
  4647. p = malloc (sizeof (struct intlistlink));
  4648. if (p == NULL)
  4649. fatal ("Ran out of storage");
  4650. /* @r{Initialize the contents.} */
  4651. p->datum = 0;
  4652. p->next = NULL;
  4653. return p;
  4654. @}
  4655. @end example
  4656. @noindent
  4657. @code{malloc} returns @code{void *}, so the assignment to @code{p}
  4658. will automatically convert it to type @code{struct intlistlink *}.
  4659. The return value of @code{malloc} is always sufficiently aligned
  4660. (@pxref{Type Alignment}) that it is valid for any data type.
  4661. The test for @code{p == NULL} is necessary because @code{malloc}
  4662. returns a null pointer if it cannot get any storage. We assume that
  4663. the program defines the function @code{fatal} to report a fatal error
  4664. to the user.
  4665. Here's how to add one more integer to the front of such a list:
  4666. @example
  4667. struct intlistlink *my_list = NULL;
  4668. void
  4669. add_to_mylist (int my_int)
  4670. @{
  4671. struct intlistlink *p = alloc_intlistlink ();
  4672. p->datum = my_int;
  4673. p->next = mylist;
  4674. mylist = p;
  4675. @}
  4676. @end example
  4677. The way to free the objects is by calling @code{free}. Here's
  4678. a function to free all the links in one of these lists:
  4679. @example
  4680. void
  4681. free_intlist (struct intlistlink *p)
  4682. @{
  4683. while (p)
  4684. @{
  4685. struct intlistlink *q = p;
  4686. p = p->next;
  4687. free (q);
  4688. @}
  4689. @}
  4690. @end example
  4691. We must extract the @code{next} pointer from the object before freeing
  4692. it, because @code{free} can clobber the data that was in the object.
  4693. For the same reason, the program must not use the list any more after
  4694. freeing its elements. To make sure it won't, it is best to clear out
  4695. the variable where the list was stored, like this:
  4696. @example
  4697. free_intlist (mylist);
  4698. mylist = NULL;
  4699. @end example
  4700. @node Field Offset
  4701. @section Field Offset
  4702. @cindex field offset
  4703. @cindex structure field offset
  4704. @cindex offset of structure fields
  4705. To determine the offset of a given field @var{field} in a structure
  4706. type @var{type}, use the macro @code{offsetof}, which is defined in
  4707. the file @file{stddef.h}. It is used like this:
  4708. @example
  4709. offsetof (@var{type}, @var{field})
  4710. @end example
  4711. Here is an example:
  4712. @example
  4713. struct foo
  4714. @{
  4715. int element;
  4716. struct foo *next;
  4717. @};
  4718. offsetof (struct foo, next)
  4719. /* @r{On most machines that is 4. It may be 8.} */
  4720. @end example
  4721. @node Structure Layout
  4722. @section Structure Layout
  4723. @cindex structure layout
  4724. @cindex layout of structures
  4725. The rest of this chapter covers advanced topics about structures. If
  4726. you are just learning C, you can skip it.
  4727. The precise layout of a @code{struct} type is crucial when using it to
  4728. overlay hardware registers, to access data structures in shared
  4729. memory, or to assemble and disassemble packets for network
  4730. communication. It is also important for avoiding memory waste when
  4731. the program makes many objects of that type. However, the layout
  4732. depends on the target platform. Each platform has conventions for
  4733. structure layout, which compilers need to follow.
  4734. Here are the conventions used on most platforms.
  4735. The structure's fields appear in the structure layout in the order
  4736. they are declared. When possible, consecutive fields occupy
  4737. consecutive bytes within the structure. However, if a field's type
  4738. demands more alignment than it would get that way, C gives it the
  4739. alignment it requires by leaving a gap after the previous field.
  4740. Once all the fields have been laid out, it is possible to determine
  4741. the structure's alignment and size. The structure's alignment is the
  4742. maximum alignment of any of the fields in it. Then the structure's
  4743. size is rounded up to a multiple of its alignment. That may require
  4744. leaving a gap at the end of the structure.
  4745. Here are some examples, where we assume that @code{char} has size and
  4746. alignment 1 (always true), and @code{int} has size and alignment 4
  4747. (true on most kinds of computers):
  4748. @example
  4749. struct foo
  4750. @{
  4751. char a, b;
  4752. int c;
  4753. @};
  4754. @end example
  4755. @noindent
  4756. This structure occupies 8 bytes, with an alignment of 4. @code{a} is
  4757. at offset 0, @code{b} is at offset 1, and @code{c} is at offset 4.
  4758. There is a gap of 2 bytes before @code{c}.
  4759. Contrast that with this structure:
  4760. @example
  4761. struct foo
  4762. @{
  4763. char a;
  4764. int c;
  4765. char b;
  4766. @};
  4767. @end example
  4768. This structure has size 12 and alignment 4. @code{a} is at offset 0,
  4769. @code{c} is at offset 4, and @code{b} is at offset 8. There are two
  4770. gaps: three bytes before @code{c}, and three bytes at the end.
  4771. These two structures have the same contents at the C level, but one
  4772. takes 8 bytes and the other takes 12 bytes due to the ordering of the
  4773. fields. A reliable way to avoid this sort of wastage is to order the
  4774. fields by size, biggest fields first.
  4775. @node Packed Structures
  4776. @section Packed Structures
  4777. @cindex packed structures
  4778. @cindex @code{__attribute__((packed))}
  4779. In GNU C you can force a structure to be laid out with no gaps by
  4780. adding @code{__attribute__((packed))} after @code{struct} (or at the
  4781. end of the structure type declaration). Here's an example:
  4782. @example
  4783. struct __attribute__((packed)) foo
  4784. @{
  4785. char a;
  4786. int c;
  4787. char b;
  4788. @};
  4789. @end example
  4790. Without @code{__attribute__((packed))}, this structure occupies 12
  4791. bytes (as described in the previous section), assuming 4-byte
  4792. alignment for @code{int}. With @code{__attribute__((packed))}, it is
  4793. only 6 bytes long---the sum of the lengths of its fields.
  4794. Use of @code{__attribute__((packed))} often results in fields that
  4795. don't have the normal alignment for their types. Taking the address
  4796. of such a field can result in an invalid pointer because of its
  4797. improper alignment. Dereferencing such a pointer can cause a
  4798. @code{SIGSEGV} signal on a machine that doesn't, in general, allow
  4799. unaligned pointers.
  4800. @xref{Attributes}.
  4801. @node Bit Fields
  4802. @section Bit Fields
  4803. @cindex bit fields
  4804. A structure field declaration with an integer type can specify the
  4805. number of bits the field should occupy. We call that a @dfn{bit
  4806. field}. These are useful because consecutive bit fields are packed
  4807. into a larger storage unit. For instance,
  4808. @example
  4809. unsigned char opcode: 4;
  4810. @end example
  4811. @noindent
  4812. specifies that this field takes just 4 bits.
  4813. Since it is unsigned, its possible values range
  4814. from 0 to 15. A signed field with 4 bits, such as this,
  4815. @example
  4816. signed char small: 4;
  4817. @end example
  4818. @noindent
  4819. can hold values from -8 to 7.
  4820. You can subdivide a single byte into those two parts by writing
  4821. @example
  4822. unsigned char opcode: 4;
  4823. signed char small: 4;
  4824. @end example
  4825. @noindent
  4826. in the structure. With bit fields, these two numbers fit into
  4827. a single @code{char}.
  4828. Here's how to declare a one-bit field that can hold either 0 or 1:
  4829. @example
  4830. unsigned char special_flag: 1;
  4831. @end example
  4832. You can also use the @code{bool} type for bit fields:
  4833. @example
  4834. bool special_flag: 1;
  4835. @end example
  4836. Except when using @code{bool} (which is always unsigned,
  4837. @pxref{Boolean Type}), always specify @code{signed} or @code{unsigned}
  4838. for a bit field. There is a default, if that's not specified: the bit
  4839. field is signed if plain @code{char} is signed, except that the option
  4840. @option{-funsigned-bitfields} forces unsigned as the default. But it
  4841. is cleaner not to depend on this default.
  4842. Bit fields are special in that you cannot take their address with
  4843. @samp{&}. They are not stored with the size and alignment appropriate
  4844. for the specified type, so they cannot be addressed through pointers
  4845. to that type.
  4846. @node Bit Field Packing
  4847. @section Bit Field Packing
  4848. Programs to communicate with low-level hardware interfaces need to
  4849. define bit fields laid out to match the hardware data. This section
  4850. explains how to do that.
  4851. Consecutive bit fields are packed together, but each bit field must
  4852. fit within a single object of its specified type. In this example,
  4853. @example
  4854. unsigned short a : 3, b : 3, c : 3, d : 3, e : 3;
  4855. @end example
  4856. @noindent
  4857. all five fields fit consecutively into one two-byte @code{short}.
  4858. They need 15 bits, and one @code{short} provides 16. By contrast,
  4859. @example
  4860. unsigned char a : 3, b : 3, c : 3, d : 3, e : 3;
  4861. @end example
  4862. @noindent
  4863. needs three bytes. It fits @code{a} and @code{b} into one
  4864. @code{char}, but @code{c} won't fit in that @code{char} (they would
  4865. add up to 9 bits). So @code{c} and @code{d} go into a second
  4866. @code{char}, leaving a gap of two bits between @code{b} and @code{c}.
  4867. Then @code{e} needs a third @code{char}. By contrast,
  4868. @example
  4869. unsigned char a : 3, b : 3;
  4870. unsigned int c : 3;
  4871. unsigned char d : 3, e : 3;
  4872. @end example
  4873. @noindent
  4874. needs only two bytes: the type @code{unsigned int}
  4875. allows @code{c} to straddle bytes that are in the same word.
  4876. You can leave a gap of a specified number of bits by defining a
  4877. nameless bit field. This looks like @code{@var{type} : @var{nbits};}.
  4878. It is allocated space in the structure just as a named bit field would
  4879. be allocated.
  4880. You can force the following bit field to advance to the following
  4881. aligned memory object with @code{@var{type} : 0;}.
  4882. Both of these constructs can syntactically share @var{type} with
  4883. ordinary bit fields. This example illustrates both:
  4884. @example
  4885. unsigned int a : 5, : 3, b : 5, : 0, c : 5, : 3, d : 5;
  4886. @end example
  4887. @noindent
  4888. It puts @code{a} and @code{b} into one @code{int}, with a 3-bit gap
  4889. between them. Then @code{: 0} advances to the next @code{int},
  4890. so @code{c} and @code{d} fit into that one.
  4891. These rules for packing bit fields apply to most target platforms,
  4892. including all the usual real computers. A few embedded controllers
  4893. have special layout rules.
  4894. @node const Fields
  4895. @section @code{const} Fields
  4896. @cindex const fields
  4897. @cindex structure fields, constant
  4898. @c ??? Is this a C standard feature?
  4899. A structure field declared @code{const} cannot be assigned to
  4900. (@pxref{const}). For instance, let's define this modified version of
  4901. @code{struct intlistlink}:
  4902. @example
  4903. struct intlistlink_ro /* @r{``ro'' for read-only.} */
  4904. @{
  4905. const int datum;
  4906. struct intlistlink *next;
  4907. @};
  4908. @end example
  4909. This structure can be used to prevent part of the code from modifying
  4910. the @code{datum} field:
  4911. @example
  4912. /* @r{@code{p} has type @code{struct intlistlink *}.}
  4913. @r{Convert it to @code{struct intlistlink_ro *}.} */
  4914. struct intlistlink_ro *q
  4915. = (struct intlistlink_ro *) p;
  4916. q->datum = 5; /* @r{Error!} */
  4917. p->datum = 5; /* @r{Valid since @code{*p} is}
  4918. @r{not a @code{struct intlistlink_ro}.} */
  4919. @end example
  4920. A @code{const} field can get a value in two ways: by initialization of
  4921. the whole structure, and by making a pointer-to-structure point to an object
  4922. in which that field already has a value.
  4923. Any @code{const} field in a structure type makes assignment impossible
  4924. for structures of that type (@pxref{Structure Assignment}). That is
  4925. because structure assignment works by assigning the structure's
  4926. fields, one by one.
  4927. @node Zero Length
  4928. @section Arrays of Length Zero
  4929. @cindex array of length zero
  4930. @cindex zero-length arrays
  4931. @cindex length-zero arrays
  4932. GNU C allows zero-length arrays. They are useful as the last element
  4933. of a structure that is really a header for a variable-length object.
  4934. Here's an example, where we construct a variable-size structure
  4935. to hold a line which is @code{this_length} characters long:
  4936. @example
  4937. struct line @{
  4938. int length;
  4939. char contents[0];
  4940. @};
  4941. struct line *thisline
  4942. = ((struct line *)
  4943. malloc (sizeof (struct line)
  4944. + this_length));
  4945. thisline->length = this_length;
  4946. @end example
  4947. In ISO C90, we would have to give @code{contents} a length of 1, which
  4948. means either wasting space or complicating the argument to @code{malloc}.
  4949. @node Flexible Array Fields
  4950. @section Flexible Array Fields
  4951. @cindex flexible array fields
  4952. @cindex array fields, flexible
  4953. The C99 standard adopted a more complex equivalent of zero-length
  4954. array fields. It's called a @dfn{flexible array}, and it's indicated
  4955. by omitting the length, like this:
  4956. @example
  4957. struct line
  4958. @{
  4959. int length;
  4960. char contents[];
  4961. @};
  4962. @end example
  4963. The flexible array has to be the last field in the structure, and there
  4964. must be other fields before it.
  4965. Under the C standard, a structure with a flexible array can't be part
  4966. of another structure, and can't be an element of an array.
  4967. GNU C allows static initialization of flexible array fields. The effect
  4968. is to ``make the array long enough'' for the initializer.
  4969. @example
  4970. struct f1 @{ int x; int y[]; @} f1
  4971. = @{ 1, @{ 2, 3, 4 @} @};
  4972. @end example
  4973. @noindent
  4974. This defines a structure variable named @code{f1}
  4975. whose type is @code{struct f1}. In C, a variable name or function name
  4976. never conflicts with a structure type tag.
  4977. Omitting the flexible array field's size lets the initializer
  4978. determine it. This is allowed only when the flexible array is defined
  4979. in the outermost structure and you declare a variable of that
  4980. structure type. For example:
  4981. @example
  4982. struct foo @{ int x; int y[]; @};
  4983. struct bar @{ struct foo z; @};
  4984. struct foo a = @{ 1, @{ 2, 3, 4 @} @}; // @r{Valid.}
  4985. struct bar b = @{ @{ 1, @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4986. struct bar c = @{ @{ 1, @{ @} @} @}; // @r{Valid.}
  4987. struct foo d[1] = @{ @{ 1 @{ 2, 3, 4 @} @} @}; // @r{Invalid.}
  4988. @end example
  4989. @node Overlaying Structures
  4990. @section Overlaying Different Structures
  4991. @cindex overlaying structures
  4992. @cindex structures, overlaying
  4993. Be careful about using different structure types to refer to the same
  4994. memory within one function, because GNU C can optimize code assuming
  4995. it never does that. @xref{Aliasing}. Here's an example of the kind of
  4996. aliasing that can cause the problem:
  4997. @example
  4998. struct a @{ int size; char *data; @};
  4999. struct b @{ int size; char *data; @};
  5000. struct a foo;
  5001. struct b *q = (struct b *) &foo;
  5002. @end example
  5003. Here @code{q} points to the same memory that the variable @code{foo}
  5004. occupies, but they have two different types. The two types
  5005. @code{struct a} and @code{struct b} are defined alike, but they are
  5006. not the same type. Interspersing references using the two types,
  5007. like this,
  5008. @example
  5009. p->size = 0;
  5010. q->size = 1;
  5011. x = p->size;
  5012. @end example
  5013. @noindent
  5014. allows GNU C to assume that @code{p->size} is still zero when it is
  5015. copied into @code{x}. The compiler ``knows'' that @code{q} points to
  5016. a @code{struct b} and this cannot overlap with a @code{struct a}.
  5017. Other compilers might also do this optimization. The ISO C standard
  5018. considers such code erroneous, precisely so that this optimization
  5019. will be valid.
  5020. @node Structure Assignment
  5021. @section Structure Assignment
  5022. @cindex structure assignment
  5023. @cindex assigning structures
  5024. Assignment operating on a structure type copies the structure. The
  5025. left and right operands must have the same type. Here is an example:
  5026. @example
  5027. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  5028. #include <stdlib.h> /* @r{Declares @code{malloc}.} */
  5029. @r{@dots{}}
  5030. struct point @{ double x, y; @};
  5031. struct point *
  5032. copy_point (struct point point)
  5033. @{
  5034. struct point *p
  5035. = (struct point *) malloc (sizeof (struct point));
  5036. if (p == NULL)
  5037. fatal ("Out of memory");
  5038. *p = point;
  5039. return p;
  5040. @}
  5041. @end example
  5042. Notionally, assignment on a structure type works by copying each of
  5043. the fields. Thus, if any of the fields has the @code{const}
  5044. qualifier, that structure type does not allow assignment:
  5045. @example
  5046. struct point @{ const double x, y; @};
  5047. struct point a, b;
  5048. a = b; /* @r{Error!} */
  5049. @end example
  5050. @xref{Assignment Expressions}.
  5051. @node Unions
  5052. @section Unions
  5053. @cindex unions
  5054. @findex union
  5055. A @dfn{union type} defines alternative ways of looking at the same
  5056. piece of memory. Each alternative view is defined with a data type,
  5057. and identified by a name. A union definition looks like this:
  5058. @example
  5059. union @var{name}
  5060. @{
  5061. @var{alternative declarations}@r{@dots{}}
  5062. @};
  5063. @end example
  5064. Each alternative declaration looks like a structure field declaration,
  5065. except that it can't be a bit field. For instance,
  5066. @example
  5067. union number
  5068. @{
  5069. long int integer;
  5070. double float;
  5071. @}
  5072. @end example
  5073. @noindent
  5074. lets you store either an integer (type @code{long int}) or a floating
  5075. point number (type @code{double}) in the same place in memory. The
  5076. length and alignment of the union type are the maximum of all the
  5077. alternatives---they do not have to be the same. In this union
  5078. example, @code{double} probably takes more space than @code{long int},
  5079. but that doesn't cause a problem in programs that use the union in the
  5080. normal way.
  5081. The members don't have to be different in data type. Sometimes
  5082. each member pertains to a way the data will be used. For instance,
  5083. @example
  5084. union datum
  5085. @{
  5086. double latitude;
  5087. double longitude;
  5088. double height;
  5089. double weight;
  5090. int continent;
  5091. @}
  5092. @end example
  5093. This union holds one of several kinds of data; most kinds are floating
  5094. points, but the value can also be a code for a continent which is an
  5095. integer. You @emph{could} use one member of type @code{double} to
  5096. access all the values which have that type, but the different member
  5097. names will make the program clearer.
  5098. The alignment of a union type is the maximum of the alignments of the
  5099. alternatives. The size of the union type is the maximum of the sizes
  5100. of the alternatives, rounded up to a multiple of the alignment
  5101. (because every type's size must be a multiple of its alignment).
  5102. All the union alternatives start at the address of the union itself.
  5103. If an alternative is shorter than the union as a whole, it occupies
  5104. the first part of the union's storage, leaving the last part unused
  5105. @emph{for that alternative}.
  5106. @strong{Warning:} if the code stores data using one union alternative
  5107. and accesses it with another, the results depend on the kind of
  5108. computer in use. Only wizards should try to do this. However, when
  5109. you need to do this, a union is a clean way to do it.
  5110. Assignment works on any union type by copying the entire value.
  5111. @node Packing With Unions
  5112. @section Packing With Unions
  5113. Sometimes we design a union with the intention of packing various
  5114. kinds of objects into a certain amount of memory space. For example.
  5115. @example
  5116. union bytes8
  5117. @{
  5118. long long big_int_elt;
  5119. double double_elt;
  5120. struct @{ int first, second; @} two_ints;
  5121. struct @{ void *first, *second; @} two_ptrs;
  5122. @};
  5123. union bytes8 *p;
  5124. @end example
  5125. This union makes it possible to look at 8 bytes of data that @code{p}
  5126. points to as a single 8-byte integer (@code{p->big_int_elt}), as a
  5127. single floating-point number (@code{p->double_elt}), as a pair of
  5128. integers (@code{p->two_ints.first} and @code{p->two_ints.second}), or
  5129. as a pair of pointers (@code{p->two_ptrs.first} and
  5130. @code{p->two_ptrs.second}).
  5131. To pack storage with such a union makes assumptions about the sizes of
  5132. all the types involved. This particular union was written expecting a
  5133. pointer to have the same size as @code{int}. On a machine where one
  5134. pointer takes 8 bytes, the code using this union probably won't work
  5135. as expected. The union, as such, will function correctly---if you
  5136. store two values through @code{two_ints} and extract them through
  5137. @code{two_ints}, you will get the same integers back---but the part of
  5138. the program that expects the union to be 8 bytes long could
  5139. malfunction, or at least use too much space.
  5140. The above example shows one case where a @code{struct} type with no
  5141. tag can be useful. Another way to get effectively the same result
  5142. is with arrays as members of the union:
  5143. @example
  5144. union eight_bytes
  5145. @{
  5146. long long big_int_elt;
  5147. double double_elt;
  5148. int two_ints[2];
  5149. void *two_ptrs[2];
  5150. @};
  5151. @end example
  5152. @node Cast to Union
  5153. @section Cast to a Union Type
  5154. @cindex cast to a union
  5155. @cindex union, casting to a
  5156. In GNU C, you can explicitly cast any of the alternative types to the
  5157. union type; for instance,
  5158. @example
  5159. (union eight_bytes) (long long) 5
  5160. @end example
  5161. @noindent
  5162. makes a value of type @code{union eight_bytes} which gets its contents
  5163. through the alternative named @code{big_int_elt}.
  5164. The value being cast must exactly match the type of the alternative,
  5165. so this is not valid:
  5166. @example
  5167. (union eight_bytes) 5 /* @r{Error! 5 is @code{int}.} */
  5168. @end example
  5169. A cast to union type looks like any other cast, except that the type
  5170. specified is a union type. You can specify the type either with
  5171. @code{union @var{tag}} or with a typedef name (@pxref{Defining
  5172. Typedef Names}).
  5173. Using the cast as the right-hand side of an assignment to a variable of
  5174. union type is equivalent to storing in an alternative of the union:
  5175. @example
  5176. union foo u;
  5177. u = (union foo) x @r{means} u.i = x
  5178. u = (union foo) y @r{means} u.d = y
  5179. @end example
  5180. You can also use the union cast as a function argument:
  5181. @example
  5182. void hack (union foo);
  5183. @r{@dots{}}
  5184. hack ((union foo) x);
  5185. @end example
  5186. @node Structure Constructors
  5187. @section Structure Constructors
  5188. @cindex structure constructors
  5189. @cindex constructors, structure
  5190. You can construct a structure value by writing its type in
  5191. parentheses, followed by an initializer that would be valid in a
  5192. declaration for that type. For instance, given this declaration,
  5193. @example
  5194. struct foo @{int a; char b[2];@} structure;
  5195. @end example
  5196. @noindent
  5197. you can create a @code{struct foo} value as follows:
  5198. @example
  5199. ((struct foo) @{x + y, 'a', 0@})
  5200. @end example
  5201. @noindent
  5202. This specifies @code{x + y} for field @code{a},
  5203. the character @samp{a} for field @code{b}'s element 0,
  5204. and the null character for field @code{b}'s element 1.
  5205. The parentheses around that constructor are to necessary, but we
  5206. recommend writing them to make the nesting of the containing
  5207. expression clearer.
  5208. You can also show the nesting of the two by writing it like
  5209. this:
  5210. @example
  5211. ((struct foo) @{x + y, @{'a', 0@} @})
  5212. @end example
  5213. Each of those is equivalent to writing the following statement
  5214. expression (@pxref{Statement Exprs}):
  5215. @example
  5216. (@{
  5217. struct foo temp = @{x + y, 'a', 0@};
  5218. temp;
  5219. @})
  5220. @end example
  5221. You can also create a union value this way, but it is not especially
  5222. useful since that is equivalent to doing a cast:
  5223. @example
  5224. ((union whosis) @{@var{value}@})
  5225. @r{is equivalent to}
  5226. ((union whosis) (@var{value}))
  5227. @end example
  5228. @node Unnamed Types as Fields
  5229. @section Unnamed Types as Fields
  5230. @cindex unnamed structures
  5231. @cindex unnamed unions
  5232. @cindex structures, unnamed
  5233. @cindex unions, unnamed
  5234. A structure or a union can contain, as fields,
  5235. unnamed structures and unions. Here's an example:
  5236. @example
  5237. struct
  5238. @{
  5239. int a;
  5240. union
  5241. @{
  5242. int b;
  5243. float c;
  5244. @};
  5245. int d;
  5246. @} foo;
  5247. @end example
  5248. @noindent
  5249. You can access the fields of the unnamed union within @code{foo} as if they
  5250. were individual fields at the same level as the union definition:
  5251. @example
  5252. foo.a = 42;
  5253. foo.b = 47;
  5254. foo.c = 5.25; // @r{Overwrites the value in @code{foo.b}}.
  5255. foo.d = 314;
  5256. @end example
  5257. Avoid using field names that could cause ambiguity. For example, with
  5258. this definition:
  5259. @example
  5260. struct
  5261. @{
  5262. int a;
  5263. struct
  5264. @{
  5265. int a;
  5266. float b;
  5267. @};
  5268. @} foo;
  5269. @end example
  5270. @noindent
  5271. it is impossible to tell what @code{foo.a} refers to. GNU C reports
  5272. an error when a definition is ambiguous in this way.
  5273. @node Incomplete Types
  5274. @section Incomplete Types
  5275. @cindex incomplete types
  5276. @cindex types, incomplete
  5277. A type that has not been fully defined is called an @dfn{incomplete
  5278. type}. Structure and union types are incomplete when the code makes a
  5279. forward reference, such as @code{struct foo}, before defining the
  5280. type. An array type is incomplete when its length is unspecified.
  5281. You can't use an incomplete type to declare a variable or field, or
  5282. use it for a function parameter or return type. The operators
  5283. @code{sizeof} and @code{_Alignof} give errors when used on an
  5284. incomplete type.
  5285. However, you can define a pointer to an incomplete type, and declare a
  5286. variable or field with such a pointer type. In general, you can do
  5287. everything with such pointers except dereference them. For example:
  5288. @example
  5289. extern void bar (struct mysterious_value *);
  5290. void
  5291. foo (struct mysterious_value *arg)
  5292. @{
  5293. bar (arg);
  5294. @}
  5295. @r{@dots{}}
  5296. @{
  5297. struct mysterious_value *p, **q;
  5298. p = *q;
  5299. foo (p);
  5300. @}
  5301. @end example
  5302. @noindent
  5303. These examples are valid because the code doesn't try to understand
  5304. what @code{p} points to; it just passes the pointer around.
  5305. (Presumably @code{bar} is defined in some other file that really does
  5306. have a definition for @code{struct mysterious_value}.) However,
  5307. dereferencing the pointer would get an error; that requires a
  5308. definition for the structure type.
  5309. @node Intertwined Incomplete Types
  5310. @section Intertwined Incomplete Types
  5311. When several structure types contain pointers to each other, you can
  5312. define the types in any order because pointers to types that come
  5313. later are incomplete types. Thus,
  5314. Here is an example.
  5315. @example
  5316. /* @r{An employee record points to a group.} */
  5317. struct employee
  5318. @{
  5319. char *name;
  5320. @r{@dots{}}
  5321. struct group *group; /* @r{incomplete type.} */
  5322. @r{@dots{}}
  5323. @};
  5324. /* @r{An employee list points to employees.} */
  5325. struct employee_list
  5326. @{
  5327. struct employee *this_one;
  5328. struct employee_list *next; /* @r{incomplete type.} */
  5329. @r{@dots{}}
  5330. @};
  5331. /* @r{A group points to one employee_list.} */
  5332. struct group
  5333. @{
  5334. char *name;
  5335. @r{@dots{}}
  5336. struct employee_list *employees;
  5337. @r{@dots{}}
  5338. @};
  5339. @end example
  5340. @node Type Tags
  5341. @section Type Tags
  5342. @cindex type tags
  5343. The name that follows @code{struct} (@pxref{Structures}), @code{union}
  5344. (@pxref{Unions}, or @code{enum} (@pxref{Enumeration Types}) is called
  5345. a @dfn{type tag}. In C, a type tag never conflicts with a variable
  5346. name or function name; the type tags have a separate @dfn{name space}.
  5347. Thus, there is no name conflict in this code:
  5348. @example
  5349. struct pair @{ int a, b; @};
  5350. int pair = 1;
  5351. @end example
  5352. @noindent
  5353. nor in this one:
  5354. @example
  5355. struct pair @{ int a, b; @} pair;
  5356. @end example
  5357. @noindent
  5358. where @code{pair} is both a structure type tag and a variable name.
  5359. However, @code{struct}, @code{union}, and @code{enum} share the same
  5360. name space of tags, so this is a conflict:
  5361. @example
  5362. struct pair @{ int a, b; @};
  5363. enum pair @{ c, d @};
  5364. @end example
  5365. @noindent
  5366. and so is this:
  5367. @example
  5368. struct pair @{ int a, b; @};
  5369. struct pair @{ int c, d; @};
  5370. @end example
  5371. When the code defines a type tag inside a block, the tag's scope is
  5372. limited to that block (as for local variables). Two definitions for
  5373. one type tag do not conflict if they are in different scopes; rather,
  5374. each is valid in its scope. For example,
  5375. @example
  5376. struct pair @{ int a, b; @};
  5377. void
  5378. pair_up_doubles (int len, double array[])
  5379. @{
  5380. struct pair @{ double a, b; @};
  5381. @r{@dots{}}
  5382. @}
  5383. @end example
  5384. @noindent
  5385. has two definitions for @code{struct pair} which do not conflict. The
  5386. one inside the function applies only within the definition of
  5387. @code{pair_up_doubles}. Within its scope, that definition
  5388. @dfn{shadows} the outer definition.
  5389. If @code{struct pair} appears inside the function body, before the
  5390. inner definition, it refers to the outer definition---the only one
  5391. that has been seen at that point. Thus, in this code,
  5392. @example
  5393. struct pair @{ int a, b; @};
  5394. void
  5395. pair_up_doubles (int len, double array[])
  5396. @{
  5397. struct two_pairs @{ struct pair *p, *q; @};
  5398. struct pair @{ double a, b; @};
  5399. @r{@dots{}}
  5400. @}
  5401. @end example
  5402. @noindent
  5403. the structure @code{two_pairs} has pointers to the outer definition of
  5404. @code{struct pair}, which is probably not desirable.
  5405. To prevent that, you can write @code{struct pair;} inside the function
  5406. body as a variable declaration with no variables. This is a
  5407. @dfn{forward declaration} of the type tag @code{pair}: it makes the
  5408. type tag local to the current block, with the details of the type to
  5409. come later. Here's an example:
  5410. @example
  5411. void
  5412. pair_up_doubles (int len, double array[])
  5413. @{
  5414. /* @r{Forward declaration for @code{pair}.} */
  5415. struct pair;
  5416. struct two_pairs @{ struct pair *p, *q; @};
  5417. /* @r{Give the details.} */
  5418. struct pair @{ double a, b; @};
  5419. @r{@dots{}}
  5420. @}
  5421. @end example
  5422. However, the cleanest practice is to avoid shadowing type tags.
  5423. @node Arrays
  5424. @chapter Arrays
  5425. @cindex array
  5426. @cindex elements of arrays
  5427. An @dfn{array} is a data object that holds a series of @dfn{elements},
  5428. all of the same data type. Each element is identified by its numeric
  5429. @var{index} within the array.
  5430. We presented arrays of numbers in the sample programs early in this
  5431. manual (@pxref{Array Example}). However, arrays can have elements of
  5432. any data type, including pointers, structures, unions, and other
  5433. arrays.
  5434. If you know another programming language, you may suppose that you know all
  5435. about arrays, but C arrays have special quirks, so in this chapter we
  5436. collect all the information about arrays in C@.
  5437. The elements of a C array are allocated consecutively in memory,
  5438. with no gaps between them. Each element is aligned as required
  5439. for its data type (@pxref{Type Alignment}).
  5440. @menu
  5441. * Accessing Array Elements:: How to access individual elements of an array.
  5442. * Declaring an Array:: How to name and reserve space for a new array.
  5443. * Strings:: A string in C is a special case of array.
  5444. * Array Type Designators:: Referring to a specific array type.
  5445. * Incomplete Array Types:: Naming, but not allocating, a new array.
  5446. * Limitations of C Arrays:: Arrays are not first-class objects.
  5447. * Multidimensional Arrays:: Arrays of arrays.
  5448. * Constructing Array Values:: Assigning values to an entire array at once.
  5449. * Arrays of Variable Length:: Declaring arrays of non-constant size.
  5450. @end menu
  5451. @node Accessing Array Elements
  5452. @section Accessing Array Elements
  5453. @cindex accessing array elements
  5454. @cindex array elements, accessing
  5455. If the variable @code{a} is an array, the @var{n}th element of
  5456. @code{a} is @code{a[@var{n}]}. You can use that expression to access
  5457. an element's value or to assign to it:
  5458. @example
  5459. x = a[5];
  5460. a[6] = 1;
  5461. @end example
  5462. @noindent
  5463. Since the variable @code{a} is an lvalue, @code{a[@var{n}]} is also an
  5464. lvalue.
  5465. The lowest valid index in an array is 0, @emph{not} 1, and the highest
  5466. valid index is one less than the number of elements.
  5467. The C language does not check whether array indices are in bounds, so
  5468. if the code uses an out-of-range index, it will access memory outside the
  5469. array.
  5470. @strong{Warning:} Using only valid index values in C is the
  5471. programmer's responsibility.
  5472. Array indexing in C is not a primitive operation: it is defined in
  5473. terms of pointer arithmetic and dereferencing. Now that we know
  5474. @emph{what} @code{a[i]} does, we can ask @emph{how} @code{a[i]} does
  5475. its job.
  5476. In C, @code{@var{x}[@var{y}]} is an abbreviation for
  5477. @code{*(@var{x}+@var{y})}. Thus, @code{a[i]} really means
  5478. @code{*(a+i)}. @xref{Pointers and Arrays}.
  5479. When an expression with array type (such as @code{a}) appears as part
  5480. of a larger C expression, it is converted automatically to a pointer
  5481. to element zero of that array. For instance, @code{a} in an
  5482. expression is equivalent to @code{&a[0]}. Thus, @code{*(a+i)} is
  5483. computed as @code{*(&a[0]+i)}.
  5484. Now we can analyze how that expression gives us the desired element of
  5485. the array. It makes a pointer to element 0 of @code{a}, advances it
  5486. by the value of @code{i}, and dereferences that pointer.
  5487. Another equivalent way to write the expression is @code{(&a[0])[i]}.
  5488. @node Declaring an Array
  5489. @section Declaring an Array
  5490. @cindex declaring an array
  5491. @cindex array, declaring
  5492. To make an array declaration, write @code{[@var{length}]} after the
  5493. name being declared. This construct is valid in the declaration of a
  5494. variable, a function parameter, a function value type (the value can't
  5495. be an array, but it can be a pointer to one), a structure field, or a
  5496. union alternative.
  5497. The surrounding declaration specifies the element type of the array;
  5498. that can be any type of data, but not @code{void} or a function type.
  5499. For instance,
  5500. @example
  5501. double a[5];
  5502. @end example
  5503. @noindent
  5504. declares @code{a} as an array of 5 @code{double}s.
  5505. @example
  5506. struct foo bstruct[length];
  5507. @end example
  5508. @noindent
  5509. declares @code{bstruct} as an array of @code{length} objects of type
  5510. @code{struct foo}. A variable array size like this is allowed when
  5511. the array is not file-scope.
  5512. Other declaration constructs can nest within the array declaration
  5513. construct. For instance:
  5514. @example
  5515. struct foo *b[length];
  5516. @end example
  5517. @noindent
  5518. declares @code{b} as an array of @code{length} pointers to
  5519. @code{struct foo}. This shows that the length need not be a constant
  5520. (@pxref{Arrays of Variable Length}).
  5521. @example
  5522. double (*c)[5];
  5523. @end example
  5524. @noindent
  5525. declares @code{c} as a pointer to an array of 5 @code{double}s, and
  5526. @example
  5527. char *(*f (int))[5];
  5528. @end example
  5529. @noindent
  5530. declares @code{f} as a function taking an @code{int} argument and
  5531. returning a pointer to an array of 5 strings (pointers to
  5532. @code{char}s).
  5533. @example
  5534. double aa[5][10];
  5535. @end example
  5536. @noindent
  5537. declares @code{aa} as an array of 5 elements, each of which is an
  5538. array of 10 @code{double}s. This shows how to declare a
  5539. multidimensional array in C (@pxref{Multidimensional Arrays}).
  5540. All these declarations specify the array's length, which is needed in
  5541. these cases in order to allocate storage for the array.
  5542. @node Strings
  5543. @section Strings
  5544. @cindex string
  5545. A string in C is a sequence of elements of type @code{char},
  5546. terminated with the null character, the character with code zero.
  5547. Programs often need to use strings with specific, fixed contents. To
  5548. write one in a C program, use a @dfn{string constant} such as
  5549. @code{"Take me to your leader!"}. The data type of a string constant
  5550. is @code{char *}. For the full syntactic details of writing string
  5551. constants, @ref{String Constants}.
  5552. To declare a place to store a non-constant string, declare an array of
  5553. @code{char}. Keep in mind that it must include one extra @code{char}
  5554. for the terminating null. For instance,
  5555. @example
  5556. char text = @{ 'H', 'e', 'l', 'l', 'o', 0 @};
  5557. @end example
  5558. @noindent
  5559. declares an array named @samp{text} with six elements---five letters
  5560. and the terminating null character. An equivalent way to get the same
  5561. result is this,
  5562. @example
  5563. char text = "Hello";
  5564. @end example
  5565. @noindent
  5566. which copies the elements of the string constant, including @emph{its}
  5567. terminating null character.
  5568. @example
  5569. char message[200];
  5570. @end example
  5571. @noindent
  5572. declares an array long enough to hold a string of 199 ASCII characters
  5573. plus the terminating null character.
  5574. When you store a string into @code{message} be sure to check or prove
  5575. that the length does not exceed its size. For example,
  5576. @example
  5577. void
  5578. set_message (char *text)
  5579. @{
  5580. int i;
  5581. for (i = 0; i < sizeof (message); i++)
  5582. @{
  5583. message[i] = text[i];
  5584. if (text[i] == 0)
  5585. return;
  5586. @}
  5587. fatal_error ("Message is too long for `message');
  5588. @}
  5589. @end example
  5590. It's easy to do this with the standard library function
  5591. @code{strncpy}, which fills out the whole destination array (up to a
  5592. specified length) with null characters. Thus, if the last character
  5593. of the destination is not null, the string did not fit. Many system
  5594. libraries, including the GNU C library, hand-optimize @code{strncpy}
  5595. to run faster than an explicit @code{for}-loop.
  5596. Here's what the code looks like:
  5597. @example
  5598. void
  5599. set_message (char *text)
  5600. @{
  5601. strncpy (message, text, sizeof (message));
  5602. if (message[sizeof (message) - 1] != 0)
  5603. fatal_error ("Message is too long for `message');
  5604. @}
  5605. @end example
  5606. @xref{String and Array Utilities, The GNU C Library, , libc, The GNU C
  5607. Library Reference Manual}, for more information about the standard
  5608. library functions for operating on strings.
  5609. You can avoid putting a fixed length limit on strings you construct or
  5610. operate on by allocating the space for them dynamically.
  5611. @xref{Dynamic Memory Allocation}.
  5612. @node Array Type Designators
  5613. @section Array Type Designators
  5614. Every C type has a type designator, which you make by deleting the
  5615. variable name and the semicolon from a declaration (@pxref{Type
  5616. Designators}). The designators for array types follow this rule, but
  5617. they may appear surprising.
  5618. @example
  5619. @r{type} int a[5]; @r{designator} int [5]
  5620. @r{type} double a[5][3]; @r{designator} double [5][3]
  5621. @r{type} struct foo *a[5]; @r{designator} struct foo *[5]
  5622. @end example
  5623. @node Incomplete Array Types
  5624. @section Incomplete Array Types
  5625. @cindex incomplete array types
  5626. @cindex array types, incomplete
  5627. An array is equivalent, for most purposes, to a pointer to its zeroth
  5628. element. When that is true, the length of the array is irrelevant.
  5629. The length needs to be known only for allocating space for the array, or
  5630. for @code{sizeof} and @code{typeof} (@pxref{Auto Type}). Thus, in some
  5631. contexts C allows
  5632. @itemize @bullet
  5633. @item
  5634. An @code{extern} declaration says how to refer to a variable allocated
  5635. elsewhere. It does not need to allocate space for the variable,
  5636. so if it is an array, you can omit the length. For example,
  5637. @example
  5638. extern int foo[];
  5639. @end example
  5640. @item
  5641. When declaring a function parameter as an array, the argument value
  5642. passed to the function is really a pointer to the array's zeroth
  5643. element. This value does not say how long the array really is, there
  5644. is no need to declare it. For example,
  5645. @example
  5646. int
  5647. func (int foo[])
  5648. @end example
  5649. @end itemize
  5650. These declarations are examples of @dfn{incomplete} array types, types
  5651. that are not fully specified. The incompleteness makes no difference
  5652. for accessing elements of the array, but it matters for some other
  5653. things. For instance, @code{sizeof} is not allowed on an incomplete
  5654. type.
  5655. With multidimensional arrays, only the first dimension can be omitted:
  5656. @example
  5657. extern struct chesspiece *funnyboard foo[][8];
  5658. @end example
  5659. In other words, the code doesn't have to say how many rows there are,
  5660. but it must state how big each row is.
  5661. @node Limitations of C Arrays
  5662. @section Limitations of C Arrays
  5663. @cindex limitations of C arrays
  5664. @cindex first-class object
  5665. Arrays have quirks in C because they are not ``first-class objects'':
  5666. there is no way in C to operate on an array as a unit.
  5667. The other composite objects in C, structures and unions, are
  5668. first-class objects: a C program can copy a structure or union value
  5669. in an assignment, or pass one as an argument to a function, or make a
  5670. function return one. You can't do those things with an array in C@.
  5671. That is because a value you can operate on never has an array type.
  5672. An expression in C can have an array type, but that doesn't produce
  5673. the array as a value. Instead it is converted automatically to a
  5674. pointer to the array's element at index zero. The code can operate
  5675. on the pointer, and through that on individual elements of the array,
  5676. but it can't get and operate on the array as a unit.
  5677. There are three exceptions to this conversion rule, but none of them
  5678. offers a way to operate on the array as a whole.
  5679. First, @samp{&} applied to an expression with array type gives you the
  5680. address of the array, as an array type. However, you can't operate on the
  5681. whole array that way---if you apply @samp{*} to get the array back,
  5682. that expression converts, as usual, to a pointer to its zeroth
  5683. element.
  5684. Second, the operators @code{sizeof}, @code{_Alignof}, and
  5685. @code{typeof} do not convert the array to a pointer; they leave it as
  5686. an array. But they don't operate on the array's data---they only give
  5687. information about its type.
  5688. Third, a string constant used as an initializer for an array is not
  5689. converted to a pointer---rather, the declaration copies the
  5690. @emph{contents} of that string in that one special case.
  5691. You @emph{can} copy the contents of an array, just not with an
  5692. assignment operator. You can do it by calling the library function
  5693. @code{memcpy} or @code{memmove} (@pxref{Copying and Concatenation, The
  5694. GNU C Library, , libc, The GNU C Library Reference Manual}). Also,
  5695. when a structure contains just an array, you can copy that structure.
  5696. An array itself is an lvalue if it is a declared variable, or part of
  5697. a structure or union that is an lvalue. When you construct an array
  5698. from elements (@pxref{Constructing Array Values}), that array is not
  5699. an lvalue.
  5700. @node Multidimensional Arrays
  5701. @section Multidimensional Arrays
  5702. @cindex multidimensional arrays
  5703. @cindex array, multidimensional
  5704. Strictly speaking, all arrays in C are unidimensional. However, you
  5705. can create an array of arrays, which is more or less equivalent to a
  5706. multidimensional array. For example,
  5707. @example
  5708. struct chesspiece *board[8][8];
  5709. @end example
  5710. @noindent
  5711. declares an array of 8 arrays of 8 pointers to @code{struct
  5712. chesspiece}. This data type could represent the state of a chess
  5713. game. To access one square's contents requires two array index
  5714. operations, one for each dimension. For instance, you can write
  5715. @code{board[row][column]}, assuming @code{row} and @code{column}
  5716. are variables with integer values in the proper range.
  5717. How does C understand @code{board[row][column]}? First of all,
  5718. @code{board} is converted automatically to a pointer to the zeroth
  5719. element (at index zero) of @code{board}. Adding @code{row} to that
  5720. makes it point to the desired element. Thus, @code{board[row]}'s
  5721. value is an element of @code{board}---an array of 8 pointers.
  5722. However, as an expression with array type, it is converted
  5723. automatically to a pointer to the array's zeroth element. The second
  5724. array index operation, @code{[column]}, accesses the chosen element
  5725. from that array.
  5726. As this shows, pointer-to-array types are meaningful in C@.
  5727. You can declare a variable that points to a row in a chess board
  5728. like this:
  5729. @example
  5730. struct chesspiece *(*rowptr)[8];
  5731. @end example
  5732. @noindent
  5733. This points to an array of 8 pointers to @code{struct chesspiece}.
  5734. You can assign to it as follows:
  5735. @example
  5736. rowptr = &board[5];
  5737. @end example
  5738. The dimensions don't have to be equal in length. Here we declare
  5739. @code{statepop} as an array to hold the population of each state in
  5740. the United States for each year since 1900:
  5741. @example
  5742. #define NSTATES 50
  5743. @{
  5744. int nyears = current_year - 1900 + 1;
  5745. int statepop[NSTATES][nyears];
  5746. @r{@dots{}}
  5747. @}
  5748. @end example
  5749. The variable @code{statepop} is an array of @code{NSTATES} subarrays,
  5750. each indexed by the year (counting from 1900). Thus, to get the
  5751. element for a particular state and year, we must subscript it first
  5752. by the number that indicates the state, and second by the index for
  5753. the year:
  5754. @example
  5755. statepop[state][year - 1900]
  5756. @end example
  5757. @cindex array, layout in memory
  5758. The subarrays within the multidimensional array are allocated
  5759. consecutively in memory, and within each subarray, its elements are
  5760. allocated consecutively in memory. The most efficient way to process
  5761. all the elements in the array is to scan the last subscript in the
  5762. innermost loop. This means consecutive accesses go to consecutive
  5763. memory locations, which optimizes use of the processor's memory cache.
  5764. For example:
  5765. @example
  5766. int total = 0;
  5767. float average;
  5768. for (int state = 0; state < NSTATES, ++state)
  5769. @{
  5770. for (int year = 0; year < nyears; ++year)
  5771. @{
  5772. total += statepop[state][year];
  5773. @}
  5774. @}
  5775. average = total / nyears;
  5776. @end example
  5777. C's layout for multidimensional arrays is different from Fortran's
  5778. layout. In Fortran, a multidimensional array is not an array of
  5779. arrays; rather, multidimensional arrays are a primitive feature, and
  5780. it is the first index that varies most rapidly between consecutive
  5781. memory locations. Thus, the memory layout of a 50x114 array in C
  5782. matches that of a 114x50 array in Fortran.
  5783. @node Constructing Array Values
  5784. @section Constructing Array Values
  5785. @cindex constructing array values
  5786. @cindex array values, constructing
  5787. You can construct an array from elements by writing them inside
  5788. braces, and preceding all that with the array type's designator in
  5789. parentheses. There is no need to specify the array length, since the
  5790. number of elements determines that. The constructor looks like this:
  5791. @example
  5792. (@var{elttype}[]) @{ @var{elements} @};
  5793. @end example
  5794. Here is an example, which constructs an array of string pointers:
  5795. @example
  5796. (char *[]) @{ "x", "y", "z" @};
  5797. @end example
  5798. That's equivalent in effect to declaring an array with the same
  5799. initializer, like this:
  5800. @example
  5801. char *array[] = @{ "x", "y", "z" @};
  5802. @end example
  5803. and then using the array.
  5804. If all the elements are simple constant expressions, or made up of
  5805. such, then the compound literal can be coerced to a pointer to its
  5806. zeroth element and used to initialize a file-scope variable
  5807. (@pxref{File-Scope Variables}), as shown here:
  5808. @example
  5809. char **foo = (char *[]) @{ "x", "y", "z" @};
  5810. @end example
  5811. @noindent
  5812. The data type of @code{foo} is @code{char **}, which is a pointer
  5813. type, not an array type. The declaration is equivalent to defining
  5814. and then using an array-type variable:
  5815. @example
  5816. char *nameless_array[] = @{ "x", "y", "z" @};
  5817. char **foo = &nameless_array[0];
  5818. @end example
  5819. @node Arrays of Variable Length
  5820. @section Arrays of Variable Length
  5821. @cindex array of variable length
  5822. @cindex variable-length arrays
  5823. In GNU C, you can declare variable-length arrays like any other
  5824. arrays, but with a length that is not a constant expression. The
  5825. storage is allocated at the point of declaration and deallocated when
  5826. the block scope containing the declaration exits. For example:
  5827. @example
  5828. #include <stdio.h> /* @r{Defines @code{FILE}.} */
  5829. #include <string.h> /* @r{Declares @code{str}.} */
  5830. FILE *
  5831. concat_fopen (char *s1, char *s2, char *mode)
  5832. @{
  5833. char str[strlen (s1) + strlen (s2) + 1];
  5834. strcpy (str, s1);
  5835. strcat (str, s2);
  5836. return fopen (str, mode);
  5837. @}
  5838. @end example
  5839. @noindent
  5840. (This uses some standard library functions; see @ref{String and Array
  5841. Utilities, , , libc, The GNU C Library Reference Manual}.)
  5842. The length of an array is computed once when the storage is allocated
  5843. and is remembered for the scope of the array in case it is used in
  5844. @code{sizeof}.
  5845. @strong{Warning:} don't allocate a variable-length array if the size
  5846. might be very large (more than 100,000), or in a recursive function,
  5847. because that is likely to cause stack overflow. Allocate the array
  5848. dynamically instead (@pxref{Dynamic Memory Allocation}).
  5849. Jumping or breaking out of the scope of the array name deallocates the
  5850. storage. Jumping into the scope is not allowed; that gives an error
  5851. message.
  5852. You can also use variable-length arrays as arguments to functions:
  5853. @example
  5854. struct entry
  5855. tester (int len, char data[len][len])
  5856. @{
  5857. @r{@dots{}}
  5858. @}
  5859. @end example
  5860. As usual, a function argument declared with an array type
  5861. is really a pointer to an array that already exists.
  5862. Calling the function does not allocate the array, so there's no
  5863. particular danger of stack overflow in using this construct.
  5864. To pass the array first and the length afterward, use a forward
  5865. declaration in the function's parameter list (another GNU extension).
  5866. For example,
  5867. @example
  5868. struct entry
  5869. tester (int len; char data[len][len], int len)
  5870. @{
  5871. @r{@dots{}}
  5872. @}
  5873. @end example
  5874. The @code{int len} before the semicolon is a @dfn{parameter forward
  5875. declaration}, and it serves the purpose of making the name @code{len}
  5876. known when the declaration of @code{data} is parsed.
  5877. You can write any number of such parameter forward declarations in the
  5878. parameter list. They can be separated by commas or semicolons, but
  5879. the last one must end with a semicolon, which is followed by the
  5880. ``real'' parameter declarations. Each forward declaration must match
  5881. a ``real'' declaration in parameter name and data type. ISO C11 does
  5882. not support parameter forward declarations.
  5883. @node Enumeration Types
  5884. @chapter Enumeration Types
  5885. @cindex enumeration types
  5886. @cindex types, enumeration
  5887. @cindex enumerator
  5888. An @dfn{enumeration type} represents a limited set of integer values,
  5889. each with a name. It is effectively equivalent to a primitive integer
  5890. type.
  5891. Suppose we have a list of possible emotional states to store in an
  5892. integer variable. We can give names to these alternative values with
  5893. an enumeration:
  5894. @example
  5895. enum emotion_state @{ neutral, happy, sad, worried,
  5896. calm, nervous @};
  5897. @end example
  5898. @noindent
  5899. (Never mind that this is a simplistic way to classify emotional states;
  5900. it's just a code example.)
  5901. The names inside the enumeration are called @dfn{enumerators}. The
  5902. enumeration type defines them as constants, and their values are
  5903. consecutive integers; @code{neutral} is 0, @code{happy} is 1,
  5904. @code{sad} is 2, and so on. Alternatively, you can specify values for
  5905. the enumerators explicitly like this:
  5906. @example
  5907. enum emotion_state @{ neutral = 2, happy = 5,
  5908. sad = 20, worried = 10,
  5909. calm = -5, nervous = -300 @};
  5910. @end example
  5911. Each enumerator which does not specify a value gets value zero
  5912. (if it is at the beginning) or the next consecutive integer.
  5913. @example
  5914. /* @r{@code{neutral} is 0 by default,}
  5915. @r{and @code{worried} is 21 by default.} */
  5916. enum emotion_state @{ neutral,
  5917. happy = 5, sad = 20, worried,
  5918. calm = -5, nervous = -300 @};
  5919. @end example
  5920. If an enumerator is obsolete, you can specify that using it should
  5921. cause a warning, by including an attribute in the enumerator's
  5922. declaration. Here is how @code{happy} would look with this
  5923. attribute:
  5924. @example
  5925. happy __attribute__
  5926. ((deprecated
  5927. ("impossible under plutocratic rule")))
  5928. = 5,
  5929. @end example
  5930. @xref{Attributes}.
  5931. You can declare variables with the enumeration type:
  5932. @example
  5933. enum emotion_state feelings_now;
  5934. @end example
  5935. In the C code itself, this is equivalent to declaring the variable
  5936. @code{int}. (If all the enumeration values are positive, it is
  5937. equivalent to @code{unsigned int}.) However, declaring it with the
  5938. enumeration type has an advantage in debugging, because GDB knows it
  5939. should display the current value of the variable using the
  5940. corresponding name. If the variable's type is @code{int}, GDB can
  5941. only show the value as a number.
  5942. The identifier that follows @code{enum} is called a @dfn{type tag}
  5943. since it distinguishes different enumeration types. Type tags are in
  5944. a separate name space and belong to scopes like most other names in C@.
  5945. @xref{Type Tags}, for explanation.
  5946. You can predeclare an @code{enum} type tag like a structure or union
  5947. type tag, like this:
  5948. @example
  5949. enum foo;
  5950. @end example
  5951. @noindent
  5952. The @code{enum} type is incomplete until you finish defining it.
  5953. You can optionally include a trailing comma at the end of a list of
  5954. enumeration values:
  5955. @example
  5956. enum emotion_state @{ neutral, happy, sad, worried,
  5957. calm, nervous, @};
  5958. @end example
  5959. @noindent
  5960. This is useful in some macro definitions, since it enables you to
  5961. assemble the list of enumerators without knowing which one is last.
  5962. The extra comma does not change the meaning of the enumeration in any
  5963. way.
  5964. @node Defining Typedef Names
  5965. @chapter Defining Typedef Names
  5966. @cindex typedef names
  5967. @findex typedef
  5968. You can define a data type keyword as an alias for any type, and then
  5969. use the alias syntactically like a built-in type keyword such as
  5970. @code{int}. You do this using @code{typedef}, so these aliases are
  5971. also called @dfn{typedef names}.
  5972. @code{typedef} is followed by text that looks just like a variable
  5973. declaration, but instead of declaring variables it defines data type
  5974. keywords.
  5975. Here's how to define @code{fooptr} as a typedef alias for the type
  5976. @code{struct foo *}, then declare @code{x} and @code{y} as variables
  5977. with that type:
  5978. @example
  5979. typedef struct foo *fooptr;
  5980. fooptr x, y;
  5981. @end example
  5982. @noindent
  5983. That declaration is equivalent to the following one:
  5984. @example
  5985. struct foo *x, *y;
  5986. @end example
  5987. You can define a typedef alias for any type. For instance, this makes
  5988. @code{frobcount} an alias for type @code{int}:
  5989. @example
  5990. typedef int frobcount;
  5991. @end example
  5992. @noindent
  5993. This doesn't define a new type distinct from @code{int}. Rather,
  5994. @code{frobcount} is another name for the type @code{int}. Once the
  5995. variable is declared, it makes no difference which name the
  5996. declaration used.
  5997. There is a syntactic difference, however, between @code{frobcount} and
  5998. @code{int}: A typedef name cannot be used with
  5999. @code{signed}, @code{unsigned}, @code{long} or @code{short}. It has
  6000. to specify the type all by itself. So you can't write this:
  6001. @example
  6002. unsigned frobcount f1; /* @r{Error!} */
  6003. @end example
  6004. But you can write this:
  6005. @example
  6006. typedef unsigned int unsigned_frobcount;
  6007. unsigned_frobcount f1;
  6008. @end example
  6009. In other words, a typedef name is not an alias for @emph{a keyword}
  6010. such as @code{int}. It stands for a @emph{type}, and that could be
  6011. the type @code{int}.
  6012. Typedef names are in the same namespace as functions and variables, so
  6013. you can't use the same name for a typedef and a function, or a typedef
  6014. and a variable. When a typedef is declared inside a code block, it is
  6015. in scope only in that block.
  6016. @strong{Warning:} Avoid defining typedef names that end in @samp{_t},
  6017. because many of these have standard meanings.
  6018. You can redefine a typedef name to the exact same type as its first
  6019. definition, but you cannot redefine a typedef name to a
  6020. different type, even if the two types are compatible. For example, this
  6021. is valid:
  6022. @example
  6023. typedef int frobcount;
  6024. typedef int frotzcount;
  6025. typedef frotzcount frobcount;
  6026. typedef frobcount frotzcount;
  6027. @end example
  6028. @noindent
  6029. because each typedef name is always defined with the same type
  6030. (@code{int}), but this is not valid:
  6031. @example
  6032. enum foo @{f1, f2, f3@};
  6033. typedef enum foo frobcount;
  6034. typedef int frobcount;
  6035. @end example
  6036. @noindent
  6037. Even though the type @code{enum foo} is compatible with @code{int},
  6038. they are not the @emph{same} type.
  6039. @node Statements
  6040. @chapter Statements
  6041. @cindex statements
  6042. A @dfn{statement} specifies computations to be done for effect; it
  6043. does not produce a value, as an expression would. In general a
  6044. statement ends with a semicolon (@samp{;}), but blocks (which are
  6045. statements, more or less) are an exception to that rule.
  6046. @ifnottex
  6047. @xref{Blocks}.
  6048. @end ifnottex
  6049. The places to use statements are inside a block, and inside a
  6050. complex statement. A @dfn{complex statement} contains one or two
  6051. components that are nested statements. Each such component must
  6052. consist of one and only one statement. The way to put multiple
  6053. statements in such a component is to group them into a @dfn{block}
  6054. (@pxref{Blocks}), which counts as one statement.
  6055. The following sections describe the various kinds of statement.
  6056. @menu
  6057. * Expression Statement:: Evaluate an expression, as a statement,
  6058. usually done for a side effect.
  6059. * if Statement:: Basic conditional execution.
  6060. * if-else Statement:: Multiple branches for conditional execution.
  6061. * Blocks:: Grouping multiple statements together.
  6062. * return Statement:: Return a value from a function.
  6063. * Loop Statements:: Repeatedly executing a statement or block.
  6064. * switch Statement:: Multi-way conditional choices.
  6065. * switch Example:: A plausible example of using @code{switch}.
  6066. * Duffs Device:: A special way to use @code{switch}.
  6067. * Case Ranges:: Ranges of values for @code{switch} cases.
  6068. * Null Statement:: A statement that does nothing.
  6069. * goto Statement:: Jump to another point in the source code,
  6070. identified by a label.
  6071. * Local Labels:: Labels with limited scope.
  6072. * Labels as Values:: Getting the address of a label.
  6073. * Statement Exprs:: A series of statements used as an expression.
  6074. @end menu
  6075. @node Expression Statement
  6076. @section Expression Statement
  6077. @cindex expression statement
  6078. @cindex statement, expression
  6079. The most common kind of statement in C is an @dfn{expression statement}.
  6080. It consists of an expression followed by a
  6081. semicolon. The expression's value is discarded, so the expressions
  6082. that are useful are those that have side effects: assignment
  6083. expressions, increment and decrement expressions, and function calls.
  6084. Here are examples of expression statements:
  6085. @smallexample
  6086. x = 5; /* @r{Assignment expression.} */
  6087. p++; /* @r{Increment expression.} */
  6088. printf ("Done\n"); /* @r{Function call expression.} */
  6089. *p; /* @r{Cause @code{SIGSEGV} signal if @code{p} is null.} */
  6090. x + y; /* @r{Useless statement without effect.} */
  6091. @end smallexample
  6092. In very unusual circumstances we use an expression statement
  6093. whose purpose is to get a fault if an address is invalid:
  6094. @smallexample
  6095. volatile char *p;
  6096. @r{@dots{}}
  6097. *p; /* @r{Cause signal if @code{p} is null.} */
  6098. @end smallexample
  6099. If the target of @code{p} is not declared @code{volatile}, the
  6100. compiler might optimize away the memory access, since it knows that
  6101. the value isn't really used. @xref{volatile}.
  6102. @node if Statement
  6103. @section @code{if} Statement
  6104. @cindex @code{if} statement
  6105. @cindex statement, @code{if}
  6106. @findex if
  6107. An @code{if} statement computes an expression to decide
  6108. whether to execute the following statement or not.
  6109. It looks like this:
  6110. @example
  6111. if (@var{condition})
  6112. @var{execute-if-true}
  6113. @end example
  6114. The first thing this does is compute the value of @var{condition}. If
  6115. that is true (nonzero), then it executes the statement
  6116. @var{execute-if-true}. If the value of @var{condition} is false
  6117. (zero), it doesn't execute @var{execute-if-true}; instead, it does
  6118. nothing.
  6119. This is a @dfn{complex statement} because it contains a component
  6120. @var{if-true-substatement} that is a nested statement. It must be one
  6121. and only one statement. The way to put multiple statements there is
  6122. to group them into a @dfn{block} (@pxref{Blocks}).
  6123. @node if-else Statement
  6124. @section @code{if-else} Statement
  6125. @cindex @code{if}@dots{}@code{else} statement
  6126. @cindex statement, @code{if}@dots{}@code{else}
  6127. @findex else
  6128. An @code{if}-@code{else} statement computes an expression to decide
  6129. which of two nested statements to execute.
  6130. It looks like this:
  6131. @example
  6132. if (@var{condition})
  6133. @var{if-true-substatement}
  6134. else
  6135. @var{if-false-substatement}
  6136. @end example
  6137. The first thing this does is compute the value of @var{condition}. If
  6138. that is true (nonzero), then it executes the statement
  6139. @var{if-true-substatement}. If the value of @var{condition} is false
  6140. (zero), then it executes the statement @var{if-false-substatement} instead.
  6141. This is a @dfn{complex statement} because it contains components
  6142. @var{if-true-substatement} and @var{if-else-substatement} that are
  6143. nested statements. Each must be one and only one statement. The way
  6144. to put multiple statements in such a component is to group them into a
  6145. @dfn{block} (@pxref{Blocks}).
  6146. @node Blocks
  6147. @section Blocks
  6148. @cindex block
  6149. @cindex compound statement
  6150. A @dfn{block} is a construct that contains multiple statements of any
  6151. kind. It begins with @samp{@{} and ends with @samp{@}}, and has a
  6152. series of statements and declarations in between. Another name for
  6153. blocks is @dfn{compound statements}.
  6154. Is a block a statement? Yes and no. It doesn't @emph{look} like a
  6155. normal statement---it does not end with a semicolon. But you can
  6156. @emph{use} it like a statement; anywhere that a statement is required
  6157. or allowed, you can write a block and consider that block a statement.
  6158. So far it seems that a block is a kind of statement with an unusual
  6159. syntax. But that is not entirely true: a function body is also a
  6160. block, and that block is definitely not a statement. The text after a
  6161. function header is not treated as a statement; only a function body is
  6162. allowed there, and nothing else would be meaningful there.
  6163. In a formal grammar we would have to choose---either a block is a kind
  6164. of statement or it is not. But this manual is meant for humans, not
  6165. for parser generators. The clearest answer for humans is, ``a block
  6166. is a statement, in some ways.''
  6167. @cindex nested block
  6168. @cindex internal block
  6169. A block that isn't a function body is called an @dfn{internal block}
  6170. or a @dfn{nested block}. You can put a nested block directly inside
  6171. another block, but more often the nested block is inside some complex
  6172. statement, such as a @code{for} statement or an @code{if} statement.
  6173. There are two uses for nested blocks in C:
  6174. @itemize @bullet
  6175. @item
  6176. To specify the scope for local declarations. For instance, a local
  6177. variable's scope is the rest of the innermost containing block.
  6178. @item
  6179. To write a series of statements where, syntactically, one statement is
  6180. called for. For instance, the @var{execute-if-true} of an @code{if}
  6181. statement is one statement. To put multiple statements there, they
  6182. have to be wrapped in a block, like this:
  6183. @example
  6184. if (x < 0)
  6185. @{
  6186. printf ("x was negative\n");
  6187. x = -x;
  6188. @}
  6189. @end example
  6190. @end itemize
  6191. This example (repeated from above) shows a nested block which serves
  6192. both purposes: it includes two statements (plus a declaration) in the
  6193. body of a @code{while} statement, and it provides the scope for the
  6194. declaration of @code{q}.
  6195. @example
  6196. void
  6197. free_intlist (struct intlistlink *p)
  6198. @{
  6199. while (p)
  6200. @{
  6201. struct intlistlink *q = p;
  6202. p = p->next;
  6203. free (q);
  6204. @}
  6205. @}
  6206. @end example
  6207. @node return Statement
  6208. @section @code{return} Statement
  6209. @cindex @code{return} statement
  6210. @cindex statement, @code{return}
  6211. @findex return
  6212. The @code{return} statement makes the containing function return
  6213. immediately. It has two forms. This one specifies no value to
  6214. return:
  6215. @example
  6216. return;
  6217. @end example
  6218. @noindent
  6219. That form is meant for functions whose return type is @code{void}
  6220. (@pxref{The Void Type}). You can also use it in a function that
  6221. returns nonvoid data, but that's a bad idea, since it makes the
  6222. function return garbage.
  6223. The form that specifies a value looks like this:
  6224. @example
  6225. return @var{value};
  6226. @end example
  6227. @noindent
  6228. which computes the expression @var{value} and makes the function
  6229. return that. If necessary, the value undergoes type conversion to
  6230. the function's declared return value type, which works like
  6231. assigning the value to a variable of that type.
  6232. @node Loop Statements
  6233. @section Loop Statements
  6234. @cindex loop statements
  6235. @cindex statements, loop
  6236. @cindex iteration
  6237. You can use a loop statement when you need to execute a series of
  6238. statements repeatedly, making an @dfn{iteration}. C provides several
  6239. different kinds of loop statements, described in the following
  6240. subsections.
  6241. Every kind of loop statement is a complex statement because contains a
  6242. component, here called @var{body}, which is a nested statement.
  6243. Most often the body is a block.
  6244. @menu
  6245. * while Statement:: Loop as long as a test expression is true.
  6246. * do-while Statement:: Execute a loop once, with further looping
  6247. as long as a test expression is true.
  6248. * break Statement:: End a loop immediately.
  6249. * for Statement:: Iterative looping.
  6250. * Example of for:: An example of iterative looping.
  6251. * Omitted for-Expressions:: for-loop expression options.
  6252. * for-Index Declarations:: for-loop declaration options.
  6253. * continue Statement:: Begin the next cycle of a loop.
  6254. @end menu
  6255. @node while Statement
  6256. @subsection @code{while} Statement
  6257. @cindex @code{while} statement
  6258. @cindex statement, @code{while}
  6259. @findex while
  6260. The @code{while} statement is the simplest loop construct.
  6261. It looks like this:
  6262. @example
  6263. while (@var{test})
  6264. @var{body}
  6265. @end example
  6266. Here, @var{body} is a statement (often a nested block) to repeat, and
  6267. @var{test} is the test expression that controls whether to repeat it again.
  6268. Each iteration of the loop starts by computing @var{test} and, if it
  6269. is true (nonzero), that means the loop should execute @var{body} again
  6270. and then start over.
  6271. Here's an example of advancing to the last structure in a chain of
  6272. structures chained through the @code{next} field:
  6273. @example
  6274. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  6275. @r{@dots{}}
  6276. while (chain->next != NULL)
  6277. chain = chain->next;
  6278. @end example
  6279. @noindent
  6280. This code assumes the chain isn't empty to start with; if the chain is
  6281. empty (that is, if @code{chain} is a null pointer), the code gets a
  6282. @code{SIGSEGV} signal trying to dereference that null pointer (@pxref{Signals}).
  6283. @node do-while Statement
  6284. @subsection @code{do-while} Statement
  6285. @cindex @code{do}--@code{while} statement
  6286. @cindex statement, @code{do}--@code{while}
  6287. @findex do
  6288. The @code{do}--@code{while} statement is a simple loop construct that
  6289. performs the test at the end of the iteration.
  6290. @example
  6291. do
  6292. @var{body}
  6293. while (@var{test});
  6294. @end example
  6295. Here, @var{body} is a statement (possibly a block) to repeat, and
  6296. @var{test} is an expression that controls whether to repeat it again.
  6297. Each iteration of the loop starts by executing @var{body}. Then it
  6298. computes @var{test} and, if it is true (nonzero), that means to go
  6299. back and start over with @var{body}. If @var{test} is false (zero),
  6300. then the loop stops repeating and execution moves on past it.
  6301. @node break Statement
  6302. @subsection @code{break} Statement
  6303. @cindex @code{break} statement
  6304. @cindex statement, @code{break}
  6305. @findex break
  6306. The @code{break} statement looks like @samp{break;}. Its effect is to
  6307. exit immediately from the innermost loop construct or @code{switch}
  6308. statement (@pxref{switch Statement}).
  6309. For example, this loop advances @code{p} until the next null
  6310. character or newline.
  6311. @example
  6312. while (*p)
  6313. @{
  6314. /* @r{End loop if we have reached a newline.} */
  6315. if (*p == '\n')
  6316. break;
  6317. p++
  6318. @}
  6319. @end example
  6320. When there are nested loops, the @code{break} statement exits from the
  6321. innermost loop containing it.
  6322. @example
  6323. struct list_if_tuples
  6324. @{
  6325. struct list_if_tuples next;
  6326. int length;
  6327. data *contents;
  6328. @};
  6329. void
  6330. process_all_elements (struct list_if_tuples *list)
  6331. @{
  6332. while (list)
  6333. @{
  6334. /* @r{Process all the elements in this node's vector,}
  6335. @r{stopping when we reach one that is null.} */
  6336. for (i = 0; i < list->length; i++
  6337. @{
  6338. /* @r{Null element terminates this node's vector.} */
  6339. if (list->contents[i] == NULL)
  6340. /* @r{Exit the @code{for} loop.} */
  6341. break;
  6342. /* @r{Operate on the next element.} */
  6343. process_element (list->contents[i]);
  6344. @}
  6345. list = list->next;
  6346. @}
  6347. @}
  6348. @end example
  6349. The only way in C to exit from an outer loop is with
  6350. @code{goto} (@pxref{goto Statement}).
  6351. @node for Statement
  6352. @subsection @code{for} Statement
  6353. @cindex @code{for} statement
  6354. @cindex statement, @code{for}
  6355. @findex for
  6356. A @code{for} statement uses three expressions written inside a
  6357. parenthetical group to define the repetition of the loop. The first
  6358. expression says how to prepare to start the loop. The second says how
  6359. to test, before each iteration, whether to continue looping. The
  6360. third says how to advance, at the end of an iteration, for the next
  6361. iteration. All together, it looks like this:
  6362. @example
  6363. for (@var{start}; @var{continue-test}; @var{advance})
  6364. @var{body}
  6365. @end example
  6366. The first thing the @code{for} statement does is compute @var{start}.
  6367. The next thing it does is compute the expression @var{continue-test}.
  6368. If that expression is false (zero), the @code{for} statement finishes
  6369. immediately, so @var{body} is executed zero times.
  6370. However, if @var{continue-test} is true (nonzero), the @code{for}
  6371. statement executes @var{body}, then @var{advance}. Then it loops back
  6372. to the not-quite-top to test @var{continue-test} again. But it does
  6373. not compute @var{start} again.
  6374. @node Example of for
  6375. @subsection Example of @code{for}
  6376. Here is the @code{for} statement from the iterative Fibonacci
  6377. function:
  6378. @example
  6379. int i;
  6380. for (i = 1; i < n; ++i)
  6381. /* @r{If @code{n} is 1 or less, the loop runs zero times,} */
  6382. /* @r{since @code{i < n} is false the first time.} */
  6383. @{
  6384. /* @r{Now @var{last} is @code{fib (@var{i})}}
  6385. @r{and @var{prev} is @code{fib (@var{i} @minus{} 1)}.} */
  6386. /* @r{Compute @code{fib (@var{i} + 1)}.} */
  6387. int next = prev + last;
  6388. /* @r{Shift the values down.} */
  6389. prev = last;
  6390. last = next;
  6391. /* @r{Now @var{last} is @code{fib (@var{i} + 1)}}
  6392. @r{and @var{prev} is @code{fib (@var{i})}.}
  6393. @r{But that won't stay true for long,}
  6394. @r{because we are about to increment @var{i}.} */
  6395. @}
  6396. @end example
  6397. In this example, @var{start} is @code{i = 1}, meaning set @code{i} to
  6398. 1. @var{continue-test} is @code{i < n}, meaning keep repeating the
  6399. loop as long as @code{i} is less than @code{n}. @var{advance} is
  6400. @code{i++}, meaning increment @code{i} by 1. The body is a block
  6401. that contains a declaration and two statements.
  6402. @node Omitted for-Expressions
  6403. @subsection Omitted @code{for}-Expressions
  6404. A fully-fleshed @code{for} statement contains all these parts,
  6405. @example
  6406. for (@var{start}; @var{continue-test}; @var{advance})
  6407. @var{body}
  6408. @end example
  6409. @noindent
  6410. but you can omit any of the three expressions inside the parentheses.
  6411. The parentheses and the two semicolons are required syntactically, but
  6412. the expressions between them may be missing. A missing expression
  6413. means this loop doesn't use that particular feature of the @code{for}
  6414. statement.
  6415. Instead of using @var{start}, you can do the loop preparation
  6416. before the @code{for} statement: the effect is the same. So we
  6417. could have written the beginning of the previous example this way:
  6418. @example
  6419. int i = 0;
  6420. for (; i < n; ++i)
  6421. @end example
  6422. @noindent
  6423. instead of this way:
  6424. @example
  6425. int i;
  6426. for (i = 0; i < n; ++i)
  6427. @end example
  6428. Omitting @var{continue-test} means the loop runs forever (or until
  6429. something else causes exit from it). Statements inside the loop can
  6430. test conditions for termination and use @samp{break;} to exit. This
  6431. is more flexible since you can put those tests anywhere in the loop,
  6432. not solely at the beginning.
  6433. Putting an expression in @var{advance} is almost equivalent to writing
  6434. it at the end of the loop body; it does almost the same thing. The
  6435. only difference is for the @code{continue} statement (@pxref{continue
  6436. Statement}). So we could have written this:
  6437. @example
  6438. for (i = 0; i < n;)
  6439. @{
  6440. @r{@dots{}}
  6441. ++i;
  6442. @}
  6443. @end example
  6444. @noindent
  6445. instead of this:
  6446. @example
  6447. for (i = 0; i < n; ++i)
  6448. @{
  6449. @r{@dots{}}
  6450. @}
  6451. @end example
  6452. The choice is mainly a matter of what is more readable for
  6453. programmers. However, there is also a syntactic difference:
  6454. @var{advance} is an expression, not a statement. It can't include
  6455. loops, blocks, declarations, etc.
  6456. @node for-Index Declarations
  6457. @subsection @code{for}-Index Declarations
  6458. You can declare loop-index variables directly in the @var{start}
  6459. portion of the @code{for}-loop, like this:
  6460. @example
  6461. for (int i = 0; i < n; ++i)
  6462. @{
  6463. @r{@dots{}}
  6464. @}
  6465. @end example
  6466. This kind of @var{start} is limited to a single declaration; it can
  6467. declare one or more variables, separated by commas, all of which are
  6468. the same @var{basetype} (@code{int}, in this example):
  6469. @example
  6470. for (int i = 0, j = 1, *p = NULL; i < n; ++i, ++j, ++p)
  6471. @{
  6472. @r{@dots{}}
  6473. @}
  6474. @end example
  6475. @noindent
  6476. The scope of these variables is the @code{for} statement as a whole.
  6477. See @ref{Variable Declarations} for a explanation of @var{basetype}.
  6478. Variables declared in @code{for} statements should have initializers.
  6479. Omitting the initialization gives the variables unpredictable initial
  6480. values, so this code is erroneous.
  6481. @example
  6482. for (int i; i < n; ++i)
  6483. @{
  6484. @r{@dots{}}
  6485. @}
  6486. @end example
  6487. @node continue Statement
  6488. @subsection @code{continue} Statement
  6489. @cindex @code{continue} statement
  6490. @cindex statement, @code{continue}
  6491. @findex continue
  6492. The @code{continue} statement looks like @samp{continue;}, and its
  6493. effect is to jump immediately to the end of the innermost loop
  6494. construct. If it is a @code{for}-loop, the next thing that happens
  6495. is to execute the loop's @var{advance} expression.
  6496. For example, this loop increments @code{p} until the next null character
  6497. or newline, and operates (in some way not shown) on all the characters
  6498. in the line except for spaces. All it does with spaces is skip them.
  6499. @example
  6500. for (;*p; ++p)
  6501. @{
  6502. /* @r{End loop if we have reached a newline.} */
  6503. if (*p == '\n')
  6504. break;
  6505. /* @r{Pay no attention to spaces.} */
  6506. if (*p == ' ')
  6507. continue;
  6508. /* @r{Operate on the next character.} */
  6509. @r{@dots{}}
  6510. @}
  6511. @end example
  6512. @noindent
  6513. Executing @samp{continue;} skips the loop body but it does not
  6514. skip the @var{advance} expression, @code{p++}.
  6515. We could also write it like this:
  6516. @example
  6517. for (;*p; ++p)
  6518. @{
  6519. /* @r{Exit if we have reached a newline.} */
  6520. if (*p == '\n')
  6521. break;
  6522. /* @r{Pay no attention to spaces.} */
  6523. if (*p != ' ')
  6524. @{
  6525. /* @r{Operate on the next character.} */
  6526. @r{@dots{}}
  6527. @}
  6528. @}
  6529. @end example
  6530. The advantage of using @code{continue} is that it reduces the
  6531. depth of nesting.
  6532. Contrast @code{continue} with the @code{break} statement. @xref{break
  6533. Statement}.
  6534. @node switch Statement
  6535. @section @code{switch} Statement
  6536. @cindex @code{switch} statement
  6537. @cindex statement, @code{switch}
  6538. @findex switch
  6539. @findex case
  6540. @findex default
  6541. The @code{switch} statement selects code to run according to the value
  6542. of an expression. The expression, in parentheses, follows the keyword
  6543. @code{switch}. After that come all the cases to select among,
  6544. inside braces. It looks like this:
  6545. @example
  6546. switch (@var{selector})
  6547. @{
  6548. @var{cases}@r{@dots{}}
  6549. @}
  6550. @end example
  6551. A case can look like this:
  6552. @example
  6553. case @var{value}:
  6554. @var{statements}
  6555. break;
  6556. @end example
  6557. @noindent
  6558. which means ``come here if @var{selector} happens to have the value
  6559. @var{value},'' or like this (a GNU C extension):
  6560. @example
  6561. case @var{rangestart} ... @var{rangeend}:
  6562. @var{statements}
  6563. break;
  6564. @end example
  6565. @noindent
  6566. which means ``come here if @var{selector} happens to have a value
  6567. between @var{rangestart} and @var{rangeend} (inclusive).'' @xref{Case
  6568. Ranges}.
  6569. The values in @code{case} labels must reduce to integer constants.
  6570. They can use arithmetic, and @code{enum} constants, but they cannot
  6571. refer to data in memory, because they have to be computed at compile
  6572. time. It is an error if two @code{case} labels specify the same
  6573. value, or ranges that overlap, or if one is a range and the other is a
  6574. value in that range.
  6575. You can also define a default case to handle ``any other value,'' like
  6576. this:
  6577. @example
  6578. default:
  6579. @var{statements}
  6580. break;
  6581. @end example
  6582. If the @code{switch} statement has no @code{default:} label, then it
  6583. does nothing when the value matches none of the cases.
  6584. The brace-group inside the @code{switch} statement is a block, and you
  6585. can declare variables with that scope just as in any other block
  6586. (@pxref{Blocks}). However, initializers in these declarations won't
  6587. necessarily be executed every time the @code{switch} statement runs,
  6588. so it is best to avoid giving them initializers.
  6589. @code{break;} inside a @code{switch} statement exits immediately from
  6590. the @code{switch} statement. @xref{break Statement}.
  6591. If there is no @code{break;} at the end of the code for a case,
  6592. execution continues into the code for the following case. This
  6593. happens more often by mistake than intentionally, but since this
  6594. feature is used in real code, we cannot eliminate it.
  6595. @strong{Warning:} When one case is intended to fall through to the
  6596. next, write a comment like @samp{falls through} to say it's
  6597. intentional. That way, other programmers won't assume it was an error
  6598. and ``fix'' it erroneously.
  6599. Consecutive @code{case} statements could, pedantically, be considered
  6600. an instance of falling through, but we don't consider or treat them that
  6601. way because they won't confuse anyone.
  6602. @node switch Example
  6603. @section Example of @code{switch}
  6604. Here's an example of using the @code{switch} statement
  6605. to distinguish among characters:
  6606. @cindex counting vowels and punctuation
  6607. @example
  6608. struct vp @{ int vowels, punct; @};
  6609. struct vp
  6610. count_vowels_and_punct (char *string)
  6611. @{
  6612. int c;
  6613. int vowels = 0;
  6614. int punct = 0;
  6615. /* @r{Don't change the parameter itself.} */
  6616. /* @r{That helps in debugging.} */
  6617. char *p = string;
  6618. struct vp value;
  6619. while (c = *p++)
  6620. switch (c)
  6621. @{
  6622. case 'y':
  6623. case 'Y':
  6624. /* @r{We assume @code{y_is_consonant} will check surrounding
  6625. letters to determine whether this y is a vowel.} */
  6626. if (y_is_consonant (p - 1))
  6627. break;
  6628. /* @r{Falls through} */
  6629. case 'a':
  6630. case 'e':
  6631. case 'i':
  6632. case 'o':
  6633. case 'u':
  6634. case 'A':
  6635. case 'E':
  6636. case 'I':
  6637. case 'O':
  6638. case 'U':
  6639. vowels++;
  6640. break;
  6641. case '.':
  6642. case ',':
  6643. case ':':
  6644. case ';':
  6645. case '?':
  6646. case '!':
  6647. case '\"':
  6648. case '\'':
  6649. punct++;
  6650. break;
  6651. @}
  6652. value.vowels = vowels;
  6653. value.punct = punct;
  6654. return value;
  6655. @}
  6656. @end example
  6657. @node Duffs Device
  6658. @section Duff's Device
  6659. @cindex Duff's device
  6660. The cases in a @code{switch} statement can be inside other control
  6661. constructs. For instance, we can use a technique known as @dfn{Duff's
  6662. device} to optimize this simple function,
  6663. @example
  6664. void
  6665. copy (char *to, char *from, int count)
  6666. @{
  6667. while (count > 0)
  6668. *to++ = *from++, count--;
  6669. @}
  6670. @end example
  6671. @noindent
  6672. which copies memory starting at @var{from} to memory starting at
  6673. @var{to}.
  6674. Duff's device involves unrolling the loop so that it copies
  6675. several characters each time around, and using a @code{switch} statement
  6676. to enter the loop body at the proper point:
  6677. @example
  6678. void
  6679. copy (char *to, char *from, int count)
  6680. @{
  6681. if (count <= 0)
  6682. return;
  6683. int n = (count + 7) / 8;
  6684. switch (count % 8)
  6685. @{
  6686. do @{
  6687. case 0: *to++ = *from++;
  6688. case 7: *to++ = *from++;
  6689. case 6: *to++ = *from++;
  6690. case 5: *to++ = *from++;
  6691. case 4: *to++ = *from++;
  6692. case 3: *to++ = *from++;
  6693. case 2: *to++ = *from++;
  6694. case 1: *to++ = *from++;
  6695. @} while (--n > 0);
  6696. @}
  6697. @}
  6698. @end example
  6699. @node Case Ranges
  6700. @section Case Ranges
  6701. @cindex case ranges
  6702. @cindex ranges in case statements
  6703. You can specify a range of consecutive values in a single @code{case} label,
  6704. like this:
  6705. @example
  6706. case @var{low} ... @var{high}:
  6707. @end example
  6708. @noindent
  6709. This has the same effect as the proper number of individual @code{case}
  6710. labels, one for each integer value from @var{low} to @var{high}, inclusive.
  6711. This feature is especially useful for ranges of ASCII character codes:
  6712. @example
  6713. case 'A' ... 'Z':
  6714. @end example
  6715. @strong{Be careful:} with integers, write spaces around the @code{...}
  6716. to prevent it from being parsed wrong. For example, write this:
  6717. @example
  6718. case 1 ... 5:
  6719. @end example
  6720. @noindent
  6721. rather than this:
  6722. @example
  6723. case 1...5:
  6724. @end example
  6725. @node Null Statement
  6726. @section Null Statement
  6727. @cindex null statement
  6728. @cindex statement, null
  6729. A @dfn{null statement} is just a semicolon. It does nothing.
  6730. A null statement is a placeholder for use where a statement is
  6731. grammatically required, but there is nothing to be done. For
  6732. instance, sometimes all the work of a @code{for}-loop is done in the
  6733. @code{for}-header itself, leaving no work for the body. Here is an
  6734. example that searches for the first newline in @code{array}:
  6735. @example
  6736. for (p = array; *p != '\n'; p++)
  6737. ;
  6738. @end example
  6739. @node goto Statement
  6740. @section @code{goto} Statement and Labels
  6741. @cindex @code{goto} statement
  6742. @cindex statement, @code{goto}
  6743. @cindex label
  6744. @findex goto
  6745. The @code{goto} statement looks like this:
  6746. @example
  6747. goto @var{label};
  6748. @end example
  6749. @noindent
  6750. Its effect is to transfer control immediately to another part of the
  6751. current function---where the label named @var{label} is defined.
  6752. An ordinary label definition looks like this:
  6753. @example
  6754. @var{label}:
  6755. @end example
  6756. @noindent
  6757. and it can appear before any statement. You can't use @code{default}
  6758. as a label, since that has a special meaning for @code{switch}
  6759. statements.
  6760. An ordinary label doesn't need a separate declaration; defining it is
  6761. enough.
  6762. Here's an example of using @code{goto} to implement a loop
  6763. equivalent to @code{do}--@code{while}:
  6764. @example
  6765. @{
  6766. loop_restart:
  6767. @var{body}
  6768. if (@var{condition})
  6769. goto loop_restart;
  6770. @}
  6771. @end example
  6772. The name space of labels is separate from that of variables and functions.
  6773. Thus, there is no error in using a single name in both ways:
  6774. @example
  6775. @{
  6776. int foo; // @r{Variable @code{foo}.}
  6777. foo: // @r{Label @code{foo}.}
  6778. @var{body}
  6779. if (foo > 0) // @r{Variable @code{foo}.}
  6780. goto foo; // @r{Label @code{foo}.}
  6781. @}
  6782. @end example
  6783. Blocks have no effect on ordinary labels; each label name is defined
  6784. throughout the whole of the function it appears in. It looks strange to
  6785. jump into a block with @code{goto}, but it works. For example,
  6786. @example
  6787. if (x < 0)
  6788. goto negative;
  6789. if (y < 0)
  6790. @{
  6791. negative:
  6792. printf ("Negative\n");
  6793. return;
  6794. @}
  6795. @end example
  6796. If the goto jumps into the scope of a variable, it does not
  6797. initialize the variable. For example, if @code{x} is negative,
  6798. @example
  6799. if (x < 0)
  6800. goto negative;
  6801. if (y < 0)
  6802. @{
  6803. int i = 5;
  6804. negative:
  6805. printf ("Negative, and i is %d\n", i);
  6806. return;
  6807. @}
  6808. @end example
  6809. @noindent
  6810. prints junk because @code{i} was not initialized.
  6811. If the block declares a variable-length automatic array, jumping into
  6812. it gives a compilation error. However, jumping out of the scope of a
  6813. variable-length array works fine, and deallocates its storage.
  6814. A label can't come directly before a declaration, so the code can't
  6815. jump directly to one. For example, this is not allowed:
  6816. @example
  6817. @{
  6818. goto foo;
  6819. foo:
  6820. int x = 5;
  6821. bar(&x);
  6822. @}
  6823. @end example
  6824. @noindent
  6825. The workaround is to add a statement, even an empty statement,
  6826. directly after the label. For example:
  6827. @example
  6828. @{
  6829. goto foo;
  6830. foo:
  6831. ;
  6832. int x = 5;
  6833. bar(&x);
  6834. @}
  6835. @end example
  6836. Likewise, a label can't be the last thing in a block. The workaround
  6837. solution is the same: add a semicolon after the label.
  6838. These unnecessary restrictions on labels make no sense, and ought in
  6839. principle to be removed; but they do only a little harm since labels
  6840. and @code{goto} are rarely the best way to write a program.
  6841. These examples are all artificial; it would be more natural to
  6842. write them in other ways, without @code{goto}. For instance,
  6843. the clean way to write the example that prints @samp{Negative} is this:
  6844. @example
  6845. if (x < 0 || y < 0)
  6846. @{
  6847. printf ("Negative\n");
  6848. return;
  6849. @}
  6850. @end example
  6851. @noindent
  6852. It is hard to construct simple examples where @code{goto} is actually
  6853. the best way to write a program. Its rare good uses tend to be in
  6854. complex code, thus not apt for the purpose of explaining the meaning
  6855. of @code{goto}.
  6856. The only good time to use @code{goto} is when it makes the code
  6857. simpler than any alternative. Jumping backward is rarely desirable,
  6858. because usually the other looping and control constructs give simpler
  6859. code. Using @code{goto} to jump forward is more often desirable, for
  6860. instance when a function needs to do some processing in an error case
  6861. and errors can occur at various different places within the function.
  6862. @node Local Labels
  6863. @section Locally Declared Labels
  6864. @cindex local labels
  6865. @cindex macros, local labels
  6866. @findex __label__
  6867. In GNU C you can declare @dfn{local labels} in any nested block
  6868. scope. A local label is used in a @code{goto} statement just like an
  6869. ordinary label, but you can only reference it within the block in
  6870. which it was declared.
  6871. A local label declaration looks like this:
  6872. @example
  6873. __label__ @var{label};
  6874. @end example
  6875. @noindent
  6876. or
  6877. @example
  6878. __label__ @var{label1}, @var{label2}, @r{@dots{}};
  6879. @end example
  6880. Local label declarations must come at the beginning of the block,
  6881. before any ordinary declarations or statements.
  6882. The label declaration declares the label @emph{name}, but does not define
  6883. the label itself. That's done in the usual way, with
  6884. @code{@var{label}:}, before one of the statements in the block.
  6885. The local label feature is useful for complex macros. If a macro
  6886. contains nested loops, a @code{goto} can be useful for breaking out of
  6887. them. However, an ordinary label whose scope is the whole function
  6888. cannot be used: if the macro can be expanded several times in one
  6889. function, the label will be multiply defined in that function. A
  6890. local label avoids this problem. For example:
  6891. @example
  6892. #define SEARCH(value, array, target) \
  6893. do @{ \
  6894. __label__ found; \
  6895. __auto_type _SEARCH_target = (target); \
  6896. __auto_type _SEARCH_array = (array); \
  6897. int i, j; \
  6898. int value; \
  6899. for (i = 0; i < max; i++) \
  6900. for (j = 0; j < max; j++) \
  6901. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6902. @{ (value) = i; goto found; @} \
  6903. (value) = -1; \
  6904. found:; \
  6905. @} while (0)
  6906. @end example
  6907. This could also be written using a statement expression
  6908. (@pxref{Statement Exprs}):
  6909. @example
  6910. #define SEARCH(array, target) \
  6911. (@{ \
  6912. __label__ found; \
  6913. __auto_type _SEARCH_target = (target); \
  6914. __auto_type _SEARCH_array = (array); \
  6915. int i, j; \
  6916. int value; \
  6917. for (i = 0; i < max; i++) \
  6918. for (j = 0; j < max; j++) \
  6919. if (_SEARCH_array[i][j] == _SEARCH_target) \
  6920. @{ value = i; goto found; @} \
  6921. value = -1; \
  6922. found: \
  6923. value; \
  6924. @})
  6925. @end example
  6926. Ordinary labels are visible throughout the function where they are
  6927. defined, and only in that function. However, explicitly declared
  6928. local labels of a block are visible in nested functions declared
  6929. within that block. @xref{Nested Functions}, for details.
  6930. @xref{goto Statement}.
  6931. @node Labels as Values
  6932. @section Labels as Values
  6933. @cindex labels as values
  6934. @cindex computed gotos
  6935. @cindex goto with computed label
  6936. @cindex address of a label
  6937. In GNU C, you can get the address of a label defined in the current
  6938. function (or a local label defined in the containing function) with
  6939. the unary operator @samp{&&}. The value has type @code{void *}. This
  6940. value is a constant and can be used wherever a constant of that type
  6941. is valid. For example:
  6942. @example
  6943. void *ptr;
  6944. @r{@dots{}}
  6945. ptr = &&foo;
  6946. @end example
  6947. To use these values requires a way to jump to one. This is done
  6948. with the computed goto statement@footnote{The analogous feature in
  6949. Fortran is called an assigned goto, but that name seems inappropriate in
  6950. C, since you can do more with label addresses than store them in special label
  6951. variables.}, @code{goto *@var{exp};}. For example,
  6952. @example
  6953. goto *ptr;
  6954. @end example
  6955. @noindent
  6956. Any expression of type @code{void *} is allowed.
  6957. @xref{goto Statement}.
  6958. @menu
  6959. * Label Value Uses:: Examples of using label values.
  6960. * Label Value Caveats:: Limitations of label values.
  6961. @end menu
  6962. @node Label Value Uses
  6963. @subsection Label Value Uses
  6964. One use for label-valued constants is to initialize a static array to
  6965. serve as a jump table:
  6966. @example
  6967. static void *array[] = @{ &&foo, &&bar, &&hack @};
  6968. @end example
  6969. Then you can select a label with indexing, like this:
  6970. @example
  6971. goto *array[i];
  6972. @end example
  6973. @noindent
  6974. Note that this does not check whether the subscript is in bounds---array
  6975. indexing in C never checks that.
  6976. You can make the table entries offsets instead of addresses
  6977. by subtracting one label from the others. Here is an example:
  6978. @example
  6979. static const int array[] = @{ &&foo - &&foo, &&bar - &&foo,
  6980. &&hack - &&foo @};
  6981. goto *(&&foo + array[i]);
  6982. @end example
  6983. @noindent
  6984. Using offsets is preferable in shared libraries, as it avoids the need
  6985. for dynamic relocation of the array elements; therefore, the array can
  6986. be read-only.
  6987. An array of label values or offsets serves a purpose much like that of
  6988. the @code{switch} statement. The @code{switch} statement is cleaner,
  6989. so use @code{switch} by preference when feasible.
  6990. Another use of label values is in an interpreter for threaded code.
  6991. The labels within the interpreter function can be stored in the
  6992. threaded code for super-fast dispatching.
  6993. @node Label Value Caveats
  6994. @subsection Label Value Caveats
  6995. Jumping to a label defined in another function does not work.
  6996. It can cause unpredictable results.
  6997. The best way to avoid this is to store label values only in
  6998. automatic variables, or static variables whose names are declared
  6999. within the function. Never pass them as arguments.
  7000. @cindex cloning
  7001. An optimization known as @dfn{cloning} generates multiple simplified
  7002. variants of a function's code, for use with specific fixed arguments.
  7003. Using label values in certain ways, such as saving the address in one
  7004. call to the function and using it again in another call, would make cloning
  7005. give incorrect results. These functions must disable cloning.
  7006. Inlining calls to the function would also result in multiple copies of
  7007. the code, each with its own value of the same label. Using the label
  7008. in a computed goto is no problem, because the computed goto inhibits
  7009. inlining. However, using the label value in some other way, such as
  7010. an indication of where an error occurred, would be optimized wrong.
  7011. These functions must disable inlining.
  7012. To prevent inlining or cloning of a function, specify
  7013. @code{__attribute__((__noinline__,__noclone__))} in its definition.
  7014. @xref{Attributes}.
  7015. When a function uses a label value in a static variable initializer,
  7016. that automatically prevents inlining or cloning the function.
  7017. @node Statement Exprs
  7018. @section Statements and Declarations in Expressions
  7019. @cindex statements inside expressions
  7020. @cindex declarations inside expressions
  7021. @cindex expressions containing statements
  7022. @c the above section title wrapped and causes an underfull hbox.. i
  7023. @c changed it from "within" to "in". --mew 4feb93
  7024. A block enclosed in parentheses can be used as an expression in GNU
  7025. C@. This provides a way to use local variables, loops and switches within
  7026. an expression. We call it a @dfn{statement expression}.
  7027. Recall that a block is a sequence of statements
  7028. surrounded by braces. In this construct, parentheses go around the
  7029. braces. For example:
  7030. @example
  7031. (@{ int y = foo (); int z;
  7032. if (y > 0) z = y;
  7033. else z = - y;
  7034. z; @})
  7035. @end example
  7036. @noindent
  7037. is a valid (though slightly more complex than necessary) expression
  7038. for the absolute value of @code{foo ()}.
  7039. The last statement in the block should be an expression statement; an
  7040. expression followed by a semicolon, that is. The value of this
  7041. expression serves as the value of statement expression. If the last
  7042. statement is anything else, the statement expression's value is
  7043. @code{void}.
  7044. This feature is mainly useful in making macro definitions compute each
  7045. operand exactly once. @xref{Macros and Auto Type}.
  7046. Statement expressions are not allowed in expressions that must be
  7047. constant, such as the value for an enumerator, the width of a
  7048. bit-field, or the initial value of a static variable.
  7049. Jumping into a statement expression---with @code{goto}, or using a
  7050. @code{switch} statement outside the statement expression---is an
  7051. error. With a computed @code{goto} (@pxref{Labels as Values}), the
  7052. compiler can't detect the error, but it still won't work.
  7053. Jumping out of a statement expression is permitted, but since
  7054. subexpressions in C are not computed in a strict order, it is
  7055. unpredictable which other subexpressions will have been computed by
  7056. then. For example,
  7057. @example
  7058. foo (), ((@{ bar1 (); goto a; 0; @}) + bar2 ()), baz();
  7059. @end example
  7060. @noindent
  7061. calls @code{foo} and @code{bar1} before it jumps, and never
  7062. calls @code{baz}, but may or may not call @code{bar2}. If @code{bar2}
  7063. does get called, that occurs after @code{foo} and before @code{bar1}.
  7064. @node Variables
  7065. @chapter Variables
  7066. @cindex variables
  7067. Every variable used in a C program needs to be made known by a
  7068. @dfn{declaration}. It can be used only after it has been declared.
  7069. It is an error to declare a variable name more than once in the same
  7070. scope; an exception is that @code{extern} declarations and tentative
  7071. definitions can coexist with another declaration of the same
  7072. variable.
  7073. Variables can be declared anywhere within a block or file. (Older
  7074. versions of C required that all variable declarations within a block
  7075. occur before any statements.)
  7076. Variables declared within a function or block are @dfn{local} to
  7077. it. This means that the variable name is visible only until the end
  7078. of that function or block, and the memory space is allocated only
  7079. while control is within it.
  7080. Variables declared at the top level in a file are called @dfn{file-scope}.
  7081. They are assigned fixed, distinct memory locations, so they retain
  7082. their values for the whole execution of the program.
  7083. @menu
  7084. * Variable Declarations:: Name a variable and and reserve space for it.
  7085. * Initializers:: Assigning inital values to variables.
  7086. * Designated Inits:: Assigning initial values to array elements
  7087. at particular array indices.
  7088. * Auto Type:: Obtaining the type of a variable.
  7089. * Local Variables:: Variables declared in function definitions.
  7090. * File-Scope Variables:: Variables declared outside of
  7091. function definitions.
  7092. * Static Local Variables:: Variables declared within functions,
  7093. but with permanent storage allocation.
  7094. * Extern Declarations:: Declaring a variable
  7095. which is allocated somewhere else.
  7096. * Allocating File-Scope:: When is space allocated
  7097. for file-scope variables?
  7098. * auto and register:: Historically used storage directions.
  7099. * Omitting Types:: The bad practice of declaring variables
  7100. with implicit type.
  7101. @end menu
  7102. @node Variable Declarations
  7103. @section Variable Declarations
  7104. @cindex variable declarations
  7105. @cindex declaration of variables
  7106. Here's what a variable declaration looks like:
  7107. @example
  7108. @var{keywords} @var{basetype} @var{decorated-variable} @r{[}= @var{init}@r{]};
  7109. @end example
  7110. The @var{keywords} specify how to handle the scope of the variable
  7111. name and the allocation of its storage. Most declarations have
  7112. no keywords because the defaults are right for them.
  7113. C allows these keywords to come before or after @var{basetype}, or
  7114. even in the middle of it as in @code{unsigned static int}, but don't
  7115. do that---it would surprise other programmers. Always write the
  7116. keywords first.
  7117. The @var{basetype} can be any of the predefined types of C, or a type
  7118. keyword defined with @code{typedef}. It can also be @code{struct
  7119. @var{tag}}, @code{union @var{tag}}, or @code{enum @var{tag}}. In
  7120. addition, it can include type qualifiers such as @code{const} and
  7121. @code{volatile} (@pxref{Type Qualifiers}).
  7122. In the simplest case, @var{decorated-variable} is just the variable
  7123. name. That declares the variable with the type specified by
  7124. @var{basetype}. For instance,
  7125. @example
  7126. int foo;
  7127. @end example
  7128. @noindent
  7129. uses @code{int} as the @var{basetype} and @code{foo} as the
  7130. @var{decorated-variable}. It declares @code{foo} with type
  7131. @code{int}.
  7132. @example
  7133. struct tree_node foo;
  7134. @end example
  7135. @noindent
  7136. declares @code{foo} with type @code{struct tree_node}.
  7137. @menu
  7138. * Declaring Arrays and Pointers:: Declaration syntax for variables of
  7139. array and pointer types.
  7140. * Combining Variable Declarations:: More than one variable declaration
  7141. in a single statement.
  7142. @end menu
  7143. @node Declaring Arrays and Pointers
  7144. @subsection Declaring Arrays and Pointers
  7145. @cindex declaring arrays and pointers
  7146. @cindex array, declaring
  7147. @cindex pointers, declaring
  7148. To declare a variable that is an array, write
  7149. @code{@var{variable}[@var{length}]} for @var{decorated-variable}:
  7150. @example
  7151. int foo[5];
  7152. @end example
  7153. To declare a variable that has a pointer type, write
  7154. @code{*@var{variable}} for @var{decorated-variable}:
  7155. @example
  7156. struct list_elt *foo;
  7157. @end example
  7158. These constructs nest. For instance,
  7159. @example
  7160. int foo[3][5];
  7161. @end example
  7162. @noindent
  7163. declares @code{foo} as an array of 3 arrays of 5 integers each,
  7164. @example
  7165. struct list_elt *foo[5];
  7166. @end example
  7167. @noindent
  7168. declares @code{foo} as an array of 5 pointers to structures, and
  7169. @example
  7170. struct list_elt **foo;
  7171. @end example
  7172. @noindent
  7173. declares @code{foo} as a pointer to a pointer to a structure.
  7174. @example
  7175. int **(*foo[30])(int, double);
  7176. @end example
  7177. @noindent
  7178. declares @code{foo} as an array of 30 pointers to functions
  7179. (@pxref{Function Pointers}), each of which must accept two arguments
  7180. (one @code{int} and one @code{double}) and return type @code{int **}.
  7181. @example
  7182. void
  7183. bar (int size)
  7184. @{
  7185. int foo[size];
  7186. @r{@dots{}}
  7187. @}
  7188. @end example
  7189. @noindent
  7190. declares @code{foo} as an array of integers with a size specified at
  7191. run time when the function @code{bar} is called.
  7192. @node Combining Variable Declarations
  7193. @subsection Combining Variable Declarations
  7194. @cindex combining variable declarations
  7195. @cindex variable declarations, combining
  7196. @cindex declarations, combining
  7197. When multiple declarations have the same @var{keywords} and
  7198. @var{basetype}, you can combine them using commas. Thus,
  7199. @example
  7200. @var{keywords} @var{basetype}
  7201. @var{decorated-variable-1} @r{[}= @var{init1}@r{]},
  7202. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7203. @end example
  7204. @noindent
  7205. is equivalent to
  7206. @example
  7207. @var{keywords} @var{basetype}
  7208. @var{decorated-variable-1} @r{[}= @var{init1}@r{]};
  7209. @var{keywords} @var{basetype}
  7210. @var{decorated-variable-2} @r{[}= @var{init2}@r{]};
  7211. @end example
  7212. Here are some simple examples:
  7213. @example
  7214. int a, b;
  7215. int a = 1, b = 2;
  7216. int a, *p, array[5];
  7217. int a = 0, *p = &a, array[5] = @{1, 2@};
  7218. @end example
  7219. @noindent
  7220. In the last two examples, @code{a} is an @code{int}, @code{p} is a
  7221. pointer to @code{int}, and @code{array} is an array of 5 @code{int}s.
  7222. Since the initializer for @code{array} specifies only two elements,
  7223. the other three elements are initialized to zero.
  7224. @node Initializers
  7225. @section Initializers
  7226. @cindex initializers
  7227. A variable's declaration, unless it is @code{extern}, should also
  7228. specify its initial value. For numeric and pointer-type variables,
  7229. the initializer is an expression for the value. If necessary, it is
  7230. converted to the variable's type, just as in an assignment.
  7231. You can also initialize a local structure-type (@pxref{Structures}) or
  7232. local union-type (@pxref{Unions}) variable this way, from an
  7233. expression whose value has the same type. But you can't initialize an
  7234. array this way (@pxref{Arrays}), since arrays are not first-class
  7235. objects in C (@pxref{Limitations of C Arrays}) and there is no array
  7236. assignment.
  7237. You can initialize arrays and structures componentwise,
  7238. with a list of the elements or components. You can initialize
  7239. a union with any one of its alternatives.
  7240. @itemize @bullet
  7241. @item
  7242. A component-wise initializer for an array consists of element values
  7243. surrounded by @samp{@{@r{@dots{}}@}}. If the values in the initializer
  7244. don't cover all the elements in the array, the remaining elements are
  7245. initialized to zero.
  7246. You can omit the size of the array when you declare it, and let
  7247. the initializer specify the size:
  7248. @example
  7249. int array[] = @{ 3, 9, 12 @};
  7250. @end example
  7251. @item
  7252. A component-wise initializer for a structure consists of field values
  7253. surrounded by @samp{@{@r{@dots{}}@}}. Write the field values in the same
  7254. order as the fields are declared in the structure. If the values in
  7255. the initializer don't cover all the fields in the structure, the
  7256. remaining fields are initialized to zero.
  7257. @item
  7258. The initializer for a union-type variable has the form @code{@{
  7259. @var{value} @}}, where @var{value} initializes the @emph{first alternative}
  7260. in the union definition.
  7261. @end itemize
  7262. For an array of arrays, a structure containing arrays, an array of
  7263. structures, etc., you can nest these constructs. For example,
  7264. @example
  7265. struct point @{ double x, y; @};
  7266. struct point series[]
  7267. = @{ @{0, 0@}, @{1.5, 2.8@}, @{99, 100.0004@} @};
  7268. @end example
  7269. You can omit a pair of inner braces if they contain the right
  7270. number of elements for the sub-value they initialize, so that
  7271. no elements or fields need to be filled in with zeros.
  7272. But don't do that very much, as it gets confusing.
  7273. An array of @code{char} can be initialized using a string constant.
  7274. Recall that the string constant includes an implicit null character at
  7275. the end (@pxref{String Constants}). Using a string constant as
  7276. initializer means to use its contents as the initial values of the
  7277. array elements. Here are examples:
  7278. @example
  7279. char text[6] = "text!"; /* @r{Includes the null.} */
  7280. char text[5] = "text!"; /* @r{Excludes the null.} */
  7281. char text[] = "text!"; /* @r{Gets length 6.} */
  7282. char text[]
  7283. = @{ 't', 'e', 'x', 't', '!', 0 @}; /* @r{same as above.} */
  7284. char text[] = @{ "text!" @}; /* @r{Braces are optional.} */
  7285. @end example
  7286. @noindent
  7287. and this kind of initializer can be nested inside braces to initialize
  7288. structures or arrays that contain a @code{char}-array.
  7289. In like manner, you can use a wide string constant to initialize
  7290. an array of @code{wchar_t}.
  7291. @node Designated Inits
  7292. @section Designated Initializers
  7293. @cindex initializers with labeled elements
  7294. @cindex labeled elements in initializers
  7295. @cindex case labels in initializers
  7296. @cindex designated initializers
  7297. In a complex structure or long array, it's useful to indicate
  7298. which field or element we are initializing.
  7299. To designate specific array elements during initialization, include
  7300. the array index in brackets, and an assignment operator, for each
  7301. element:
  7302. @example
  7303. int foo[10] = @{ [3] = 42, [7] = 58 @};
  7304. @end example
  7305. @noindent
  7306. This does the same thing as:
  7307. @example
  7308. int foo[10] = @{ 0, 0, 0, 42, 0, 0, 0, 58, 0, 0 @};
  7309. @end example
  7310. The array initialization can include non-designated element values
  7311. alongside designated indices; these follow the expected ordering
  7312. of the array initialization, so that
  7313. @example
  7314. int foo[10] = @{ [3] = 42, 43, 44, [7] = 58 @};
  7315. @end example
  7316. @noindent
  7317. does the same thing as:
  7318. @example
  7319. int foo[10] = @{ 0, 0, 0, 42, 43, 44, 0, 58, 0, 0 @};
  7320. @end example
  7321. Note that you can only use constant expressions as array index values,
  7322. not variables.
  7323. If you need to initialize a subsequence of sequential array elements to
  7324. the same value, you can specify a range:
  7325. @example
  7326. int foo[100] = @{ [0 ... 19] = 42, [20 ... 99] = 43 @};
  7327. @end example
  7328. @noindent
  7329. Using a range this way is a GNU C extension.
  7330. When subsequence ranges overlap, each element is initialized by the
  7331. last specification that applies to it. Thus, this initialization is
  7332. equivalent to the previous one.
  7333. @example
  7334. int foo[100] = @{ [0 ... 99] = 43, [0 ... 19] = 42 @};
  7335. @end example
  7336. @noindent
  7337. as the second overrides the first for elements 0 through 19.
  7338. The value used to initialize a range of elements is evaluated only
  7339. once, for the first element in the range. So for example, this code
  7340. @example
  7341. int random_values[100]
  7342. = @{ [0 ... 99] = get_random_number() @};
  7343. @end example
  7344. @noindent
  7345. would initialize all 100 elements of the array @code{random_values} to
  7346. the same value---probably not what is intended.
  7347. Similarly, you can initialize specific fields of a structure variable
  7348. by specifying the field name prefixed with a dot:
  7349. @example
  7350. struct point @{ int x; int y; @};
  7351. struct point foo = @{ .y = 42; @};
  7352. @end example
  7353. @noindent
  7354. The same syntax works for union variables as well:
  7355. @example
  7356. union int_double @{ int i; double d; @};
  7357. union int_double foo = @{ .d = 34 @};
  7358. @end example
  7359. @noindent
  7360. This casts the integer value 34 to a double and stores it
  7361. in the union variable @code{foo}.
  7362. You can designate both array elements and structure elements in
  7363. the same initialization; for example, here's an array of point
  7364. structures:
  7365. @example
  7366. struct point point_array[10] = @{ [4].y = 32, [6].y = 39 @};
  7367. @end example
  7368. Along with the capability to specify particular array and structure
  7369. elements to initialize comes the possibility of initializing the same
  7370. element more than once:
  7371. @example
  7372. int foo[10] = @{ [4] = 42, [4] = 98 @};
  7373. @end example
  7374. @noindent
  7375. In such a case, the last initialization value is retained.
  7376. @node Auto Type
  7377. @section Referring to a Type with @code{__auto_type}
  7378. @findex __auto_type
  7379. @findex typeof
  7380. @cindex macros, types of arguments
  7381. You can declare a variable copying the type from
  7382. the initializer by using @code{__auto_type} instead of a particular type.
  7383. Here's an example:
  7384. @example
  7385. #define max(a,b) \
  7386. (@{ __auto_type _a = (a); \
  7387. __auto_type _b = (b); \
  7388. _a > _b ? _a : _b @})
  7389. @end example
  7390. This defines @code{_a} to be of the same type as @code{a}, and
  7391. @code{_b} to be of the same type as @code{b}. This is a useful thing
  7392. to do in a macro that ought to be able to handle any type of data
  7393. (@pxref{Macros and Auto Type}).
  7394. The original GNU C method for obtaining the type of a value is to use
  7395. @code{typeof}, which takes as an argument either a value or the name of
  7396. a type. The previous example could also be written as:
  7397. @example
  7398. #define max(a,b) \
  7399. (@{ typeof(a) _a = (a); \
  7400. typeof(b) _b = (b); \
  7401. _a > _b ? _a : _b @})
  7402. @end example
  7403. @code{typeof} is more flexible than @code{__auto_type}; however, the
  7404. principal use case for @code{typeof} is in variable declarations with
  7405. initialization, which is exactly what @code{__auto_type} handles.
  7406. @node Local Variables
  7407. @section Local Variables
  7408. @cindex local variables
  7409. @cindex variables, local
  7410. Declaring a variable inside a function definition (@pxref{Function
  7411. Definitions}) makes the variable name @dfn{local} to the containing
  7412. block---that is, the containing pair of braces. More precisely, the
  7413. variable's name is visible starting just after where it appears in the
  7414. declaration, and its visibility continues until the end of the block.
  7415. Local variables in C are generally @dfn{automatic} variables: each
  7416. variable's storage exists only from the declaration to the end of the
  7417. block. Execution of the declaration allocates the storage, computes
  7418. the initial value, and stores it in the variable. The end of the
  7419. block deallocates the storage.@footnote{Due to compiler optimizations,
  7420. allocation and deallocation don't necessarily really happen at
  7421. those times.}
  7422. @strong{Warning:} Two declarations for the same local variable
  7423. in the same scope are an error.
  7424. @strong{Warning:} Automatic variables are stored in the run-time stack.
  7425. The total space for the program's stack may be limited; therefore,
  7426. in using very large arrays, it may be necessary to allocate
  7427. them in some other way to stop the program from crashing.
  7428. @strong{Warning:} If the declaration of an automatic variable does not
  7429. specify an initial value, the variable starts out containing garbage.
  7430. In this example, the value printed could be anything at all:
  7431. @example
  7432. @{
  7433. int i;
  7434. printf ("Print junk %d\n", i);
  7435. @}
  7436. @end example
  7437. In a simple test program, that statement is likely to print 0, simply
  7438. because every process starts with memory zeroed. But don't rely on it
  7439. to be zero---that is erroneous.
  7440. @strong{Note:} Make sure to store a value into each local variable (by
  7441. assignment, or by initialization) before referring to its value.
  7442. @node File-Scope Variables
  7443. @section File-Scope Variables
  7444. @cindex file-scope variables
  7445. @cindex global variables
  7446. @cindex variables, file-scope
  7447. @cindex variables, global
  7448. A variable declaration at the top level in a file (not inside a
  7449. function definition) declares a @dfn{file-scope variable}. Loading a
  7450. program allocates the storage for all the file-scope variables in it,
  7451. and initializes them too.
  7452. Each file-scope variable is either @dfn{static} (limited to one
  7453. compilation module) or @dfn{global} (shared with all compilation
  7454. modules in the program). To make the variable static, write the
  7455. keyword @code{static} at the start of the declaration. Omitting
  7456. @code{static} makes the variable global.
  7457. The initial value for a file-scope variable can't depend on the
  7458. contents of storage, and can't call any functions.
  7459. @example
  7460. int foo = 5; /* @r{Valid.} */
  7461. int bar = foo; /* @r{Invalid!} */
  7462. int bar = sin (1.0); /* @r{Invalid!} */
  7463. @end example
  7464. But it can use the address of another file-scope variable:
  7465. @example
  7466. int foo;
  7467. int *bar = &foo; /* @r{Valid.} */
  7468. int arr[5];
  7469. int *bar3 = &arr[3]; /* @r{Valid.} */
  7470. int *bar4 = arr + 4; /* @r{Valid.} */
  7471. @end example
  7472. It is valid for a module to have multiple declarations for a
  7473. file-scope variable, as long as they are all global or all static, but
  7474. at most one declaration can specify an initial value for it.
  7475. @node Static Local Variables
  7476. @section Static Local Variables
  7477. @cindex static local variables
  7478. @cindex variables, static local
  7479. @findex static
  7480. The keyword @code{static} in a local variable declaration says to
  7481. allocate the storage for the variable permanently, just like a
  7482. file-scope variable, even if the declaration is within a function.
  7483. Here's an example:
  7484. @example
  7485. int
  7486. increment_counter ()
  7487. @{
  7488. static int counter = 0;
  7489. return ++counter;
  7490. @}
  7491. @end example
  7492. The scope of the name @code{counter} runs from the declaration to the
  7493. end of the containing block, just like an automatic local variable,
  7494. but its storage is permanent, so the value persists from one call to
  7495. the next. As a result, each call to @code{increment_counter}
  7496. returns a different, unique value.
  7497. The initial value of a static local variable has the same limitations
  7498. as for file-scope variables: it can't depend on the contents of
  7499. storage or call any functions. It can use the address of a file-scope
  7500. variable or a static local variable, because those addresses are
  7501. determined before the program runs.
  7502. @node Extern Declarations
  7503. @section @code{extern} Declarations
  7504. @cindex @code{extern} declarations
  7505. @cindex declarations, @code{extern}
  7506. @findex extern
  7507. An @code{extern} declaration is used to refer to a global variable
  7508. whose principal declaration comes elsewhere---in the same module, or in
  7509. another compilation module. It looks like this:
  7510. @example
  7511. extern @var{basetype} @var{decorated-variable};
  7512. @end example
  7513. Its meaning is that, in the current scope, the variable name refers to
  7514. the file-scope variable of that name---which needs to be declared in a
  7515. non-@code{extern}, non-@code{static} way somewhere else.
  7516. For instance, if one compilation module has this global variable
  7517. declaration
  7518. @example
  7519. int error_count = 0;
  7520. @end example
  7521. @noindent
  7522. then other compilation modules can specify this
  7523. @example
  7524. extern int error_count;
  7525. @end example
  7526. @noindent
  7527. to allow reference to the same variable.
  7528. The usual place to write an @code{extern} declaration is at top level
  7529. in a source file, but you can write an @code{extern} declaration
  7530. inside a block to make a global or static file-scope variable
  7531. accessible in that block.
  7532. Since an @code{extern} declaration does not allocate space for the
  7533. variable, it can omit the size of an array:
  7534. @example
  7535. extern int array[];
  7536. @end example
  7537. You can use @code{array} normally in all contexts where it is
  7538. converted automatically to a pointer. However, to use it as the
  7539. operand of @code{sizeof} is an error, since the size is unknown.
  7540. It is valid to have multiple @code{extern} declarations for the same
  7541. variable, even in the same scope, if they give the same type. They do
  7542. not conflict---they agree. For an array, it is legitimate for some
  7543. @code{extern} declarations can specify the size while others omit it.
  7544. However, if two declarations give different sizes, that is an error.
  7545. Likewise, you can use @code{extern} declarations at file scope
  7546. (@pxref{File-Scope Variables}) followed by an ordinary global
  7547. (non-static) declaration of the same variable. They do not conflict,
  7548. because they say compatible things about the same meaning of the variable.
  7549. @node Allocating File-Scope
  7550. @section Allocating File-Scope Variables
  7551. @cindex allocation file-scope variables
  7552. @cindex file-scope variables, allocating
  7553. Some file-scope declarations allocate space for the variable, and some
  7554. don't.
  7555. A file-scope declaration with an initial value @emph{must} allocate
  7556. space for the variable; if there are two of such declarations for the
  7557. same variable, even in different compilation modules, they conflict.
  7558. An @code{extern} declaration @emph{never} allocates space for the variable.
  7559. If all the top-level declarations of a certain variable are
  7560. @code{extern}, the variable never gets memory space. If that variable
  7561. is used anywhere in the program, the use will be reported as an error,
  7562. saying that the variable is not defined.
  7563. @cindex tentative definition
  7564. A file-scope declaration without an initial value is called a
  7565. @dfn{tentative definition}. This is a strange hybrid: it @emph{can}
  7566. allocate space for the variable, but does not insist. So it causes no
  7567. conflict, no error, if the variable has another declaration that
  7568. allocates space for it, perhaps in another compilation module. But if
  7569. nothing else allocates space for the variable, the tentative
  7570. definition will do it. Any number of compilation modules can declare
  7571. the same variable in this way, and that is sufficient for all of them
  7572. to use the variable.
  7573. @c @opindex -fno-common
  7574. @c @opindex --warn_common
  7575. In programs that are very large or have many contributors, it may be
  7576. wise to adopt the convention of never using tentative definitions.
  7577. You can use the compilation option @option{-fno-common} to make them
  7578. an error, or @option{--warn-common} to warn about them.
  7579. If a file-scope variable gets its space through a tentative
  7580. definition, it starts out containing all zeros.
  7581. @node auto and register
  7582. @section @code{auto} and @code{register}
  7583. @cindex @code{auto} declarations
  7584. @cindex @code{register} declarations
  7585. @findex auto
  7586. @findex register
  7587. For historical reasons, you can write @code{auto} or @code{register}
  7588. before a local variable declaration. @code{auto} merely emphasizes
  7589. that the variable isn't static; it changes nothing.
  7590. @code{register} suggests to the compiler storing this variable in a
  7591. register. However, GNU C ignores this suggestion, since it can
  7592. choose the best variables to store in registers without any hints.
  7593. It is an error to take the address of a variable declared
  7594. @code{register}, so you cannot use the unary @samp{&} operator on it.
  7595. If the variable is an array, you can't use it at all (other than as
  7596. the operand of @code{sizeof}), which makes it rather useless.
  7597. @node Omitting Types
  7598. @section Omitting Types in Declarations
  7599. @cindex omitting types in declarations
  7600. The syntax of C traditionally allows omitting the data type in a
  7601. declaration if it specifies a storage class, a type qualifier (see the
  7602. next chapter), or @code{auto} or @code{register}. Then the type
  7603. defaults to @code{int}. For example:
  7604. @example
  7605. auto foo = 42;
  7606. @end example
  7607. This is bad practice; if you see it, fix it.
  7608. @node Type Qualifiers
  7609. @chapter Type Qualifiers
  7610. A declaration can include type qualifiers to advise the compiler
  7611. about how the variable will be used. There are three different
  7612. qualifiers, @code{const}, @code{volatile} and @code{restrict}. They
  7613. pertain to different issues, so you can use more than one together.
  7614. For instance, @code{const volatile} describes a value that the
  7615. program is not allowed to change, but might have a different value
  7616. each time the program examines it. (This might perhaps be a special
  7617. hardware register, or part of shared memory.)
  7618. If you are just learning C, you can skip this chapter.
  7619. @menu
  7620. * const:: Variables whose values don't change.
  7621. * volatile:: Variables whose values may be accessed
  7622. or changed outside of the control of
  7623. this program.
  7624. * restrict Pointers:: Restricted pointers for code optimization.
  7625. * restrict Pointer Example:: Example of how that works.
  7626. @end menu
  7627. @node const
  7628. @section @code{const} Variables and Fields
  7629. @cindex @code{const} variables and fields
  7630. @cindex variables, @code{const}
  7631. @findex const
  7632. You can mark a variable as ``constant'' by writing @code{const} in
  7633. front of the declaration. This says to treat any assignment to that
  7634. variable as an error. It may also permit some compiler
  7635. optimizations---for instance, to fetch the value only once to satisfy
  7636. multiple references to it. The construct looks like this:
  7637. @example
  7638. const double pi = 3.14159;
  7639. @end example
  7640. After this definition, the code can use the variable @code{pi}
  7641. but cannot assign a different value to it.
  7642. @example
  7643. pi = 3.0; /* @r{Error!} */
  7644. @end example
  7645. Simple variables that are constant can be used for the same purposes
  7646. as enumeration constants, and they are not limited to integers. The
  7647. constantness of the variable propagates into pointers, too.
  7648. A pointer type can specify that the @emph{target} is constant. For
  7649. example, the pointer type @code{const double *} stands for a pointer
  7650. to a constant @code{double}. That's the typethat results from taking
  7651. the address of @code{pi}. Such a pointer can't be dereferenced in the
  7652. left side of an assignment.
  7653. @example
  7654. *(&pi) = 3.0; /* @r{Error!} */
  7655. @end example
  7656. Nonconstant pointers can be converted automatically to constant
  7657. pointers, but not vice versa. For instance,
  7658. @example
  7659. const double *cptr;
  7660. double *ptr;
  7661. cptr = &pi; /* @r{Valid.} */
  7662. cptr = ptr; /* @r{Valid.} */
  7663. ptr = cptr; /* @r{Error!} */
  7664. ptr = &pi; /* @r{Error!} */
  7665. @end example
  7666. This is not an ironclad protection against modifying the value. You
  7667. can always cast the constant pointer to a nonconstant pointer type:
  7668. @example
  7669. ptr = (double *)cptr; /* @r{Valid.} */
  7670. ptr = (double *)&pi; /* @r{Valid.} */
  7671. @end example
  7672. However, @code{const} provides a way to show that a certain function
  7673. won't modify the data structure whose address is passed to it. Here's
  7674. an example:
  7675. @example
  7676. int
  7677. string_length (const char *string)
  7678. @{
  7679. int count = 0;
  7680. while (*string++)
  7681. count++;
  7682. return count;
  7683. @}
  7684. @end example
  7685. @noindent
  7686. Using @code{const char *} for the parameter is a way of saying this
  7687. function never modifies the memory of the string itself.
  7688. In calling @code{string_length}, you can specify an ordinary
  7689. @code{char *} since that can be converted automatically to @code{const
  7690. char *}.
  7691. @node volatile
  7692. @section @code{volatile} Variables and Fields
  7693. @cindex @code{volatile} variables and fields
  7694. @cindex variables, @code{volatile}
  7695. @findex volatile
  7696. The GNU C compiler often performs optimizations that eliminate the
  7697. need to write or read a variable. For instance,
  7698. @example
  7699. int foo;
  7700. foo = 1;
  7701. foo++;
  7702. @end example
  7703. @noindent
  7704. might simply store the value 2 into @code{foo}, without ever storing 1.
  7705. These optimizations can also apply to structure fields in some cases.
  7706. If the memory containing @code{foo} is shared with another program,
  7707. or if it is examined asynchronously by hardware, such optimizations
  7708. could confuse the communication. Using @code{volatile} is one way
  7709. to prevent them.
  7710. Writing @code{volatile} with the type in a variable or field declaration
  7711. says that the value may be examined or changed for reasons outside the
  7712. control of the program at any moment. Therefore, the program must
  7713. execute in a careful way to assure correct interaction with those
  7714. accesses, whenever they may occur.
  7715. The simplest use looks like this:
  7716. @example
  7717. volatile int lock;
  7718. @end example
  7719. This directs the compiler not to do certain common optimizations on
  7720. use of the variable @code{lock}. All the reads and writes for a volatile
  7721. variable or field are really done, and done in the order specified
  7722. by the source code. Thus, this code:
  7723. @example
  7724. lock = 1;
  7725. list = list->next;
  7726. if (lock)
  7727. lock_broken (&lock);
  7728. lock = 0;
  7729. @end example
  7730. @noindent
  7731. really stores the value 1 in @code{lock}, even though there is no
  7732. sign it is really used, and the @code{if} statement reads and
  7733. checks the value of @code{lock}, rather than assuming it is still 1.
  7734. A limited amount of optimization can be done, in principle, on
  7735. @code{volatile} variables and fields: multiple references between two
  7736. sequence points (@pxref{Sequence Points}) can be simplified together.
  7737. Use of @code{volatile} does not eliminate the flexibility in ordering
  7738. the computation of the operands of most operators. For instance, in
  7739. @code{lock + foo ()}, the order of accessing @code{lock} and calling
  7740. @code{foo} is not specified, so they may be done in either order; the
  7741. fact that @code{lock} is @code{volatile} has no effect on that.
  7742. @node restrict Pointers
  7743. @section @code{restrict}-Qualified Pointers
  7744. @cindex @code{restrict} pointers
  7745. @cindex pointers, @code{restrict}-qualified
  7746. @findex restrict
  7747. You can declare a pointer as ``restricted'' using the @code{restrict}
  7748. type qualifier, like this:
  7749. @example
  7750. int *restrict p = x;
  7751. @end example
  7752. @noindent
  7753. This enables better optimization of code that uses the pointer.
  7754. If @code{p} is declared with @code{restrict}, and then the code
  7755. references the object that @code{p} points to (using @code{*p} or
  7756. @code{p[@var{i}]}), the @code{restrict} declaration promises that the
  7757. code will not access that object in any other way---only through
  7758. @code{p}.
  7759. For instance, it means the code must not use another pointer
  7760. to access the same space, as shown here:
  7761. @example
  7762. int *restrict p = @var{whatever};
  7763. int *q = p;
  7764. foo (*p, *q);
  7765. @end example
  7766. @noindent
  7767. That contradicts the @code{restrict} promise by accessing the object
  7768. that @code{p} points to using @code{q}, which bypasses @code{p}.
  7769. Likewise, it must not do this:
  7770. @example
  7771. int *restrict p = @var{whatever};
  7772. struct @{ int *a, *b; @} s;
  7773. s.a = p;
  7774. foo (*p, *s.a);
  7775. @end example
  7776. @noindent
  7777. This example uses a structure field instead of the variable @code{q}
  7778. to hold the other pointer, and that contradicts the promise just the
  7779. same.
  7780. The keyword @code{restrict} also promises that @code{p} won't point to
  7781. the allocated space of any automatic or static variable. So the code
  7782. must not do this:
  7783. @example
  7784. int a;
  7785. int *restrict p = &a;
  7786. foo (*p, a);
  7787. @end example
  7788. @noindent
  7789. because that does direct access to the object (@code{a}) that @code{p}
  7790. points to, which bypasses @code{p}.
  7791. If the code makes such promises with @code{restrict} then breaks them,
  7792. execution is unpredictable.
  7793. @node restrict Pointer Example
  7794. @section @code{restrict} Pointer Example
  7795. Here are examples where @code{restrict} enables real optimization.
  7796. In this example, @code{restrict} assures GCC that the array @code{out}
  7797. points to does not overlap with the array @code{in} points to.
  7798. @example
  7799. void
  7800. process_data (const char *in,
  7801. char * restrict out,
  7802. size_t size)
  7803. @{
  7804. for (i = 0; i < size; i++)
  7805. out[i] = in[i] + in[i + 1];
  7806. @}
  7807. @end example
  7808. Here's a simple tree structure, where each tree node holds data of
  7809. type @code{PAYLOAD} plus two subtrees.
  7810. @example
  7811. struct foo
  7812. @{
  7813. PAYLOAD payload;
  7814. struct foo *left;
  7815. struct foo *right;
  7816. @};
  7817. @end example
  7818. Now here's a function to null out both pointers in the @code{left}
  7819. subtree.
  7820. @example
  7821. void
  7822. null_left (struct foo *a)
  7823. @{
  7824. a->left->left = NULL;
  7825. a->left->right = NULL;
  7826. @}
  7827. @end example
  7828. Since @code{*a} and @code{*a->left} have the same data type,
  7829. they could legitimately alias (@pxref{Aliasing}). Therefore,
  7830. the compiled code for @code{null_left} must read @code{a->left}
  7831. again from memory when executing the second assignment statement.
  7832. We can enable optimization, so that it does not need to read
  7833. @code{a->left} again, by writing @code{null_left} this in a less
  7834. obvious way.
  7835. @example
  7836. void
  7837. null_left (struct foo *a)
  7838. @{
  7839. struct foo *b = a->left;
  7840. b->left = NULL;
  7841. b->right = NULL;
  7842. @}
  7843. @end example
  7844. A more elegant way to fix this is with @code{restrict}.
  7845. @example
  7846. void
  7847. null_left (struct foo *restrict a)
  7848. @{
  7849. a->left->left = NULL;
  7850. a->left->right = NULL;
  7851. @}
  7852. @end example
  7853. Declaring @code{a} as @code{restrict} asserts that other pointers such
  7854. as @code{a->left} will not point to the same memory space as @code{a}.
  7855. Therefore, the memory location @code{a->left->left} cannot be the same
  7856. memory as @code{a->left}. Knowing this, the compiled code may avoid
  7857. reloading @code{a->left} for the second statement.
  7858. @node Functions
  7859. @chapter Functions
  7860. @cindex functions
  7861. We have already presented many examples of functions, so if you've
  7862. read this far, you basically understand the concept of a function. It
  7863. is vital, nonetheless, to have a chapter in the manual that collects
  7864. all the information about functions.
  7865. @menu
  7866. * Function Definitions:: Writing the body of a function.
  7867. * Function Declarations:: Declaring the interface of a function.
  7868. * Function Calls:: Using functions.
  7869. * Function Call Semantics:: Call-by-value argument passing.
  7870. * Function Pointers:: Using references to functions.
  7871. * The main Function:: Where execution of a GNU C program begins.
  7872. * Advanced Definitions:: Advanced features of function definitions.
  7873. * Obsolete Definitions:: Obsolete features still used
  7874. in function definitions in old code.
  7875. @end menu
  7876. @node Function Definitions
  7877. @section Function Definitions
  7878. @cindex function definitions
  7879. @cindex defining functions
  7880. We have already presented many examples of function definitions. To
  7881. summarize the rules, a function definition looks like this:
  7882. @example
  7883. @var{returntype}
  7884. @var{functionname} (@var{parm_declarations}@r{@dots{}})
  7885. @{
  7886. @var{body}
  7887. @}
  7888. @end example
  7889. The part before the open-brace is called the @dfn{function header}.
  7890. Write @code{void} as the @var{returntype} if the function does
  7891. not return a value.
  7892. @menu
  7893. * Function Parameter Variables:: Syntax and semantics
  7894. of function parameters.
  7895. * Forward Function Declarations:: Functions can only be called after
  7896. they have been defined or declared.
  7897. * Static Functions:: Limiting visibility of a function.
  7898. * Arrays as Parameters:: Functions that accept array arguments.
  7899. * Structs as Parameters:: Functions that accept structure arguments.
  7900. @end menu
  7901. @node Function Parameter Variables
  7902. @subsection Function Parameter Variables
  7903. @cindex function parameter variables
  7904. @cindex parameter variables in functions
  7905. @cindex parameter list
  7906. A function parameter variable is a local variable (@pxref{Local
  7907. Variables}) used within the function to store the value passed as an
  7908. argument in a call to the function. Usually we say ``function
  7909. parameter'' or ``parameter'' for short, not mentioning the fact that
  7910. it's a variable.
  7911. We declare these variables in the beginning of the function
  7912. definition, in the @dfn{parameter list}. For example,
  7913. @example
  7914. fib (int n)
  7915. @end example
  7916. @noindent
  7917. has a parameter list with one function parameter @code{n}, which has
  7918. type @code{int}.
  7919. Function parameter declarations differ from ordinary variable
  7920. declarations in several ways:
  7921. @itemize @bullet
  7922. @item
  7923. Inside the function definition header, commas separate parameter
  7924. declarations, and each parameter needs a complete declaration
  7925. including the type. For instance, if a function @code{foo} has two
  7926. @code{int} parameters, write this:
  7927. @example
  7928. foo (int a, int b)
  7929. @end example
  7930. You can't share the common @code{int} between the two declarations:
  7931. @example
  7932. foo (int a, b) /* @r{Invalid!} */
  7933. @end example
  7934. @item
  7935. A function parameter variable is initialized to whatever value is
  7936. passed in the function call, so its declaration cannot specify an
  7937. initial value.
  7938. @item
  7939. Writing an array type in a function parameter declaration has the
  7940. effect of declaring it as a pointer. The size specified for the array
  7941. has no effect at all, and we normally omit the size. Thus,
  7942. @example
  7943. foo (int a[5])
  7944. foo (int a[])
  7945. foo (int *a)
  7946. @end example
  7947. @noindent
  7948. are equivalent.
  7949. @item
  7950. The scope of the parameter variables is the entire function body,
  7951. notwithstanding the fact that they are written in the function header,
  7952. which is just outside the function body.
  7953. @end itemize
  7954. If a function has no parameters, it would be most natural for the
  7955. list of parameters in its definition to be empty. But that, in C, has
  7956. a special meaning for historical reasons: ``Do not check that calls to
  7957. this function have the right number of arguments.'' Thus,
  7958. @example
  7959. int
  7960. foo ()
  7961. @{
  7962. return 5;
  7963. @}
  7964. int
  7965. bar (int x)
  7966. @{
  7967. return foo (x);
  7968. @}
  7969. @end example
  7970. @noindent
  7971. would not report a compilation error in passing @code{x} as an
  7972. argument to @code{foo}. By contrast,
  7973. @example
  7974. int
  7975. foo (void)
  7976. @{
  7977. return 5;
  7978. @}
  7979. int
  7980. bar (int x)
  7981. @{
  7982. return foo (x);
  7983. @}
  7984. @end example
  7985. @noindent
  7986. would report an error because @code{foo} is supposed to receive
  7987. no arguments.
  7988. @node Forward Function Declarations
  7989. @subsection Forward Function Declarations
  7990. @cindex forward function declarations
  7991. @cindex function declarations, forward
  7992. The order of the function definitions in the source code makes no
  7993. difference, except that each function needs to be defined or declared
  7994. before code uses it.
  7995. The definition of a function also declares its name for the rest of
  7996. the containing scope. But what if you want to call the function
  7997. before its definition? To permit that, write a compatible declaration
  7998. of the same function, before the first call. A declaration that
  7999. prefigures a subsequent definition in this way is called a
  8000. @dfn{forward declaration}. The function declaration can be at top
  8001. @c ??? file scope
  8002. level or within a block, and it applies until the end of the containing
  8003. scope.
  8004. @xref{Function Declarations}, for more information about these
  8005. declarations.
  8006. @node Static Functions
  8007. @subsection Static Functions
  8008. @cindex static functions
  8009. @cindex functions, static
  8010. @findex static
  8011. The keyword @code{static} in a function definition limits the
  8012. visibility of the name to the current compilation module. (That's the
  8013. same thing @code{static} does in variable declarations;
  8014. @pxref{File-Scope Variables}.) For instance, if one compilation module
  8015. contains this code:
  8016. @example
  8017. static int
  8018. foo (void)
  8019. @{
  8020. @r{@dots{}}
  8021. @}
  8022. @end example
  8023. @noindent
  8024. then the code of that compilation module can call @code{foo} anywhere
  8025. after the definition, but other compilation modules cannot refer to it
  8026. at all.
  8027. @cindex forward declaration
  8028. @cindex static function, declaration
  8029. To call @code{foo} before its definition, it needs a forward
  8030. declaration, which should use @code{static} since the function
  8031. definition does. For this function, it looks like this:
  8032. @example
  8033. static int foo (void);
  8034. @end example
  8035. It is generally wise to use @code{static} on the definitions of
  8036. functions that won't be called from outside the same compilation
  8037. module. This makes sure that calls are not added in other modules.
  8038. If programmers decide to change the function's calling convention, or
  8039. understand all the consequences of its use, they will only have to
  8040. check for calls in the same compilation module.
  8041. @node Arrays as Parameters
  8042. @subsection Arrays as Parameters
  8043. @cindex array as parameters
  8044. @cindex functions with array parameters
  8045. Arrays in C are not first-class objects: it is impossible to copy
  8046. them. So they cannot be passed as arguments like other values.
  8047. @xref{Limitations of C Arrays}. Rather, array parameters work in
  8048. a special way.
  8049. @menu
  8050. * Array Parm Pointer::
  8051. * Passing Array Args::
  8052. * Array Parm Qualifiers::
  8053. @end menu
  8054. @node Array Parm Pointer
  8055. @subsubsection Array parameters are pointers
  8056. Declaring a function parameter variable as an array really gives it a
  8057. pointer type. C does this because an expression with array type, if
  8058. used as an argument in a function call, is converted automatically to
  8059. a pointer (to the zeroth element of the array). If you declare the
  8060. corresponding parameter as an ``array'', it will work correctly with
  8061. the pointer value that really gets passed.
  8062. This relates to the fact that C does not check array bounds in access
  8063. to elements of the array (@pxref{Accessing Array Elements}).
  8064. For example, in this function,
  8065. @example
  8066. void
  8067. clobber4 (int array[20])
  8068. @{
  8069. array[4] = 0;
  8070. @}
  8071. @end example
  8072. @noindent
  8073. the parameter @code{array}'s real type is @code{int *}; the specified
  8074. length, 20, has no effect on the program. You can leave out the length
  8075. and write this:
  8076. @example
  8077. void
  8078. clobber4 (int array[])
  8079. @{
  8080. array[4] = 0;
  8081. @}
  8082. @end example
  8083. @noindent
  8084. or write the parameter declaration explicitly as a pointer:
  8085. @example
  8086. void
  8087. clobber4 (int *array)
  8088. @{
  8089. array[4] = 0;
  8090. @}
  8091. @end example
  8092. They are all equivalent.
  8093. @node Passing Array Args
  8094. @subsubsection Passing array arguments
  8095. The function call passes this pointer by
  8096. value, like all argument values in C@. However, the result is
  8097. paradoxical in that the array itself is passed by reference: its
  8098. contents are treated as shared memory---shared between the caller and
  8099. the called function, that is. When @code{clobber4} assigns to element
  8100. 4 of @code{array}, the effect is to alter element 4 of the array
  8101. specified in the call.
  8102. @example
  8103. #include <stddef.h> /* @r{Defines @code{NULL}.} */
  8104. #include <stdlib.h> /* @r{Declares @code{malloc},} */
  8105. /* @r{Defines @code{EXIT_SUCCESS}.} */
  8106. int
  8107. main (void)
  8108. @{
  8109. int data[] = @{1, 2, 3, 4, 5, 6@};
  8110. int i;
  8111. /* @r{Show the initial value of element 4.} */
  8112. for (i = 0; i < 6; i++)
  8113. printf ("data[%d] = %d\n", i, data[i]);
  8114. printf ("\n");
  8115. clobber4 (data);
  8116. /* @r{Show that element 4 has been changed.} */
  8117. for (i = 0; i < 6; i++)
  8118. printf ("data[%d] = %d\n", i, data[i]);
  8119. printf ("\n");
  8120. return EXIT_SUCCESS;
  8121. @}
  8122. @end example
  8123. @noindent
  8124. shows that @code{data[4]} has become zero after the call to
  8125. @code{clobber4}.
  8126. The array @code{data} has 6 elements, but passing it to a function
  8127. whose argument type is written as @code{int [20]} is not an error,
  8128. because that really stands for @code{int *}. The pointer that is the
  8129. real argument carries no indication of the length of the array it
  8130. points into. It is not required to point to the beginning of the
  8131. array, either. For instance,
  8132. @example
  8133. clobber4 (data+1);
  8134. @end example
  8135. @noindent
  8136. passes an ``array'' that starts at element 1 of @code{data}, and the
  8137. effect is to zero @code{data[5]} instead of @code{data[4]}.
  8138. If all calls to the function will provide an array of a particular
  8139. size, you can specify the size of the array to be @code{static}:
  8140. @example
  8141. void
  8142. clobber4 (int array[static 20])
  8143. @r{@dots{}}
  8144. @end example
  8145. @noindent
  8146. This is a promise to the compiler that the function will always be
  8147. called with an array of 20 elements, so that the compiler can optimize
  8148. code accordingly. If the code breaks this promise and calls the
  8149. function with, for example, a shorter array, unpredictable things may
  8150. happen.
  8151. @node Array Parm Qualifiers
  8152. @subsubsection Type qualifiers on array parameters
  8153. You can use the type qualifiers @code{const}, @code{restrict}, and
  8154. @code{volatile} with array parameters; for example:
  8155. @example
  8156. void
  8157. clobber4 (volatile int array[20])
  8158. @r{@dots{}}
  8159. @end example
  8160. @noindent
  8161. denotes that @code{array} is equivalent to a pointer to a volatile
  8162. @code{int}. Alternatively:
  8163. @example
  8164. void
  8165. clobber4 (int array[const 20])
  8166. @r{@dots{}}
  8167. @end example
  8168. @noindent
  8169. makes the array parameter equivalent to a constant pointer to an
  8170. @code{int}. If we want the @code{clobber4} function to succeed, it
  8171. would not make sense to write
  8172. @example
  8173. void
  8174. clobber4 (const int array[20])
  8175. @r{@dots{}}
  8176. @end example
  8177. @noindent
  8178. as this would tell the compiler that the parameter should point to an
  8179. array of constant @code{int} values, and then we would not be able to
  8180. store zeros in them.
  8181. In a function with multiple array parameters, you can use @code{restrict}
  8182. to tell the compiler that each array parameter passed in will be distinct:
  8183. @example
  8184. void
  8185. foo (int array1[restrict 10], int array2[restrict 10])
  8186. @r{@dots{}}
  8187. @end example
  8188. @noindent
  8189. Using @code{restrict} promises the compiler that callers will
  8190. not pass in the same array for more than one @code{restrict} array
  8191. parameter. Knowing this enables the compiler to perform better code
  8192. optimization. This is the same effect as using @code{restrict}
  8193. pointers (@pxref{restrict Pointers}), but makes it clear when reading
  8194. the code that an array of a specific size is expected.
  8195. @node Structs as Parameters
  8196. @subsection Functions That Accept Structure Arguments
  8197. Structures in GNU C are first-class objects, so using them as function
  8198. parameters and arguments works in the natural way. This function
  8199. @code{swapfoo} takes a @code{struct foo} with two fields as argument,
  8200. and returns a structure of the same type but with the fields
  8201. exchanged.
  8202. @example
  8203. struct foo @{ int a, b; @};
  8204. struct foo x;
  8205. struct foo
  8206. swapfoo (struct foo inval)
  8207. @{
  8208. struct foo outval;
  8209. outval.a = inval.b;
  8210. outval.b = inval.a;
  8211. return outval;
  8212. @}
  8213. @end example
  8214. This simpler definition of @code{swapfoo} avoids using a local
  8215. variable to hold the result about to be return, by using a structure
  8216. constructor (@pxref{Structure Constructors}), like this:
  8217. @example
  8218. struct foo
  8219. swapfoo (struct foo inval)
  8220. @{
  8221. return (struct foo) @{ inval.b, inval.a @};
  8222. @}
  8223. @end example
  8224. It is valid to define a structure type in a function's parameter list,
  8225. as in
  8226. @example
  8227. int
  8228. frob_bar (struct bar @{ int a, b; @} inval)
  8229. @{
  8230. @var{body}
  8231. @}
  8232. @end example
  8233. @noindent
  8234. and @var{body} can access the fields of @var{inval} since the
  8235. structure type @code{struct bar} is defined for the whole function
  8236. body. However, there is no way to create a @code{struct bar} argument
  8237. to pass to @code{frob_bar}, except with kludges. As a result,
  8238. defining a structure type in a parameter list is useless in practice.
  8239. @node Function Declarations
  8240. @section Function Declarations
  8241. @cindex function declarations
  8242. @cindex declararing functions
  8243. To call a function, or use its name as a pointer, a @dfn{function
  8244. declaration} for the function name must be in effect at that point in
  8245. the code. The function's definition serves as a declaration of that
  8246. function for the rest of the containing scope, but to use the function
  8247. in code before the definition, or from another compilation module, a
  8248. separate function declaration must precede the use.
  8249. A function declaration looks like the start of a function definition.
  8250. It begins with the return value type (@code{void} if none) and the
  8251. function name, followed by argument declarations in parentheses
  8252. (though these can sometimes be omitted). But that's as far as the
  8253. similarity goes: instead of the function body, the declaration uses a
  8254. semicolon.
  8255. @cindex function prototype
  8256. @cindex prototype of a function
  8257. A declaration that specifies argument types is called a @dfn{function
  8258. prototype}. You can include the argument names or omit them. The
  8259. names, if included in the declaration, have no effect, but they may
  8260. serve as documentation.
  8261. This form of prototype specifies fixed argument types:
  8262. @example
  8263. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}});
  8264. @end example
  8265. @noindent
  8266. This form says the function takes no arguments:
  8267. @example
  8268. @var{rettype} @var{function} (void);
  8269. @end example
  8270. @noindent
  8271. This form declares types for some arguments, and allows additional
  8272. arguments whose types are not specified:
  8273. @example
  8274. @var{rettype} @var{function} (@var{argtypes}@r{@dots{}}, ...);
  8275. @end example
  8276. For a parameter that's an array of variable length, you can write
  8277. its declaration with @samp{*} where the ``length'' of the array would
  8278. normally go; for example, these are all equivalent.
  8279. @example
  8280. double maximum (int n, int m, double a[n][m]);
  8281. double maximum (int n, int m, double a[*][*]);
  8282. double maximum (int n, int m, double a[ ][*]);
  8283. double maximum (int n, int m, double a[ ][m]);
  8284. @end example
  8285. @noindent
  8286. The old-fashioned form of declaration, which is not a prototype, says
  8287. nothing about the types of arguments or how many they should be:
  8288. @example
  8289. @var{rettype} @var{function} ();
  8290. @end example
  8291. @strong{Warning:} Arguments passed to a function declared without a
  8292. prototype are converted with the default argument promotions
  8293. (@pxref{Argument Promotions}. Likewise for additional arguments whose
  8294. types are unspecified.
  8295. Function declarations are usually written at the top level in a source file,
  8296. but you can also put them inside code blocks. Then the function name
  8297. is visible for the rest of the containing scope. For example:
  8298. @example
  8299. void
  8300. foo (char *file_name)
  8301. @{
  8302. void save_file (char *);
  8303. save_file (file_name);
  8304. @}
  8305. @end example
  8306. If another part of the code tries to call the function
  8307. @code{save_file}, this declaration won't be in effect there. So the
  8308. function will get an implicit declaration of the form @code{extern int
  8309. save_file ();}. That conflicts with the explicit declaration
  8310. here, and the discrepancy generates a warning.
  8311. The syntax of C traditionally allows omitting the data type in a
  8312. function declaration if it specifies a storage class or a qualifier.
  8313. Then the type defaults to @code{int}. For example:
  8314. @example
  8315. static foo (double x);
  8316. @end example
  8317. @noindent
  8318. defaults the return type to @code{int}.
  8319. This is bad practice; if you see it, fix it.
  8320. Calling a function that is undeclared has the effect of an creating
  8321. @dfn{implicit} declaration in the innermost containing scope,
  8322. equivalent to this:
  8323. @example
  8324. extern int @dfn{function} ();
  8325. @end example
  8326. @noindent
  8327. This declaration says that the function returns @code{int} but leaves
  8328. its argument types unspecified. If that does not accurately fit the
  8329. function, then the program @strong{needs} an explicit declaration of
  8330. the function with argument types in order to call it correctly.
  8331. Implicit declarations are deprecated, and a function call that creates one
  8332. causes a warning.
  8333. @node Function Calls
  8334. @section Function Calls
  8335. @cindex function calls
  8336. @cindex calling functions
  8337. Starting a program automatically calls the function named @code{main}
  8338. (@pxref{The main Function}). Aside from that, a function does nothing
  8339. except when it is @dfn{called}. That occurs during the execution of a
  8340. function-call expression specifying that function.
  8341. A function-call expression looks like this:
  8342. @example
  8343. @var{function} (@var{arguments}@r{@dots{}})
  8344. @end example
  8345. Most of the time, @var{function} is a function name. However, it can
  8346. also be an expression with a function pointer value; that way, the
  8347. program can determine at run time which function to call.
  8348. The @var{arguments} are a series of expressions separated by commas.
  8349. Each expression specifies one argument to pass to the function.
  8350. The list of arguments in a function call looks just like use of the
  8351. comma operator (@pxref{Comma Operator}), but the fact that it fills
  8352. the parentheses of a function call gives it a different meaning.
  8353. Here's an example of a function call, taken from an example near the
  8354. beginning (@pxref{Complete Program}).
  8355. @example
  8356. printf ("Fibonacci series item %d is %d\n",
  8357. 19, fib (19));
  8358. @end example
  8359. The three arguments given to @code{printf} are a constant string, the
  8360. integer 19, and the integer returned by @code{fib (19)}.
  8361. @node Function Call Semantics
  8362. @section Function Call Semantics
  8363. @cindex function call semantics
  8364. @cindex semantics of function calls
  8365. @cindex call-by-value
  8366. The meaning of a function call is to compute the specified argument
  8367. expressions, convert their values according to the function's
  8368. declaration, then run the function giving it copies of the converted
  8369. values. (This method of argument passing is known as
  8370. @dfn{call-by-value}.) When the function finishes, the value it
  8371. returns becomes the value of the function-call expression.
  8372. Call-by-value implies that an assignment to the function argument
  8373. variable has no direct effect on the caller. For instance,
  8374. @example
  8375. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}.} */
  8376. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8377. void
  8378. subroutine (int x)
  8379. @{
  8380. x = 5;
  8381. @}
  8382. void
  8383. main (void)
  8384. @{
  8385. int y = 20;
  8386. subroutine (y);
  8387. printf ("y is %d\n", y);
  8388. return EXIT_SUCCESS;
  8389. @}
  8390. @end example
  8391. @noindent
  8392. prints @samp{y is 20}. Calling @code{subroutine} initializes @code{x}
  8393. from the value of @code{y}, but this does not establish any other
  8394. relationship between the two variables. Thus, the assignment to
  8395. @code{x}, inside @code{subroutine}, changes only @emph{that} @code{x}.
  8396. If an argument's type is specified by the function's declaration, the
  8397. function call converts the argument expression to that type if
  8398. possible. If the conversion is impossible, that is an error.
  8399. If the function's declaration doesn't specify the type of that
  8400. argument, then the @emph{default argument promotions} apply.
  8401. @xref{Argument Promotions}.
  8402. @node Function Pointers
  8403. @section Function Pointers
  8404. @cindex function pointers
  8405. @cindex pointers to functions
  8406. A function name refers to a fixed function. Sometimes it is useful to
  8407. call a function to be determined at run time; to do this, you can use
  8408. a @dfn{function pointer value} that points to the chosen function
  8409. (@pxref{Pointers}).
  8410. Pointer-to-function types can be used to declare variables and other
  8411. data, including array elements, structure fields, and union
  8412. alternatives. They can also be used for function arguments and return
  8413. values. These types have the peculiarity that they are never
  8414. converted automatically to @code{void *} or vice versa. However, you
  8415. can do that conversion with a cast.
  8416. @menu
  8417. * Declaring Function Pointers:: How to declare a pointer to a function.
  8418. * Assigning Function Pointers:: How to assign values to function pointers.
  8419. * Calling Function Pointers:: How to call functions through pointers.
  8420. @end menu
  8421. @node Declaring Function Pointers
  8422. @subsection Declaring Function Pointers
  8423. @cindex declaring function pointers
  8424. @cindex function pointers, declaring
  8425. The declaration of a function pointer variable (or structure field)
  8426. looks almost like a function declaration, except it has an additional
  8427. @samp{*} just before the variable name. Proper nesting requires a
  8428. pair of parentheses around the two of them. For instance, @code{int
  8429. (*a) ();} says, ``Declare @code{a} as a pointer such that @code{*a} is
  8430. an @code{int}-returning function.''
  8431. Contrast these three declarations:
  8432. @example
  8433. /* @r{Declare a function returning @code{char *}.} */
  8434. char *a (char *);
  8435. /* @r{Declare a pointer to a function returning @code{char}.} */
  8436. char (*a) (char *);
  8437. /* @r{Declare a pointer to a function returning @code{char *}.} */
  8438. char *(*a) (char *);
  8439. @end example
  8440. The possible argument types of the function pointed to are the same
  8441. as in a function declaration. You can write a prototype
  8442. that specifies all the argument types:
  8443. @example
  8444. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}});
  8445. @end example
  8446. @noindent
  8447. or one that specifies some and leaves the rest unspecified:
  8448. @example
  8449. @var{rettype} (*@var{function}) (@var{arguments}@r{@dots{}}, ...);
  8450. @end example
  8451. @noindent
  8452. or one that says there are no arguments:
  8453. @example
  8454. @var{rettype} (*@var{function}) (void);
  8455. @end example
  8456. You can also write a non-prototype declaration that says
  8457. nothing about the argument types:
  8458. @example
  8459. @var{rettype} (*@var{function}) ();
  8460. @end example
  8461. For example, here's a declaration for a variable that should
  8462. point to some arithmetic function that operates on two @code{double}s:
  8463. @example
  8464. double (*binary_op) (double, double);
  8465. @end example
  8466. Structure fields, union alternatives, and array elements can be
  8467. function pointers; so can parameter variables. The function pointer
  8468. declaration construct can also be combined with other operators
  8469. allowed in declarations. For instance,
  8470. @example
  8471. int **(*foo)();
  8472. @end example
  8473. @noindent
  8474. declares @code{foo} as a pointer to a function that returns
  8475. type @code{int **}, and
  8476. @example
  8477. int **(*foo[30])();
  8478. @end example
  8479. @noindent
  8480. declares @code{foo} as an array of 30 pointers to functions that
  8481. return type @code{int **}.
  8482. @example
  8483. int **(**foo)();
  8484. @end example
  8485. @noindent
  8486. declares @code{foo} as a pointer to a pointer to a function that
  8487. returns type @code{int **}.
  8488. @node Assigning Function Pointers
  8489. @subsection Assigning Function Pointers
  8490. @cindex assigning function pointers
  8491. @cindex function pointers, assigning
  8492. Assuming we have declared the variable @code{binary_op} as in the
  8493. previous section, giving it a value requires a suitable function to
  8494. use. So let's define a function suitable for the variable to point
  8495. to. Here's one:
  8496. @example
  8497. double
  8498. double_add (double a, double b)
  8499. @{
  8500. return a+b;
  8501. @}
  8502. @end example
  8503. Now we can give it a value:
  8504. @example
  8505. binary_op = double_add;
  8506. @end example
  8507. The target type of the function pointer must be upward compatible with
  8508. the type of the function (@pxref{Compatible Types}).
  8509. There is no need for @samp{&} in front of @code{double_add}.
  8510. Using a function name such as @code{double_add} as an expression
  8511. automatically converts it to the function's address, with the
  8512. appropriate function pointer type. However, it is ok to use
  8513. @samp{&} if you feel that is clearer:
  8514. @example
  8515. binary_op = &double_add;
  8516. @end example
  8517. @node Calling Function Pointers
  8518. @subsection Calling Function Pointers
  8519. @cindex calling function pointers
  8520. @cindex function pointers, calling
  8521. To call the function specified by a function pointer, just write the
  8522. function pointer value in a function call. For instance, here's a
  8523. call to the function @code{binary_op} points to:
  8524. @example
  8525. binary_op (x, 5)
  8526. @end example
  8527. Since the data type of @code{binary_op} explicitly specifies type
  8528. @code{double} for the arguments, the call converts @code{x} and 5 to
  8529. @code{double}.
  8530. The call conceptually dereferences the pointer @code{binary_op} to
  8531. ``get'' the function it points to, and calls that function. If you
  8532. wish, you can explicitly represent the derefence by writing the
  8533. @code{*} operator:
  8534. @example
  8535. (*binary_op) (x, 5)
  8536. @end example
  8537. The @samp{*} reminds people reading the code that @code{binary_op} is
  8538. a function pointer rather than the name of a specific function.
  8539. @node The main Function
  8540. @section The @code{main} Function
  8541. @cindex @code{main} function
  8542. @findex main
  8543. Every complete executable program requires at least one function,
  8544. called @code{main}, which is where execution begins. You do not have
  8545. to explicitly declare @code{main}, though GNU C permits you to do so.
  8546. Conventionally, @code{main} should be defined to follow one of these
  8547. calling conventions:
  8548. @example
  8549. int main (void) @{@r{@dots{}}@}
  8550. int main (int argc, char *argv[]) @{@r{@dots{}}@}
  8551. int main (int argc, char *argv[], char *envp[]) @{@r{@dots{}}@}
  8552. @end example
  8553. @noindent
  8554. Using @code{void} as the parameter list means that @code{main} does
  8555. not use the arguments. You can write @code{char **argv} instead of
  8556. @code{char *argv[]}, and likewise for @code{envp}, as the two
  8557. constructs are equivalent.
  8558. @ignore @c Not so at present
  8559. Defining @code{main} in any other way generates a warning. Your
  8560. program will still compile, but you may get unexpected results when
  8561. executing it.
  8562. @end ignore
  8563. You can call @code{main} from C code, as you can call any other
  8564. function, though that is an unusual thing to do. When you do that,
  8565. you must write the call to pass arguments that match the parameters in
  8566. the definition of @code{main}.
  8567. The @code{main} function is not actually the first code that runs when
  8568. a program starts. In fact, the first code that runs is system code
  8569. from the file @file{crt0.o}. In Unix, this was hand-written assembler
  8570. code, but in GNU we replaced it with C code. Its job is to find
  8571. the arguments for @code{main} and call that.
  8572. @menu
  8573. * Values from main:: Returning values from the main function.
  8574. * Command-line Parameters:: Accessing command-line parameters
  8575. provided to the program.
  8576. * Environment Variables:: Accessing system environment variables.
  8577. @end menu
  8578. @node Values from main
  8579. @subsection Returning Values from @code{main}
  8580. @cindex returning values from @code{main}
  8581. @cindex success
  8582. @cindex failure
  8583. @cindex exit status
  8584. When @code{main} returns, the process terminates. Whatever value
  8585. @code{main} returns becomes the exit status which is reported to the
  8586. parent process. While nominally the return value is of type
  8587. @code{int}, in fact the exit status gets truncated to eight bits; if
  8588. @code{main} returns the value 256, the exit status is 0.
  8589. Normally, programs return only one of two values: 0 for success,
  8590. and 1 for failure. For maximum portability, use the macro
  8591. values @code{EXIT_SUCCESS} and @code{EXIT_FAILURE} defined in
  8592. @code{stdlib.h}. Here's an example:
  8593. @cindex @code{EXIT_FAILURE}
  8594. @cindex @code{EXIT_SUCCESS}
  8595. @example
  8596. #include <stdlib.h> /* @r{Defines @code{EXIT_SUCCESS}} */
  8597. /* @r{and @code{EXIT_FAILURE}.} */
  8598. int
  8599. main (void)
  8600. @{
  8601. @r{@dots{}}
  8602. if (foo)
  8603. return EXIT_SUCCESS;
  8604. else
  8605. return EXIT_FAILURE;
  8606. @}
  8607. @end example
  8608. Some types of programs maintain special conventions for various return
  8609. values; for example, comparison programs including @code{cmp} and
  8610. @code{diff} return 1 to indicate a mismatch, and 2 to indicate that
  8611. the comparison couldn't be performed.
  8612. @node Command-line Parameters
  8613. @subsection Accessing Command-line Parameters
  8614. @cindex command-line parameters
  8615. @cindex parameters, command-line
  8616. If the program was invoked with any command-line arguments, it can
  8617. access them through the arguments of @code{main}, @code{argc} and
  8618. @code{argv}. (You can give these arguments any names, but the names
  8619. @code{argc} and @code{argv} are customary.)
  8620. The value of @code{argv} is an array containing all of the
  8621. command-line arguments as strings, with the name of the command
  8622. invoked as the first string. @code{argc} is an integer that says how
  8623. many strings @code{argv} contains. Here is an example of accessing
  8624. the command-line parameters, retrieving the program's name and
  8625. checking for the standard @option{--version} and @option{--help} options:
  8626. @example
  8627. #include <string.h> /* @r{Declare @code{strcmp}.} */
  8628. int
  8629. main (int argc, char *argv[])
  8630. @{
  8631. char *program_name = argv[0];
  8632. for (int i = 1; i < argc; i++)
  8633. @{
  8634. if (!strcmp (argv[i], "--version"))
  8635. @{
  8636. /* @r{Print version information and exit.} */
  8637. @r{@dots{}}
  8638. @}
  8639. else if (!strcmp (argv[i], "--help"))
  8640. @{
  8641. /* @r{Print help information and exit.} */
  8642. @r{@dots{}}
  8643. @}
  8644. @}
  8645. @r{@dots{}}
  8646. @}
  8647. @end example
  8648. @node Environment Variables
  8649. @subsection Accessing Environment Variables
  8650. @cindex environment variables
  8651. You can optionally include a third parameter to @code{main}, another
  8652. array of strings, to capture the environment variables available to
  8653. the program. Unlike what happens with @code{argv}, there is no
  8654. additional parameter for the count of environment variables; rather,
  8655. the array of environment variables concludes with a null pointer.
  8656. @example
  8657. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8658. int
  8659. main (int argc, char *argv[], char *envp[])
  8660. @{
  8661. /* @r{Print out all environment variables.} */
  8662. int i = 0;
  8663. while (envp[i])
  8664. @{
  8665. printf ("%s\n", envp[i]);
  8666. i++;
  8667. @}
  8668. @}
  8669. @end example
  8670. Another method of retrieving environment variables is to use the
  8671. library function @code{getenv}, which is defined in @code{stdlib.h}.
  8672. Using @code{getenv} does not require defining @code{main} to accept the
  8673. @code{envp} pointer. For example, here is a program that fetches and prints
  8674. the user's home directory (if defined):
  8675. @example
  8676. #include <stdlib.h> /* @r{Declares @code{getenv}.} */
  8677. #include <stdio.h> /* @r{Declares @code{printf}.} */
  8678. int
  8679. main (void)
  8680. @{
  8681. char *home_directory = getenv ("HOME");
  8682. if (home_directory)
  8683. printf ("My home directory is: %s\n", home_directory);
  8684. else
  8685. printf ("My home directory is not defined!\n");
  8686. @}
  8687. @end example
  8688. @node Advanced Definitions
  8689. @section Advanced Function Features
  8690. This section describes some advanced or obscure features for GNU C
  8691. function definitions. If you are just learning C, you can skip the
  8692. rest of this chapter.
  8693. @menu
  8694. * Variable-Length Array Parameters:: Functions that accept arrays
  8695. of variable length.
  8696. * Variable Number of Arguments:: Variadic functions.
  8697. * Nested Functions:: Defining functions within functions.
  8698. * Inline Function Definitions:: A function call optimization technique.
  8699. @end menu
  8700. @node Variable-Length Array Parameters
  8701. @subsection Variable-Length Array Parameters
  8702. @cindex variable-length array parameters
  8703. @cindex array parameters, variable-length
  8704. @cindex functions that accept variable-length arrays
  8705. An array parameter can have variable length: simply declare the array
  8706. type with a size that isn't constant. In a nested function, the
  8707. length can refer to a variable defined in a containing scope. In any
  8708. function, it can refer to a previous parameter, like this:
  8709. @example
  8710. struct entry
  8711. tester (int len, char data[len][len])
  8712. @{
  8713. @r{@dots{}}
  8714. @}
  8715. @end example
  8716. Alternatively, in function declarations (but not in function
  8717. definitions), you can use @code{[*]} to denote that the array
  8718. parameter is of a variable length, such that these two declarations
  8719. mean the same thing:
  8720. @example
  8721. struct entry
  8722. tester (int len, char data[len][len]);
  8723. @end example
  8724. @example
  8725. struct entry
  8726. tester (int len, char data[*][*]);
  8727. @end example
  8728. @noindent
  8729. The two forms of input are equivalent in GNU C, but emphasizing that
  8730. the array parameter is variable-length may be helpful to those
  8731. studying the code.
  8732. You can also omit the length parameter, and instead use some other
  8733. in-scope variable for the length in the function definition:
  8734. @example
  8735. struct entry
  8736. tester (char data[*][*]);
  8737. @r{@dots{}}
  8738. int dataLength = 20;
  8739. @r{@dots{}}
  8740. struct entry
  8741. tester (char data[dataLength][dataLength])
  8742. @{
  8743. @r{@dots{}}
  8744. @}
  8745. @end example
  8746. @c ??? check text above
  8747. @cindex parameter forward declaration
  8748. In GNU C, to pass the array first and the length afterward, you can
  8749. use a @dfn{parameter forward declaration}, like this:
  8750. @example
  8751. struct entry
  8752. tester (int len; char data[len][len], int len)
  8753. @{
  8754. @r{@dots{}}
  8755. @}
  8756. @end example
  8757. The @samp{int len} before the semicolon is the parameter forward
  8758. declaration; it serves the purpose of making the name @code{len} known
  8759. when the declaration of @code{data} is parsed.
  8760. You can write any number of such parameter forward declarations in the
  8761. parameter list. They can be separated by commas or semicolons, but
  8762. the last one must end with a semicolon, which is followed by the
  8763. ``real'' parameter declarations. Each forward declaration must match
  8764. a subsequent ``real'' declaration in parameter name and data type.
  8765. Standard C does not support parameter forward declarations.
  8766. @node Variable Number of Arguments
  8767. @subsection Variable-Length Parameter Lists
  8768. @cindex variable-length parameter lists
  8769. @cindex parameters lists, variable length
  8770. @cindex function parameter lists, variable length
  8771. @cindex variadic function
  8772. A function that takes a variable number of arguments is called a
  8773. @dfn{variadic function}. In C, a variadic function must specify at
  8774. least one fixed argument with an explicitly declared data type.
  8775. Additional arguments can follow, and can vary in both quantity and
  8776. data type.
  8777. In the function header, declare the fixed parameters in the normal
  8778. way, then write a comma and an ellipsis: @samp{, ...}. Here is an
  8779. example of a variadic function header:
  8780. @example
  8781. int add_multiple_values (int number, ...)
  8782. @end example
  8783. @cindex @code{va_list}
  8784. @cindex @code{va_start}
  8785. @cindex @code{va_end}
  8786. The function body can refer to fixed arguments by their parameter
  8787. names, but the additional arguments have no names. Accessing them in
  8788. the function body uses certain standard macros. They are defined in
  8789. the library header file @file{stdarg.h}, so the code must
  8790. @code{#include} that file.
  8791. In the body, write
  8792. @example
  8793. va_list ap;
  8794. va_start (ap, @var{last_fixed_parameter});
  8795. @end example
  8796. @noindent
  8797. This declares the variable @code{ap} (you can use any name for it)
  8798. and then sets it up to point before the first additional argument.
  8799. Then, to fetch the next consecutive additional argument, write this:
  8800. @example
  8801. va_arg (ap, @var{type})
  8802. @end example
  8803. After fetching all the additional arguments (or as many as need to be
  8804. used), write this:
  8805. @example
  8806. va_end (ap);
  8807. @end example
  8808. Here's an example of a variadic function definition that adds any
  8809. number of @code{int} arguments. The first (fixed) argument says how
  8810. many more arguments follow.
  8811. @example
  8812. #include <stdarg.h> /* @r{Defines @code{va}@r{@dots{}} macros.} */
  8813. @r{@dots{}}
  8814. int
  8815. add_multiple_values (int argcount, ...)
  8816. @{
  8817. int counter, total = 0;
  8818. /* @r{Declare a variable of type @code{va_list}.} */
  8819. va_list argptr;
  8820. /* @r{Initialize that variable..} */
  8821. va_start (argptr, argcount);
  8822. for (counter = 0; counter < argcount; counter++)
  8823. @{
  8824. /* @r{Get the next additional argument.} */
  8825. total += va_arg (argptr, int);
  8826. @}
  8827. /* @r{End use of the @code{argptr} variable.} */
  8828. va_end (argptr);
  8829. return total;
  8830. @}
  8831. @end example
  8832. With GNU C, @code{va_end} is superfluous, but some other compilers
  8833. might make @code{va_start} allocate memory so that calling
  8834. @code{va_end} is necessary to avoid a memory leak. Before doing
  8835. @code{va_start} again with the same variable, do @code{va_end}
  8836. first.
  8837. @cindex @code{va_copy}
  8838. Because of this possible memory allocation, it is risky (in principle)
  8839. to copy one @code{va_list} variable to another with assignment.
  8840. Instead, use @code{va_copy}, which copies the substance but allocates
  8841. separate memory in the variable you copy to. The call looks like
  8842. @code{va_copy (@var{to}, @var{from})}, where both @var{to} and
  8843. @var{from} should be variables of type @code{va_list}. In principle,
  8844. do @code{va_end} on each of these variables before its scope ends.
  8845. Since the additional arguments' types are not specified in the
  8846. function's definition, the default argument promotions
  8847. (@pxref{Argument Promotions}) apply to them in function calls. The
  8848. function definition must take account of this; thus, if an argument
  8849. was passed as @code{short}, the function should get it as @code{int}.
  8850. If an argument was passed as @code{float}, the function should get it
  8851. as @code{double}.
  8852. C has no mechanism to tell the variadic function how many arguments
  8853. were passed to it, so its calling convention must give it a way to
  8854. determine this. That's why @code{add_multiple_values} takes a fixed
  8855. argument that says how many more arguments follow. Thus, you can
  8856. call the function like this:
  8857. @example
  8858. sum = add_multiple_values (3, 12, 34, 190);
  8859. /* @r{Value is 12+34+190.} */
  8860. @end example
  8861. In GNU C, there is no actual need to use the @code{va_end} function.
  8862. In fact, it does nothing. It's used for compatibility with other
  8863. compilers, when that matters.
  8864. It is a mistake to access variables declared as @code{va_list} except
  8865. in the specific ways described here. Just what that type consists of
  8866. is an implementation detail, which could vary from one platform to
  8867. another.
  8868. @node Nested Functions
  8869. @subsection Nested Functions
  8870. @cindex nested functions
  8871. @cindex functions, nested
  8872. @cindex downward funargs
  8873. @cindex thunks
  8874. A @dfn{nested function} is a function defined inside another function.
  8875. The nested function's name is local to the block where it is defined.
  8876. For example, here we define a nested function named @code{square}, and
  8877. call it twice:
  8878. @example
  8879. @group
  8880. foo (double a, double b)
  8881. @{
  8882. double square (double z) @{ return z * z; @}
  8883. return square (a) + square (b);
  8884. @}
  8885. @end group
  8886. @end example
  8887. The nested function can access all the variables of the containing
  8888. function that are visible at the point of its definition. This is
  8889. called @dfn{lexical scoping}. For example, here we show a nested
  8890. function that uses an inherited variable named @code{offset}:
  8891. @example
  8892. @group
  8893. bar (int *array, int offset, int size)
  8894. @{
  8895. int access (int *array, int index)
  8896. @{ return array[index + offset]; @}
  8897. int i;
  8898. @r{@dots{}}
  8899. for (i = 0; i < size; i++)
  8900. @r{@dots{}} access (array, i) @r{@dots{}}
  8901. @}
  8902. @end group
  8903. @end example
  8904. Nested function definitions can appear wherever automatic variable
  8905. declarations are allowed; that is, in any block, interspersed with the
  8906. other declarations and statements in the block.
  8907. The nested function's name is visible only within the parent block;
  8908. the name's scope starts from its definition and continues to the end
  8909. of the containing block. If the nested function's name
  8910. is the same as the parent function's name, there wil be
  8911. no way to refer to the parent function inside the scope of the
  8912. name of the nested function.
  8913. Using @code{extern} or @code{static} on a nested function definition
  8914. is an error.
  8915. It is possible to call the nested function from outside the scope of its
  8916. name by storing its address or passing the address to another function.
  8917. You can do this safely, but you must be careful:
  8918. @example
  8919. @group
  8920. hack (int *array, int size, int addition)
  8921. @{
  8922. void store (int index, int value)
  8923. @{ array[index] = value + addition; @}
  8924. intermediate (store, size);
  8925. @}
  8926. @end group
  8927. @end example
  8928. Here, the function @code{intermediate} receives the address of
  8929. @code{store} as an argument. If @code{intermediate} calls @code{store},
  8930. the arguments given to @code{store} are used to store into @code{array}.
  8931. @code{store} also accesses @code{hack}'s local variable @code{addition}.
  8932. It is safe for @code{intermediate} to call @code{store} because
  8933. @code{hack}'s stack frame, with its arguments and local variables,
  8934. continues to exist during the call to @code{intermediate}.
  8935. Calling the nested function through its address after the containing
  8936. function has exited is asking for trouble. If it is called after a
  8937. containing scope level has exited, and if it refers to some of the
  8938. variables that are no longer in scope, it will refer to memory
  8939. containing junk or other data. It's not wise to take the risk.
  8940. The GNU C Compiler implements taking the address of a nested function
  8941. using a technique called @dfn{trampolines}. This technique was
  8942. described in @cite{Lexical Closures for C@t{++}} (Thomas M. Breuel,
  8943. USENIX C@t{++} Conference Proceedings, October 17--21, 1988).
  8944. A nested function can jump to a label inherited from a containing
  8945. function, provided the label was explicitly declared in the containing
  8946. function (@pxref{Local Labels}). Such a jump returns instantly to the
  8947. containing function, exiting the nested function that did the
  8948. @code{goto} and any intermediate function invocations as well. Here
  8949. is an example:
  8950. @example
  8951. @group
  8952. bar (int *array, int offset, int size)
  8953. @{
  8954. /* @r{Explicitly declare the label @code{failure}.} */
  8955. __label__ failure;
  8956. int access (int *array, int index)
  8957. @{
  8958. if (index > size)
  8959. /* @r{Exit this function,}
  8960. @r{and return to @code{bar}.} */
  8961. goto failure;
  8962. return array[index + offset];
  8963. @}
  8964. @end group
  8965. @group
  8966. int i;
  8967. @r{@dots{}}
  8968. for (i = 0; i < size; i++)
  8969. @r{@dots{}} access (array, i) @r{@dots{}}
  8970. @r{@dots{}}
  8971. return 0;
  8972. /* @r{Control comes here from @code{access}
  8973. if it does the @code{goto}.} */
  8974. failure:
  8975. return -1;
  8976. @}
  8977. @end group
  8978. @end example
  8979. To declare the nested function before its definition, use
  8980. @code{auto} (which is otherwise meaningless for function declarations;
  8981. @pxref{auto and register}). For example,
  8982. @example
  8983. bar (int *array, int offset, int size)
  8984. @{
  8985. auto int access (int *, int);
  8986. @r{@dots{}}
  8987. @r{@dots{}} access (array, i) @r{@dots{}}
  8988. @r{@dots{}}
  8989. int access (int *array, int index)
  8990. @{
  8991. @r{@dots{}}
  8992. @}
  8993. @r{@dots{}}
  8994. @}
  8995. @end example
  8996. @node Inline Function Definitions
  8997. @subsection Inline Function Definitions
  8998. @cindex inline function definitions
  8999. @cindex function definitions, inline
  9000. @findex inline
  9001. To declare a function inline, use the @code{inline} keyword in its
  9002. definition. Here's a simple function that takes a pointer-to-@code{int}
  9003. and increments the integer stored there---declared inline.
  9004. @example
  9005. struct list
  9006. @{
  9007. struct list *first, *second;
  9008. @};
  9009. inline struct list *
  9010. list_first (struct list *p)
  9011. @{
  9012. return p->first;
  9013. @}
  9014. inline struct list *
  9015. list_second (struct list *p)
  9016. @{
  9017. return p->second;
  9018. @}
  9019. @end example
  9020. optimized compilation can substitute the inline function's body for
  9021. any call to it. This is called @emph{inlining} the function. It
  9022. makes the code that contains the call run faster, significantly so if
  9023. the inline function is small.
  9024. Here's a function that uses @code{pair_second}:
  9025. @example
  9026. int
  9027. pairlist_length (struct list *l)
  9028. @{
  9029. int length = 0;
  9030. while (l)
  9031. @{
  9032. length++;
  9033. l = pair_second (l);
  9034. @}
  9035. return length;
  9036. @}
  9037. @end example
  9038. Substituting the code of @code{pair_second} into the definition of
  9039. @code{pairlist_length} results in this code, in effect:
  9040. @example
  9041. int
  9042. pairlist_length (struct list *l)
  9043. @{
  9044. int length = 0;
  9045. while (l)
  9046. @{
  9047. length++;
  9048. l = l->second;
  9049. @}
  9050. return length;
  9051. @}
  9052. @end example
  9053. Since the definition of @code{pair_second} does not say @code{extern}
  9054. or @code{static}, that definition is used only for inlining. It
  9055. doesn't generate code that can be called at run time. If not all the
  9056. calls to the function are inlined, there must be a definition of the
  9057. same function name in another module for them to call.
  9058. @cindex inline functions, omission of
  9059. @c @opindex fkeep-inline-functions
  9060. Adding @code{static} to an inline function definition means the
  9061. function definition is limited to this compilation module. Also, it
  9062. generates run-time code if necessary for the sake of any calls that
  9063. were not inlined. If all calls are inlined then the function
  9064. definition does not generate run-time code, but you can force
  9065. generation of run-time code with the option
  9066. @option{-fkeep-inline-functions}.
  9067. @cindex extern inline function
  9068. Specifying @code{extern} along with @code{inline} means the function is
  9069. external and generates run-time code to be called from other
  9070. separately compiled modules, as well as inlined. You can define the
  9071. function as @code{inline} without @code{extern} in other modules so as
  9072. to inline calls to the same function in those modules.
  9073. Why are some calls not inlined? First of all, inlining is an
  9074. optimization, so non-optimized compilation does not inline.
  9075. Some calls cannot be inlined for technical reasons. Also, certain
  9076. usages in a function definition can make it unsuitable for inline
  9077. substitution. Among these usages are: variadic functions, use of
  9078. @code{alloca}, use of computed goto (@pxref{Labels as Values}), and
  9079. use of nonlocal goto. The option @option{-Winline} requests a warning
  9080. when a function marked @code{inline} is unsuitable to be inlined. The
  9081. warning explains what obstacle makes it unsuitable.
  9082. Just because a call @emph{can} be inlined does not mean it
  9083. @emph{should} be inlined. The GNU C compiler weighs costs and
  9084. benefits to decide whether inlining a particular call is advantageous.
  9085. You can force inlining of all calls to a given function that can be
  9086. inlined, even in a non-optimized compilation. by specifying the
  9087. @samp{always_inline} attribute for the function, like this:
  9088. @example
  9089. /* @r{Prototype.} */
  9090. inline void foo (const char) __attribute__((always_inline));
  9091. @end example
  9092. @noindent
  9093. This is a GNU C extension. @xref{Attributes}.
  9094. A function call may be inlined even if not declared @code{inline} in
  9095. special cases where the compiler can determine this is correct and
  9096. desirable. For instance, when a static function is called only once,
  9097. it will very likely be inlined. With @option{-flto}, link-time
  9098. optimization, any function might be inlined. To absolutely prevent
  9099. inlining of a specific function, specify
  9100. @code{__attribute__((__noinline__))} in the function's definition.
  9101. @node Obsolete Definitions
  9102. @section Obsolete Function Features
  9103. These features of function definitions are still used in old
  9104. programs, but you shouldn't write code this way today.
  9105. If you are just learning C, you can skip this section.
  9106. @menu
  9107. * Old GNU Inlining:: An older inlining technique.
  9108. * Old-Style Function Definitions:: Original K&R style functions.
  9109. @end menu
  9110. @node Old GNU Inlining
  9111. @subsection Older GNU C Inlining
  9112. The GNU C spec for inline functions, before GCC version 5, defined
  9113. @code{extern inline} on a function definition to mean to inline calls
  9114. to it but @emph{not} generate code for the function that could be
  9115. called at run time. By contrast, @code{inline} without @code{extern}
  9116. specified to generate run-time code for the function. In effect, ISO
  9117. incompatibly flipped the meanings of these two cases. We changed GCC
  9118. in version 5 to adopt the ISO specification.
  9119. Many programs still use these cases with the previous GNU C meanings.
  9120. You can specify use of those meanings with the option
  9121. @option{-fgnu89-inline}. You can also specify this for a single
  9122. function with @code{__attribute__ ((gnu_inline))}. Here's an example:
  9123. @example
  9124. inline __attribute__ ((gnu_inline))
  9125. int
  9126. inc (int *a)
  9127. @{
  9128. (*a)++;
  9129. @}
  9130. @end example
  9131. @node Old-Style Function Definitions
  9132. @subsection Old-Style Function Definitions
  9133. @cindex old-style function definitions
  9134. @cindex function definitions, old-style
  9135. @cindex K&R-style function definitions
  9136. The syntax of C traditionally allows omitting the data type in a
  9137. function declaration if it specifies a storage class or a qualifier.
  9138. Then the type defaults to @code{int}. For example:
  9139. @example
  9140. static foo (double x);
  9141. @end example
  9142. @noindent
  9143. defaults the return type to @code{int}. This is bad practice; if you
  9144. see it, fix it.
  9145. An @dfn{old-style} (or ``K&R'') function definition is the way
  9146. function definitions were written in the 1980s. It looks like this:
  9147. @example
  9148. @var{rettype}
  9149. @var{function} (@var{parmnames})
  9150. @var{parm_declarations}
  9151. @{
  9152. @var{body}
  9153. @}
  9154. @end example
  9155. In @var{parmnames}, only the parameter names are listed, separated by
  9156. commas. Then @var{parm_declarations} declares their data types; these
  9157. declarations look just like variable declarations. If a parameter is
  9158. listed in @var{parmnames} but has no declaration, it is implicitly
  9159. declared @code{int}.
  9160. There is no reason to write a definition this way nowadays, but they
  9161. can still be seen in older GNU programs.
  9162. An old-style variadic function definition looks like this:
  9163. @example
  9164. #include <varargs.h>
  9165. int
  9166. add_multiple_values (va_alist)
  9167. va_dcl
  9168. @{
  9169. int argcount;
  9170. int counter, total = 0;
  9171. /* @r{Declare a variable of type @code{va_list}.} */
  9172. va_list argptr;
  9173. /* @r{Initialize that variable.} */
  9174. va_start (argptr);
  9175. /* @r{Get the first argument (fixed).} */
  9176. argcount = va_arg (int);
  9177. for (counter = 0; counter < argcount; counter++)
  9178. @{
  9179. /* @r{Get the next additional argument.} */
  9180. total += va_arg (argptr, int);
  9181. @}
  9182. /* @r{End use of the @code{argptr} variable.} */
  9183. va_end (argptr);
  9184. return total;
  9185. @}
  9186. @end example
  9187. Note that the old-style variadic function definition has no fixed
  9188. parameter variables; all arguments must be obtained with
  9189. @code{va_arg}.
  9190. @node Compatible Types
  9191. @chapter Compatible Types
  9192. @cindex compatible types
  9193. @cindex types, compatible
  9194. Declaring a function or variable twice is valid in C only if the two
  9195. declarations specify @dfn{compatible} types. In addition, some
  9196. operations on pointers require operands to have compatible target
  9197. types.
  9198. In C, two different primitive types are never compatible. Likewise for
  9199. the defined types @code{struct}, @code{union} and @code{enum}: two
  9200. separately defined types are incompatible unless they are defined
  9201. exactly the same way.
  9202. However, there are a few cases where different types can be
  9203. compatible:
  9204. @itemize @bullet
  9205. @item
  9206. Every enumeration type is compatible with some integer type. In GNU
  9207. C, the choice of integer type depends on the largest enumeration
  9208. value.
  9209. @c ??? Which one, in GCC?
  9210. @c ??? ... it varies, depending on the enum values. Testing on
  9211. @c ??? fencepost, it appears to use a 4-byte signed integer first,
  9212. @c ??? then moves on to an 8-byte signed integer. These details
  9213. @c ??? might be platform-dependent, as the C standard says that even
  9214. @c ??? char could be used as an enum type, but it's at least true
  9215. @c ??? that GCC chooses a type that is at least large enough to
  9216. @c ??? hold the largest enum value.
  9217. @item
  9218. Array types are compatible if the element types are compatible
  9219. and the sizes (when specified) match.
  9220. @item
  9221. Pointer types are compatible if the pointer target types are
  9222. compatible.
  9223. @item
  9224. Function types that specify argument types are compatible if the
  9225. return types are compatible and the argument types are compatible,
  9226. argument by argument. In addition, they must all agree in whether
  9227. they use @code{...} to allow additional arguments.
  9228. @item
  9229. Function types that don't specify argument types are compatible if the
  9230. return types are.
  9231. @item
  9232. Function types that specify the argument types are compatible with
  9233. function types that omit them, if the return types are compatible and
  9234. the specified argument types are unaltered by the argument promotions
  9235. (@pxref{Argument Promotions}).
  9236. @end itemize
  9237. In order for types to be compatible, they must agree in their type
  9238. qualifiers. Thus, @code{const int} and @code{int} are incompatible.
  9239. It follows that @code{const int *} and @code{int *} are incompatible
  9240. too (they are pointers to types that are not compatible).
  9241. If two types are compatible ignoring the qualifiers, we call them
  9242. @dfn{nearly compatible}. (If they are array types, we ignore
  9243. qualifiers on the element types.@footnote{This is a GNU C extension.})
  9244. Comparison of pointers is valid if the pointers' target types are
  9245. nearly compatible. Likewise, the two branches of a conditional
  9246. expression may be pointers to nearly compatible target types.
  9247. If two types are compatible ignoring the qualifiers, and the first
  9248. type has all the qualifiers of the second type, we say the first is
  9249. @dfn{upward compatible} with the second. Assignment of pointers
  9250. requires the assigned pointer's target type to be upward compatible
  9251. with the right operand (the new value)'s target type.
  9252. @node Type Conversions
  9253. @chapter Type Conversions
  9254. @cindex type conversions
  9255. @cindex conversions, type
  9256. C converts between data types automatically when that seems clearly
  9257. necessary. In addition, you can convert explicitly with a @dfn{cast}.
  9258. @menu
  9259. * Explicit Type Conversion:: Casting a value from one type to another.
  9260. * Assignment Type Conversions:: Automatic conversion by assignment operation.
  9261. * Argument Promotions:: Automatic conversion of function parameters.
  9262. * Operand Promotions:: Automatic conversion of arithmetic operands.
  9263. * Common Type:: When operand types differ, which one is used?
  9264. @end menu
  9265. @node Explicit Type Conversion
  9266. @section Explicit Type Conversion
  9267. @cindex cast
  9268. @cindex explicit type conversion
  9269. You can do explicit conversions using the unary @dfn{cast} operator,
  9270. which is written as a type designator (@pxref{Type Designators}) in
  9271. parentheses. For example, @code{(int)} is the operator to cast to
  9272. type @code{int}. Here's an example of using it:
  9273. @example
  9274. @{
  9275. double d = 5.5;
  9276. printf ("Floating point value: %f\n", d);
  9277. printf ("Rounded to integer: %d\n", (int) d);
  9278. @}
  9279. @end example
  9280. Using @code{(int) d} passes an @code{int} value as argument to
  9281. @code{printf}, so you can print it with @samp{%d}. Using just
  9282. @code{d} without the cast would pass the value as @code{double}.
  9283. That won't work at all with @samp{%d}; the results would be gibberish.
  9284. To divide one integer by another without rounding,
  9285. cast either of the integers to @code{double} first:
  9286. @example
  9287. (double) @var{dividend} / @var{divisor}
  9288. @var{dividend} / (double) @var{divisor}
  9289. @end example
  9290. It is enough to cast one of them, because that forces the common type
  9291. to @code{double} so the other will be converted automatically.
  9292. The valid cast conversions are:
  9293. @itemize @bullet
  9294. @item
  9295. One numerical type to another.
  9296. @item
  9297. One pointer type to another.
  9298. (Converting between pointers that point to functions
  9299. and pointers that point to data is not standard C.)
  9300. @item
  9301. A pointer type to an integer type.
  9302. @item
  9303. An integer type to a pointer type.
  9304. @item
  9305. To a union type, from the type of any alternative in the union
  9306. (@pxref{Unions}). (This is a GNU extension.)
  9307. @item
  9308. Anything, to @code{void}.
  9309. @end itemize
  9310. @node Assignment Type Conversions
  9311. @section Assignment Type Conversions
  9312. @cindex assignment type conversions
  9313. Certain type conversions occur automatically in assignments
  9314. and certain other contexts. These are the conversions
  9315. assignments can do:
  9316. @itemize @bullet
  9317. @item
  9318. Converting any numeric type to any other numeric type.
  9319. @item
  9320. Converting @code{void *} to any other pointer type
  9321. (except pointer-to-function types).
  9322. @item
  9323. Converting any other pointer type to @code{void *}.
  9324. (except pointer-to-function types).
  9325. @item
  9326. Converting 0 (a null pointer constant) to any pointer type.
  9327. @item
  9328. Converting any pointer type to @code{bool}. (The result is
  9329. 1 if the pointer is not null.)
  9330. @item
  9331. Converting between pointer types when the left-hand target type is
  9332. upward compatible with the right-hand target type. @xref{Compatible
  9333. Types}.
  9334. @end itemize
  9335. These type conversions occur automatically in certain contexts,
  9336. which are:
  9337. @itemize @bullet
  9338. @item
  9339. An assignment converts the type of the right-hand expression
  9340. to the type wanted by the left-hand expression. For example,
  9341. @example
  9342. double i;
  9343. i = 5;
  9344. @end example
  9345. @noindent
  9346. converts 5 to @code{double}.
  9347. @item
  9348. A function call, when the function specifies the type for that
  9349. argument, converts the argument value to that type. For example,
  9350. @example
  9351. void foo (double);
  9352. foo (5);
  9353. @end example
  9354. @noindent
  9355. converts 5 to @code{double}.
  9356. @item
  9357. A @code{return} statement converts the specified value to the type
  9358. that the function is declared to return. For example,
  9359. @example
  9360. double
  9361. foo ()
  9362. @{
  9363. return 5;
  9364. @}
  9365. @end example
  9366. @noindent
  9367. also converts 5 to @code{double}.
  9368. @end itemize
  9369. In all three contexts, if the conversion is impossible, that
  9370. constitutes an error.
  9371. @node Argument Promotions
  9372. @section Argument Promotions
  9373. @cindex argument promotions
  9374. @cindex promotion of arguments
  9375. When a function's definition or declaration does not specify the type
  9376. of an argument, that argument is passed without conversion in whatever
  9377. type it has, with these exceptions:
  9378. @itemize @bullet
  9379. @item
  9380. Some narrow numeric values are @dfn{promoted} to a wider type. If the
  9381. expression is a narrow integer, such as @code{char} or @code{short},
  9382. the call converts it automatically to @code{int} (@pxref{Integer
  9383. Types}).@footnote{On an embedded controller where @code{char}
  9384. or @code{short} is the same width as @code{int}, @code{unsigned char}
  9385. or @code{unsigned short} promotes to @code{unsigned int}, but that
  9386. never occurs in GNU C on real computers.}
  9387. In this example, the expression @code{c} is passed as an @code{int}:
  9388. @example
  9389. char c = '$';
  9390. printf ("Character c is '%c'\n", c);
  9391. @end example
  9392. @item
  9393. If the expression
  9394. has type @code{float}, the call converts it automatically to
  9395. @code{double}.
  9396. @item
  9397. An array as argument is converted to a pointer to its zeroth element.
  9398. @item
  9399. A function name as argument is converted to a pointer to that function.
  9400. @end itemize
  9401. @node Operand Promotions
  9402. @section Operand Promotions
  9403. @cindex operand promotions
  9404. The operands in arithmetic operations undergo type conversion automatically.
  9405. These @dfn{operand promotions} are the same as the argument promotions
  9406. except without converting @code{float} to @code{double}. In other words,
  9407. the operand promotions convert
  9408. @itemize @bullet
  9409. @item
  9410. @code{char} or @code{short} (whether signed or not) to @code{int}.
  9411. @item
  9412. an array to a pointer to its zeroth element, and
  9413. @item
  9414. a function name to a pointer to that function.
  9415. @end itemize
  9416. @node Common Type
  9417. @section Common Type
  9418. @cindex common type
  9419. Arithmetic binary operators (except the shift operators) convert their
  9420. operands to the @dfn{common type} before operating on them.
  9421. Conditional expressions also convert the two possible results to their
  9422. common type. Here are the rules for determining the common type.
  9423. If one of the numbers has a floating-point type and the other is an
  9424. integer, the common type is that floating-point type. For instance,
  9425. @example
  9426. 5.6 * 2 @result{} 11.2 /* @r{a @code{double} value} */
  9427. @end example
  9428. If both are floating point, the type with the larger range is the
  9429. common type.
  9430. If both are integers but of different widths, the common type
  9431. is the wider of the two.
  9432. If they are integer types of the same width, the common type is
  9433. unsigned if either operand is unsigned, and it's @code{long} if either
  9434. operand is @code{long}. It's @code{long long} if either operand is
  9435. @code{long long}.
  9436. These rules apply to addition, subtraction, multiplication, division,
  9437. remainder, comparisons, and bitwise operations. They also apply to
  9438. the two branches of a conditional expression, and to the arithmetic
  9439. done in a modifying assignment operation.
  9440. @node Scope
  9441. @chapter Scope
  9442. @cindex scope
  9443. @cindex block scope
  9444. @cindex function scope
  9445. @cindex function prototype scope
  9446. Each definition or declaration of an identifier is visible
  9447. in certain parts of the program, which is typically less than the whole
  9448. of the program. The parts where it is visible are called its @dfn{scope}.
  9449. Normally, declarations made at the top-level in the source -- that is,
  9450. not within any blocks and function definitions -- are visible for the
  9451. entire contents of the source file after that point. This is called
  9452. @dfn{file scope} (@pxref{File-Scope Variables}).
  9453. Declarations made within blocks of code, including within function
  9454. definitions, are visible only within those blocks. This is called
  9455. @dfn{block scope}. Here is an example:
  9456. @example
  9457. @group
  9458. void
  9459. foo (void)
  9460. @{
  9461. int x = 42;
  9462. @}
  9463. @end group
  9464. @end example
  9465. @noindent
  9466. In this example, the variable @code{x} has block scope; it is visible
  9467. only within the @code{foo} function definition block. Thus, other
  9468. blocks could have their own variables, also named @code{x}, without
  9469. any conflict between those variables.
  9470. A variable declared inside a subblock has a scope limited to
  9471. that subblock,
  9472. @example
  9473. @group
  9474. void
  9475. foo (void)
  9476. @{
  9477. @{
  9478. int x = 42;
  9479. @}
  9480. // @r{@code{x} is out of scope here.}
  9481. @}
  9482. @end group
  9483. @end example
  9484. If a variable declared within a block has the same name as a variable
  9485. declared outside of that block, the definition within the block
  9486. takes precedence during its scope:
  9487. @example
  9488. @group
  9489. int x = 42;
  9490. void
  9491. foo (void)
  9492. @{
  9493. int x = 17;
  9494. printf ("%d\n", x);
  9495. @}
  9496. @end group
  9497. @end example
  9498. @noindent
  9499. This prints 17, the value of the variable @code{x} declared in the
  9500. function body block, rather than the value of the variable @code{x} at
  9501. file scope. We say that the inner declaration of @code{x}
  9502. @dfn{shadows} the outer declaration, for the extent of the inner
  9503. declaration's scope.
  9504. A declaration with block scope can be shadowed by another declaration
  9505. with the same name in a subblock.
  9506. @example
  9507. @group
  9508. void
  9509. foo (void)
  9510. @{
  9511. char *x = "foo";
  9512. @{
  9513. int x = 42;
  9514. @r{@dots{}}
  9515. exit (x / 6);
  9516. @}
  9517. @}
  9518. @end group
  9519. @end example
  9520. A function parameter's scope is the entire function body, but it can
  9521. be shadowed. For example:
  9522. @example
  9523. @group
  9524. int x = 42;
  9525. void
  9526. foo (int x)
  9527. @{
  9528. printf ("%d\n", x);
  9529. @}
  9530. @end group
  9531. @end example
  9532. @noindent
  9533. This prints the value of @code{x} the function parameter, rather than
  9534. the value of the file-scope variable @code{x}. However,
  9535. Labels (@pxref{goto Statement}) have @dfn{function} scope: each label
  9536. is visible for the whole of the containing function body, both before
  9537. and after the label declaration:
  9538. @example
  9539. @group
  9540. void
  9541. foo (void)
  9542. @{
  9543. @r{@dots{}}
  9544. goto bar;
  9545. @r{@dots{}}
  9546. @{ // @r{Subblock does not affect labels.}
  9547. bar:
  9548. @r{@dots{}}
  9549. @}
  9550. goto bar;
  9551. @}
  9552. @end group
  9553. @end example
  9554. Except for labels, a declared identifier is not
  9555. visible to code before its declaration. For example:
  9556. @example
  9557. @group
  9558. int x = 5;
  9559. int y = x + 10;
  9560. @end group
  9561. @end example
  9562. @noindent
  9563. will work, but:
  9564. @example
  9565. @group
  9566. int x = y + 10;
  9567. int y = 5;
  9568. @end group
  9569. @end example
  9570. @noindent
  9571. cannot refer to the variable @code{y} before its declaration.
  9572. @include cpp.texi
  9573. @node Integers in Depth
  9574. @chapter Integers in Depth
  9575. This chapter explains the machine-level details of integer types: how
  9576. they are represented as bits in memory, and the range of possible
  9577. values for each integer type.
  9578. @menu
  9579. * Integer Representations:: How integer values appear in memory.
  9580. * Maximum and Minimum Values:: Value ranges of integer types.
  9581. @end menu
  9582. @node Integer Representations
  9583. @section Integer Representations
  9584. @cindex integer representations
  9585. @cindex representation of integers
  9586. Modern computers store integer values as binary (base-2) numbers that
  9587. occupy a single unit of storage, typically either as an 8-bit
  9588. @code{char}, a 16-bit @code{short int}, a 32-bit @code{int}, or
  9589. possibly, a 64-bit @code{long long int}. Whether a @code{long int} is
  9590. a 32-bit or a 64-bit value is system dependent.@footnote{In theory,
  9591. any of these types could have some other size, bit it's not worth even
  9592. a minute to cater to that possibility. It never happens on
  9593. GNU/Linux.}
  9594. @cindex @code{CHAR_BIT}
  9595. The macro @code{CHAR_BIT}, defined in @file{limits.h}, gives the number
  9596. of bits in type @code{char}. On any real operating system, the value
  9597. is 8.
  9598. The fixed sizes of numeric types necessarily limits their @dfn{range
  9599. of values}, and the particular encoding of integers decides what that
  9600. range is.
  9601. @cindex two's-complement representation
  9602. For unsigned integers, the entire space is used to represent a
  9603. nonnegative value. Signed integers are stored using
  9604. @dfn{two's-complement representation}: a signed integer with @var{n}
  9605. bits has a range from @math{-2@sup{(@var{n} - 1)}} to @minus{}1 to 0
  9606. to 1 to @math{+2@sup{(@var{n} - 1)} - 1}, inclusive. The leftmost, or
  9607. high-order, bit is called the @dfn{sign bit}.
  9608. @c ??? Needs correcting
  9609. There is only one value that means zero, and the most negative number
  9610. lacks a positive counterpart. As a result, negating that number
  9611. causes overflow; in practice, its result is that number back again.
  9612. For example, a two's-complement signed 8-bit integer can represent all
  9613. decimal numbers from @minus{}128 to +127. We will revisit that
  9614. peculiarity shortly.
  9615. Decades ago, there were computers that didn't use two's-complement
  9616. representation for integers (@pxref{Integers in Depth}), but they are
  9617. long gone and not worth any effort to support.
  9618. @c ??? Is this duplicate?
  9619. When an arithmetic operation produces a value that is too big to
  9620. represent, the operation is said to @dfn{overflow}. In C, integer
  9621. overflow does not interrupt the control flow or signal an error.
  9622. What it does depends on signedness.
  9623. For unsigned arithmetic, the result of an operation that overflows is
  9624. the @var{n} low-order bits of the correct value. If the correct value
  9625. is representable in @var{n} bits, that is always the result;
  9626. thus we often say that ``integer arithmetic is exact,'' omitting the
  9627. crucial qualifying phrase ``as long as the exact result is
  9628. representable.''
  9629. In principle, a C program should be written so that overflow never
  9630. occurs for signed integers, but in GNU C you can specify various ways
  9631. of handling such overflow (@pxref{Integer Overflow}).
  9632. Integer representations are best understood by looking at a table for
  9633. a tiny integer size; here are the possible values for an integer with
  9634. three bits:
  9635. @multitable @columnfractions .25 .25 .25 .25
  9636. @headitem Unsigned @tab Signed @tab Bits @tab 2s Complement
  9637. @item 0 @tab 0 @tab 000 @tab 000 (0)
  9638. @item 1 @tab 1 @tab 001 @tab 111 (-1)
  9639. @item 2 @tab 2 @tab 010 @tab 110 (-2)
  9640. @item 3 @tab 3 @tab 011 @tab 101 (-3)
  9641. @item 4 @tab -4 @tab 100 @tab 100 (-4)
  9642. @item 5 @tab -3 @tab 101 @tab 011 (3)
  9643. @item 6 @tab -2 @tab 110 @tab 010 (2)
  9644. @item 7 @tab -1 @tab 111 @tab 001 (1)
  9645. @end multitable
  9646. The parenthesized decimal numbers in the last column represent the
  9647. signed meanings of the two's-complement of the line's value. Recall
  9648. that, in two's-complement encoding, the high-order bit is 0 when
  9649. the number is nonnegative.
  9650. We can now understand the peculiar behavior of negation of the
  9651. most negative two's-complement integer: start with 0b100,
  9652. invert the bits to get 0b011, and add 1: we get
  9653. 0b100, the value we started with.
  9654. We can also see overflow behavior in two's-complement:
  9655. @example
  9656. 3 + 1 = 0b011 + 0b001 = 0b100 = (-4)
  9657. 3 + 2 = 0b011 + 0b010 = 0b101 = (-3)
  9658. 3 + 3 = 0b011 + 0b011 = 0b110 = (-2)
  9659. @end example
  9660. @noindent
  9661. A sum of two nonnegative signed values that overflows has a 1 in the
  9662. sign bit, so the exact positive result is truncated to a negative
  9663. value.
  9664. @c =====================================================================
  9665. @node Maximum and Minimum Values
  9666. @section Maximum and Minimum Values
  9667. @cindex maximum integer values
  9668. @cindex minimum integer values
  9669. @cindex integer ranges
  9670. @cindex ranges of integer types
  9671. @findex INT_MAX
  9672. @findex UINT_MAX
  9673. @findex SHRT_MAX
  9674. @findex LONG_MAX
  9675. @findex LLONG_MAX
  9676. @findex USHRT_MAX
  9677. @findex ULONG_MAX
  9678. @findex ULLONG_MAX
  9679. @findex CHAR_MAX
  9680. @findex SCHAR_MAX
  9681. @findex UCHAR_MAX
  9682. For each primitive integer type, there is a standard macro defined in
  9683. @file{limits.h} that gives the largest value that type can hold. For
  9684. instance, for type @code{int}, the maximum value is @code{INT_MAX}.
  9685. On a 32-bit computer, that is equal to 2,147,483,647. The
  9686. maximum value for @code{unsigned int} is @code{UINT_MAX}, which on a
  9687. 32-bit computer is equal to 4,294,967,295. Likewise, there are
  9688. @code{SHRT_MAX}, @code{LONG_MAX}, and @code{LLONG_MAX}, and
  9689. corresponding unsigned limits @code{USHRT_MAX}, @code{ULONG_MAX}, and
  9690. @code{ULLONG_MAX}.
  9691. Since there are three ways to specify a @code{char} type, there are
  9692. also three limits: @code{CHAR_MAX}, @code{SCHAR_MAX}, and
  9693. @code{UCHAR_MAX}.
  9694. For each type that is or might be signed, there is another symbol that
  9695. gives the minimum value it can hold. (Just replace @code{MAX} with
  9696. @code{MIN} in the names listed above.) There is no minimum limit
  9697. symbol for types specified with @code{unsigned} because the
  9698. minimum for them is universally zero.
  9699. @code{INT_MIN} is not the negative of @code{INT_MAX}. In
  9700. two's-complement representation, the most negative number is 1 less
  9701. than the negative of the most positive number. Thus, @code{INT_MIN}
  9702. on a 32-bit computer has the value @minus{}2,147,483,648. You can't
  9703. actually write the value that way in C, since it would overflow.
  9704. That's a good reason to use @code{INT_MIN} to specify
  9705. that value. Its definition is written to avoid overflow.
  9706. @include fp.texi
  9707. @node Compilation
  9708. @chapter Compilation
  9709. @cindex object file
  9710. @cindex compilation module
  9711. @cindex make rules
  9712. Early in the manual we explained how to compile a simple C program
  9713. that consists of a single source file (@pxref{Compile Example}).
  9714. However, we handle only short programs that way. A typical C program
  9715. consists of many source files, each of which is a separate
  9716. @dfn{compilation module}---meaning that it has to be compiled
  9717. separately.
  9718. The full details of how to compile with GCC are documented in xxxx.
  9719. @c ??? ref
  9720. Here we give only a simple introduction.
  9721. These are the commands to compile two compilation modules,
  9722. @file{foo.c} and @file{bar.c}, with a command for each module:
  9723. @example
  9724. gcc -c -O -g foo.c
  9725. gcc -c -O -g bar.c
  9726. @end example
  9727. @noindent
  9728. In these commands, @option{-g} says to generate debugging information,
  9729. @option{-O} says to do some optimization, and @option{-c} says to put
  9730. the compiled code for that module into a corresponding @dfn{object
  9731. file} and go no further. The object file for @file{foo.c} is called
  9732. @file{foo.o}, and so on.
  9733. If you wish, you can specify the additional options @option{-Wformat
  9734. -Wparenthesis -Wstrict-prototypes}, which request additional warnings.
  9735. One reason to divide a large program into multiple compilation modules
  9736. is to control how each module can access the internals of the others.
  9737. When a module declares a function or variable @code{extern}, other
  9738. modules can access it. The other functions and variables in
  9739. a module can't be accessed from outside that module.
  9740. The other reason for using multiple modules is so that changing
  9741. one source file does not require recompiling all of them in order
  9742. to try the modified program. Dividing a large program into many
  9743. substantial modules in this way typically makes recompilation much faster.
  9744. @cindex linking object files
  9745. After you compile all the program's modules, in order to run the
  9746. program you must @dfn{link} the object files into a combined
  9747. executable, like this:
  9748. @example
  9749. gcc -o foo foo.o bar.o
  9750. @end example
  9751. @noindent
  9752. In this command, @option{-o foo} species the file name for the
  9753. executable file, and the other arguments are the object files to link.
  9754. Always specify the executable file name in a command that generates
  9755. one.
  9756. Normally we don't run any of these commands directly. Instead we
  9757. write a set of @dfn{make rules} for the program, then use the
  9758. @command{make} program to recompile only the source files that need to
  9759. be recompiled.
  9760. @c ??? ref to make manual
  9761. @node Directing Compilation
  9762. @chapter Directing Compilation
  9763. This chapter describes C constructs that don't alter the program's
  9764. meaning @emph{as such}, but rather direct the compiler how to treat
  9765. some aspects of the program.
  9766. @menu
  9767. * Pragmas:: Controling compilation of some constructs.
  9768. * Static Assertions:: Compile-time tests for conditions.
  9769. @end menu
  9770. @node Pragmas
  9771. @section Pragmas
  9772. A @dfn{pragma} is an annotation in a program that gives direction to
  9773. the compiler.
  9774. @menu
  9775. * Pragma Basics:: Pragma syntax and usage.
  9776. * Severity Pragmas:: Settings for compile-time pragma output.
  9777. * Optimization Pragmas:: Controlling optimizations.
  9778. @end menu
  9779. @c See also @ref{Macro Pragmas}, which save and restore macro definitions.
  9780. @node Pragma Basics
  9781. @subsection Pragma Basics
  9782. C defines two syntactical forms for pragmas, the line form and the
  9783. token form. You can write any pragma in either form, with the same
  9784. meaning.
  9785. The line form is a line in the source code, like this:
  9786. @example
  9787. #pragma @var{line}
  9788. @end example
  9789. @noindent
  9790. The line pragma has no effect on the parsing of the lines around it.
  9791. This form has the drawback that it can't be generated by a macro expansion.
  9792. The token form is a series of tokens; it can appear anywhere in the
  9793. program between the other tokens.
  9794. @example
  9795. _Pragma (@var{stringconstant})
  9796. @end example
  9797. @noindent
  9798. The pragma has no effect on the syntax of the tokens that surround it;
  9799. thus, here's a pragma in the middle of an @code{if} statement:
  9800. @example
  9801. if _Pragma ("hello") (x > 1)
  9802. @end example
  9803. @noindent
  9804. However, that's an unclear thing to do; for the sake of
  9805. understandability, it is better to put a pragma on a line by itself
  9806. and not embedded in the middle of another construct.
  9807. Both forms of pragma have a textual argument. In a line pragma, the
  9808. text is the rest of the line. The textual argument to @code{_Pragma}
  9809. uses the same syntax as a C string constant: surround the text with
  9810. two @samp{"} characters, and add a backslash before each @samp{"} or
  9811. @samp{\} character in it.
  9812. With either syntax, the textual argument specifies what to do.
  9813. It begins with one or several words that specify the operation.
  9814. If the compiler does not recognize them, it ignores the pragma.
  9815. Here are the pragma operations supported in GNU C@.
  9816. @c ??? Verify font for []
  9817. @table @code
  9818. @item #pragma GCC dependency "@var{file}" [@var{message}]
  9819. @itemx _Pragma ("GCC dependency \"@var{file}\" [@var{message}]")
  9820. Declares that the current source file depends on @var{file}, so GNU C
  9821. compares the file times and gives a warning if @var{file} is newer
  9822. than the current source file.
  9823. This directive searches for @var{file} the way @code{#include}
  9824. searches for a non-system header file.
  9825. If @var{message} is given, the warning message includes that text.
  9826. Examples:
  9827. @example
  9828. #pragma GCC dependency "parse.y"
  9829. _pragma ("GCC dependency \"/usr/include/time.h\" \
  9830. rerun fixincludes")
  9831. @end example
  9832. @item #pragma GCC poison @var{identifiers}
  9833. @itemx _Pragma ("GCC poison @var{identifiers}")
  9834. Poisons the identifiers listed in @var{identifiers}.
  9835. This is useful to make sure all mention of @var{identifiers} has been
  9836. deleted from the program and that no reference to them creeps back in.
  9837. If any of those identifiers appears anywhere in the source after the
  9838. directive, it causes a compilation error. For example,
  9839. @example
  9840. #pragma GCC poison printf sprintf fprintf
  9841. sprintf(some_string, "hello");
  9842. @end example
  9843. @noindent
  9844. generates an error.
  9845. If a poisoned identifier appears as part of the expansion of a macro
  9846. that was defined before the identifier was poisoned, it will @emph{not}
  9847. cause an error. Thus, system headers that define macros that use
  9848. the identifier will not cause errors.
  9849. For example,
  9850. @example
  9851. #define strrchr rindex
  9852. _Pragma ("GCC poison rindex")
  9853. strrchr(some_string, 'h');
  9854. @end example
  9855. @noindent
  9856. does not cause a compilation error.
  9857. @item #pragma GCC system_header
  9858. @itemx _Pragma ("GCC system_header")
  9859. Specify treating the rest of the current source file as if it came
  9860. from a system header file. @xref{System Headers, System Headers,
  9861. System Headers, gcc, Using the GNU Compiler Collection}.
  9862. @item #pragma GCC warning @var{message}
  9863. @itemx _Pragma ("GCC warning @var{message}")
  9864. Equivalent to @code{#warning}. Its advantage is that the
  9865. @code{_Pragma} form can be included in a macro definition.
  9866. @item #pragma GCC error @var{message}
  9867. @itemx _Pragma ("GCC error @var{message}")
  9868. Equivalent to @code{#error}. Its advantage is that the
  9869. @code{_Pragma} form can be included in a macro definition.
  9870. @item #pragma GCC message @var{message}
  9871. @itemx _Pragma ("GCC message @var{message}")
  9872. Similar to @samp{GCC warning} and @samp{GCC error}, this simply prints an
  9873. informational message, and could be used to include additional warning
  9874. or error text without triggering more warnings or errors. (Note that
  9875. unlike @samp{warning} and @samp{error}, @samp{message} does not include
  9876. @samp{GCC} as part of the pragma.)
  9877. @end table
  9878. @node Severity Pragmas
  9879. @subsection Severity Pragmas
  9880. These pragmas control the severity of classes of diagnostics.
  9881. You can specify the class of diagnostic with the GCC option that causes
  9882. those diagnostics to be generated.
  9883. @table @code
  9884. @item #pragma GCC diagnostic error @var{option}
  9885. @itemx _Pragma ("GCC diagnostic error @var{option}")
  9886. For code following this pragma, treat diagnostics of the variety
  9887. specified by @var{option} as errors. For example:
  9888. @example
  9889. _Pragma ("GCC diagnostic error -Wformat")
  9890. @end example
  9891. @noindent
  9892. specifies to treat diagnostics enabled by the @var{-Wformat} option
  9893. as errors rather than warnings.
  9894. @item #pragma GCC diagnostic warning @var{option}
  9895. @itemx _Pragma ("GCC diagnostic warning @var{option}")
  9896. For code following this pragma, treat diagnostics of the variety
  9897. specified by @var{option} as warnings. This overrides the
  9898. @var{-Werror} option which says to treat warnings as errors.
  9899. @item #pragma GCC diagnostic ignore @var{option}
  9900. @itemx _Pragma ("GCC diagnostic ignore @var{option}")
  9901. For code following this pragma, refrain from reporting any diagnostics
  9902. of the variety specified by @var{option}.
  9903. @item #pragma GCC diagnostic push
  9904. @itemx _Pragma ("GCC diagnostic push")
  9905. @itemx #pragma GCC diagnostic pop
  9906. @itemx _Pragma ("GCC diagnostic pop")
  9907. These pragmas maintain a stack of states for severity settings.
  9908. @samp{GCC diagnostic push} saves the current settings on the stack,
  9909. and @samp{GCC diagnostic pop} pops the last stack item and restores
  9910. the current settings from that.
  9911. @samp{GCC diagnostic pop} when the severity setting stack is empty
  9912. restores the settings to what they were at the start of compilation.
  9913. Here is an example:
  9914. @example
  9915. _Pragma ("GCC diagnostic error -Wformat")
  9916. /* @r{@option{-Wformat} messages treated as errors. } */
  9917. _Pragma ("GCC diagnostic push")
  9918. _Pragma ("GCC diagnostic warning -Wformat")
  9919. /* @r{@option{-Wformat} messages treated as warnings. } */
  9920. _Pragma ("GCC diagnostic push")
  9921. _Pragma ("GCC diagnostic ignored -Wformat")
  9922. /* @r{@option{-Wformat} messages suppressed. } */
  9923. _Pragma ("GCC diagnostic pop")
  9924. /* @r{@option{-Wformat} messages treated as warnings again. } */
  9925. _Pragma ("GCC diagnostic pop")
  9926. /* @r{@option{-Wformat} messages treated as errors again. } */
  9927. /* @r{This is an excess @samp{pop} that matches no @samp{push}. } */
  9928. _Pragma ("GCC diagnostic pop")
  9929. /* @r{@option{-Wformat} messages treated once again}
  9930. @r{as specified by the GCC command-line options.} */
  9931. @end example
  9932. @end table
  9933. @node Optimization Pragmas
  9934. @subsection Optimization Pragmas
  9935. These pragmas enable a particular optimization for specific function
  9936. definitions. The settings take effect at the end of a function
  9937. definition, so the clean place to use these pragmas is between
  9938. function definitions.
  9939. @table @code
  9940. @item #pragma GCC optimize @var{optimization}
  9941. @itemx _Pragma ("GCC optimize @var{optimization}")
  9942. These pragmas enable the optimization @var{optimization} for the
  9943. following functions. For example,
  9944. @example
  9945. _Pragma ("GCC optimize -fforward-propagate")
  9946. @end example
  9947. @noindent
  9948. says to apply the @samp{forward-propagate} optimization to all
  9949. following function definitions. Specifying optimizations for
  9950. individual functions, rather than for the entire program, is rare but
  9951. can be useful for getting around a bug in the compiler.
  9952. If @var{optimization} does not correspond to a defined optimization
  9953. option, the pragma is erroneous. To turn off an optimization, use the
  9954. corresponding @samp{-fno-} option, such as
  9955. @samp{-fno-forward-propagate}.
  9956. @item #pragma GCC target @var{optimizations}
  9957. @itemx _Pragma ("GCC target @var{optimizations}")
  9958. The pragma @samp{GCC target} is similar to @samp{GCC optimize} but is
  9959. used for platform-specific optimizations. Thus,
  9960. @example
  9961. _Pragma ("GCC target popcnt")
  9962. @end example
  9963. @noindent
  9964. activates the optimization @samp{popcnt} for all
  9965. following function definitions. This optimization is supported
  9966. on a few common targets but not on others.
  9967. @item #pragma GCC push_options
  9968. @itemx _Pragma ("GCC push_options")
  9969. The @samp{push_options} pragma saves on a stack the current settings
  9970. specified with the @samp{target} and @samp{optimize} pragmas.
  9971. @item #pragma GCC pop_options
  9972. @itemx _Pragma ("GCC pop_options")
  9973. The @samp{pop_options} pragma pops saved settings from that stack.
  9974. Here's an example of using this stack.
  9975. @example
  9976. _Pragma ("GCC push_options")
  9977. _Pragma ("GCC optimize forward-propagate")
  9978. /* @r{Functions to compile}
  9979. @r{with the @code{forward-propagate} optimization.} */
  9980. _Pragma ("GCC pop_options")
  9981. /* @r{Ends enablement of @code{forward-propagate}.} */
  9982. @end example
  9983. @item #pragma GCC reset_options
  9984. @itemx _Pragma ("GCC reset_options")
  9985. Clears all pragma-defined @samp{target} and @samp{optimize}
  9986. optimization settings.
  9987. @end table
  9988. @node Static Assertions
  9989. @section Static Assertions
  9990. @cindex static assertions
  9991. @findex _Static_assert
  9992. You can add compiler-time tests for necessary conditions into your
  9993. code using @code{_Static_assert}. This can be useful, for example, to
  9994. check that the compilation target platform supports the type sizes
  9995. that the code expects. For example,
  9996. @example
  9997. _Static_assert ((sizeof (long int) >= 8),
  9998. "long int needs to be at least 8 bytes");
  9999. @end example
  10000. @noindent
  10001. reports a compile-time error if compiled on a system with long
  10002. integers smaller than 8 bytes, with @samp{long int needs to be at
  10003. least 8 bytes} as the error message.
  10004. Since calls @code{_Static_assert} are processed at compile time, the
  10005. expression must be computable at compile time and the error message
  10006. must be a literal string. The expression can refer to the sizes of
  10007. variables, but can't refer to their values. For example, the
  10008. following static assertion is invalid for two reasons:
  10009. @example
  10010. char *error_message
  10011. = "long int needs to be at least 8 bytes";
  10012. int size_of_long_int = sizeof (long int);
  10013. _Static_assert (size_of_long_int == 8, error_message);
  10014. @end example
  10015. @noindent
  10016. The expression @code{size_of_long_int == 8} isn't computable at
  10017. compile time, and the error message isn't a literal string.
  10018. You can, though, use preprocessor definition values with
  10019. @code{_Static_assert}:
  10020. @example
  10021. #define LONG_INT_ERROR_MESSAGE "long int needs to be \
  10022. at least 8 bytes"
  10023. _Static_assert ((sizeof (long int) == 8),
  10024. LONG_INT_ERROR_MESSAGE);
  10025. @end example
  10026. Static assertions are permitted wherever a statement or declaration is
  10027. permitted, including at top level in the file, and also inside the
  10028. definition of a type.
  10029. @example
  10030. union y
  10031. @{
  10032. int i;
  10033. int *ptr;
  10034. _Static_assert (sizeof (int *) == sizeof (int),
  10035. "Pointer and int not same size");
  10036. @};
  10037. @end example
  10038. @node Type Alignment
  10039. @appendix Type Alignment
  10040. @cindex type alignment
  10041. @cindex alignment of type
  10042. @findex _Alignof
  10043. @findex __alignof__
  10044. Code for device drivers and other communication with low-level
  10045. hardware sometimes needs to be concerned with the alignment of
  10046. data objects in memory.
  10047. Each data type has a required @dfn{alignment}, always a power of 2,
  10048. that says at which memory addresses an object of that type can validly
  10049. start. A valid address for the type must be a multiple of its
  10050. alignment. If a type's alignment is 1, that means it can validly
  10051. start at any address. If a type's alignment is 2, that means it can
  10052. only start at an even address. If a type's alignment is 4, that means
  10053. it can only start at an address that is a multiple of 4.
  10054. The alignment of a type (except @code{char}) can vary depending on the
  10055. kind of computer in use. To refer to the alignment of a type in a C
  10056. program, use @code{_Alignof}, whose syntax parallels that of
  10057. @code{sizeof}. Like @code{sizeof}, @code{_Alignof} is a compile-time
  10058. operation, and it doesn't compute the value of the expression used
  10059. as its argument.
  10060. Nominally, each integer and floating-point type has an alignment equal to
  10061. the largest power of 2 that divides its size. Thus, @code{int} with
  10062. size 4 has a nominal alignment of 4, and @code{long long int} with
  10063. size 8 has a nominal alignment of 8.
  10064. However, each kind of computer generally has a maximum alignment, and
  10065. no type needs more alignment than that. If the computer's maximum
  10066. alignment is 4 (which is common), then no type's alignment is more
  10067. than 4.
  10068. The size of any type is always a multiple of its alignment; that way,
  10069. in an array whose elements have that type, all the elements are
  10070. properly aligned if the first one is.
  10071. These rules apply to all real computers today, but some embedded
  10072. controllers have odd exceptions. We don't have references to cite for
  10073. them.
  10074. @c We can't cite a nonfree manual as documentation.
  10075. Ordinary C code guarantees that every object of a given type is in
  10076. fact aligned as that type requires.
  10077. If the operand of @code{_Alignof} is a structure field, the value
  10078. is the alignment it requires. It may have a greater alignment by
  10079. coincidence, due to the other fields, but @code{_Alignof} is not
  10080. concerned about that. @xref{Structures}.
  10081. Older versions of GNU C used the keyword @code{__alignof__} for this,
  10082. but now that the feature has been standardized, it is better
  10083. to use the standard keyword @code{_Alignof}.
  10084. @findex _Alignas
  10085. @findex __aligned__
  10086. You can explicitly specify an alignment requirement for a particular
  10087. variable or structure field by adding @code{_Alignas
  10088. (@var{alignment})} to the declaration, where @var{alignment} is a
  10089. power of 2 or a type name. For instance:
  10090. @example
  10091. char _Alignas (8) x;
  10092. @end example
  10093. @noindent
  10094. or
  10095. @example
  10096. char _Alignas (double) x;
  10097. @end example
  10098. @noindent
  10099. specifies that @code{x} must start on an address that is a multiple of
  10100. 8. However, if @var{alignment} exceeds the maximum alignment for the
  10101. machine, that maximum is how much alignment @code{x} will get.
  10102. The older GNU C syntax for this feature looked like
  10103. @code{__attribute__ ((__aligned__ (@var{alignment})))} to the
  10104. declaration, and was added after the variable. For instance:
  10105. @example
  10106. char x __attribute__ ((__aligned__ 8));
  10107. @end example
  10108. @xref{Attributes}.
  10109. @node Aliasing
  10110. @appendix Aliasing
  10111. @cindex aliasing (of storage)
  10112. @cindex pointer type conversion
  10113. @cindex type conversion, pointer
  10114. We have already presented examples of casting a @code{void *} pointer
  10115. to another pointer type, and casting another pointer type to
  10116. @code{void *}.
  10117. One common kind of pointer cast is guaranteed safe: casting the value
  10118. returned by @code{malloc} and related functions (@pxref{Dynamic Memory
  10119. Allocation}). It is safe because these functions do not save the
  10120. pointer anywhere else; the only way the program will access the newly
  10121. allocated memory is via the pointer just returned.
  10122. In fact, C allows casting any pointer type to any other pointer type.
  10123. Using this to access the same place in memory using two
  10124. different data types is called @dfn{aliasing}.
  10125. Aliasing is necessary in some programs that do sophisticated memory
  10126. management, such as GNU Emacs, but most C programs don't need to do
  10127. aliasing. When it isn't needed, @strong{stay away from it!} To do
  10128. aliasing correctly requires following the rules stated below.
  10129. Otherwise, the aliasing may result in malfunctions when the program
  10130. runs.
  10131. The rest of this appendix explains the pitfalls and rules of aliasing.
  10132. @menu
  10133. * Aliasing Alignment:: Memory alignment considerations for
  10134. casting between pointer types.
  10135. * Aliasing Length:: Type size considerations for
  10136. casting between pointer types.
  10137. * Aliasing Type Rules:: Even when type alignment and size matches,
  10138. aliasing can still have surprising results.
  10139. @end menu
  10140. @node Aliasing Alignment
  10141. @appendixsection Aliasing and Alignment
  10142. In order for a type-converted pointer to be valid, it must have the
  10143. alignment that the new pointer type requires. For instance, on most
  10144. computers, @code{int} has alignment 4; the address of an @code{int}
  10145. must be a multiple of 4. However, @code{char} has alignment 1, so the
  10146. address of a @code{char} is usually not a multiple of 4. Taking the
  10147. address of such a @code{char} and casting it to @code{int *} probably
  10148. results in an invalid pointer. Trying to dereference it may cause a
  10149. @code{SIGBUS} signal, depending on the platform in use (@pxref{Signals}).
  10150. @example
  10151. foo ()
  10152. @{
  10153. char i[4];
  10154. int *p = (int *) &i[1]; /* @r{Misaligned pointer!} */
  10155. return *p; /* @r{Crash!} */
  10156. @}
  10157. @end example
  10158. This requirement is never a problem when casting the return value
  10159. of @code{malloc} because that function always returns a pointer
  10160. with as much alignment as any type can require.
  10161. @node Aliasing Length
  10162. @appendixsection Aliasing and Length
  10163. When converting a pointer to a different pointer type, make sure the
  10164. object it really points to is at least as long as the target of the
  10165. converted pointer. For instance, suppose @code{p} has type @code{int
  10166. *} and it's cast as follows:
  10167. @example
  10168. int *p;
  10169. struct
  10170. @{
  10171. double d, e, f;
  10172. @} foo;
  10173. struct foo *q = (struct foo *)p;
  10174. q->f = 5.14159;
  10175. @end example
  10176. @noindent
  10177. the value @code{q->f} will run past the end of the @code{int} that
  10178. @code{p} points to. If @code{p} was initialized to the start of an
  10179. array of type @code{int[6]}, the object is long enough for three
  10180. @code{double}s. But if @code{p} points to something shorter,
  10181. @code{q->f} will run on beyond the end of that, overlaying some other
  10182. data. Storing that will garble that other data. Or it could extend
  10183. past the end of memory space and cause a @code{SIGSEGV} signal
  10184. (@pxref{Signals}).
  10185. @node Aliasing Type Rules
  10186. @appendixsection Type Rules for Aliasing
  10187. C code that converts a pointer to a different pointer type can use the
  10188. pointers to access the same memory locations with two different data
  10189. types. If the same address is accessed with different types in a
  10190. single control thread, optimization can make the code do surprising
  10191. things (in effect, make it malfunction).
  10192. Here's a concrete example where aliasing that can change the code's
  10193. behavior when it is optimized. We assume that @code{float} is 4 bytes
  10194. long, like @code{int}, and so is every pointer. Thus, the structures
  10195. @code{struct a} and @code{struct b} are both 8 bytes.
  10196. @example
  10197. #include <stdio.h>
  10198. struct a @{ int size; char *data; @};
  10199. struct b @{ float size; char *data; @};
  10200. void sub (struct a *p, struct b *q)
  10201. @{
  10202.   int x;
  10203.   p->size = 0;
  10204.   q->size = 1;
  10205.   x = p->size;
  10206.   printf("x       =%d\n", x);
  10207.   printf("p->size =%d\n", (int)p->size);
  10208.   printf("q->size =%d\n", (int)q->size);
  10209. @}
  10210. int main(void)
  10211. @{
  10212.   struct a foo;
  10213.   struct a *p = &foo;
  10214.   struct b *q = (struct b *) &foo;
  10215.   sub (p, q);
  10216. @}
  10217. @end example
  10218. This code works as intended when compiled without optimization. All
  10219. the operations are carried out sequentially as written. The code
  10220. sets @code{x} to @code{p->size}, but what it actually gets is the
  10221. bits of the floating point number 1, as type @code{int}.
  10222. However, when optimizing, the compiler is allowed to assume
  10223. (mistakenly, here) that @code{q} does not point to the same storage as
  10224. @code{p}, because their data types are not allowed to alias.
  10225. From this assumption, the compiler can deduce (falsely, here) that the
  10226. assignment into @code{q->size} has no effect on the value of
  10227. @code{p->size}, which must therefore still be 0. Thus, @code{x} will
  10228. be set to 0.
  10229. GNU C, following the C standard, @emph{defines} this optimization as
  10230. legitimate. Code that misbehaves when optimized following these rules
  10231. is, by definition, incorrect C code.
  10232. The rules for storage aliasing in C are based on the two data types:
  10233. the type of the object, and the type it is accessed through. The
  10234. rules permit accessing part of a storage object of type @var{t} using
  10235. only these types:
  10236. @itemize @bullet
  10237. @item
  10238. @var{t}.
  10239. @item
  10240. A type compatible with @var{t}. @xref{Compatible Types}.
  10241. @item
  10242. A signed or unsigned version of one of the above.
  10243. @item
  10244. A qualifed version of one of the above.
  10245. @xref{Type Qualifiers}.
  10246. @item
  10247. An array, structure (@pxref{Structures}), or union type
  10248. (@code{Unions}) that contains one of the above, either directly as a
  10249. field or through multiple levels of fields. If @var{t} is
  10250. @code{double}, this would include @code{struct s @{ union @{ double
  10251. d[2]; int i[4]; @} u; int i; @};} because there's a @code{double}
  10252. inside it somewhere.
  10253. @item
  10254. A character type.
  10255. @end itemize
  10256. What do these rules say about the example in this subsection?
  10257. For @code{foo.size} (equivalently, @code{a->size}), @var{t} is
  10258. @code{int}. The type @code{float} is not allowed as an aliasing type
  10259. by those rules, so @code{b->size} is not supposed to alias with
  10260. elements of @code{j}. Based on that assumption, GNU C makes a
  10261. permitted optimization that was not, in this case, consistent with
  10262. what the programmer intended the program to do.
  10263. Whether GCC actually performs type-based aliasing analysis depends on
  10264. the details of the code. GCC has other ways to determine (in some cases)
  10265. whether objects alias, and if it gets a reliable answer that way, it won't
  10266. fall back on type-based heuristics.
  10267. @c @opindex -fno-strict-aliasing
  10268. The importance of knowing the type-based aliasing rules is not so as
  10269. to ensure that the optimization is done where it would be safe, but so
  10270. as to ensure it is @emph{not} done in a way that would break the
  10271. program. You can turn off type-based aliasing analysis by giving GCC
  10272. the option @option{-fno-strict-aliasing}.
  10273. @node Digraphs
  10274. @appendix Digraphs
  10275. @cindex digraphs
  10276. C accepts aliases for certain characters. Apparently in the 1990s
  10277. some computer systems had trouble inputting these characters, or
  10278. trouble displaying them. These digraphs almost never appear in C
  10279. programs nowadays, but we mention them for completeness.
  10280. @table @samp
  10281. @item <:
  10282. An alias for @samp{[}.
  10283. @item :>
  10284. An alias for @samp{]}.
  10285. @item <%
  10286. An alias for @samp{@{}.
  10287. @item %>
  10288. An alias for @samp{@}}.
  10289. @item %:
  10290. An alias for @samp{#},
  10291. used for preprocessing directives (@pxref{Directives}) and
  10292. macros (@pxref{Macros}).
  10293. @end table
  10294. @node Attributes
  10295. @appendix Attributes in Declarations
  10296. @cindex attributes
  10297. @findex __attribute__
  10298. You can specify certain additional requirements in a declaration, to
  10299. get fine-grained control over code generation, and helpful
  10300. informational messages during compilation. We use a few attributes in
  10301. code examples throughout this manual, including
  10302. @table @code
  10303. @item aligned
  10304. The @code{aligned} attribute specifies a minimum alignment for a
  10305. variable or structure field, measured in bytes:
  10306. @example
  10307. int foo __attribute__ ((aligned (8))) = 0;
  10308. @end example
  10309. @noindent
  10310. This directs GNU C to allocate @code{foo} at an address that is a
  10311. multiple of 8 bytes. However, you can't force an alignment bigger
  10312. than the computer's maximum meaningful alignment.
  10313. @item packed
  10314. The @code{packed} attribute specifies to compact the fields of a
  10315. structure by not leaving gaps between fields. For example,
  10316. @example
  10317. struct __attribute__ ((packed)) bar
  10318. @{
  10319. char a;
  10320. int b;
  10321. @};
  10322. @end example
  10323. @noindent
  10324. allocates the integer field @code{b} at byte 1 in the structure,
  10325. immediately after the character field @code{a}. The packed structure
  10326. is just 5 bytes long (assuming @code{int} is 4 bytes) and its
  10327. alignment is 1, that of @code{char}.
  10328. @item deprecated
  10329. Applicable to both variables and functions, the @code{deprecated}
  10330. attribute tells the compiler to issue a warning if the variable or
  10331. function is ever used in the source file.
  10332. @example
  10333. int old_foo __attribute__ ((deprecated));
  10334. int old_quux () __attribute__ ((deprecated));
  10335. @end example
  10336. @item __noinline__
  10337. The @code{__noinline__} attribute, in a function's declaration or
  10338. definition, specifies never to inline calls to that function. All
  10339. calls to that function, in a compilation unit where it has this
  10340. attribute, will be compiled to invoke the separately compiled
  10341. function. @xref{Inline Function Definitions}.
  10342. @item __noclone__
  10343. The @code{__noclone__} attribute, in a function's declaration or
  10344. definition, specifies never to clone that function. Thus, there will
  10345. be only one compiled version of the function. @xref{Label Value
  10346. Caveats}, for more information about cloning.
  10347. @item always_inline
  10348. The @code{always_inline} attribute, in a function's declaration or
  10349. definition, specifies to inline all calls to that function (unless
  10350. something about the function makes inlining impossible). This applies
  10351. to all calls to that function in a compilation unit where it has this
  10352. attribute. @xref{Inline Function Definitions}.
  10353. @item gnu_inline
  10354. The @code{gnu_inline} attribute, in a function's declaration or
  10355. definition, specifies to handle the @code{inline} keywprd the way GNU
  10356. C originally implemented it, many years before ISO C said anything
  10357. about inlining. @xref{Inline Function Definitions}.
  10358. @end table
  10359. For full documentation of attributes, see the GCC manual.
  10360. @xref{Attribute Syntax, Attribute Syntax, System Headers, gcc, Using
  10361. the GNU Compiler Collection}.
  10362. @node Signals
  10363. @appendix Signals
  10364. @cindex signal
  10365. @cindex handler (for signal)
  10366. @cindex @code{SIGSEGV}
  10367. @cindex @code{SIGFPE}
  10368. @cindex @code{SIGBUS}
  10369. Some program operations bring about an error condition called a
  10370. @dfn{signal}. These signals terminate the program, by default.
  10371. There are various different kinds of signals, each with a name. We
  10372. have seen several such error conditions through this manual:
  10373. @table @code
  10374. @item SIGSEGV
  10375. This signal is generated when a program tries to read or write outside
  10376. the memory that is allocated for it, or to write memory that can only
  10377. be read. The name is an abbreviation for ``segmentation violation''.
  10378. @item SIGFPE
  10379. This signal indicates a fatal arithmetic error. The name is an
  10380. abbreviation for ``floating-point exception'', but covers all types of
  10381. arithmetic errors, including division by zero and overflow.
  10382. @item SIGBUS
  10383. This signal is generated when an invalid pointer is dereferenced,
  10384. typically the result of dereferencing an uninintalized pointer. It is
  10385. similar to @code{SIGSEGV}, except that @code{SIGSEGV} indicates
  10386. invalid access to valid memory, while @code{SIGBUS} indicates an
  10387. attempt to access an invalid address.
  10388. @end table
  10389. These kinds of signal allow the program to specify a function as a
  10390. @dfn{signal handler}. When a signal has a handler, it doesn't
  10391. terminate the program; instead it calls the handler.
  10392. There are many other kinds of signal; here we list only those that
  10393. come from run-time errors in C operations. The rest have to do with
  10394. the functioning of the operating system. The GNU C Library Reference
  10395. Manual gives more explanation about signals (@pxref{Program Signal
  10396. Handling, The GNU C Library, , libc, The GNU C Library Reference
  10397. Manual}).
  10398. @node GNU Free Documentation License
  10399. @appendix GNU Free Documentation License
  10400. @include fdl.texi
  10401. @node Symbol Index
  10402. @unnumbered Index of Symbols and Keywords
  10403. @printindex fn
  10404. @node Concept Index
  10405. @unnumbered Concept Index
  10406. @printindex cp
  10407. @bye