Making something 'vif.nable tS ea's]/.

Controillinig dura'lion alt oonmancy is irhe trirJk.

Declar Ition'·· pJa,y, a central role in 1'1 pregramming. B'_ I Ieclaring vari bles and

unctions.u l -, ish ' itajj informed n that ih mpiler w"U need in .Irder t,

heck 'I progn m fer _. tenti - rrors and tran slate it into : '~Ie,c 10 de"

Previous chapt rs have provided e arnples of declarations without gOiJlg into full d tails: tbi· chapt 'r - H. i in thes - ,p c. It ,- plore the pili', Ii 'at _cd I pti - th I can b used ill declarations and re eal lhat varia' III declaration and Iun tion declarari I :C,' have qui e _ bit in I:_.' IJItm, n, aJ 0 provide a firm gr mndins in the im] ortant en .. ·· -p", f· to ~ag· durz tion, k ap',., and linkas .. ,

S .. I 8 1 . ill 1 . f 'II· .. '~I. 'Il... .. . ... ,1I~

ecuen Ix, e· rmnes ine s ntax 0-1 'IC,'tj3[, Itll In m tnetr most g ":B ~tH rorm,

' __ topi that 'J e m oided up U)I thi point, . he Dr four secti n· fc C'_ 00 the

items that appear in declarntions: . tornge 'Cl,l:~l S (Section 18~. -,t type qualifier [Section I:~t, l decl "~. r'~ ,'~, ion 1:.,4 " id initi~eI"le:- tin I.')~ Section

18.16 . iseusses the keyword, which call appear ill C function deelarations.

Deelar tion furnish infnn, '[ion to the compiler bout th _ me' iiug ,f identifier ,. 'When w write

int i;'

,," 'r ~ informin ~ the' ompiler that, in [b _ CWT n:[op' ~ tn - -,am1e i r, present a variable of [ype Lnt., The declaration

floar. f(float);


...... ..... '


, .. I

", -'. - ,

, ,

tells the compiler that f is a function that return 0. f Loat; value and bas one ,argument, also of type flo'8t.

In general a declaranon ha the foD,owi-ng appearance;

D',CIar:lltW'll Ilpl'ci/ierr describe the properties of the' variables 101' functions being declared. Det',llUtutors: give their names and ma,,Y pro- 'id, additional in ormation about their properties.

Declaration specifiers fal] into three categories:

I. Stomgle; classes .. , There are four storage classes: aut.o, stat,ic extern-I and relgister. A'I 1l10S,t Ollie storage class may I:ppcar in it declaration: if pre, ent, i1 should come first,

II l)JJ'e qBoli/ii!. j r~ In C8,9~ there are only 'two type qualifiers: ~.on,sJt and VIiD',e, C9J9! has a ldlird, tY,PlC qualifier, re,strict. A declaration lln,ay contml) zero or mer ' Itype q ual ifier .

