You are on page 1of 20

Ons' dOB,S not learn co'm;puting by ,using a hand t!alsuJal,riol, but one can' forgfJlt H'rlth'm,sHc'.

One of C (I distinguishing char'. eteri tiles i, it empha i, . ),Il] 1.'Kp' ,e i "1;- ormul that shos 11' to compute 1_ v Ju --- rath er than . ,.' tem ':nt ~ 'TI_,_ -simples t e'_ presI j. ns are variabl es and 0- I tant - " " variable repre ,en' ./' I" Iue to be iomput d ,1'1 th .progn m rU11~ ': con tara represent value that don't chang ~ More complic tied expre sions apply operators to operand , i(whi b at -, themselves expres ,io;ns). 10 the exprle . ion a + (b ;t' c) .' the + operator ~ ", applied to th oper·. nds a and

(b * C)I -, both IOf which are e:, pre rsl ns in the ir wn right.

"P_ r til, ar . the ba i,c '~ , ,I 'l ~I r building . X,-: _ e sion and t h· an unnsualf

rich cc Ile ,ion 0 _ them, 1i start o " I flT vid 7'. 'the rudim en ary I' "pe~ rtor that ali'

found in most programming langunge :

: rithmetic operator I~ ineludin - nl' diti n, su tr~ ti ]1- rnultipiit IIi en and divi-

.,

. lOla

• Relational opera or

1., L gi,I' a] IP· r, '[ If than II 0.:"

-C . 1.1 [i! II I 0'

to - en orm compans ··0· U,·,' .~ l g rearer ,~'ll/n I.,.,

build om ~U .'b as " i .. greaterthan 0 rand i i )1"

Brut I' - doe n ,'1. P hen · it goc; r I, ,n topr . idl dozen' 0 - I· th -~r operator "i Ther I '~'f . so many operators in f et that we'Il need to introdu I. them gradually over the fir: t twenty cna ter of this book. MJa~·b~ting '0 many op raters can he a chor - bm it'··. essenti 1- I to b ecomiag profi,. -j,cnl . 1 '_I.

In thi chapter, ve U c ver some 0' I', s most fnndamental ~f',aJjr,:th' arithme °IC I - _rat, [' 'Se tion .. 1 - thl ' , . 'ignm n'L pr~ rnr .... ection 4.21 and the

increment and decremen 0' ra'IOI" ·-,e' ion 4,,3).~ Section ·-.1 'p~ail '. ope[ - tar PJl:1 edence and a .. ' ,o,t]otrvit_ ~ . lid hare important F r expo ssl ,'[(. that contain more than D . operator, .~ . ection '. describe ... how Ie cx'pre ssion .. - ,are eval Uf led. Finall , ,: eetion .5 introduce the express in '; _ ement, . n unusual f~ amr thai allows an ex pre. sian to '"er- e us I t statemenr.

53

The a~'--,_ OJm tic' tJP~ratfJl~ -----0' - erato '. that perform addition subtractioncmultiplic non and ,di- -ii Iil-,' ethe . -'rkh, if .. _ 0 "laD)' _ rogrurnmin ' 1-, l'gU~I', ~ in lud-

. C 111:' hi 4] h ·c· ~ ~ hmeri .

Ill1g .' . ~ la' e _c ~ . S,OW I, - ,e, ar]~'~,D}eU_' operaton .

/

-t rem a II nde

.

.... 'Unary nnn

+ addition subtraction

The additiv and multipli u rive op rater 31'"1_ aid l be bin"", because th :' lie, uir __ - _ ,0 operand .,' _-_ II tI _ r ' operat .. I r - quir ' Oll_ op r,:_ n, :

; 1 1* us'ed op1er,ator ",/
lL "'i 'I + a~ B unary'
- ,
I I /* use,d op1erato,r *l
J - -~ ,. as a unary
, _ h unary + 0 " _ r uor does [1: thing: in ',. c _ i didn t CV,-D exi t in C, I t' : us ed

primaril - emphasize thar a numeric ionstant i· po itive,

'Ihe binary. peraters f "ly l I k familis . The 1 nlv one tha mi :_~I[ nc - i, , % tll rem· lnder opel, tor, The alae f i D j i the remaind 'r when i is di - id '- b j. - or c-' ample, the alue of 1. 0 % 3 L 1 , 'In the: value 0'- 12 % 4: i -, O.

l1li: Ih binary .·per:_,-,·; in T ble ,4~ I ~\ irh the e . " ~ ·00 ,-J %---=110-' I ither inn ..

ger or floating-point eper nds with mixing allowed," hen int and f Loat, o er ... anc ~. mixed lb, r ault has type flcal • 'Ihus 9 + 2 .. Sf has the I lne J I,,·. and 6 .. 7£ I 2 h '., the va1u~" 3,.·'5~

The I and t op _ raton require pecial care:

• Th I operate can nreduce surprising r esu ] is. When: both of its op _- rand are

inter' ,1 ( I'" /1 perar r vtrunc es" th r c ult 'b_ dropping the 1-:, in, pan,

Thus th value of 1 l 2 i 0 not 1 .,5.

• Tbe,~ operator require I imegeroperend ,; if either op rand i"" not ;aJl inteser th program w· n!lr. unpile.

• U ,1nS 7_'_T a the right op rand t feither I or ,% I_ use undefin d beh . i 'r ..

I. Dese "bm6 the re mlt WhiCH 1 and '% ar usee ,ei'tb.n nve op rands is . icky.

The C'89 ·'-·[8_ idard , t e ~ that if ithe r o ierartd i· negative." lb· ' I ::;. LdL . 'f Ci._ ,,_ ivi ...

sin can b mUD - ed _ ith r up -, ~ 'Fr e ~ am - ~ -- th, ' - - 9' I ?'

could b e either "-. 0 -~, I .. If i or jI is Deg riv " the sign .f i %: jl " C89 depend on the impl mentation. " _f example, tile value. _ '"" 9 % 7' could be either -2r It In C' :!In lhe other hind e result f a divisioni .alway

trunc: t d t ward zero (··0 -- '9 I 7 ha . alu -I and the valu of i t ,j h~ '.,

the 'sam . . ign a', i 11 nee t:h. alue c - - 9 .%- ? j ~'~I"

The term tmpl/emenra'tiDln-cletlned will II arise often lenoug'lh that ifs worth taking a moment to d~s'cuss it. The C standard deillibera.te~y leaves parts, lof tt"U3 II [a1nll!;J'u[age' unspecifie,d., w'ith the undlers,tand~ng that an '~lmp~emeJ1tation th,e :s,oftwiare n[e:e,died to Ic,olmpille" link, and execute prolgrams, on a particular p~!a,tfo'rm.-UI fin iln the details. As a result, the behavior ot the proglr'am rnay Ivary somewhat from one implementatlon to another, The behavior c,f the I and % operators fair Inegatiive, operaods in IC[B9 i[s an 'e'xa.mlplte off' ilmp:llementation-de1firnlsd behavler.

L[B'3vjng parts of the Ilanguage unspeclfied may seem add or e~en ,d!anlger[D'us, IblUlt lit Irs[flects CJls Iphillo[sophy~ [One olf the' II,anguag,e.,s, IQlo,als is eflicile[nlc'~, whlc:h o[ften means mI8,!lching the way'that hardware behaves, Some CPUs yile~,d -1 wlhen -9 ls d~vi,d,ed 'by 7 whUe lothers produoe -2: the CB9 standard si'mplly fl· . fleets this 'faet [of liife_

~t~s best to avoidr 'wri inlg proglr,B,lms; that depend o'n ilmp,i'sml,enta,tion-defiinedl b[Bha~iilolrr. lit that's not lP[o[sslib:lle,~ at ~east [check the manual car,e[funy-the C standard reqelres that ~mpI9,men'~a'tion-d'efined be avlor be documented.

Op

Wben an expres: ion contain: mre than me operator, its interpre tion ma no' b .

'tJll. ........... - .. ' di ely c] '~I ~ For examplr d ... i + j * k mean ad. i and j - then multiply 'the result by k-~'r does rt mean II multiply j and k then add L"? One solution to Ibis proble m i to add paren heses i ing either (i + j,) -It k or i + (j * k) i ~

' __ gem ral ruh , C allows the U',-'· o Pi I .enthe II ': '_[ r grot rin in all, xpre : ·OIl, ..

"What . ~ we d- n't u e parenthes .... , thouzh? WiU the compiler in' erpret i ' j '.' k .... (i of jl) * k or i + (j '* k) 't ~ j, many other language C uses IOple[ I,· tor

P' ece e _ ee rules tc resolv this P t enti "1 ambiguity, The arith neti operat ors b, e the follo ing relative precede DC ':

Ighest: -t, - (. nar .)

/

.,

-mm), .

Opr tor It- t d O[D the a, 'I in ( sue 'hi I (. d iiii) have Ql)~ lerec eden 'e.,

Wh. n tWOI orr more op - ran r a - pear in the am .:_' Ie, ,._ (I :_ ssion .. we can de termi _e

how the compiler wilt int rpre _ the exp ession --y T' peatedly putting parenthese

sround subexpressi ·c ~ ·1 .. tlng _itb high-pr ceo _C'_ lope ators an.- W:,-·I in do" n

_,0 10· -pn , edenc , operator ,. Th followi g' xarn I les illustran h, result:

i + j *k

i.L I

'I!!O~ ~ -]

-L + j / k

is equival .. nt to is ec uivalent tc i '_ [ :_ I ui - II: n 1 to

i + (jl * k) (-i) * (-jll' {+i) + (j / k)

Operator pr nee ule alon aren't e n ughi zhen ,_ exp essi n 1_ - nt ins two

lor more operat rr [t the same Ievel 0 - pro ee,· ~nc .. In this ; itu .ion.the a,jso~iati,Uy

of tl]J~ operators comes into play. An operator is said to be'elt ffs'socia'tive li:fit .gl·oup~ from left to ri,&bL The bi nary arithmetic operators '( 'It Ii / '1 % ~ +'., 3rnd -) ar-e all left asso-

iIi"'~ 'I': ative il':'O ~.'_J - _UIjI'. """,,. o I

, . k . equivalent . ( i • ) k
1. - ]; '!!!!!I lC- [01 ]
" * j I k !' eq ui \lalen t to (1 '* • ) /' k
~ ts ] An operator is rigllt IlI,S(JI,t:'iB_til~;t! if it grou.pl. trom right [0 1 left., The un~try arithmefie operators ( fWd -) are both r~,gh_t associative, .' Q

Precedence and associativity rule I are important in many languages, but especially so in C,. HOWlevler~'C has 0 many operator .. I (almost fifty!:) that few program .. , men bother to memorize the precedence ,Ind I. ssoeiariviry rule'. Instead, they lafl1~ lof aper~bJ~,Si "Appendi~ A con 'uU a table of op erators when in doubt orjust use plenty of parentheses,

For a BU mber 'of YCia\JS" manufacturer of good sold In U .,S. and Canadian stores have PUl a bar code on each product. This cod I !I known as ,3, Universal Product Code (UPC)~ j,dentifie·· both the manufactnrer and the product. Each bar code represent a twelve-digit II!U1Unbe:r which is USIl1lHUy printed underneath tbe bars, For examlplil!, (he foHowing barcode comes from a package of Stouffer's French Bread Pepperoni Pizza":'

5

The digits,

o 13BDO 15173 5

appear underneath the bar code. The first digit identilic- the '[YP'C of item (0 or 7 for most item ~ :2 [or items that must be weighed, 3 for drug I and health ... related merchandise and 5 for ICOUPO:rl_s). The ftr~ t group of DV,e' digits identifies the manu ... faeturer (13800 is 'the code tor Nestle USA'~s, Frozen ~ood Division), 'Tile S,et' nd group of five digits identifies the product (including package '. ize), The final digit is a "cheek digit," whose only purpose 1, to help identify an error in the 'Preceding digits, ~f the upe j. .scannedincorrectly thefirst 11 dlgi probahJ,y \\rOn~l be IC_Ofl- istem with the last digi I~ and the store 9, scann _ r 'wiJ~ reject the entire code,

Here s one method 0-1 computing the eh ck digit;

Add the fir t, third .. fifth" seventh, ninth- anc eleventh digits. Add the second, fourth ~ sixth, eighth, and "tenth digits.

Multip1y th first - urn by and, add it LO the sec nd um.

Subtract I from til L

Compu " Lh'" remainder when the adju ted total '\1' ~ ided by liD., S,U btra, t th r emai nder from 9.

Using the Stouffer's - xample, we g_ to + 3 + 10 ,+ 1 + 1 + 3. = or the first sum and 1 +,8 + '0 + 5 + 7 == 21 fo the I. econd sum, - , ultiplying tb, - -- .t sum b 'and dding the second yields 45,~·cubtr_,cling I givl' ,44" Thr r mainder upon di idina by 110 is 4,~ When til. - remainder is subtracted from '9 th result i 5. Here are a ICOUP] _ of other P in c e yu ant to tr,' your h __ nd at nmputing the h i,bit .. ritchen cabinet for the ans WI_ r i UI I' aU,D' ed):

J. - r, arm Peanu - Butter 1'1 0 .i: 0 515001 24128,

,

Ocean Spray Jellied Cranberr Sauce t-, oz,,):.fJ 31200 01005

?

.,

?

"'

- O,_ answer -, app ar at th ' bottom of the pa.~ e.

Let I ' rite a program th t calcul tie" thl. che '- I -li,_ i ,-' r n -bitrar,Y UP ;;

We'Jl ask the u ,Ir t, I nter the first II digl -, of the UPC"I then we II display he IC"(resp nding check digit. To a oid confusion we 11 ask th user to enter the number in thre , part: the ' insle digit ,at the [ ft, t I first '~r,ollp of fi e eli ii, '_ nd tbe _C~,

ond group , five di 'it m Here .what 1-,_ _',. i n withthe progr rn . ill] ',_, Iil e:

Enter the ir-,t (single) digit: _p

Ent.er first group of five digits: 13800

- nter aeoond grolup 01£ five: digits:: 15173 Ch'E!ck digi t ~ 5

Instead _.~' r adir '0" each digit group 8!" afive-,diQ:it number ., e 'II read it a' f ,., IDlne-dig:t numbs rs, Reading the number as single digiti L more Icon ni nt; also

~- - on' h:a,. _ '_. ." that o'oe 01 th i e-'I~ I~gi't number i too larg "I .. st [r,e in :an

int v riable, I Some oldercompil r~ limitthe maximum ',aiu'.· an int variable to 32,767.) TOI read singk digiti, W _'11 use acanf 'with 'hie %ld c ,nversiolD specific, lion, .. hich match '-- a in - ... digit integer,

! t- ~, Id)

lnma1n \'VQ,1··,'

{

i nt; d, il" i2, i3, i4~, i5" j'l, j2, j3, j,4" j5~ first_sum, second aum, total;

printf (.IIEnter the fir,st (single) digit: III) ,; scanf ( .~ "ld,1II' I &Id);

pzLnt.f (UE,nter first group of five di'gi'ts,·: ml)l; scanf I( n %.1d%ld%ld%l,d%ldU ,f &il" &i2, ,&i3, &i,4, &i5);' p,rintf (IiEnter second groupef five ,digits ~ II);

f (. 'II ~1d't.ldQ Id'O ld'O Ld II ,['- 'I ' 2·· If" i -3 r-_j' ~ 5- )

s, can _. ~·I "0 , ii J . ;ii - _ I f6 I - I «x J , & J ., oc] _'" 'giC t &; J ... ;

,58

'~XP' ''''iiD,S' ,QI,n1nS-

~I" --"f'IU' -.~,.U __ I_:____I

f i r'D sum =: d i 2 + i-= L j 1. - ~ j 3 --11- j 5 i

S'B'CO: d_sum ~ i~ 'i3 i5 + j2 ' j';

total = :3 "* first aura ' sec'oD,d sum;;

~ -

return 0,

}

, th ,t the ex r . ,i n 91 - (( total - 1)1 %, 10) _' uld ha

,SI 9 - (t.ot.a L - 1) % 101" but the ex ~ fparenth es

unden rand,

be ,n 'ri' ten ~"_'_~.<..J!", it '_ : _ r t

One ' the valu

- em I nm ut d, ''11 ften i eed to stor - i' in

r U, 0' ed or h t pur, or ~I' in a. lII.iah,le, C pr idesan s , rtment of

4.2 A· signment Ope,B 'or,

Th'- ,''''-,11" 'e ".,~

in' I .'

_' 1m, ~ lie , ted "

- .

, ' :c D[ ,,' I, _ OIP'" .1'_'"

-j ble or a m -{Ie

, .

p . I Ii ,r u ' I'", In: I

compound [, ignrnent opr f, tl "r .

" 5 .' 1* " 5, *1
a ::::;; ,~' 18 now
, ,I' 1* " II 5, I
]I a .. J 16 ,OIW
- ~
k 10 'IIr' i I /'* k 'I 55 *1
,_ 1:; J • 19 not
, l' -' , - e d D' ,t hav "he" am ype, then 'I_ - ~ alu of e is eon' rted to th ' ty e 'f~}

~ '," th 'a ignm nttake " -l c ::

int i; float f;

• 72,. 9'91£; /* i ~ 72 /.
1 - 1 IS nOlw
f - 1361i' I f' is nOI'w 136 ,i (I 'Ill/ cOH'IIersitm d ,I n 'assignment:. 7.4 " , I' II ' '_ ' urn to I he topm" f It pe ' I" ,r,

I __ ma_n,,' programming ] 10- 8, D.l_ ,i, n ne , 'I. a tr 11'" '" t: in C howe. er,

assignment is an opetutar. just lik ' +~ 10 ' th r wo d the act, ,I _'I i n 11 nt pre-

IU I~ a resul I 'U,' ," adding two numb ns produces ", ">lllilt'hc", alue iQf an

~lUILlIrl_ nt 1 = e is the ·-,alu. of 1 after 'fbi c, ignment, Thu -,., th- alue of i ~

72 ,0, 99f t·_, 7,2 not 7,_ ,91- ) ••

We don't norm,a~iy expec,t operators to mOld~'fy thei'f operands, smee operators ln rnathematlcs don t Writing i + j doesn't Imodify eith,e'f i or j' ," it :simlply computes the rle'sult of addi'F1lgl i and j ~

MOist C lOPS Ira to rs dOln't m[)tdi~Y' thBJlr operands but some do, We say that thase loperators h,aV's ,Bid" 'L,~cts, sine's they' Ida [more than jiust compute a v'a~u,e" Th,B' si,mplle ass:iIQ,nm,elnt QIP'9,ra,tcllr is the, f'j;rs,t operator we\le seen that has sid,e effe,et's'· it modifies its, le,ft loplsr,and Ev,aluatinlg the exp,r'ess,i,on ' = 0 produces the result ,0 ,and-a,is, a s~'de effec't~as,s,i,gns QI to i.,

.' , k 0

~ ~ J - I, = ,":

he ~ - 'p n 't r i' ri 'ht _ i = (j = (k = 0));

'The ' JfI~ , 't i" to ass j , n 01 fir" ,t ' I, ' k, then L' j .and f nal! to i

~ I

.tnt 1;

~loat f;

f = i = 33,,,3f;

In ," n ral, an signment t f th ~ f rm v -= J L Jl .. ed -', h re r avi lue of t p _

w . ld be PI-- mi te d. tbe ,_ llov in', I _ amole tb _' xpressn n j ~ i' pies I, to

j . the' ne w valu, 1:1 j is then add, _ 1, _ roc U _-ing the new V'aID~ I k:

i ,~ 1 ~

k = ·1 + ('j ~ i) ,;

, :r in t f i( mll~ d tid 0 d \ n 'I, 1.- j, ~kJ:

Usina the ,3 ,'~,j'nmn, IOP_''"_'IOI'' tn this fashi 'I] U~U,",n, isn't a good i -,e', For one

thinu !I'I mbedded '_, signments ,r m _k~: IJ :_ am ,11; rd t read, he y _ 1- ""'1.."-'-"'''''-'''

f) I ,ourc~' II "U tle ug', ,r , ' ,,'11:,,- in S cdon .' ,~

ariables :'IOD,Jant' 'I o,r' ,,-~rl-,:i ,-,

'~ er: ' u i - -I ~ '.' ,an I ~ _ (!'

1- s its. l.~ft operand, An lvalue [pronounced ,.~, -valu ,- r present _-In. - ~e r I tored in

computer memory not a constant or the Ie lull of a computation .. Varil,-'~ .. are Ival .. ,

. -... ., " . ,- - - '1- ·10·' -, ~ * .. -. t . .t l; .. - ,.·."'·1 .' ,.', h·-··] I..' [1-, onl .

ue .expressions suc 1 a ,- or ,~. a an nor, rus nomt, v m e are 11 ~ y

I alues that we len I W about: til r kin, .. of I oJUI.~ ill appe ~ in later chapters.

S,iJJ -e til a signmen ': p' at r r quire I ,-- 1- alu re L left perand it .. illegal

to out __ ny th: r kind 10- '~-I_ r s ion Oft th left: ide f n 18:' ignme nt

/*. ' 'WRONG ***/ / .. "'* Wij..ONG **/ /*** WRONG, ***1

I ! 0

1 of J ..;;;-;

Tht compil r '_ill,del~ect errors of this nanu I. and vou' 0 get an _err' r me ssage u .I~ al·, ~ inv llid lval« - in assi .nment.

Comp nmd ··,,-'si,- nment

,'. . ignment that use the . ld val u of a variabh til - -aIu • ar - com-

mon in programs, Th followins ,tatl: m nt, for examp ~e, adds :2 _. I 'the value

stored lJ1 i.:

,-", C'O'IUPOU ~I'd as ,ign el,t oper lOJr~ all, LIS to shorten this statemen and the

lik it Using tne '+-'Iperator~, w "hnpl, rite:

i

I ,~

, same as 1. -=- 1

~ ,ii */'. 6"

- 2· •

- ~'I

The --_ operator adds the value of the right op rand to th variable on the left,

I ]:_' are nin other cornp ound ': ' signm ent op ~·.L 1"-., in -ludin.,~, 1 he foll wing:

etha aliSrg'!lm"nb~,per8lars"'M,~ I WI ~H cover th ... J m uning ccmpound a signrnent op 1": r r in a _' uer ehapter.) All

eompouru " ignrnent op erarors 'work 1m mucb the arne way:

~ += (3' add 1 to , toring the re ult in 1

V - = (1' ubtract . , fr .. m ~;j storing the re sult in l' W:; (:: multiplies - b e . torins the f'e 111l in -

- ~

1 /= e divide ~'b:- e. t rim the result in \

1 %= e .. ·;mputl~· the rem- inder when 1 t '_ lid· d by

Note that I've been c re III mot to slay that , += .. i "equivalent' t, " ~ 1 + e. One' pr,· blem ~ operstor precen nee: i *= j , k isn't th same a .i =, i * j + k. Th,711C are al rare ases in _- hi h 1 += differs fn m l~ = + -b cause i'e'lf _~" _ 3:Id .............. , ..... ect.Simil, - rernar , f appl 0 the ~tb:'r _ mponnd ,~. ssignmenr o

When usingthe eompouod as ianmen peratoe be aref I iot t I· 'i'~h tb tw baracte .. ' that mak,- up tbe . p 3'10:[. S· itching the characters rna vield an expression that .L accep able tal the compiler - 11'£ 111 a doe n't have the i 'tended meaning .. F r exarnpl i1 ',-11 mean 'to rit i +- j but typ d i ~+ j instead t:ihe

program wil still compile. - nfonun Illy, lh, latter I xpression 1', equival 11£ to i ~ (+j' -, which merely copies the value of j into i.

The compound It, signment operator, have the' same' properties as the « opera~O[. In particular, 'tbey~re righ ,._11 sociative. ' '0 the statement

.i += j += k;'

means

i -I- = (j += k');

.. 0 lor 'til" g." COI11J, 011 Q'ell ,11 -, 0'.0 a ' a·,· ble are "incremen lng" (adding 1

and "decrernen ing" (subtracting I). We can of COUf,e- accomplish tJ ese tasks b,Y · riting

• • 1;:
1. ~ 1 -+-
• " 1'~
J ~ J
- , i += 1;'

J. -= .1·'

, 'f

But C allow,", in ircments and decrements to be shor ened even funh '[II 'U"iog the ++ ,[,Ell (i"cr RII'II_,) and ~ ~(del(;'r(lme,n,t) I perator ",.,

,', .t nr t gl~"J]CC\ the increment and decrement operators are sim ~tici,!, it elf ++ ad. '. I to j',!, perand, wherea - - snbtra ts l.. Unfornmarely, thi simplicity i misIeading-r-the increment and deer-eluent operators can be trieky to use, One complication is that ++ and > -- can be used lasp,rejU operators (++i and -,_i for example) fJrposifix' operators (i++ and i -- .... I~ The correctness of a program rnay hinge on pile' I ing th prop, r v, ersio n ~

Another complic dian is, that, like the us, ignment operators, ++ and -- ~ have side effects: they modify the alue 0 - their operands, Evaluating IDe expression ,+,+i (a "pre-increment") yilcldB i + I and=-as a side e ect=-increments i,:

i ~ 1;'

printf ( III i is %d\n m~, ++i ,) ; p,rl_n,tf ( I' i is%,d \n n, i) 1

I ~ pr.int IS II~ i. is' .2 If * I

1* pr')nts ri is 21t *1

valuarlng the expression i4-+ (a "post-increment") produces tl ' re rult L but causes i to e incremented afterwards;

· 1;
1. -
p r Lnt.f (M i " td\nli1 i++) 1* prints -I I ~ 111 *1
loS Ii! mJ_, 1.9
II' ,
pr Lntf I( ~, i _j 'd\nU, i) /' 'prints ~I! • , 2U *1
:lS I! ~ loS
. ,r ,~ The firs,[ pri.n t.f -bO'Wli the original value 'of i, be ore l i' incremenn d. Th e secone printf i hows the new value, A these example illustrate .. +,+i mean

'increment i immediately , 'while i +In,e,af[' "use the ld value of i for nOiw, hut ineremee i Iater, ~ ow much later? The C standard doesn I t specify a prleci~: e time, but i " sa ';e to assume that i will be Incremented be ore the next stateme ~ i exeIC:''U ted,

The ~ - operator bas similar properties:

i = Ii

printf ( ~II i is %d~\n II' I' --1,); prinTt f ( ~~ i La %Id\n II ~ i);

I"~ prints f~ ~ _II OH *1
l.. 1-9
1* pzi.nt.s i'll i • o ~'j */
1S 1., - 1'·, '~ ,

p'l:" in tf ( ~~ i is % d\:n II ~ i - -) i pr.,int,f ( ~ i i,lS td \:0 II ~ i) ,~'

/'* prints III i ~ ~ ~ 'Ill
1 ]',9
1* prints, "i ~ 0 *1
1.tSl Wb,n ++ O]~ - ~ is 'Used more than, once ml, 'lb~ ,S3Dle expression, the result can often b hard to understand, Consider the following sn tement I~

III

l. - 1;

j- 2;

k - 4-'+ i + j T T j'

What are the values DI'· i" jl" and k after these statement are executed? Since i is incremented before its value i~'i used .. but j' ., incremented after t' is usee "1 'lill' la It statement is equivalent to

• " 1;
1- ,_ _]_
It . j
~ 1 + ..
,
jl . 1
- J + ;t,;
II' so the final values IO( i - j, and k are 2. 3,., and 4 respectivel y~ In contra texecuting the statements

• 1.
.1 - ..
I
j 2: ...
~' t
k l j 4-+
;;; 1~"+ +- .
I will give i j, and k 'El16 'ValUIC 2, 3, and, 3, r'cp ctively,

For the record. the po tfix version of ++ . and, - - ba e higher precedence th,~Ul u ml.J} pilus andminus and are left associati- e. I be prefix 'version ". havethe arne ~" recedenee 3' tl.l1atry plus, and rninu and are right associative,

able 4.2 summarize I the operators w' 'v "I-DID far, (, . ppendix A has a similar table 'm_. ows ,all operators.) The first column shows the precedence of each

Ta,b],f' 4.,2 A Pastial Lh~,t of C Operator .

4.,4 Expres'sion E'va/uation 6,3

,_.-
Precedence Name SJ'In,b,Ql(s) Associativity
1 increment (postfix) ++ lefn
decrement (postfix) "'" ....
2 increment (prefix) +,4, right
decrement (prefix) !!!!!!!! !!!!!!!!
lUlazy plus, +
.,
unary IIllIUlI:S
.....
3 multiplicative '* I % ~,eft
4 additive + .~ left
5 "~ligllJnent %= ., b
,I *,= /--- += -- flg·'t
,_ ._ - operator relati e to the other operators in the table (the highest precedence i 1; the lowest is 5'). The last column shows rhe associativity 'of each operator,

Table 4 .. 2 (or its Iarger cousin in Appendix ,) ha a V ariety of uaes. Let' . look at one of these. Suppose that we run aLCf'OSS a complicated expression such as

a ~ b +~ c++ - d + --e I -f

a,' we're reading someone's program, Thi expression would be easier to' understand if there were parentheses to' show how the' expres ion i, constructed from snbexpressions. With the help of Table 4,.2'1 adding parentheses to' an ex pre ssion is, easy: after examming the expressionto find the operator with highest precedencr ~ we pO.I parenthese around the operator and, its, operands indicating that it should be treated as a single operand from that point onwards. We then repeat tile process until the expression is, fully par enth IC sized I,

In our example the op era. tor with highest pre eed ence is, + +" u d he re 18·', a, postfix operator; so we put parenthei es around + + and its operand:

a = b += (c++) - d + --~ / -f

We now spot a prefix - - open tor and a unary minus operator (both prece denee 2) in the expression:

a, ;::: b, += tc'+ + ) - d + (- - e ) I I( - f )

Note that the other minus sign has an. operand tOI its, immediate' left, so it must be a subtractien operator, not a unary minus operator.

Next , we notice the / operator (precedence 3),:

a. ~ b +~ (0+ '=)1 ~ d -+ It ( = ~e) I ( .... f) )

TI~c expression contains two operators with precedence ,4", subtraction and addition, Whenever twa operators with the same precedence are adjacent 'to an

, .' d ",' 've " . tl to, b'·· ,.~ . efu I abc . t .' ' ' .. ~. 't' ,Or· In I." , , , .. '111. -' 'd- . c·.··.'

opelaD , we . e ,go LO. e cnre, 1 aou a.SS,OClat I.V y,. . OlU eX,8Jllp' Jl!e , , an. + ,are

both adjac,en'_ tOI ,d~lo associanvity rules apply, The - and + operators grOIUP from left to right, 8,0 parenthesesgoaround 'the subtraction first, then the addition:

'The only remaining operators are = and +.=:: .. Bluth operators are adjacent to b, SO' , e must folte u sociativily inro account Assignment operator 'gIiOIUPI from right to left. so pareutheses go around the += expression first, then the ~ expression:

(a = (b += (I( (c- ~) - d) ..J.. (( - - e )1 I I( -~f ~ ) ) ) )

The rules of operator precedence and associativity allow us ~[11 break any C expre - sion j nto eubexpressioas=-to determin ' unique lywhcrerChe parenthe: res would go if 'the 'f;XP(OO",/.iOl1 were fully parenthesized. Paradoxically, these rules don't always, a],io'w u~ to determine the value of the exprei . ion, which may depend on the ,', 'rder In which its uhexpressions are evaluated.

,o~rool andand D,opem~e:r~ "'~.1 C doesn't define rh order ill which ubexpression are Ie', aluated (with the'

'c{mdjUona:i operator"" 5J? exception of subex pre ss ions Ln'VoJ vj, n:g "tbe logical a ,,,J., logical or. conditional II and oomma apemlor.'6i.3 comma operators), Thu riO, in the' expression (a + b) 'it (c ,.,. d) we don"'[know whether I( a ~~ b) will be evaluated before (IE: - d) _

Most expression 'tU[VC the same valueregardles of [be order in, which their subexpression '. are evaluated.However .. this may DO't be '~I1U;: when a snbexpression modifie on 'of 'j? operan '~1 'Consider the following example:

a := 51;:'

c ~ (b = a + 2) - (a ~ 1);

The effect of executing lbe second statement ll!i undefined; the C standard doesn't s,ay what will bop-pen" With most compilers, the va1JL]:~ of 'C' will be either 6 or 2,~ If the subexpres ion (b ~ a + 2:) i , evaluated fir J, b, is assigned UJe _ alue 7 and E is assigned 6. But if (a ~ 1)1 j K rev,ttll uated fi rst, his assigned ,3r and c ht assigned 2"

A. ~

Avoid writing expression that access tbe value of a variable andalso f ],odlfy the variable le'~ ewhere in the expression. he expression (b ~ a ~'" 2]1 - (a = 1) accesses me value of a, CUll order to compete a + 2) and also modifies the value of a (by ,:1:S~ igning it 1)11 'some compiler _, may produce a warning message i_ uch ., "ope ration on 'a ~ lU'''> be z:t.fu/'re}i'1e{/"l1 when th,c'y encounter such an expre ,I ion.

To prevent problems if. a good idea tOI avoid [llrng the assignmenteperators 'in subexpressiom ': instead, use a series of separate a signrnents, FO'f example, the statements above could b, i rewritten as

a - .5 .
~.
b ~ at + 2: !!'
"
a" - 1 .'
t
C - b - a .
~ 4- 5-'

, - .1

III, .'

Besi e the assignmenr cpr rator "" th I. nJy operators ta 'modify their operan·d'K are increment and . ecrement, Wb,en using the e opera' ors i be car Ju~ "that your 'expressions dOD t depend Inn 121 particular order if evaluation, ln the following example j may be a '. .ign ',d on '0' ·tw.o . 'ltJues:

i = :2;'

• ~ . .L-l'

J =: -l ~ ,1-++;

f' n rural to a1 ume that j i_ assigned me value 4.. -6.W'f!Vler!! the effect 0 e ecut ... ing the ' .. tatemlent is, undeflned, and j could jus as w'cU . assigne - 61 instead, Here': the scenario: (1) Thesecond operand (tile original vahte 0'- i,) is fetched, thenI I", incremented. (2) Th _ flrst operand ([hI new value of iJ j fetch sd, (3) 'The new land ,0[1' values of ian:" multiplied yie];ding 6,. "Fetching" I, variable means, " 10 retriev th value of the variable rrorn memory, A later ch inge tOI 'lhe variable won - t effect the fetehed value, which is; typically" rored in a special locati 0111

mgisters ')1-18.2 (known as a ,'Igil',t£,-) insidethe C!IU.

U"d~jiJzed Behavior

Ac'co'rdmg to t"11 C ,stcU;'1 rdl statemlent:s such as c = {b = a -+ 2) - I~a = 1) i and! j ~ i * i ++;' cause undefindltj behallior.1 'whlic.h is di[fferfu1t from ~mpllementat'~Dn .. def ned be'hav~Qlr (see Se,ct'i:o n 4111) @ W'hs'n a plrolg'~am ventu res ~ntothe~ Ir,s,aim of undeflined behaviort a,[11 bets a rei 10"1,. 'The' prOIQ'raml m,sy behave diff:er,ent.ly' whe'n compilled witih diifte:re,nt ,compflierft But thatB not he' onlly' thJing 'the,t can happen.The pro .. gram m,ay nat co,mplne In t:he f~rst piace~ If i t ,co,m'p~~e8, ~'t may net run, and if it does run, ~t m:8'y' crash, b'eha'vs erratilca,Uy' or producs :meal'njng~'B'ss results, in other words,r undefined b,eh,a.vior s'h,ould be avo,jded II ike, tlhle p~amue'i'

C has the unu ual rule tl1;PJLt IQ/1) express ion can be 1I1 ed 3' a tarement, Tha is, any expressien=-regardles '. of it~ type 'Or' what it computes can b turned mil) a ,.tatement Ijf appending a semicolon. For example we could turn the' expression ,++i. into a" statement:



+,+1 ;

Whc'u thi I t' tell1_~ ill is executed i i . first incremented, then the new value of i i fetched (as though it we riel to be usee inan enclosing expression) .. However. since ++ i is:n l part of u luger x pre sion it value is discard d and, the next statemeor executed, (TIle' change to ii, permanent, 'of eour _ e .. )

:i"nlc_ its aJUI~- L, discard rl there's li tle point in using au expression as a tarement U nles the expre . sion ha a, 0: ide effect. Let s look at thr e 11;" amples, In

i ~ 1;

In , •. 'LI· '<' cond .... ;;-;,-, ,- ,11 Ith - ..... ,11 e of i :.',:' tch ·'d· b-I- ." -, ·:t - .. ,' d: hl·1ii '!-:-.< I "7 dec ::_.

Ute seeon . example" e vame 0 . IS re .. cr .e-UII. no - use." aowever, 1 ts I. eere

mented afterward I:

In the third example, the 'value of he expression i ~' j - 1 is computed and then discarded:

i rJIi.' j ~ :1;

Since i and j aren't changed, this statement has no effect land therefore serves no

. -

purpoisi. '.

A ~

A slip of the finger can easily create a "do-nothing" expr .. sion statement. FOIf example, instead of entering

riI iiI

1 + J;'

(This kind of error is more common than you might expect, since the = and + charaeters usually occupy the same key.) SIOO)le compilers can detect meanlngless expression statements: you' II get a warning such a "statement with no effect."

Q II~' A

Q'= notlee tll,al C has DO' expenentlatlon ope ,.'tor!! no, can I raise fa DUBl ier to I,

po,wer?1

A,: Raising an integer to a . 'mall. po_ .irti,ve integer plower is be' t done' by repeated multi-

plication (i * .i "i;' iii cubed), To raise 3, number [0 a noninteger power; call the pOW' '~urH;tiol'1f .i:3~,3 po,w fUJ1Ct' on,

Q: I w,ant 10 a.pply tb,e % o'perato,r te 11 'Doating ... point fOP cr'an,d, but my p'ro',gT,BDIJ WQD,. t eompD,e,.Wb13.t can I d.o? [p, 54]

A'·

I!!I

The % operator requires integer operands. Try the frnod function instead,

IQI= Why are th:e ··ulCS, fo,r asfUl.1 'the /,and % o,per'llto'rs, w·ith neg,alive ,ope:r',3.odsl ,. 0' compl'iea'led'? [p, 54]

A,,: The -ul,e. aren't a,: complicated Itt dl:ey may' rst appear. In both C89 and C99~ the goal is tOI ensure that the value of (a I b)' * b + a % b will always be equal to a

(and indeed, both nandsrd guarantee that this it lb. case provided tbat the value

0: a .I b i·· II Pi ntable )1- Th problem is that It en ~ I - ! 0 avs for a I b and

a %' bto satisfy lhi· equality if either a or b is negative .. I" ., se 11 in 'C8·9 where

ither - 9 I 7 h -I and - 9 % 7 i -2 r ~ 9 / 7 i_I and - 91 % 7 i :5~, -1 th fir t cas _ (= 9 I '7) * 7 + .... 9' %. 7 has the alue -1 x 7 + -2 ==: -9 Mid in the second 811 case, (- 91 I '7) * 7 + ..,. 9 %' 7 ha the value ~2 x 1+ 5 ::: -9. By th tim C9'9 rolled ar nodi" m,o~l: P - '. were de ign d to truncate the re ult of divi ,ion to:-·, , rd zero 10 this was writt ~ n int the standard I." tbe only allowable outcome,

Q: l' C has lvalues, does it also ha e ",aI,Des? [PII 59]

A: Ye 'I indeed. A_)] lv-aln, '":, I n xpr . ion that can app a Ion the left I. ide I an a ,i 11t:;1B-

men ~ an rvalue °1 I an expressionthat can appear on. the ,is'ltl.side. Thus, an rVJalu,

could b ariable constant, or In re cornple expression In 'LItis book 11(1 in the .. ,

l' and rd W·· '~ll _. th erm I. ex· -,-' . t· ..... ..1' of !oJ' alue ~I

I·'_~!III_~: I .. , . 1_ _. U· 'I, e... ' . '. pre' !;]on lnl,. _ au u ."._ -'--'.

*QI: <0'0·' id ·tb: t v += e iso't equir alent tn II = " + lei if" has ~~ ... lde e leel!! C,_ n ~-ou

I ;xp,laiD? [p. 60]

A:' Evaluating 1 += e cause 1 .'JOI be evalu ted onl. ID'e _ :;. valuating 1 = 1 + e cans e 'lobe evaluated twice. Any side ffect caused by evaluating . I will occur twice in lb e i. trier c se, In the foll I dng .. " - pl .' i is increme nted onee:

a[i+-'] += 2;

If W ' lise = instead of +=,- here- s what th . statement will look like:

a [i ,]I :: a [i ++ 11 + 2;

. alue I. '_ i is modified UI , w II· '.' U: d elsewhere in the I' atement, 'JO the eff cr of exe uting the statement is undefined, 1_'> likely thar i will be' increment d ', .. ice, but we can t say 'with certainty what will happen,

Q,:, Why does C pr:ovide the ++ and - - opera,tors?1 Are 'tb =.1. 'faster than olth" 'rl \va,Ys of iocr'menting and d ,'. r _ mlenting,1 lor t-, e . are j I,. I ere I OlD . Bient? [pI,.

61]1

A: C inherited ++ ani', .......... from .. .en hompson's . arlier II, Ian -u,ge .. Thomp on appan ntly reated these operators because ~. B compiler could .' ener ite a more compact translation ~or ·++i than for i ;; i 1. ITb e op raters have become a deeply ingrained p . t of C (in fact many of C I mo: I· f. mous idiom rely on them). With modes n com . ill - rs, U' ing + + and ~ ~ won' t make a compiled program any

I m llcr or aster: he orn ~ u d ~." oulari ty 0 these operators stem' rno tly from tbeir brevity and convenience,

Q:, Do ++ and --: I rk : ~]I f~,OIa.t . ariabl~?

A. Ye tb inl rement nod decreme 0' .. p _ rati .. 11 an b " "pitied to, fl.- I· Ing- . oint numW ~ 'ID] a', inte I· I, ~ In practic e I b '·'v'er" it' fairly rar to.in remeru or de - _ lernent I f Loa t,'ari;; bl I.

'~~:'Q:';Y.h.eD I usethe po- ,ti .. ' v'errs,ioD ,of ++ or ~ ~" ,just wh,en b;, tb,e 'incr,eme'o'l,o ',dec, .. l'le'IIH'D't performed? [p" 'fi,2]

,A,: That's am excellent question. U ofortunatcly il', also a difficult one to an' wer, The C standard introduces the concept of ~~'S,C'[!Lu':;(1ICe point" and say that ~'"'lL1pdating the stored value IOf d111e operand shan 1~1CCur between the previous and We next sequence point,' There are various kinds of SeC[U1e:O'Cie points in C: the enid of an expression statement i one example, B,y the end of an ex pte' .ion statement, all incremen I. and decrements within the statement must have been performed; the next statement can't begin Ito execute until this eondition bas been met,

Certain operators that l¥e' llencoun [er~ n Iater chapters (logical and logical or; conditional, and comma) also impose' sequence points, SOl do. function calls: the arguments in a function eall must be' fully evaluated before 'the call tan be performed, if an argument happens to be I~ expression containing a ++ or -~. operator, the increment or decrementmust occur before tile' call can ta~e place,

Q:,Wbs,l do 'you mean, ben you say OJ.:t (he," aJue of' an e':xpl:oe&si,on s,tatement is discarded'? [pll,65]

A,: By definition. an expression represents '3 value. If i ha the valueS, for .exemple, then evaluating .i, -4- I produc,~ the value 6~ Let's tumi + 1 into, a statement by puul ng a , emicolon after it:

i + 1;

Whe'o[hLtatelllen'llS; executed, 'the' value lof i + 1 is computed, Since we have failed to save tliL· value-s-or at least use It in some way-it is 108,[,.

IQ·.' ..

• • - I~

A· '.

'.

Blut wbaf ab,ou't statements like i =, 1 J '7 ~ don 1 see wba'tis, 'beil1g, dis,carde.d ... Don't forget that == is an operator ~~I] C .and produces ,3. value just like any other operator, The a sign mel] t

assigns 1 tin 1.. The value of the entire expression is 1, 'which is discarded, Discard .. ina the expression's value i , no great 10' ,'inee 'the 'reason for 'writing the tate, .. ment in the first placewas to modify i ..

1 . Show '[he output produced by each of the roU~wmg program fragm .1l1'LS" . ssume Ilhllll. j, arid k areLnt; ¥mables.

f~)l i =- 5,; j: =- 3;

p,rin:t'f { J! %'d %d,iI I 1. I j I i % j};'

(b) i .= 2; j ...., J ,;

print f ( II %d'!I~, (i +

(. c) ,~ - 7 '.'''; - 8" '0 '.""".' ,

"'" ..L. - '~oJ -- ,·t A -

p'X" in t f ( II % d 'nil ~ ( i +

10) '1IIi' , )
~ J ,.
I
9;.
10) !I!I k I , )
11 J ~
t E- .,

, XfJ,f:Ci:S'e,S

(d11 i= 1 f ji = '~i k ~ 3 f

pri nt, f ( II %0 II ,i (i,. s ) % ~ j + i~r) I k) ,;

:~J2,. If i and j are posi rive integers, does (= i) I ja1ways nave the sarne value [mrs - f i I]' ) 1 J US~ tify you r &f1Itwe:r.

3., Wlll'e is the value of eaeh of the ToUo,whlg, expressieas in C89? (IOi""e all possible values if atl expression nlay have more than one vatue.)

Ul)' B / 5

(b) - 8 I 5

(c) 8 I =5

(d) ~S I -5

S. Whut is the value of each of the fon'nw~lllg expressions in (~89't! ('Giv.e 1&111 possible values if an expres .,iO(l ,~na~y have me e than one 'vabJ!e;,.)

(~)I 8, %, 5

fb,) .~ 8% 5

( ,,, ... ), IfJ!D, '5

~ I!.t 'ICI ."0 - .. 1

7,1 The ,fLlgor~thnl for computing the UPC check digit ends wi'lJ] the follQwin,1 step~:

Subtract] rTc'm thetotal.

Compute the remainder wben the ,~Justcd tetal is divided by l£t S 1lI, btrect the remainder from ~I.

It's ternptingto try tu' simp]n-y the lrugolidhm by using these steps m$'mead~ Compute the (el)]~l,'mfl,derwben the total is divided lby In.

Subtract the remainder from '10.

Why doesn't this technlque wDrk'

,0 .. o ,

Wou[dbe upc~, e program still work lf 'Ehe lexprlcsSi,iOIl 91 - {('total - 1) % 10) 'were

replaced by (10· - (total ,'" 10'')1 , % 1'0?

81 9. Sb,ow [be oUtput produeed b;y each of the foUowing program fragments". As,sume that L, j. and k are i nt varlatde .

(a) i= 7 i '] ~ '8;

• ~ i! 1

1 ~=: JI + . ;

pr'i.nt.f { ~"' 'd, ~d II ~ i If j) 1

(b) i - J" ---- 'lr.. """ 1 '.

- . - ~ - I'

i +~ j +~ x,;'

prin:tf ( ~m %d %d- 1d II" L, j, k)';

(c \ ,~ - 1-· ]" - ~ '" k =." ,:

, .... , -I.. - f" - ,ilL 'I J'fi. ,:J.

I ! k

1. ""'= J ...... ~- ;

p'rin"tf ('I'~ !ld 'd, %;-d.1i ~ i, j ~c k) r

(d) i _- 2' ;'j = 1_~' k = 0;

-l -1i'- J' *' _ 1 .. '"_ .

..&.. - - l\...t

p,rintf ('i-td %',d %·d," f i I j $ k) ,:

J U~ Show the ou~put pjrodlUtN~db.y eaeh of ~he ~oUow'i ng program fragments". Assume that i and

JI )I, .• hi

] are l.nt vanar L eJ;.,

(a) i = 6; r

II' 'Ii '11

J -:1 +~ ~;

- .. rin t f ,t mil ~d ~'d·'1 ii I i ..

p ... _ _ • 9& _ ~I_,~ •

(b) i ~,- 5;

j ~ ( i ~= ,2, ), + 1; print f I( ~~ ·Sld %,d IT, L,

(c) i = 7 j'

]_, := Ir::::.: + t. l.-~ - ~, 5') .

~ \ -=-- [~.~J'~ i

pz i.nt.f ( ~~ ~,d ~dll, .i ~I

(d) i ""2; :5 =' :B;

j = (1 = 6) + (j = print::f ( II~ %,d %d 1111, L,

J" \ o.

, t I

'*1]. Show' the output produced by each of the foUo'\tving program fragments, A sums :tb,~u L, j, and k ereI n t:vmri,ab~e~,.

(a) i = 1;

printf I( 111'&d ~', i+--+ ~) ;'

plrin'tf ,( III %,d n~, i);

I(L ... ) 1" ::::::: '1, 0';; "il := 5·;i'

IIIJ ,- ,.L,t' ~ - ~'

p'rint:f ( II! ~d ;11, i++ - ++j)1 i

P··.,rin.'t_ f 'f II td ~d" III i. ]i ~ •

'~ .. , if! If' I ,

(c) i := '7; jl = e ,;

printf I( lI'id "HI I i++. -~ = j ); p,rintf ( II %'d ,%d;f II i ,f j l ,;

(.Id·· ,) .;; - ""}.. ]~ ~ 4·· kL' = 5' '.

,;!" _'.;), - ,t .... - ,I"

plri.o,t:f ,( II td II~, i++ ~ j +f + ~ =kJ t pr..intf ( II %d %,d '%-elll~, i i' j ~ k);

l2.. Show the output produced blyeach of the foUowing program fragmems. Assume tb,,,'t i and j' are' Lnt; variables,

(a) i = 5;

j. = ++i. * J. - 2; ~pr,in,tf (1Itd, ·~lrd,lll~ I~ it j) ,i

'.' b--I \. 0\1 -: s··,~

'" I ..Ii., ~ :".,

j ~ 3· - 2· It i-t+;

p·re in t f ( II t d %d ~~,~ i ~ j);

(c) i = '1';

". 3·.... '-, 2

] ::: - .... 1-- .... ,;

p r in t f ( II %: d % d 1W ~ i ~i j)l;

(d) i = 1;'

j '= 3 + -.~ i '. ,2; printf (iI~d 'd'III,~ .i , j);

a 13t IOfl~Y one of the expressions ++i and i ++~s eXlcl1y the same as (i +~ 1) ; whicb h; it?

Josdfy ynur ans,wer, ..

Section .,,,4

i 4. S nppW.Y paren1l1eNI~!\ to &how bo'w' a C compiler would b:uerpl[1ct each ,01 me fellowlng expres .. &iO:OS'i

fa) a. *' b = e ... d .f e
(b) a I h % c / d
(Ie) - a - b +- c -. + tl
(d) a i" - b I .(;! . _. d i'letian 4~,5

15,. Give the values of L and 'j after each 'of the foUo\vil1g expression It_8temel'llt'S has been exe ...

CU,I[ed,,, (Assume t ],tlt i bas, the value m ,wnitial.1)1ID,d j has 'the v,allle2.)

(8) i += j;i

1(b.':'lI.,. •

!'J 1--- ~ ;

(c;) i ,* j ! i;

I(d. I.}. I <IlL jj

1 ~ ++JI,:

l , Wdle ,,3 pro,gram that asks the user Ito enter a two-digil number, tb~u prints nbc Dumber with ~ts, digits reversed. A session ~fi'th the proira.1" should have [be foUowin.g appearance:

En.·tar ,at-wo-digit nun;lber: ~:B The r,eversa.li9: 82

ReadtllJ~ number using %'d,tilen break i[ hno '[\V 0, digits, Hiut: lfn is an lnteger, thenn. % 1(1 i . sthe nul digit inn and n /.10 is n with the la _,( di,gill removed.

e 2. Extend the .pifogrmn in Programming ProJe.cl I to handle l'llre" -dlglt FlU!111belll.

3. Rewrite the prcgramin Programming Project 2 SCI 1[11.31 it prints tne reversal of u three-digit number without using arithmetic' tll [S,pHL the number lmo digUs .. Hin~!~ See be upc . C program of Section 4. J •

4. Write l program 'that reads an hl'te;gJer entered by the user and dis;,pla.~5 i't in octal (base 8,)~ En.'t.er a number h,~twee,n 01 and. 3276'7: 1-953:

In octal ~ your number' is ~ 036ctl'1

The oerput shonld be displayed using five digits.even if" fewer dlgits are sufficient. Hint: To CDO.Vc'rt the nnmb&"f tD 'Ore a1~1 first divide It by tl;, U1,e remainder 'lIS the last digh of the octal number I( L, in this, case), Then ·ruJ.rid,e tlil,e' original number by t;, and repeat the process to arrive 31 the next-to-last digit. (prlntf is capable of d~s,pla~ ing numbers ill base 8~ as we'll see in Chapter 1', FlO thete 's actlud~y an easier way In MtIi1e this program.)

5. R.ewr.he the upc ~ e prow,am of Section .. !~ J '·0 iLhai,[ the' user enters 1 I digit~;811 one time, instead, of entering ione d'igill' ~ then five digits, and then another five d igits,

En't,er tJl;E first 1~ dilgits of a UPCi 0138001.517.3

Check dig'i't: 5

6,. European countries use a 13-digit cede, Imo,wu as .3, European Article Number {EAN)i Instead of the l2 .. di,gn Universal Product Code I(UPI~)1 found in NDrth Americi1~ Each EAN ends "~ilt:b .. riIl check digit jusr as, _ UPC' does. The technique for' c'al'cu~nttDg [he check digit is

_ ~~!~

also _s_uiw.mr:

Add the .second, fourth, sixth, eighth, tenth, and twelfth digits" Add the first~, third, ~if[b., seventh, ninth, ,and eleventh digJ~~s!,. M tlluplJy the flrst sum by 3 and add it to the seeond urn.

7',2 Ch,ap,ter' 4 Express,fro,ns

I ubt l- l 1m th ' total,

I maind 2r V b n the ladjU'- --d ' I i ~ divk ed b 10.

- emalnder from .'

0.- e .ample, I onsider IGuUu, ,g]u Turkish D ii~bt Pislacbio i& Coconut wbic_lb has an E

0,_' ':'69148r4260 0-'" The fir -t sum i" I(} + ] +- '-, + .:: + 10 + 0:; _ 7- and the sec nd ," um i, ,,',' + 9t +

'! +' + 0 = ~'L ullipt in _ 'lb first sum b Ii '_Dd, in, Ib- ec - ,d iel -, .:," I,. Subtr __ ~'l-

ing ]1 ,gi,~s ' L Tlu remainde u -"- di i ", b)'] I_' i_ 1 ~ , btr

1"0 ','~ the f. ul I' ", which matches the ]3' _ di it " th original c de.Your jol i; tl n1U

if the upc .. c 'pro. ram of Section 4.1 ,,0 that it cat: ulate ttl· check digit for an EAN. The userwill emer the 1-,lll~J digitsofthe -, """ as a single number:

En -Ier the firert 12 'd.igits of an &AN'~ 869.148426,000 'Check d.igi',: B

You might also like