• Typ'e specllferJ"1fj The keywords voi.d char sh,olrt Lnt., Lonq, fl,cla·t~ doub l e sig'ned, and uns,.igned are all type specifier . These word, may be combi [led 1:'1 described in Chapter '7':1 the order iB whieh they appear doesn ~ matter (int unaLqned lon-g 'is the '<lame as Lonq una.i.qrred int)" T pe specifiers al.S,OI include specifications of structures, unions, land enumerarions (for example st.rulct poin.t { Lnt; x , y,; } stru"ct { in't 'x ~ y; } ~ or atruct; pod.nt.). TY,p name created using typed,s! are Ilyp,e specifier- 8 .. well,

(e99 bas a fourth kind of declaration specifier, the /rlftC;tw'R1'ectfifl'Ij, which i used olnly [0 function declaration " This category has just IClDe m ember, the keyword inlin,e~) Type qualifiers andtype specifiers should follow th.e sterage elms '~

. -

b~! there me no other restrictions 010 their order. As a matter 0 's,tyle,,, I~U put type'

qualifiers before ~pe specifiers.

Declarators il1'cJudeldentifiers (names of simple variables), identifier followed by [] (array names), identifiers pr,~[;eded by .. (pointier names) and fudentifieli fellowed by I') (function names), D,elclanalo'r," are separated by commas, A declarator that represents a varlable may be followed by an initializer,

Let 81 look 31 a few examples that illustrate these rules, Here 5, ,I declaration with a storage class and. three declarator :


" ,I

static float x, y, .p;

The foUo,will,g declaration has a type qualifier but no storage clas I. It also has an initializer:

typ'u t1,1U aUfis'lf I

c.onst char month[] -


-type specirie'lr

II Jan 1 ary";


lnltial: ,zer

The ollowin ~ dell nation b I b th a [Ife:" el~ I. _, an a _ Pi qualifier, It -0 b ~

three lyp1e s eeifiers; their o der j D "t imp . t:

smragB class

extern cons t wls±gned lDng in, 'a [10] ;

r T

type IQua-nf~er dec~ara(loll'

Fun tion declarations, like variable declaration "1 rna.y have a torage qualifier: and type . pe' 'i ters.. '-. 1 II :. In declaratf n b " stor ty e : pecifier:

-lali~ I typ . and .1

smrage class dele arator


The next four sections 1_ ver torage clas '-'" typ qualifi IS declurators, 311d initializer in : etail,

Storage classes can be specified for 'variables and-to a le .. r exteut=Iunctiuns and arameters .. WI ~'ll concemrate I, varis -Ie' or D.·.' _~

R'6-caU from Section - - .3, tb,at the ter C'_- block fI' -. .'. £ the bod 0, " 'unction .the part enclosed in brace} 01[' ,8 compound '. t: rem nt, p ssibly containin . decla .. _ rations. In C' :19, < slection ' rarenu nrs (i ,- · d swi' ch and iter · " D" at eo' I

(while.~ do, and far)----alr(lrng with the inner" tatemen lha·t tb 0., control-vare

IIEI considered to' be blocks la., W U, althou _h this i primarilya [,- hnicalit t;

Properties o'f Varia,bles

Every variable in ;~. C program has three properties:

S -grtl;ge d"'.'.tiOIl~ The storage duration of a vari'"_' I determln II. when l11e1l1- ory is set aside for the variable ,and . ben that m 'mory i ' rele c ed.,· '1. rag _' r it variable 'with rtJllto,_~tltic S orale llll:,-lltiJJ ,- i. tl! 11Ioc~' d 'when the '. urroundin

...... - .....

block is executed: storage i - deallocated wbe'D the block terminates, can ing the variable to lose its val "e. ,A variable wi tl1 static sto,r~gie dJlr-tltiD'l slays, at 'the' arne '. torage Iocatiea as long as the program liS running, allowing it Ito retain its value indefinitely,

III ISclope .. The II: cope of a variable i8 the PO[lti00 0l the program text in wrucll the variable can be referenced, A variable can have either block Icope (the variable is visible from its point of declaration to the end of tbe enclosing block) or file S"C'OP',f} (tbe vlriaE:"h~' 1.."" visible from its point of deciaration to the lend of the eaclosing file).

• Li"'ka,,e,~ The lil1k~ ge of a variable determines the extent to which. it can oe shared bIll different plan's 'of a prDgr~UJ] i, A variable with I'le,r:nd'lli.nkdge ma)' be shared by several (perhaps all) fil ~ S 'in a p'f am ~ A variab le wi th ii,l'ter',la' linkag,_ i restricted to a ingle file, but may be shar d by the function s in that file. (If a varlable with the same name ,appe,ar in another file, if " treated as a I liffereut variable.) A variable with ,11,0 li.I,,"ag,e belongs to a single function and IL: an -, t be sh aredat ,_ 11",

The defaWt storage duration, scope" and ninka"ge 'of ,I variable depend on wbere it's declared:

• declared inside a block (including a "function, body) ha' e automatic ) ,tQrage duratio ,I, block scope, and no linkage.

I. Variables declared outside an ybloek, at tbe outermost 'level ofa prngram, have static storage duration .file scope, and external linkage.

The following example show" the default properties of the variables i and j ~

»-> s~a,tic s~orage d uIFafi'OII1 Ln t i i - flile S'tiOP e

.____,_ external ~inlkalge

vod.d f (void)


For rnany variablea the defau·lt storage duration ~ scope, and linkage are ll'ti ~= factory. When they Men t, we can alter these p operties by specifying an explicit

- cl t - -. - I

storage crass: au '_ o, ac, 'extern~1 lor r'leg:l.S,t'e.r'.

The a.ut.o storage 'ClaSS is legal only fur variables that belong to, a block. An auto variable has automatic storage duration (not surprisingly) block scope, ,IJ1d 'ItO linkage. The eut o storage class is, almost never specified explicitly .. since it's the default for variables declared inside a block,

The s,tatilc Storaee ' •• 1'

The Istiiti,c' .' orage ela I can be' used. with all variable , regardles

thev're d I' fared but 11 ha a different errect on a varis III declan d ._'U 11-

than it do's on a variable declar d inside a --, lock, b" D u cd our ltfe a 'I, " >"'1 t11_ word specifies thr t a ariable bas internal link, J • ' hen used inside a -.e lock s ta ti c hange ~ the' ariabJ '" storae dun ion fr un ante mati I _ tc , tatl " The following figure shows th effect of declaring i and j t be a at.Lc:

.:»: sta ti c storage du,ratl,on s a tic int i; tile scope

--.... __ l"t.'rn8,11 n'nkag:e

~ static stora,ge' IduraUoln

st.a tic int j;l block scope no linkage


-, n user m a d Iaration outsid a bl _" ~ s, a.tic _" nti.,-~: hide: a variable within the file in which it's declared: I nil' functi -lJI)" 'that appear Lim the same file can . j the variable, In th "ollov.Jin,g example, the function f1,aD f2 both have acces'· to i bur tun tions in other file don't: Lc int i;

void f1 (void)
/'*' has to' ~ ./
.a,cC'sse 1.
void f2 (void)
1* h_SlS tQ • I
accl9S8 ~
~ ,~

I formaJllon hld!In.; ,., ',9.2 InQ~

A s,tatic' th' 1 3D]IC 5 orL~ge, lo a-

tinn throughout program execution. UnH ke · utomatic vatlables, which lose their alu ' I aeh time the (lr! gram le . es the DIC!' in b1 c, I sta.tic ~ ~ ble ill] retain it value indefinitely, stat'ie' 'Variable. have some int re ting properti ~". :

• s - at j c . ~ riahle In a hl~I"C, L initialized onl . nco " prior I pr,o rn e te "u-

tion .. An au to variable is initialized ev ~ ry time it com s into existen e (pro .. ;-~. ided of COUll ,e, ha i ha an initializer).

!. Each time a function is called recursively it ge ", a new set 0 -, auto variables If it ha . a at e.t i.c variabl .. OIn the other hand th:' u ,- ariable i shar d by all calls of the fu notion.

• Jb, uzh ,8 fnnc ~. I ould t tUTD ~ p -ell rr __ r to ' II aut.o variable, ih fl,

n thin: wren 'with it r turninga pointer 'fI, I stati,e' ariable,

D eel tng (Ole' of W'·· .- ariables to, b : st,a.t Lc allows a tunen mati :-1 b l~· e'_D call - in __ c'hl._ e . - 3li ~ I lb~ t tlu rest of the I

01 - ften, hwe -r, WI ' Il L1J" static ILl rnase p .'

slder th .' fo lOiwin,g unction;

return hex_ch, [digit.] ;


m· the digit- to hex char fun. li-n (' called

. - ~ -

r012,345167,B9AB(~]]EF -~-UI e c'opi' d inti the hex char s a

~ -OW~, let ., mak the array s

char ,dig'.it_tc~b,eX_lchar tint cligit)

{ -

stati,e const; char hex chaz-s [16] ~ n0123456'78,9ABCDEFII;

- -

.re'turn bex~cbars [digi't] ,-

I ~,~ _., '. t 1"1 ;i! '~bI'" .

. Joel: SL,a :LIC ~m, __ , '_ _ ali,

d, I git_to~hex~lcha:r~


e e impro ed be -P" ed '

QUIte fi] I,' to share the t JDle -, riahle . o exte~l~' 'WI .n t evot mu. h

" ecti n j '.,2 ICOI p, ice tl it here.F _c,aU tho :l the [- '-,cl"ti 'n

extern Lnt; i;

info pi]', i· .-1 Lnt; ,aria-I. _, . u doe n l I.", use i- .1 ,_0 _' I'te memory for i. In. terminology this eclarati n i· not, lieJ;',,-ili n of L: it ruer ]y , ~ (:, rnpiler t' I 1 .' n d aeees to va iabl that's defined e] ewhere

. perhaps 1_' r in he .. ' '-II' r-~rel i', n=-i notber filet .. ,.~ ari le - I

have m,any declannlons 'io a program - ntsl , . ulld have only one ,{leflnitiol~l,.

Ihere's one exception " be rul th t tn extern de 1 fanion I a . arieble

isn't ' __ def ~; '. D. '-. ext.exn de, I_~ _ ·_~tio lb' initialize i:abl, er' ._ def-

ini rion of tb - variable, For e eample th de claration

i" effecti ely tb s me int i = 0;

This rule prevents multiple extern declara ·'011,' from Inltializing variable ill different w~ays.,

A ;- ariable in an ext'ern d r tion .I, a_I . h t tic' tor ~' dur rti 'fl •. he

l cope of the variabl dep nds 01'- the declar ion '. placement, tb declaration i mid ,3 bl ck, the v[ari,abl ha bl .ck ICOP'~· oth rwise, i bas file e pe:

.i-> statto stora'ge duratiion

ext.e rn int i i IUe scope

..____ " linkage

Determining th linkag of, n ext,ern" .- iahle I, • I bit harder, If the. variable . '" .

declared a earlier in the file (OD tsi de' of an· function definition) th n j'[ has internal linkage. 'Otherwise (the -, rmal case I~ the ~ bl h _. external link, ge,

Using the register'tor~ge class in the deelarati m . f i variahl ask tbe compiler to store '[he vm iable in a register in, t ad of ke -ping it in marin U11. mory like other vari sbles. IA rB,g[i~ ter i~ a storage area 1 car __ l[ in " c mpu T'[, :p[ . Data

on d in a regi ter [ an be accessed am updated fa ·,ter than data stored in ordins --, memory.) Specifying the storage class of ' .. vari ble to ln regi 51 t:,er i IK reque .. ,~ not a ommand. The compil r i ree _0 ~ tore a, register varia ]1 in memory if it choose ~

The register orag cla legal only _ or variable declared in, bln 'k~, , r,egister ariable ha the : arne . to ",' dura ion, _' pe _ and j"-. ' ge .an auto

variable. However, a regi:st1er variable lack.' one properly tha,. an aut-o varlable .has: ~. me regis ters don t ba ad re ses if s ille gal '0 U '0 the & per tor t. take the address 'Of a re,g.i[s,ter 'nri~ ble. Thisrestricti n appli .'. even if the , ompiler has elecn d tOI ore the variable in memory,

regi,st[er is be, t u' ed ~l r . ariable '. . _ are ac'c ~. ed and/or updated . Y •. ,_

quently, For ex . mple the Ioop control variable in a f'Q'r ,. tatement i· [B zood candidate for re:gister treatment:

int sum~array (int ,at [], in n)


r'egis tier int i;' int Bum = 0;

for (i = 0; i < n; i++) Sum += a[i]:

rlsturn sum;


regis,t,er isn" n .';' I . I. PI, pul r am ng I, : 11* ,~-'I!mm r ',I lt once was,

'Ioday's compilers are n1U h m ,_. s ~ phii tic t, d Ul_c· < " '. ly Ie c. mpilers: many II det nnine au omatic ll - which - ariables , . 111 hen fit the me st rom being kept in registers ~ Still. U, ing register •. Ij. 'i, , use ul in I rms Ii ·n th t C I help the compiler optimiz .h .. perf rnu inee ,fa pr gram. In '811i mlar the . rnpil r kno . '

ba ' regis,teryariab~,e can't have it addre taken .. an therefor C,' 't b m : iflcd rhrnu Ib - . poin r, r [n " [, '1 ct the regis,tar kev ,ord i~ Ji' lated '

I 99" r@strict, keyw'Drd,

'un,ction declarati '0' (and definition )., like variable declaration ' m y Include a

-t,lf, ge lass, but the only option -Ie extlern nd Lc, T11e . ord 'extern

at I he ::.1 ginning of ~ unction de I ararl n s '·cifi,e', Ln· _'I the fun' ",10 has external IUFlk1i ige, allowin it to be called -r m other files, IS t.a tic indicate internal link, g ,- linn ins U~"_ '. f the 11m, tion .name ti '11, ~IID hich it s defined. If n 'It I rage ~J," ....• ~ i specifie -~ the fun tion i'" assumed hay I xt mal linki ze,

lon~,' i le '11 follos in function de l rations:


extern int f(int i), ,static: int 'gl(int '); in h (imt i),:

f has Ie'· rernai 'linkage 9 h _.' internal linkag and h I b default) has external link. ,g' 0' '- I~ ~IU ~I jt h I. internal linkage I 9 ell] 1 be called ~ irectl . from nun ,1d - h fii."

in' hi h it' defined. D - lui 1_ g to b a't a tic 1_ " n ~'-I nplet -I-. ore "nil i

frOID, b. ing called in aaoth ·r fil ~ an indir ct caU via a fun tion p jO[I[, i' still po ,' .... slbl .,

DI 1 rin fun til ' " hi - extern i 'Ii ' ' d Iari 6 - :- riabl ~ _0 ' aut; a-it

serves DC) purpos I~'. or tbat reason, [I don 't u . _ ext.ezn in function de I, -atio,,, B,~ war -'1 howe :['1 t -I, l orne pr: r nun rs use extern. 1 'te~ j' _-I, i hich c ,_ tai 11 [, '01'. D" harm.

De laring un tl ns to be s ta t Lc, on theother hi' nd, j - .. ,gRil. us eful, In faer, ]

rec '. nd u in, static ,', 'Ii'D declaring IDly un :i, n thr i ·n'llt intended L be

call . fr m tber file". Til - ben ~l din_) includ

• Easier ';~tli:R,te',na'l e. Declarin - · functi 11 static zu .. r .n ' '_~ that f

_ I

isn't vi" ible outsid ~ the Il 1.1.= in wh ich its de tini tion appears, A result, orne-

. -ne ". dilying ih program lat r i t ' I, that .' hang t, J t affect unctilQ ..... in . tbl l' fi~e ~ (One, I' p'tion: ,,' function in ~In.· rher file that spassed poin '. r [1_ f might be atfe [I. by changes to f~ Fortune Lily that ,itualilon 1

',fl' _ b, ','pot b~, examining .. file in whi "h f i . I. : fin· d'U Im I. the fun, tion th p',ar .1., _ s f must alsc be d ~ Ined til ere.)

• Rdu'ce;d "name space po' _gtiO",iw,' Sin < fuuctiom decle red ,stati.c ha- e

in imal Iinkaae lh eir 11· 01 c' C:al1 b r - U ,,: in . th _ r fil . OJ ~'. the u~h '\ I ~ pr -·bn~·

~'bl' 18,., Prop, rue' 01 ';arinhl " and Paramen 1""

18.,2 Storage Clalsses 4,65

bl wonldn't deliberately reusea iJnction name for iom other purposevit can be hard to a . id in large programs, An excessi- e number f name', with extern, 1 linkage cam resulr in whal I programmers call "ns me ~ pace pollution": names in different fil s accid,entall confli Ling with ea 11. other, U: in ~ static' help pre 'nl this problem,

Functlon parameters hav the same propertie as aut.o - ariebles: automatic storage duration, block .. cope, and no linkage, The '. nlystorag " cla .. ~ that lean be _ pecifte '- or parameter regi 6 t ez,


_ OW' rh t we' e cov red th _ - ari 'U,S, '. 'orage cl ' se I ers surru arize what we know, The followin program ragment : how all possible W31, to include-s-or omit-s- torage cla sses '10 declaration of variables and parameters,

int a;

sxt .. ern int b: stati.c: J..nt: c~

void f (Lnt d , regist,er int e,


auco int g; Lnt; h~ int: i; extl~cn i 'It j; intk.;


Table I :··'i [ bllW· the propertie, of each variable and pararnetei in this e mple,

b, hIe' -I..
C I .ali~' tile' intern.
d aut .111181 i hl k none
e ~Ul tn mati . ~ bl k none
9 ,DUlOmau· blo-k non
b au . omati ' bI! 1 .It none
, UJJlic bJ,. ck
1 non
• stane hi ck t
k ,[tUltomalJi.c l( k none . _ finiu 10'· f b and j .:Hen tho" , . oil n 'pc . ible [00 termlne the Iinkuge . If these .. ,ariahl:, s. In, 01 i( ca· es, the 'J!2rri;,~bl~~ wj U be d find in anolher fHe and 'Nil) ha\ e tern 1 ~il1kttge~

Of 1111 t, 'Or ,_' orage lasses rh mo ,t imp ,rL I_ aee ,st,atic. nd extern"

aut.o b-e '. 110 . ffe r, and modt rn compilers have made re'gister ~. ' , impor ... Ilmt.

., here _,I' ',- ~p~ _'U Ii ers: canst .~ id vOllati,le" C99 has; a hird . pe ',u. ,_,

reSlri,ctea PQ~nter,s"J7_B ifier; restrict, which i 1\J',d - Inl_ 'with iointers. I Sine the use vo.Lat; j-] e is i'- ite to 1"'" -Ievel pro '"'anlDlj~g _' n p - rpcn discu J'D,':' it until. ecti n 2 ~_~ con,s t I,~ l1~,OO, to declar objects that r' semble ' ariable - aut ,arle - - ,- d- - nJ1: a pr - gram may acees - the ViJ lue of ~' cons t objet. but can't change it. F' -- r exampl e, the declaration

const; tnt n = 10 Ii

cr • It I , " a canst 0:11 -, t named n whose v lue i 101. The decl 'ation

cons I int ta-x hx"ack,ets [] == {"1'5,iQl, 2:250; 3'15[)', S2 50,11 7QlOO} ,;

crea es a canst, rra named bracket;e,

eels _., ',_ ~ objle~ , LI be cOins" b~ -' J - -,eral _ ,d' ~nt, g :

• I -I ,a orm of eLI" ntation: it alerts .>on~ reading hi, Pi ogram 0 [',e read only nature ,of the obj ct.

• The et mpiler I, he k ths -, thep 0,1

change the alu 0 _ the obje to,

• en programs are '.ntten - or aia f_ P ~ " _: -'I lications I, mbed ed sys-

tlemf~ in particular - tb_._ c mpiler IC'8B u e the. 'I rd canst l i,~ I-n' if da>-, 'I b'- storec im RO'M 1 read-only - ,',mor· .

. t fi -" glanc it might appl __ I tlll t coriat; ,,' rves the am r I ~ ,~.' the #,dlsf ine:. ireetiv , ,- hich - ,e" -. 'e u e_ in .pr,- io . eh __ pte - to cr _ "_ . nam . '_'or eonstanra There are signi neant differen e- between #def Lne " d cons ' ~ h . ever;

.1 e can use J'ld.lefine "a' "I nam _ nnmericak ch i'-a' ·f-If s

- n ItD_nt cons t ,--"'RO 1- e U c .ed t .. , . eate read-onl bjec ts of any' ty' e in clu in,

~ 1 rays, poin ers structure I,,, and unions;

const. objects ,MI .snbje t to th, · rune c pe rule", a rari bles: constann C"Iated u,ing#defi,ne aren't, In particular 'we cant use #defi'ne to reate s C -,01 ant w1ili~_]tOck ICOP.,

,. The valu ,-I - a cons cob] _. t unlike the valu Oi a macro c'an -. i, we'd in I~ I. -'bu- 8_ F ..

. 1 Unlik macros, conat obj 'C_I- can't be used in constant lexpr·';'ioD,.~or ampl - '. e ·n -t write

conat; in'n :: 10 i int a [n.]j "

1** WRONG '*'**/

c leaal if a ha automatic ,tt"ag dura i -n-11 '~. suld be t '. ated 3: length atrl\y-but 1110t if it has static storage duration .. )

• It . legal" '- pp)y :he '_ ddre: '. II -rat r I & [0 eonat; obj '. , ~n- "'1 h" an address, A macro doesn ~'l have ,3'[) addr ' """

There are no abs lute rule- hal dicta when II U'" "' .def Lne ' n· ,~~ ben I use ooria t.. I recommend using #define or con stants that represent uumbe ~ or characters, That w,s.y you II be abk La U,_:-I the ICODJmnt: ,;; ana . dime ,il'n'" in

s.W'.i I'. tsternents - nd in other p],o_le~ wh _ [' '. constant e XPIi' '. are Jiequired~

'18· .. -:.· .• 14·· I Da-·cla·ra·t-·· 1!I1S-'

I~. J . ,~ __ ., ''':' III"':__'

A declara or consists I an id ntifi r Oh - D1 e . ~ the v riabl r un _,: n b Lng

declared) po ssibly preceded b: the -II .... ymb ,lor - - 11" ec I' []_ r I( ) • By '_ om-

blning .. '! []: and '). we 'han create declarators 'of' mind-numbing I .omplexity ..

Before we II ok at the more c mplican -d declar tor' let" iewth deetar ,~ ...

tors that WIC 've I' een in pres ious chapt -1:51,. In the . implest c 'e,1 declar' tor ls [u 1

• d- .. I ,. t, •• 'b if;' 11 t ~.

an JI enn ier, rtJ: a In t~ . ro _o'wmg exampi ,:

D eclarat rs may also contain the * Il an ():

• A d claran r that begins with '* pr-e ·ent a p. dnter:

'. t l.n


• A de, laran r thai, Jl· " -. ~rb [] represl D' "I an array: int a. [10.] ;

Th brackets may be II, ft .. mpty if the arr ~I parameter L it ha an initial-

izer or if its storage el . - I ext ern:

Since a i defin - d else here 10 the' PflOBfWTI be c mpiler do . n't need to kno- i:_, length h ~- e, I - n the case I a multi irnen i sal am !' only lb." first set

., 'Q brackets can be empty.) C919 provi es wo additlonal options for what goes bet ceo th I braek tsi the d laration f n arr ,. param ,I 'f. 01.0 option i' the keyw rid at,atic'jI tollowed by anexpres Jon that specifie tile arsayminimum length, The ther i til 1'r'. mb t -- hich IC·. II ~ used in '_; function prototyp .-, to indica re a, variabl -I mgth arr,ay ;' rgument, Se 'Ii n'I~- discus e both C99 fe ~ tures,

• . -. declare ~ r thatends with r) repre enn a fun lion:'

int all,s (int i),;

va · d Sl\!-ap I( int a, · n:t ir-b)~.

in .. t fin,d_la"rg'le,at (Lnt. a [] I Lnt; n),~

allo " .parameu 'r nann t '_ b _ omi t, d in a.functic n d claratio _: int abs(int);,

VG'd s,w_ap i( int * ~ Lnt. 11:) i

rot f ~ nd~largBErt (inE [J t in·'t);

'The p'- renthe: ',_ ' 1 'an even be le mpt,: in,t abs () ;

void swap (') ;

int find_- large,st: ()I ;

The d clarati n in the 1'-, '-'m group specify the return typ ofthe aba" swapand finld~l,a,rgeslt functiens bur provide no inform· tkm about their arguments, Leaving. 'he parenth 'L~' empty I"D't the same as putting 01-' word void, bet ween them, which Indicates that ther ~ eno _ rgum ts, The empty par, ntheses style of fun ti_'n declara ion b~ lQf"<, Iy di ppeared, If ' Inferior

o the prototyp ,- vle in Jl" due" '" in C ,-~ .. sine - j,ll 1 esn't the- mpiler to

check wheth r Iuncf - n c~_- -, h- I the right arsuments ~

If-all le Itt tr W"-', as simple --, these I, I I 'gr mming " ould be a snap,

Unf'Etuna_'-ly_, declarato - in actual pr srams Or ten combin '- the - l I . nd () notation s. We ~ e seen examp l.e, ,r", mch combination ~ air . Idy. ~ . kn w tha '

declares an array

. know that

float*'fpl (float) ;

declares a unction that bas a float argum nt and returns a pointer a f Loa t. And in Sec tic n J 7.7 we learned that

void (*pf) (int) f

.. :ecipber'lng Complex D, clarations

o far we ha_ n't had [00 much trouble un, erstanding de .larator ~ Buf . h ' about deelaraton , like 'the on: '. in ih _ ~ Ilowin declaraticn ?

int .. (' *x [10] J (voiel) ;

This _ c h"1I_ tOI I rnbine '*. l l and (}, N" i' ~, nor ob io I'. hether x is a pointer - n anay io ,or ,_ lunction.

F I tun' lely'! the", are t o imple [111"1 tJ1,:-'~ will _H c, us t under nand an declaration, no matter h '''~ '~n, I, luted:

.- iw« "lltul,d~c'lllf";deOr:, I~om th' 1"'11 ?,id'~ out In . 'be',', I, - ,,_' loc r' lb' i I. nti-

'fir that': being declared, and start leclph rin~ th d claration _,;1111 there,

18~4 Dec/artatDrs 46'9·

Wile,,! ,11I,e're' 's Q' choice, alw'Q:J'" }b,,'O,,' [ ] oD'd (') loper'''' ~ If -* precedes the identifier and [] follows it, tbe identifier represents an array .. no:t pointer, Likewise if * precedes the and ') follows, it the ldentifier r-epI",e-sents a function, not a pointer, (Of course, we can ,always use parenthe es to override the normal priority of [] and {) over *,,,)

Let's apply these rules to our simple examples first, In [be declaration

the identifier is ap. Since 'If. precedes ap and I[] follow ' it, we give preference to' [] , so, ap is an array ofpoin,te,~~~. III the declaratien

float *fp(flcat);

the identifier is, fp,. Since • precedes fp an.d() foUows, it, we give preference to ( ) 'I sorp is .fl,tuncti(J'I1 'that returns {ill pointer.

Tbe declaration ( '*p f) (.int) ;'

". " little t ricki .. SCI~ I . -k. ·····f .~ 11,- ·1_....:11" rentb ,. . .. f 'I '.'1' be .. ". ue D' 'p

IS, anttte mckrer; ,IlDcep. H~I enClOS;;U In paren __ .,_.e e, 't, P ~ must .f: a P01.D er, U1,

("kpf) is, followed b:y I( Lnt.) '. 8'0 p"f must point to a function with an int ,Mg.U'menr, The word voi.d represents the return 'ryptt of this function,

As the last example shows, understanding a complex declarator ofteninvolves zigzagging from one '" ide or the identifier U)I the other:

voi,d C~plf) (int) ; -,J


_______ 2

Type 1~J1! p't: ~" po:ln~er 10

2'. flJnc~ 10 n wirth in t. ,ar'gume'f1'l 3.. fllturning voi d

Let 8 use this zigzaggi ng technique to decipher the declaration given earlier:

Lnt; "' {*X [ltQIJ 1 (voi,d) ;

'irst we locate the identifier being declared (x), We see that x is preceded by·' land followed by []; since [] have lRJiority over 'It, we go right (x is an array), Next, we ,go left to find out the type of the elements ill the ,atTI:Y (pointers), Next we go right to find out what kind of data the pointers p10iJIIlO (functions with DO arguments). Finally. we go left to see Wh:E11 each function returns (.a pointer toan Lnt.). Grapbically.bere'r whatthe PlIiOCICSB looks like:

int *' (, * x [ 1 0] ) (vci d) ;


Type of ~ : 1 . II r-ray of

2~ p.o~nte'rs to,

a. rUnd~fm:! w'i~h no ,81flL]Uments 4~ retu rr1li'ng panter to i nt


Ma le,rin,g ,e dec larati Ion , tatU:~i time and practice The only good news is that there late certain tlljld"" that can't be. declared in ,",~ ., Functions can r return arrays:

i.nt f{int) [J;

Functions can't return Functions':

tnt 9 ,( int 1 (in.t _) ,;

in t a [10] (in't):

Ineach case, we can use pointersto getthe desired effect, A function can't return an array, but it em return, a pointert an, aIT~" y. A functicn can n re turn a function, hilt it tan return 13: pointer to 13 func lion .. Array of'functlons aren't allowed, but an array dl,ay COD,[ainpO'tntetJ [01 funcnons, (Section 17.7 has an example of uch an ,arr!ay~J

Us;in'g, Type Deflnltlons to SimpUfy Declarations

Some programmers u e 'type' definitions, [0 belp simplify complex declarations. Consider the declaration of x that we examined earlier in this section:

To make x\-, Itype easier t.O understand, we could use the following series of type dfi ni tions:

tyP1ed'ef int *Ben (void) ;

typ'etlef Fen *Fcn~tr~' typ<e:d'efFcn_p,tr Fc:n_ptr~array [lI.1] ; FcnJ1"tr~array x:~'

If we read these I~ne'! in rever e order, we see 'that x has type Fcny'tr ........ array, a Fen _pt.r_array is an array of Fen ~Itr Va1UICSh, it Fen yt'r k s pointer to type Fc:n, and a Fen is a function that has no arguments and ret urn s a pointier '~O III int value.


or convenience C allows us, to specify initial values for varisble , as we're declar .. ing them. To initialize a - ariable, 'we write the = symbol after Its declarator, then ollow tt_h,a{ with an initia]jll!eI. (DQn'·~ confuse the ~ symbol in II declaration with the assignment OPI rater: 'inillaJizatio'D isn't the arne as assignment.)

WBt\re seen various kinds of initializers in pre ious chapters, The iWtializer for ,8 simple variable is an expression or die same type 1'-1 the' v,ariable':

int i ~ 5 I 2;

1* i is initial~y 2 */

18Lw5 'nit~afizers



If the typies don't march, C co· vert I the initializer using the same rules c', for

a It!I si Inl n"'Ii .D Ih

,- ~l~ .r_.'UJLU . ,iii'

int j :::: S ,.5 i

- he initializer for ,~ pointer variable must be' a, pointer expression IDf the same rype 1.'-, the 'variable or lof 'lYP, va io. *:

The initializer for an attay, structure. Of' union is usually it sene - of values enclosed In braces:

int a[S] :;: {I, 2, 3~ ~ 5}:

I(f_i, In le9g- brace-enclosed ilii\tj_ali~e:rl can bave other forms, thanks to desisnated iai-

'd'eslg~ated i"ltial~lIem ~,s. t. US. 1 j IIi zers,

To complete our eOV'Brage; of declarations, let's take ,I look at some additional rules that govern i n~ti alizers:

An ;i nitializer for a 'faria,b~e with static torage duration mu t be cons ~lJ1t

#d,efine FIRST 1 #defin.e LAStT 10'C

st.atic tnt i : LA8'T ~ FIRST + 1:,


Since LAST and FIRST are macro", be compiler elm COmpUI~C the ~niti;aJ value of i 1(1 Oe-] + 1 ~. 100). If LA;ST and FIRrST bad been, variables, the initializer would be. illegal.

• IT a variahle 'bas automatic stDtl,glC duration, its initializer need [JJO'~ be con .... stant:

in't f lin·t. n)


int last = D - l~


II iii Il


• A brace-enclosed initializer for an array, structure or union must contain only constant expre sions never _ ariables or function calls:

#defin~ N 2

Lnt; p·· .: ,OIWieJrS ii'5J- .;;;;;; {l N N * N N '* N It" N' N.' N *" N * N·l,·

- ,- . Ib I ,I, =,I! '-'" ,_:: . . . ,'. ' "" ., ~ ,', , ' , - . . . <' "

Since N is, ,I constant, the initializer for ,power,s is legal: if N were a variable,! Ul program wouldn' r compile, In C99, this 1i1:estric'doQ applies ooly lfthe VlD"" ,8 ble b as static storage deratio 0,

• The initializer for an automatic structure or union can be another structure lor union:

void 9 (, ,tIUCt pa-,- pa-L-tl)


aJ:ruct part par··t:2' .=, pr,artl ~


The iniei lizer d! es I t h b 3: or '3l" m [ name - _ Jthough t noe need to bean. xpr ssion of the proper Lype'.' r exampl '. part2 I ini ...

tializer could be *p where p Is of typ (If f {p,art~) -

here f i'l w function that r - turn .. par,- r ~

U .' itia 1,:: d "".r. Iii bl

_ n:IDI,I_ auzi e -yarI31,1-.',-·

ln ,- !I, . iUI J ~h - pt -' c ~, Ie ", implied that uuinitialized - r riable have undefined ~,al", ue M 'That' ,n · I . ay true: be inl ial . lu 'a -, .,.- ble dep '_ _ _~ it, duro, .:

cat Loc ItUr1~1 an ~ 17.3

•. Variable, wirh OIi'Utl1Jn(I.I.'i " torag durlltilD have n default ini[~' ~ alue, The initial " f Iu r Ian automatic variable can't be' pr '- i 'lot d and rna be 1_ t. ferent

e~ eh tim tbe : ariable '. ". esint I . j uence.

• Variable '_. ith s ta tc storm , .. duration have the _.~ lue zero hy d, fault Unli ' memory allo rated -y ca'l Lcc. which is simply set to, z rn bit at static variable i -0 I.' Ul' initial" - _ db,'. sed on its ~yp e: integer ariablet are Inltialized '~O

O tl- o~ tin ariable ... lnl ltl I~ t· 0 0 , .............. 1 II! t r _f! - ble . ~ .. ull

~ .' I r·. 'r.u., 11 - ~ _ml - II "" . . '. ,II" auu p. ] n '- _ . I:__n ,3. . e' _: on'lmn a n


. " n man, r l_ I ir's b tter to pr ,- ide initializ .1. far ]11UC' aris bl . rath r'

than rely IOn the fact that they're gUSJ'OJ1b:: - d to be zero, If a program cc sses ,3 . ,m ble tha hasn't been ini ialized explicitl ,"' someone reading til: -1[': am later

.' a.n t I_a iJ 'It min ": '11· I r -, ' variable L __ ',urn, - zer. or . fb e it'

inith Iized ~, an assignmen . [- . ,11,. \. in til pro'grfIm.

C9191 function d __ ar~atilo.D.'. ha - an additi nal option th ,- do SUi t exist in eR9,: th,ey may contain the. keyword inline~ Thi ke word i ,I new breed I declaration

p -- ifi r, du un "Il ]"1 m storage classes It, .. ' 'PI quali 6 rs '-n° typ' 'P . ifier ~ _

und . tand - 'I' l'~ .. '_- Ln.I Lne we U De ~ d 'to - "c" - *. _, . _ aehin _ instru eti ID,/

that l lie gen ate b a C ompik r t . harulle the procer r of calling I. function an l r "turning trorn a func ion .

. ' 'UI rna hine Ie" 1 .. I.~- eral Instructinn may need " b executed tl, prepare

, it th - rall Ut! J il t, - If requir jum l~ to the - r ,'l i 111', ucti m in th function,

and there m .. , b additk '1'1 I in tructi ns - cut by th ,I ~OD it; L ,I' It beaim

to execute, U- the function hs ~ areumen I. ~ they U need '[0 b, copied (be ,3lt e C P.D~ se HI arguments by valine'). Returning from a fune '~OI1 requi - a imlta

ami 'UDt f effort Oil b th th" part of U1e fun' "H' n til [ . ,_: c lled and th on that called it The cumulaiiv work required to call ,0 function and later rerum from it is often re -, ned .o '. "overhead, sin _ it's extr \. ork an rd beyond ' hat the fur lion i '., re _uP'P' "e, t· ac I.' n li b. . lth ugh the 10 erh ado," fun ti n e II '~ ", pli gram -'1_ onl- a tin- ~ moun - it ma d up in ' , rtain imation .su h a when a function I r alled ~ illion or billions ,f ime '" 'who ,0 'ld_r·l ... r pro essor is in u (_ might be' Hle c' . 'e ln an embedded ~,yl-t:e-m), or 'when 8\ pro-

gra, h __ ' Il' '. m _ 'l very .; trict d adlin w, . W ;a real -time sysn In .

In IC89. theonl - ,ll '. tc -lY',id h -,' erh ad . - ,3 funcri nr 1_ c _. i to u' 'e . p - ',aIn-

paramatf3rimd macros 1 . .1 l ri~ a macr _ P unm _.' r~ e m _' r i have 11, in .awb ,_~k_:' th ~ gh. ,3; bettersohmon l" ,I tbj' prehlern: create an inlin' /r1£'DDI,II' .. Th ' ord "inline "sugge as an implementation strate y in which the compiler replace each call of the fun ction by the machine in; ,tru· 'lion 'or the _~UllIC ion. This t hnique a '"id, [he usual . verhead ,_' a fun tin call . lth ugh it I ,_,' caus e " min r increr e In be size of the compil d rog am

Declaring a -fOil. tion t b inline dn l actually f R!_' the eompller [10 biotin ,'I, the function, howevet I merely s'~gge Is that the compiler '. h.,ul'd 'try )1

... ,1.... ..... 11 .. II... '. • , ] h "~':. _J: ......

111lULe ICCU,_I 'c' tn .un Din a" ast . possin p r aps " per I rnung an mnne

.:pan i· n when th '- fun __ ion isc: ]1- d L i he . mpik . i '" j', t, ign re thi sugges-

! ~'D. 111 this re peer _ inl i ne is sir - HaT tc th ~ r'eg 1 s t.ez and rest:ri ct; ke - w'(n~·· 1 which tl~e compiler may ll'· e to improve the perforrnance r ,3 program but ulay 01.0 choose to ignore.

Inline Definitions

inlin,e double average (,double at doubf,e b,)


H, r ' I where thingt ,t a. bit complicated, avexaqe has e .' em . al Iinkage.. other soure _ rule' mu c J],-' lin calls uf average. How ~"r lh defini jon of ave:r'Ia'ge

in r " n ider d to b an external I e miLion I th, complle i" - inlfJ_' dttft,rj

'. I' ,aL f - ring te c U a ~ ,srage.' m WI "ther Il'k will be on id ered ,an D'O,r ..

The '- ar t- n w,ly '1'0 a oid ilii error, IOn- I ~ ptioni: to flL! d lh _' .. ord s t.a tic: r'l he function defini ". n:

static inline



return (a + b) I 2;

average now h internal link . ~! it can called f.r, luther file. Oth r

fil ~ may contain . h i 0' n Id_' ini jnn·. of av'erage., .. hieh mJbh'l b. the 1m, - c,.~ his definition or might b ' different

Tbe other option i' ·to provide an external definition for aVlerage so tl13't calls are permitted £rOO} other - '-'., One way to do thi,- i I 0 write tl: e average func tiona econd time (' , ithout using inline,} ,aDd p'llt thesecond deflnirion in ,3 ' if ... ferent source [tie .. Doing so i- legal, bu it ~- not a gooc i [0 hav two versions of the same function, becaus , we can ~ ,I guarantee 1L111t.'1 they' ~ ~ remaln con ~ istent when the program is modified.

Here's a 'better approach, First we'll pJDr the' lnline definition of ave,rage in a header file (let's ne me if !average .. h):

#ifndef AVERAGE fi

.u d f' ':n,,'1r '1"iIi"::i1!'D 7i,g- '0' 'LI" 1't ~ Ie I ~ 'ne ,~V J:!IJ,"U:'1.-C: h

inlin,e doub~e ave ': ,ag'e (doubl.e a~, doubl,s :0)



#inc,lude lI.aver,ageiih~

Now, any file tb~_t'L need' ,\0 call the avezaqe "Wl'CtiOO may simply includ average .. h"wbi,cil contains 'the inline definition of ,ave,rage. avez'aqe '. C file contains a prototype fOI' aver'age that use the ext.errikeywerd which cau '-_ the definition of a've-rsge included from ave raqe 'I h ~o be treated Il' an external definition in average ~ e.

TIle' H" neral rule in C'919 is that if all top-Jevel declarations of a fu'nctio,n in I particular file includ -' inline but not extern- [bien the efinition of the function in that file Jis inline, ]1' the function i " used anywhere in th,c program (including l'he file that contains its inline d fiuition) then an external definition 0 the function will need to be provided by ome other file, Wb,en the function Is caned" -:e com ... piler m,m), choose to perform an ordinary call (u ,ing thefuncrion's e; t, mal defini .. tion) or perform Inline-expansion (using the function's inline definitionj.There's no w,ay ItOI til] 'which IC--O· Cit he compiler will _ ake so if s crucial that the two definitions b eonsi tent. The teehniqu lha~ we ju t discu -' id (using the aVle'rage ~ h and 6lv'e:r',age .~c filesjguarantee malt the defimlloDs are the-same,

Restrictions Ion Inline :'unctions

Since inline functions, are im-plemented in a w'y tb,of, quite different from onlinary functicns, they'r su ~~Iec[ to difler,el)'" rules - nd restriction -. ',ariabl,-- - 'with stati, storage ," ur,3ti n 01\, a part icular pro Iem lor in H ne flu ncticns W ~tb Ie, t,erna~ link e Consequently C919 imposer the fcllowing re tric,oions on an inline function with external linkage (but not on one with internal linkage):

'b\ are ~IC on [_ ,_ '_·1 ~leD[ .- d itl' ~[ , .0,

, .

(.)I~tateInents) ooDidl~r ed lobe bloc.[2_1 in rC99~ [PHI" 59]


• Tb c:- function rna 0" define I_' m,," -. ,I'· ' __ ble s t a ~ l.C [ari- ,-,1- co

The unctlen m_y not contain r ererences to v ri bles 'with ,int rnal Iinka ,e ..

Su 'b _ fun ition 1"" allowed to de' n, . ariabh that 'L .. -:' th static 81 d conat;


dard, ',' r_ i 3:

dard, In particular, the scheme des ribed e Iier U ing the ave.rage"h and

a,vera,g'le Ii C files) may not work witb these co pllers. Vel:-;,rD1J1 ~31 of IG_'. . ( '.Jot

available the time this book - ~ . ritt n) i . tu - lnllne functions in the . lay d .' [I. -'!'b, d m the ., _., ~ tand -d.

~uD_i'~n· tha are speeified to _ both at.a Le and Ln'lLnc should wor fine [,'~ar ess or tb . r Ion c I n: I. _ hi~ strate !- i legal in - 9 A, W 1]'0 j s the satest bet A statio _inline function c n 'be used within a single file Of' placed HI a hie del' 11 " I~Dd inch], ' _ intn an, IOurl. fit th t n, 1·,'_. '00 call the func-


hie -I -, anotlu ra t bar' Ian Inllne ~- Ilion m n,g mul-'ipl file . bat

works wit older version o' CC ut conflict ' witht~9. Thi I technique in elves putting ,R definition of the function ~D a header tile. specifying th· t th functi 'rn " both extern an:IJ inline r then in .luding tho hei Id r file in 0 . ' . urc . file that

contai ,'~ [ ell of th ., .', .' i' Jon~ ~.. 011, COrp'~,. l~.~, definition-s- .. 1

,extrsrn and inl ine~ plac d in on r. ftb .. I ur -e file ,~' I I'~", plleri unab e tOi inline I he function ~or any reason it will . till 11.-

" final ate 11: . ut GC~: uncti' n ar-e 'inlin d' OIn] y b 11 1 .plii ntiz, Ii 'D i requester . - ia the 0 .··~m--- :1 d-lin I pti0115

to d eus .'. that I··SO first,

The C99 standan states that ti- object represented by a compound lite al has tatie storage dur _ l~ on !,~ 1111 r : comp rood lite ral r . cur . out ide th body -'n-, tlon. O'th, rwise, i ha au I' rna ,.' _ .: _'.ra: dur : "'OD'· """ r sult, th, mem .. _ o· "U-

plied by the object is de lloca ed it h, end o he ~1 ck in hicl the c mp :nd literal appean . Con ··~der the followin function hich returns : po in t structure ~ r ·:a~ .d using a compound literal:

9·1:ruot point



ret~urn '(struct poin't) {x, vl.

s,t,ruct. po i.nt; *~re,ate_poi,nt (i,nt x, in.t y)



This vel' ion of createy,oint suffers from undefined behavior, because it retums a pointer '[.0 an object [bat ha~ I automatic '. torage duration and won't exi t after the function returns.

No,w let's return ~o the question we started with: Why are selection statement and iteration statements considered to be blo "kJ ? Consider tbe rollow:i_De" e ample:

if 'tpolynami.al_s,elec'ted == '1)

coef f ic.ient& - (d,ouble [3])' [l,!, 5, ~ 3 .' 0 ~ 6 ~ O}- ; e,lsH:

cas'ff.icienLB, = <doub~e[3]) [4",5", 1"O~ -3.,S}; value:::::; levaluabe_polynomial (coe:tficients) ,;

This pfograJn fragment apparently behaves In the desired fa, hion (but read Ian) .. cQef~icienlts will point (0 one of two objects created by eempeund literal Ii and tbi object will still .exis,l 1.1. .be time eval.uat;e J)o,lyn'omi,al is called, N O'W consider wb,al b app ens, if we put braces around the "i nner" statemenrs=-the ones controlled bJ' the i ,f ' uare me nt;

t= Example 2. - if st.acement; with braJce"s *1

double *ccefficients, ¥alue;

if (p,olynomial ,sel,ecten == 1) {


c,oe!ff ic:i'Ents, - (doU:bl,~' ~ 3,]) {I, .. 5 f - 3, '" O~, 6" o} ;

} e Lae (

aoeffic.ie11t~ - (dou.ble [3])' { 4 ~ 5" 1. '. 0 " - 3, " 5} ;


va.l ue = eva~ uat,e _po l)rD.o'm±a~ It coe t fi c i.en t 5) r

No:w we're in trouble, Each compound Iiteral cau I.'S, an object to' be created, but that object exisu (H1~y within the block formed by the braces that enclose tbe stutement in which the literal ,appcE. B"Y the time. evaluate:_jplolyn'omia.l ~,~ called 'c.o'efficient,s; p' ints to an object that no longer exists. The result: undefined behav i ofr.

,.1 . , ere unh p . i th ihis state

mer ,i ere unlikel toexpec ~ ,- ,-d- g bTF , ithln an L: su ement wou1d cUll'e und fined, b ha l' I, To a oid be _ r blem I'll y decided til t the inner ita ements would alwa s b: 'C'OD i de red blo k ih' a result.B: am -I '_ i and E,\ am-

pll' I, I" iqu or, alent -, i h, b, " h exhibi in," IlI1 efined bell '1,' i 'r"

sl nlla pre ,1_ rn can . ' - h n a '~.' i' P rnd III 'f_. is th I 'UI 11'011;n

expressi n ,f~. electi n ,tal ~ or ite - ti -I statemen . For this r son each

entire s ,- 11 "Lion t~1.~, 'm - nt land Iteration ' tatement L' . on' litl.: r d to hi' il, block ' .

well in i, lble set of braces surround. the I ntir statement .,1 • or hree bl ,k' . ea -,h s f

bl ~ with au~t'o',nl;a:tjc l'tOI,'", _Jle dura j'OID "II aulD--

'_ ,roundiiJlg hll,ock .:' ,~" t ': r- ~ I ",,'1"1 anabl,~

,-',., 't I~ ge for a variable-l ng h a ~a~ isn't ~]1 IC· ted t t '[11 eginnin r - til _ surrounding block b cause ~b'e I r 1t of the arra i n't yet kJ]owl1~ In read it' ". alto ....

cat _ d hen th d, Iarati n 'he _ r~ L-:, I 'ached durin I - 11.

bl I ~ In this respe t varii [-I"~D rth arra ' ,1m th _ r . II rrn l'I"le

A:' ,"OP i,' f r the > -' ~- It of fil, link' ,0


t,', name' wit in' i sible t the link r,

" ariable 1 ,I,

int i ,.

L, t' s rune thar Lb e definiti n of i jj" QU't ide I ny funct] on so i h. 0" bv d "fault In alb, 'f f1J~. here' .' a fun tion f that 11 ,,', to ' od f d Iares i a ext.e.rn:


1 .. !o

void, f (vo.i.dl


ex'tern int i,:


In th ~ first fil - i ha file cope. --ithin Ie h w., er i ha bl ck 'CIP' I. • to 'her fun, t]IU: be ide, f need u, ces '. t ' i,~, I' rI,ey ]J need to d ilare il separat ~y. (Or ',- e


~ ... :


can simply move the deci9lra'li.on of i outside f so '[hal i has file se pe.) What' confusing about this en' -ne business is thllt each declaration ,or definitic '0 of i establishes a different scope: sometimes ifs file scope." land sometimes it's block scope,

Why ,can't ,can.,'t loh!jec'It!, 'be: RSed in 'COI.nstant lexpresmoo:s,':' COD,st. means

U ' , "- ,. b- , q [-C , 4-6' 6'-]

- \plft'n!li!"iquf., "n-D - t r P'I . .f.;, I

't!...U1l1II~lllg_.J" ~.'~I_ I - 'II =-"!!i' _'

In C, cons t mear " "rea ~,-I', ,n]y~, '" not ~'~'cornslmt,,~tLeft, look at a few examples th,at illustrate wby CO',IlSt obiects can't be used in 00-11 tant expressions,

'To stan with, a. const; Q,bj'8C't mi,gblt only be 'CO''Dstan[ during, it 'ifetf'ml,e'~ not throughout the execution of' the program, Suppose tb,llt 8·ICiC;;:U1St object i' , declared inside a function:

v,o,id f (;in1:n)


conat; int. m - n I 2:;:

When f is called, m will be initialized to tbe value of n I 2., The' val ne ef m wi II then remain C'OD,SUtn't until f returns, When f j,!11 calledthe next time, m' w]]] ~i_kely be given 13 different value" That's wbere tbe problem arises, S'UpPQI~e lbal m ~'ppeu in a ,swi t1c.h statement;

void f (in'c, n)


CODst int m = n I 21


awi'tch (,n.') {

I * 'K '. WROl'JG ;JiJ' * *' 1


The value of m won't be known until f is called which violates, ells role 'that the values of case labels must b . constant expressions.

Next, let's look ait cons t objects declared outside bloc' rs. These objecn have 'external linkage and can be shared ,anIonS file . If C allowed rhe use of conat; ohdects. in constant ex _ificssioDS" we could easily find ourselves in the following shnation:

ext:e:;rn conat, ,in-t n;

I ~ ,tr] / .... w * lilTBOll.Tn *' '** /'

:t.n ~ a ~ n; . . '~,(A.. ol'14 \3

n 'is probably defined in an.otbler file, making it impossible for the compiler to determine a.'s, length. (I'm assuming that a is an external variable i so it can't be a variable-length array.)

H that' DOt enoughto convince you consider thi I: If (. cons"t object 1:8 also volatile type'QM_itie-r :.aitS declared Ito be vo'l at i Le itsvalu may change at an· time during execution, Here's M example [rom the Cstandard:

The real~time_· ,C!lc,ck 'variable may not be changed by the program (because lt's declared can,e'r.)., yel its value may Change via so/me other mechanism (because it' I declared vo'Lati.Le),


'.A. ,0


Declarations are intended to mlmic us e. A pointer declararor has the "~urm *p~ wh ich matches 'Ell w,ay the indirection operator 'win later be applied '[01 Pi .. An array declarator 'hi', the form a [, . ,,] " whlcb matches 'the way the array will later be sub .. scripted, A function declarator has the form f I( .,.".) " wbiicb matche 5, the syntax 0-1 a, function call, Tim reasoning extends 'to "eve-n the most complicated declarator '. Consider tile f i 1 e cmd ,array of Section 1 7.~ 7 '! whose elem nts are poi nters to functions. TIle declarator for f i 1 e' c'lnd has the form

and a call of ODe of the' functions bas the form ( .. file_,omd en] ) () ,i

1,,, For each of ~he foHow ~"ng declarations, ioond-ry mhe ' ILQrage class, type qualtH:~I\~,~ type specifj,lers deelarators, and in'itlaUZBr1 ' ..

(a) srtrtatie char' ·!4k~ockup (in'~ level); (b)vclartlrle u:nsigrne(\ l'Dn'9' ~o~fl,a,gs;

(~) -Bx'terrn chaz .ftle~na,m€ [NAX_FILESJ ~ _plath~]; (d) atati"c CO.l'1S't eharl:oken~buf [] = ~ II ;

Sacti'cln 1 :8~2

2.. An,sw'tr each IOf the foU.o'win,g q[oesfons, 'with aut.o, e,xtern,regislter,~ andJor ,s,"ta t i.IC"

(a)W]lich s,~or,m,ge elass j used primMily toindj'liilf~e lha.l ,3 variable Dr funetkm Cart be shared b~ several rue~'"

(b) Suppose ~'U a variablex is to be shared b,Y several functions in lone 'n~e bu~; bldd~n 'rom runEriml'~' till, other Illes. Which 1iltorag~ class ~hOIUJdx be declared to bav,e?'

(c) Wl'liel1 st'OrQg;e classes canaffect the s,torage duration ofa vm;itbl,e?'

3. List the storage duratien (slath= or automatic), scope [block or file), and Ilink_age [internal, external. or none) of each varrable ,3o.d parameter in the foUowing file:


C'L,. t '18""

Ifl',ap,'B,' ,,-'

ext'ernfl.oat at;

ved d f (regi2,ster double b,)'


t ,I 1_ t

6' B'['_JLC l:n'l - c;

aut.o ebaz' d,;

LeL f "be the roHo.~rjn.,g [unction., Wh~_IL "till b the value of f flO) if f has never been Icalled befere? Wba[will be the 'vaJu!e of f I( 10) if f his been called-five times, previuusly?

i1r1t f (int. i)


static tnt j = 0;

ret,urn i




5" State wberJller leach of the foUowing statements hi, true or false, lu~tir}1 each :an" wet. (a) Eve:ry variable with static 8lor,~Ige' duration has file Sl':'OP· •.•

(b) Every variable declared m_side' a functiun b,2l. :mo, linkage.

(I~) Every variable with internal hnkmF has static !!ilOfage duration, (elll Every bai block cepe,

6 The foUowlll.g function is supposed to print ,;m errol" Illess:a!e.a.cb message is. Pi recede tU b)1 tun integer, ind]c'ILlng the number Itlf limes 1111. funcrion has been called. Unfortunately, the function aJwa;y~ d· splays 1 a's the 'number 'of the error rnes age, ocate the errorand sb,uw how to fix it without making an.l' changes outside the function.

void print err'or (conat; char' *mf!sst!'ge)

,( ~

int n ~ 1;

printf I( ~~'Error %,d:: '"s\nlli I n+-+" 'mes,Bage);


IS' ",.,."' " - 1-1 B'" 3"" ,eCdDln I I. '~(.

7. Suppo e 'that we declare x to be ,I C:OQ;s't· object. \Vlli,cl:i one of' the following j'tltements ubeut x is folse?

,ajt ~.r x is of type int in can be used as the value of ,0 ease label. in a ,~i:rwi Lc'htnlement~ (b) The eompiter will check tJurl no as 19nment i s Dude ~IO x.

(c )1 X is ' ubject to the saute scope rule as variables,

(d) :x can be of any 'typ'c ..

III .8L W~rite a complete$,c:ripLioll 'of the lype of x L~ ~pecifi,ed, by leach of the follo'J.1In,g declaranons,

(a) char 1(, *x [1.0] ) (int j ; (b) Lnt; ( .x (int)1 , [.5J ,;

(c) float it ( - x (void) ) (int) ;

(cn vod d 1(, "-x, (,in.'t~, void I( .y) (.i.nt) ,)i ) (int) ;

.," ] o. W[i~e declarations ferthe ~ono~rjjng variables und functions:

(a) p is a pointer UJ .a function with a character peinter argument thai rerern ' a character pointer,

(b) f is a function with two arg-uments: P" a pointer '~O a structure witb t3\g t'l and n, a long integer, f returns a poi nter tOI a functiO'flJ that h21S no I1'gllJmeltl'[s and returns nothing,

(c) a is Wll array of four pointers to funetions tha! have nn arguments and return nothing, The elements O'f il, iru lial~y point to func ioo .. named ins er-t.~, 8 earah. qpdlErte" and prilnt,,"

(d) b i 2 ,an a.rr,IY of ~ 0 poi nters to funeti 011!! wj,~tij two' in 1: BLIt':!umcnts Uutl rerum structu res w[tb tagt;

11. 10 Section 18,.4, we saw that the following declarations are illegal:

int f (int) [] ; intg (in1t)' (int,), ;' int. a [10] I( Lnt.) ;

I*' fun.f::t:i,ons can 'It re'turn arrayis "'"/ t= fuo'c'tio,ns can I t .ret'uIn functicnlB * I 1* arr;.a,y element!J c,anil t; be Iun,ctiofiS * I

We can, however, achieve similar effects by using -pointers:: a function cam return a ,poinurf' to the first element io an array, a function can return ill p(li'~llft'r to a function. and the elements of an army can be pointers e» fW1CtiOIlS. Revl se leach of these d,ecll.tTal~frn5, accordingly,

* 12~", "a) 'Wrire 3, complete description of the type of tile limclion t:" assuming that j'l "s declared as follows:

in't r *t (fl'o,at '~,) (long), char *)) (double) ; (bj Give an example showing how f would be called,

e L3.WmGh.of (be foU,(liwj-n,g declarations are legal' (Assume, thai PI is a. maero mal I,epr'C-senl 3.14159.)

(a) ch,ar c (b) ata t.i.c (el doub'l.e (d) double

- 1;.5'"

,_, IV .,

int i =5~, j - d = :2 * PI; ,angles I[] = r: e

~, ~ ,.

1.. ~ 1;,

PI I 2Jf PI, 3

. PI I :2);

14. Wmch kind of variables cannot be initialized? (3) Array variables,

(b) Enumeration variables (e) Structure variables

(dl Union variables

(e ) None of the above

!'" l5.W11~"ch property of ,I variable determines whether or ",IDt it basi a default Initlal VW,'11U~"'! (a) Storage dw"ation

(b) Scop{j

(Ie) Linkage

(d) Type

Sign up to vote on this title
UsefulNot useful