HAake no m,is,take ab,Dut it: Computers process numoets-« ned ,sym'b.als-.

Wei measure OUf understa',fl'ding (,s'/1ld ,clarJ,rrol) by the extent to which we aan arithms't/ze ,an ,activity.

,I~·O far W'·· 've used ,'Diy two f", basic (builr-i n 19pe'I': inti nd __ loa t ~ . . '1-

-] .'. 'JCJ_1l BooL which i a ba ic t,' ne in '., ... 1 I.) Thi . pte' deseril I. _. the r~'~ t 0_ til ~ bas i· typ '~" nd iscu " s important L,·'U:_', ab III t pin· neral, I' "e'ctin 7 .. 1 reveals the fuH rang _ of intezer p .. " ~ wtli, b include lone intesers. short int g: rs ~ and unsigned integers, ",,- ti, 11 7,,--' introduce: th~ doub Le d Lonq d'oub'le' types which prov'id_ a lara r range of value and greater pre ision than f l.oat.. S'I,- 'jon 7-3 lei er the char type . hich we .I neec in -rder 0 ork ~ ith char eter data, Sects n 7.4 tackles the th rny topic of CODVe1:lin _.~ value I, f on . typ 0 an

I ui ~111't· alue 01' another, ection 7.5 sh I· h-', I u t.ypedef (I '. efin n w

1_ pe names, _ inally, Section 7.,1 descri es the si aeo iperetor; whi 11 mea IUTe'~ tbe amount of storage required for a typ -

.' I uppn . tWI[]1 func ,arDI ntall: di_ ferent ~ - ds .' cum, ric type. ~ in leg· " -: p.. " nd flouting ~yp, S~, Valu " . I ,~- "1,llee."~II, type" [I . h lie number '. whil - alue or a ... ating type can 113,. a fractional pan a w It The int ger type - in turn, _ re -~ivid'f:d i nto tw ~. :: tegories: '. igned and un 1:E!1}ed.

The ,I,eftmos't bU of a s'lglJ'ed integer (iknown as theslg,n' b't)1 is 0 If 'he number is iposiHv,e lor zero 1 jf it's negatlvle. ThIUS,- 1he' I'argest 116-blit integer nas the b~nary representation

125

0111111111111111

whii'ch hasjhe _ a'llu,e 32,,7'167 (21,5 - 1). The: largest 32~bit integs'r is 01111111111111111111111111111111

'whilch Ihas tine val,ue 2~ '147'11,481311647 (23,1 .~ 1)" An ~nte:!ger with no slj,gn bitt ,(the lettm,OSI! bit 'irs Ic.onstd,e,red pert ot tihsi number's Imagnitude) is said to 'be uns,g~ed. The largs'st' 16~,bi·t unsi:gned 'i:ntegef~r i,81 65~ 53,5, 1(2 6 ..- ") I and the Ilargest 32--b,it uns'ilgned integer js, 4·2!94~ 967,295 (23,2 - 1) ~

By defaulit inl,ei~' v'alriiab~esl are s'i'gned irw G-the le,ffmost Ibn IS, reserved florthe sig,n. To tleU the IcompUer 'tihat a v8!rii,abJel has nOI sign biit.. 'W'B decla're It ic be una . gned. Unsigned numbers are prrima'rny useflull fOlr systelms pre'Q:rs:m'lmi',n,gl and low,·,llevel ,machine ... dlspendent' apJPliUcatio1ns,,, WIB'U discussl typlIcal1 applica ions for unsilgned numbers in ICha·pter 20: until th len 'I wain gfenerBI~y ,Bvo,id thiem.

~II lnte 1 er re~ come in ~ 'Ii nt sizes. The int' '.~ js U ,Uall, .2 bu bu

_ -

maybe '16 . irs QO old r CP'U·. SinDC,OTI1,C prograrr ' require- numbers 'th', are t .1

Ian t i store in i t·, c C _J., .provides I'(J,R. fit ~ zer ~ 'J tir _ .1, con." . (VIe memory by instructing tbe compiler to tor . number in less spa I, th,· D n rmal: IU. _cb it number is called a. j 'DI. lnt . ~ir~,

I

, c n truct an in _-'gle_ typ that 17~-.' tt m ~. I_ In "1 I_.'. ify th t

variable j- 10'9 01:" Ish,or't". s:igned or unsd Ignle d. -c c In even combin .

pe -" lers te.g., long unsigned int I" H-, -I'. ~ I -11l 'h follov in' i~. eon bi-

Dati~OI1, a ~ tually pr duo differ ent t_ pe :

ahozt; int u.nsli'gned ahoxt; int

.i.rrt un:s:igne,d int

lo:n'g int

uns ign,led lo'ng int

Other om binati 'n': atI. . , -r I. 1,1 _ ' f the e .J -' typ ~ _ I : I 'r .... ,amp ~ 10 ~g

s,i'gned Lnt, -', ~I ' b, I. ame as lo'n'g' Lnt., ,~ in. e in lege " I" Ie ,alw,ay: I. isned unle '~'I 0:' rwi specified.) lucidentall- th., ordl~'f of he sp cifier doesn't matt r: unsigned, shczt; int lS the I arne ~ s short unsigne,d Lnt..

I I allow UI. to abbr viare tl e name ,f integer '~e~ by dr p'_ 'n~- the w rd

Lnt., ~~ nr example unsigned short int niay b - abbre- ated un,signe,d short and long Lnt; may be abbre vi- ted to ju long" Omitting int is a

wide pre d pn ctice among Ie arogr -- ~ . I -, and ;' nne r e _Ier· -ba ed l-lngu81' .'

.' including lava) aetualli ·I~'qujr' the ~ ro trammer to wri,'t. short or long rather than aho'rt; int 11- _ ong int,~ _ ,~ r thes rl~, OD' 'U I ften .. , _ t 'h . 'I dint wh ~'n it' not rtricUy neces sary,

[Iabl.!' 7 .. .1 Integer T', . 1]] , n· - ... bn .-achine'

Inte erI p - ··n- 32-bit ,. chin c

Tal1'~' 7,~:' Integer yp. ,,' on '-

bit Machin - . l'h,aCUlJtl' .

.1 the six intege ty~ ~' om

a _ ouple 10 rule ~ ta allc mpif [S standard requin '.,1 that shozt, Lnt , int ,flD1d lOlng int

. -~'T ' cert in mlmmum r-_n" . alu -. " [ee Section ~' ,;2,-or d, tail: ~ Sec-

- tandard requi _:, th _,t int n t be horter If ran short int and long int D,lot be short r than Lnt.. -lowe "e. if'~ possibh lbalt short :i nt renresents 'the ~,-_D'_' ra f value as Lnt.: Ill, ',_ int m I- 11-' the sam __ ze - i Lonq int

. able 7. I . hows tl -, U JU al [angle of' value , for the integer t<Y- ··e··. ons 6·bil machin ,~ non that short i I rt and int h.' .,- ~ id n j ~-:~J ra ,- es.

ahozt; int unsigned ahoz inint

una i.gn'ed int long int

uns Lqned long int

- i,-' 7'-.8

' . .

l, 7.1 It: ~ -~. the 'Dual ra I 'a' id - ntical raJl -C ~

shoo tint

llnsi·gneld. sibert int

in,t

unsi'gne,d in 10' '9 in-

· d 1 "~

uns~gn'~,- ,ong l.D',,",

_D 'C nr y ar . l-bit I Pi " h

ranges for the in 1-, ze 11 ,.' P'

u' ..... ,!.;II"U':&.:II.·JI, e _ 'ore I -.ommoln. 11 ble 7 '" ~I, 64-bit machine I esoeciall UD_-'

..

- 'I~ typical

.) .

ahozt; int una igned shar IE int in'l: unsi'gns'd int long int UDsigne'Q lon.g Lnt;

----------~--------~~--~------------------------~

~ ",_,~47 41~13 .. 6·1'" o ~'-..i.L2,· - ~ 72 0/ ... 1_. _ 77' ,'0,

o

IOn .. ' m . re. 'II. I mi. emph thAI the ran es .... he n in Ts '-1_· 7~ I 7 .. ;"- and 7 ~3

arel] . mandated b,y the I" st , dard and In - - .' ar-·- 'Im I D' compi er to another,

O d i!l ... 1 .. , 0IIi" ul ~ 'I .

1·:'ID,e',·a 0 - I r I ' 1m _' rB_r_l -' t r t 'p- fOI' at partu __ . ~ I ,I ] 'm 1.-' -~_-

~limi B.h~ header;a..23.2 tion "S~, check the <limi tSI,~ h 'a.' er which i. Pl,~ of ,11_ ' d" ,I libr-~ .

. is hes __ ler defiru macro, 11131 represent the ~. r I n es a id 1 '-g:: .. t 'V, lues 0'- ea 'n pe,

C9S}' provides IL 0 additiunul taulfbud inte . r typo " Lonq long in-to and un.sign,edlcng Lonq into Thet lyp,·· \ ere added -~~_U-'II the __ rowim need ti. r - ,.~i lar Integ n and the al ility . f D·W r proce ssot . __ I I UpP'T an hrnetic, Both long long t~. :Pl~~ ar requin d L be at lea .. '9 bit wid· ,,0 th .

f 1 1 ~ t 1 ~ ~ l ~ ..,[ ( . "'17 . - 775 I.' 0 r. I)

aLte '_ ong _ on,g ~n'· '.,'~ .• u, l .. ~ . plla JI_ - ....... ,=,,"'. -~_I .. - '~I ".;' ,;I,';~' ~ ,. ,", .•.. 1

to 2~3 = 1 (9.~.2~3.37" I' ,l) 8;4-775,,'-07 and ranse of Lln.signed .Lonq long~

int slue i, 1'U' II ,'1 I' - 1 I( 1 : .. 446 .. 7 ~ -013 701 ,~,55 ~ 151.

The shor·t int~ illt .. long int .. and long long int types (at ng with signed r:har type' :'7.3 the signed char typ olle called IlIl,Jdtl d,ig.ll',d .int-,' - - 1 'pe', in C -9'" The unsigned shDrt int .. unsigned int una i.qried long Lnt , and l.sign . eh . tYIP'e .7.3 unsigned Loner Loriq int types (along wi h th unsigned char [p and _8aol type .52 1b - _Bool tel ~_r call d ; It I ,,'da '11'11 'i i :':1,_ dint·· r typ .. ~

In addi L1 - n to the standard Integer types, tb C9Y,'E,anaurd allo ' .. impl rment -

ti I -I. ' " d uended inte: _'_' = I __ "rp',e - be h .. j,c n·· d an ,1 unl" .i~n ed, F r e '. ampl

compiler rni .. ght pro' ide - igned and unsi _ ned 12:",-bit integer type '.' ~

Let" urn iur at -111i1OO to can ,(a·fl......_,.,nUlnb rs that r. ppear in lb te-~t I' J I .. pregr,;IIIIl .. Dot Dumber; that ar, read, _- rit en, or compute ~ Ie all w' lot II. c- - I.'onlanl~ 1. ,b '~rwtt n if) decimal .. 'ale Hl), ctal I, ase ";Jr- or he' tadecimal I, e I., .

. mb ... ·~~, I

rAn actEd number is wril1en us~nrgl ,onl!y the dli,g:~ts, 0 thro[~gh 7. lEach pos~t,io'n rn an octal number represents a power of 8 Ous,t as each plos~tliDnl in at dec,rmal number represents a power of 1 O)~Thusl the ectal number 237 represents, the dec!ims,1 nurn .. ber ,2 x 18[2 + :3 x 8 ~ + 7 x· S10 ::: "28 2·4 + l' -=- 15~t

A hexadecimal (IQf hllelx) num:bet is written IUlsinl~1 the digits 0 throughl 9 p,ll~s, ·thisl

- -

letters A thro,ugh F~ 'whlich stand for 10 thrlough 1,5 respecttvelly. Each position in a

hex number represents a power of 16" the hex number 1 AF has '~he decimal vahJe '1 x 1162 + 10' x -1161+ 15 x 1'6°' ~2156 + 1610 + 15:::: 431 .

• 1 Dec;",lal constan ts ontai n digi t· zero:

• -. tal,c'mL~t_ __ . conn in Int digit'> , tw _'·_11 0 I' nd 7, and "'1IU~'1 begin ith I . zero:

017 0377 077777

I. Hexad. 'ci--'lal const n -O!otain digit - between 0 and 9 land Ie' I ~ bet I en a

and f, and alwa s beain with OX~'

Oxf Oxff ox7fff

on tant rna he eJ h · r- upp 'I or low

Oxff OxfF OxF OxF,F OXff OXfF OXFf OIXrF

'"

. I. ~p in mind that I t td hie "·d, cimal - I - nothina n1 - ~ ,- " ternatr e

'wa,l' of writins numbers: the have no effec I. 1 U'· .

, tored, (Integers are al - :y- st rec in binary r egardle ~.I.-- -hat notation we -,I.

used to expres them.) W- c'· ,- - witch from on D- 't,: dOD to nothei at an time, land

even mi them: 10 + 0115 + Ox210 has the c alue _1- I decimal). Octal and hex ;I\r,

1110' 1 conv eni 01 ~o- - ruing 10 --~Ie Ie] rogn WOI1'"t U'_' ' th '1_ norari ns

m'~L h until Chi ipter 0,.

Ttl typ - _ de inu ,[ inte er _ on tant 0; DOnna} _',' int 110,' "'f, _[- tb "I~ lUI"

f Lb, nstant i ,JO 'I lan I~ to sto I" <, an int the onstan I, . t, .p, Lonq int

lnste d. In th unlikel: ca e tha theco uant i "'11 . .or ~ uz a lon\g int, th rompiler ill try una ignled Lonq int :. , a I t re I, r -. Th rules ,r determn "ng '[he type 0 - WI acral 0- hexadecimal lei-Ill 1'1 - _ --liglltl_ different: the c m ..... piler win go through the type-· int" unsigned i,nt~l Lonq ~nt, and 'unsigned long int unti . It finds me cape bl . o representing tile constant.

11-.1 tL rc the nmpll "' .' con t nt ,al _ ]0, t ir t ger, just '"UO~ i itb

th _ ], tter L, I· _ 1):

1SL 0377L ox7fffL

To indic c· ••

l'

15U 0371U Ox7fffU

L, and tr 'mat, be us -d in c 'mb'~n,ati'on to sh -w the 'l it con st 1- _t i oth long and unsis n ~: OxffffffffU-L. "Th order of "he L , __ nd U doe D t rna ter, nor doe: their' cas e.

__ Intes I - . ClODS _ nt : in :-99

- n C99 in' I,~ -'r "':0' tann tlu t .01' ,- zifh either LIL . ,= ll.tb,e cas ~ of the twc 1 tter

I . long Lonq int iddina th ')1 te U I or u before lor _l' ter

'. I ~ 1'01, istanr f pi unsigned Lonq long Lnr.

tle I for' d t - rmining 'the type of . .' . _'c' - - _'~ constant ar bit

dif erent hom he' -. in C8 ~I TI1e Ity ~. 'I dec im'a1 cons: an' with nc . uffix I U u L

L, LL, or 11 is the t'smallesr 'of the type- int" long Lrrt., or long Long int tlla,,' ~a_[1 repres ~n the-value of that ' on': ant. For 'n I ctal or '. . ~ .. ~' ecimal constant, however, the list of 'II ssibl ype is Lnt unsilgned int~ Lonq .int., uns i.qned long' Lnt., long long Lnt; and unsigned Lortq Lonq i nt in that ord co" An u I .... a tbe len of, I In ,- ,I h _ _-' the Ii I of possible tv e I. -0

exa . ple a constant that nds with U (Dr u) must have one of fte type una igned

• - ' I d 1 - · t; ,II' -- '- - d 1-- - 1 '~t d -, .' nal

Lnt; uns1gnel .J ong a n ",o,r unaa.qne ong 'ong ant .' ecimai con-

stant that enid 'w,wtb. L, (Of' I) must have one of the ty:P~'·, lo',ng Lnt, .0[[ Lonq Lonq Lnt., There s also a provision for a, constant to have anex ,- nded int ger typei,{' if's too large '·0 represent using one of the standard integer types,

When arhbmedc operations are performed on, integers, it",.· possible that th ' result will be too large 10 represent, 'lor example, when an adthmetle operation i. per'fOfilleld 011 (WID int values, the-result mu ., be' able :0 be represented 81:1 an i.nt. U the result can't be represen ed __ I an int (becaus - 61, requires too many ~il, we Silly that ov'e,.jJfJ'W 'bas OCtU rred,

The behavior when integer overflow OC'CUT'" depends 010 whether the operands were signed err unsigned, "When overflow occurs r .-ng an ,peralion on ig'ILd Integers, tile program's behaviori , undefined, Recall from Section 4,t4 'that the COD"" sequences of undefined behavior m1ay v,ary,. Most lilely the result of the: operation will , 'imply be wrong" but the program could crash or exhibit other undesirable behavior,

When overflow !QC'CU[-', during anoperation OD unJtig",eld integers, though. [hie result is defined; we get the correct answer modulo 2" where n is the nu-mber of bits US ed to store 'the resnl .~ For example, if 'WI ~ add 1 to the unsigned 16 ... bit rnnnber 65,53,5" the result UI guaranteed to, be 10"

R d- d 'c-w' '-. I!:tm-' II Jnt

.. - ,- . - - r· '. - . - - - - : I -' II . I - j'" - .,' l

lea m,g ,1lIl!~. ,rl_ - ,;1; ~~-_ egers

Suppose that a program isn I, worki ng because O'D_' of' its i,nt varia.ble·' is overfl!o,win.g,. Our fu·~:t thought i to change the IlCype of tblfe variable from int to Loriq in t., But 'W'IC'~ re not done yet; 'Ill: need '~D see blOW th _ change wil I affect the rest of the program. D particular WI_ mus t check, whether the variable is used in a 'call of p'rin'tf Of' acanf. If ·0'1 the format string in the call will need to be changed" since the ,t.(l conversion works 00.1'1 for the int type,

Reading and writing un;~ ,i,!h.€d, short, and, long integers requires se eralnew conversion specifiers:

.Wllen reading.or writing an ,un igned integer, use the letter u, o, or x instead of d in the conversion specification, I:_" the U specifier is present, th Dumb. r " read (or written) in decimal notation: 0 indicates, octal no,tati.'OD., and x indi .. , cates hexadecimal notation.

E? can;f ,( mil '='Ull ~ &;'\1) I' pr'in'tf ., '11'Un.l U) j'" acanf ( UI %0 '!!, &u) ,I pz i.nt.f I( III 'o'U 1 'u) ,i

I '* r'e.a,Qs i ;b,ase 10 .. I
'U 1n
/ '* !t . base 1.D *1
'wrJ.', e.s u In
I 'It reaids- . baae 8 .'/
'U 1.n.
I .. wr.ites u in base '8, *'1 soanf , ,II "X'II, &u); printf ( I'~ %ix'll, \1':

1* re,ads • bae.'E 16 wI
u l.n
I" wr1tes i bas, e lb '. I
u l.n acanf I' III %:h,d t,~ Ii,S); ~u=in~t.f ( ~II %hdU, ,s.);'

, n fe_ ding r, riting '-, il ,Ig ~ " eg " ,IU, the 1 'I', 1 ( _11 'f d. 0 u. 01 x:

D,"

long 1;

• When reading I _ :, riting a r Ion ' inteae r I I

ft 'nt- _ 'd ,0" U 'OJ" x::

pu the letter 11 in

long Lone 11;

B,canf ( U 'lld" ~ &:11); printf("%lldP, ll) i

In Se tion " 1 jj ,e rote '_ - If I 'am I hat "unlS a seri - int, _ r 1 n're _ b tb '

I'

us" r; On,~ problem ' Ith this program ~ , '~il the sum ror on of thl:_ input nu nb rs

'"Ight exceed thl 'large value allow d for an int variable. Here s what might

h- tppen if the p, DI,b am m' I Tun on r ,,_- hine whose intes _ are I. " bit- 10 g:

Tl1,is pT'logram sums a a,arie,s :of integers '"

Ent,er int'eg'ers (Or to 'ern1in,ate): lQ10f.H1 20000 ]QJ)IDQ 0 The aum is,: -55036

The sumwas 60-00 I, which wonldn l fit in an int variable N~' 0 erflo occurred. - mr with igne d numbers, the outc ome i' unde I - ed, In this ._pp I-' mil "I aningless number. To improve "he program let

, " ble

_I '. ~ - t

print-- I( II Thi.s p,r'ogram sums it series of nLegers" \nn) ~

132

acanf ( III i ld II ~ &n); while (n~= 0) {

sum +~ fit

aeanf I{ u '%ldn, &n~I;

}

pzi.rit.f (II Tae -su-m :ts: %~d\D III, sum) J'

return 0;

}

The change was fairly simple: we declared n and sum Ito be long' variables " d f . bi t~I ... , b' d th . ':,m.. .i:" mstea 01,· 1nt vanao es.tnen we c ange . e conversion specmcauons m acanr

and printf to tId instead of %d.

T-he int,eger types aren't suitable for ~J] applications, Sometimes we U need. vari- .. able: Lbaol can store nnmberswith dJl,gits after the decimal pOInt" or numbers that are exceedingly large Of small, Numbers like these Ule stored in floating-point format (so called because thedecimal point "floats"). C provides th:reejlotJting fJp:t!,s COTresponding to different floatin -point formats:

fLoat; double

long double

Sin~61e-,pfecision floating- point Double-precision ftoatlng-poim Extended-precision floating-point

float is suitable ~ hen the amount of precision isn't critical (calculating temperatures to one decimal point for example) .. doubl.e provides greater precision-« enough fotmost programs. lo',n,g dO\lble wbicb supplies 'the ultimate in preci .. sion is rarely used ..

The e standard doesn t state IIOW' much precision the fl,oat., doub Le, and lon.g doub.Ie types provide, since different computers may store floeting-pcint numb rs in different ways, Most modern computers follow the specifications in JEEIB Standard 754 (also known as lEe 60!;,S91), so we'Il use it as an example.

The IE'ER Flo,aling-Paillt SttJlzdard

II EEE Sitanda f'\d 154, dev,e~oped by the ~ nst~tute a,f Electrica I and IE~e:ctronjics Engjii ... neers, provid'8S t.WOI ptilm,sry' fofma1s, tor f~O.attng-lPoi nt numbers: slng:h! P'flslci,s:j:on (3,2 bi~s) ,snl'd dOlublle p,reai,!l'icn 1(64 tdts). Num,cers are sio,red IIMI afcrm loff' sc~ent~fh:: notation, w'ilth each numbe'r hav'~ngf thr'ee parts,: a 5,ign, an expfJnen','. and ,EI flac'tjan'. The number Qf b~ts raserved fOlr this exponl9,nt dat,B'Tmines how ~lar'g'e (Dr ama,U) num .. , bers c,an be" while the' number 10if biJts in this fnlct~o'" dilsts1rmlne,s the, p,re,c.siion. lin srInQile .. preelslon format" the' eXlPonent ls ,S b!ts; IOlnlg~ w'hne the' f'r,alction cccupies 23

biteS. As a r'Bsullt .. " a s.ingh~iJ~.preoif1dDn numbslr has a Im"axi,mUlm va~ue' of a,pprioximB.'te~y 3.40 x 1 O:n~ ~ wilth a preci:sjo,n IOit abcllut 6, deci"mIJaJ ,digits ..

The, IEEE standard also describes two, other 'fO'rn"ats,~, s~nQlha ,9x:te1ndie;d preclslon land double extsndsd p,rec,i!sion,! The sitandalf1d dO'B,sn'-, s'p'8c'i:fy thenu'mber of' bits in thes,Q formats, a'ltlhoUigh 'it requires that 0,18 singJ'B extended tvP'B !DCCUP'Y at least ,43 b:Jts and the doub~e' sxte'nd,ed type at ~e',ast '79' bjts~ Far more 'iinrormlati'on about the ~EEE standalid and 'flloat1ing"'"point' ,ari"'h'n119'tij'c in Q,ene'lfaJ, see uWha1, '9ve!ry 'CDm~pU'ter 5ciBntiist shou~d know 2}lbc;ut fllc~a;tr,ng'-poi nt ariltihlmlet~c1" by C'Bvid 'G"cddberg (A,CM Co,mpU'.fing S.urllBys. vo~ .. 231, no". 1 (:M:a reb '1' 99 '11 ): ~8)i ~

Table 7 ~:4- shows the charaeteri - f cs of the fl oaring ~ype'- when implemented according to the lEEE . tandard, I The ta lie S,OOW"', the smalle t positive n(},rR1a:liZJ~'ld subnO'fmalnWflbers)t!o-23.4 values. Subnormal numbers lean be maller.) The long doub Le type isn't shown in the tablesince its length varies from one mJ8chiD,e to another.with 8,0 bits and 1.281 bit being the T11!O'St com! mU'R sizes,

''''1'''. hl' '7.' 4

,13 - ;e , ,.1_

1)pe

~-

floa,t

double

SIlJQ,lles;t p(J'riri1~e'ulrl'e P,~.,cis,iI',.

--~--~--~------~----------~

~ .,17.549 X JO~JI 6 digits

2",,22507 x ] O~30R 15 digi~~

Fleating Type Cba.r,acleri stie s (IE'EE Standard)

<: float. n"> heade:r "'\~3:, "

,

.

,

O'D computers 'that don't follow the ruBE standard. Table 7 ~4 won" t be val id, In fact. on some machines fLoat; may have the-arne I et of value's, a - douhl.e . r doubl.e may have tJ~,e s me values as Lonq doub Le. M~"C'fOS ILbal define the cbaracteristics of the fh}sting types can be found in the' -cf Loar .. , h» header.

In C9g.~ the floaring type,. are divided into rwo categories. The fLoat., douhIe:, nnd long doub'l.e types fall into one categorjveulled the real flo{ltil',' types'!lP1loatingtypcs also include the ,COfllp,ltJx 9pes (float _CQ"mplex double _Complex~ and Lonq doub Le __ complex),,- 'which are new in 'C99~,

Floating, Constants

Floating constants can be written in ,8 variety ofways, The following constant' '~, for example, are all valid- 'W,Q,ys of 'writing the number 57,~O::

'A floating c . n.: tant must contain a decimal point and/or an exponent: 'tile exponent indicates the power of ],01 by which the number is tc be scaled .. H an exponent is pre sent, it must be' preced!ed by the letter ':8: (or e}.All! optional + or - sign may appear after the E (I. .rm'· e)~,

By default fJoating con stants are stored as double-preci io,n number .. In other words when a. C compiler finds HIe constant 57.,10 in a program, it .~ _ ranger for the ('iii' number to be stored U1I memory :01 the. same format a· a doubl e variable, This rulegenerally cau es no, problems, since doub.l.e values are converted automati ... c,aUy to f Loat; when necess £iI[).

IOn occasion .. it may be necessary to' force the compiler to store a floating constant in fl'oat or .Lonq doub.Le format, To indicate that only single precision i· lesired, putt the. letter F or f) at the end of the' constant ( "or example, 5 7 ~ IOFI)~ To indicate 1bhat ,3 constant should be stored in Lonq double format, pu '[he letter LI (or 1) at d1C lend (5'7 ~ OL).,

1(11) C99 bas, a provision for writing floating constants, in hexadecimal. Such a 'COD-'

stant begins with Ox or Q,X (like a hexadecimal integer constant). Thi feature i rarely UI ed,

As we've discussed" '[he conversion specifications %e, %f ~ and %,g are used for reading and writing .~. mgle-preeision Iloaring-point numbers, Values, of types doubI,s, and long' double require sligh ly different conversions:

.' When reading a value of type doub.l e put the letter 1 in. front of Ie" f, or g:: doubl,e d,

Note: Use 1 only in a scant format string, not ,~1 pr i.nt.f string, In a pz i rrt f format string" the e,~ f, and 9 conversions can be used 10 write either f 1 oa t or doub.I e values, f'C991 legalizes the use of % 1 e" %'1 f, and ,% 1 9 in calls. of pr i.nt.f, although the '1 has no, effect)

Whlcn reading or writing r value of type long' doub l e put 'the letter L in front of' e',r f, or g:

acanf ( ~~ %:L:f 1'! ~ &ld)l:

prl.· nt f' 'i ~-L~ III Ld )1 .;;

.. I._~ ~. J.. , -- .... t'

The only remaining basic type ische'r. the character type" The value I of type char' can vary from one computer to, another, because different machines nlay have different underlying character sets,

ASCII onara~t,er set ~'Appandix E Today~s mcst popular character set ilB ASC" ,(Ameriir;an S~andalld Cod,efar I rnormatijc'n II nl'IBrch'ang'e)1 I a 7'~bit, code CIBpllbJe of ,reprr!B,sentil'ng 112!8 characters. ln AJS'CI:I~ the digilts 01 tOI !91 are relPrel~uE!nte!d 'by 'the cedes 01 '1IOOOO~1 '11001 rand 'th'e upperca,se'.II'eHer-s, A te Z are, represented b1y 101001 . 1=101110110. ASC I III is often ax,tendiedi

to B 25,6~characte';r code known as L. -',nn' 1·hat pro, idss the cha __ acters necessary for ·Western Eu'ropean and manlY African languag'9s,,,

ch == ch - ch - db -

I,a II ; m A II i I 0' ~ .,

,

: s ,

,

l lo"wer-c,a,se g. * I I,' uppez+caae A * I

1* zero . /

/* */

apace

'Wori-,g ith charact -(, in C is unple, bee e f one act: ••.. ,', . 'at. chan ctets a' small imeger«, _ Jer all, characters are ,en· odie - in binary, and it daesn t take much im __ gination to iew these binary de -,' a.' int g T' ~ In '·S', ~II, r r ex rnple, charac-

t i ,. es range fr In : 1 ] 1 III J \ hi h ~ . - " , I ,. 1 " 'I') ~ , , the ,i nteger

0' 1_7 Th ' . h - '.' b " ihe \J"UI-· 97. ~ A'l :' tb' IU;Il,,' • a II h

I has the zalue 3-- The conn ction IL t., len characten I and int .6 ers in C. j '., ',0 " trong that Chk racter con ,·tan,l'S, actualh h.a, 'L in.t typ rath_ r than char '[t p. I an in resti g' ct, but not RC that -,- U] etten m( ter tr u: .).

, hen a ,ch_ ~L~ , er I pp ears in a '. Jmplut~ j" r ~' lmpl valu 'JL

·orO' id r the f 11 'win, exarnpl ,I hich : . sume

chaz c'h,; in,t 1.0;

; ~ I. ~ II ~

~ - '!i,;liIl ,

ch = 165,;

ch ,- ch + 1 i eh ~ ;

/* . '. 97 */
1 1'S D,ew
1* ch • IAI *1
19 DQW
1* ch , IS I */
1-5 now'
1* ch is now "el *1 haraeter an oe omps r j [a, n < n. The foll 'win ,- .i.f st ternen;

, he, ,;- - " heth r ch ' n lain' "_ In~ - r-ca e I . 'UI, . if so .. it c, , .. , ch to upp,r C _:,f\,

if (I a' <-= ch && cb <= I z , ). ch ~ ch - ~a~ + ~Ali

'mp risens I h III II a I' <= ch ared n u ing the in, , er aluei ,I

t . in oJ, ed, The: - aloe, depend n the char ieter e in U'· -': ~ ,I pri gram <: -e == :> and >==. to, C Impar" I' b ~ ~'- cte ~:,m3'Y not be po-r able.

fa, t that I, haracters I -~'i,e' , num,:- ers has .·:·Im

-r exampl " c, - , , f,o - statem ·~'Il . h '"e l,fO, n

through all lb~' upper-

characl.:. t [I-Ie

On the otherhand, treating characters fa numbers can le,ld to various programming errors tbat won't be caught by the compiler, and let, US, 'write meaningles expresjon." such as I a' "* I" b I I I~ C f • It can also hamper portability, since OUT programs may be b sed on a ssumption about the underlying character set, (IOIUf' 'for loop, for example .. assume: that th Iett r~ from' A toZ hav i consecutive codes.)

Since C allows characters to be used as integers.jt shouldn't be surprising that the c:h,ar ~ypeL_ like the integer type.. exisr in both l i,gne,d and unsigned versions. Signed characters normally have value .. between -1:18 and 1'7~, while unsigned charac 'e~~, have 'values between O,a.Jld 255.

The C ~ tandard rloe'~n'~. specify whether ordinary ohax is, a signed or an unsigned type; some compilers treat itt ;.IS a signed ILype .. while Olber!1 treat it as an unsigned type, (Some even m110lw the programmer to select, via a compiler option, whether char' should be signed IOf unsigned.)

Most of the time, we don't really care whether chaz is signed or unsigned, Once in a while, though, we do, especially if we're using a character variable Ito ___ store a mall integer. For this, reaSOCL C allows [he use of the words signe,d and uns Lqned to modify char:

,s,ig~ed char ach, unsign'B,d ch . .a.r uch,

po,rtalbnlity t'ip D011 JI a~fl,SUI11e thar char is eisher 81~8ne,tl or un .' igned by dej,ntl'l. If h matters, use ,s!ig'o.ed ch,ar or unsig,ned char In .. a. €tId of chaz;

In Iight of the close I" Iationship between characters and integers, e89 uses the enumsnlted W~es.16i.,5 term li:"l'~grr_' r,ple" [0 rerer to boththe integer types and the character types, Enumerated types are also in'te,gral types,

eti) eg9 doesn't use the tern, ~integtal types," Instead, it expands the' meaning of

"integer' vnes" to include the character types and the enumerated types, e99"ls

"BQ,ol lytle .\~ .. 2 ,_:8,001 type is considered to be' an un·· '],gD,ed integer type,

ThE integer ~yp!~.- and floating types are collectively known as ari",,"I'e,tic t]pe'sjj Here's ,6 summary of the arithmetic rype s in C,89 divided mr· categories and sub ... categories:

• Integral types '. char'

I. Signed integer type (signe,d ehac shext, Lnt ~I int, long Lnt.)

• Unsigned integer type', (unsigne'Q chaz. unsigned short int, -ur11sign-ed Lnt., une i.qned 10'TI,lg Lnt.)

7.3 Ch'ara'cter Type,s 137

• Enumer ated ,ty p t.; I .

_ loating typo .. (float, doub Le, long doubl e)

Ita) Ie . 91 has amon complicated hi _ rarch . or its arithmeticty pe s:

• lntegt r types • oha r

_ I. Iel'l d il1tl~(l. r type. b th standard fsigned char .. s,hort .i.nt; int'l

l'on,g in.t I long lolng int) and I xte nded

I. Unsigned integer yp ,.~ both standard Ilunsigned char ahoz t, Lnt., unsigned int., unsigned long into Long lon'9 Lnt, _BOd,l) and extended

• Enu erated typ

• F1o,atin ' tv ~e' ,

I. Real [loa: g typ,f!"" (f Loa.t., doub Le, long doubie)

• CODIp),ex . pe (fi'Q.at ~Co'mplex" doub'l e _Complex. long d,OIUble C'omp,lex)

Eec'a.p· , S·· e' q uenee

'i,;i, ': .,_,' ~ "_'. ., , . ,I • "1

unsigned " d uris i.gnen

A character IC. 0' tant is II ually cne chara ·'ler enclo ed in . Ingle quotes, . s ~ een in previous examples, However certain special charactcrs=-includingthe ne ,-.linlc. ha I cter . 1 be writt n in II i "ay. bee .H' J th ',_' I , in jsible " nonprinting) or becaus th ' can't be ntere I from the k' '.' b ard, ':,0 that program can deal with every character in he underlying character let." provides, a sp ci.~ n tation tile ". C1Jrp'f/ sequen« e.

Ther-e U. tw kilt' 0' escape "equ, 'ne s: c'IJ'lUllctllT e ,CIlP','S and ,Nl'I'.11r-'~: ~ .. es,cQ.p,e!,."W i aw . parti ~~ Ii r of charact . r ' " cape. i n- ection ], .L; Table 7.,5 gi ves he I,· OIJnp'1', I", t.

I -

Tr' brim ".5 Character Escapes

he \ a \' b \. f- \ r- \ t ·1IIn'· \. v ,!!=II cape: r'Ap'li . uu ~. rnrn m A···leD· 'Il '-no o l

I 'iI'- ~ . !~ '," '~I ly .. 1 I , ~It- a_' '-1 ~ ,~·_-' .. _'Li_ ~I '_ I,", _ "U, _.

chara ter'i Ih_ \n e C'" p, renr . ,. nL the A,I] lin _ .. d character, The \ \. sc pe allows a character constant or string to ~I ntaln the \ character, Th.1 \ I' escape

Bac P'il e Form reed

,~ew line Carriase return

j!l .

H rizonn I tab ~ertica1 ". b

Bae k lash

Qn tion murk Sl ngle qu ote Double quote

allows a character constam ~(J containthe ~ character while the \ III escape a)]ow' a Ii!II stdng to containthe n character, The \? escape is rarely used,

Character escape's are handy, but they have a problem': the list of character escapes doesn 't include all the nc nprinting,- C~I characters just tbe most COll1- loon. Character escapes are also useless for .representing characters be'yond the basic [2,8. AScn characters, Numeric escapes, which can represent any character, are rhe solution to this problem,

To write a numeric es,capl! for a particular character. first lo,ok upthe charaeter's octal or hexadecimal value in a table like the ODe in Appendix E. For example the ASCn escape character (decimal value: 27) has, the' value 33iin octal and 1 B ,II] hex. Either IOf these codes, can be used ~o wri ean escape equence:

• An octal esclap' se'9E1'J,iC" consists of the \ character followed by an octal number with ·at mo 1 three digits. (This :OUIL1,ber must be representable W an unsigned character 80 its maximum value is normally 371 octal.) For example, the lescape character could be written \ 3,3 Oil \ 0 3 3., Octal numbers, in escape seqoencea=unhke octal COD<:.tll1'ts-dO'O·!;1 have 1[0 begin with o .

• A .hez'Q,'de·cuRtJ'l,il'Scape sequence consi ",'[i of \x followed by a hexadecimal number, Although C places no limit on th ~ number of digits in the hexadecimal number it 'must be represe[Jltable a'> an unsigned character (hence it can't exceed FF if characters ate eight bits, long I. Using this uotation, the escape character would be written \x:1b or \.xllt, The' x must be in lower case, but [he hex digits (such as ,b) can be upper or lower case,

When used as ;1 character constant, an escape sequence must be enclosed in single quotea For example, 1 Icon Itan'! representing the escape character would be written ,\ 3:3 II (or m \x,lb, II). Escape sequencestend '~O get a 'bit cryptic. 0 it's often a good idea to give them Dames using #,define':

#define ESC ~\3]1

[1. be en b dd d .. J- ~II ,i S "' ~ 1

risc,ape sequences can ne ern -e_ e m . r~g, ,~t_, w'c' , I~ lIS we saw U1'ecttOrn.;t. ~

Escape sequences, aren't the 'only special notations for representing CbM3C ters, Trigraph sequences .. provide away to represent the characters #,' C., \, ] '" A -, {

I }., and -~ which may not be available on k:eyboard~ ~nl some countrie ". C99r adds universal character names, which r semble escape equences, Unlike escape sequences however" universal character names are allowed in identifiers,

C 'h'" raeter-H I' id -I· .' F' "'\ti!l!'I' '1 . .. ' ._sraClJer ., an· UK - DDC, ODS

Earlier III thlssection.we saw' how 11] writean if statement that converts a lowerCa~!H;: letter 'to upp er-case:

if (ma~ <~ ch && ch c= 1Z~) ch :;;;:; ch ... ~ a m + I A ,

This Isn ,t the best method, though, A fas,telr-Q'nd more portable=-way 'to convert caseis to (:'1811 C's tcuppez library function:

When it', called, t o upp e r' checks whether its argument (ch in thi case) i a Iower-case letter. If SO~ m'r returns the corresponding upper-case letter, Otherwise touppex returns the value of the argument. In our exampl we' e used the assignment operator to store the return value of t.ouppe r back into the ch variable although we could just a.'s easily have done something else' with it==-"s'tored it 111R another variable, s,ay, , or tested it in an if statement:

Programs that call t.ouppe r ned. to b,8V,_, th,e following #in,clud,e directive at the top:

#in.clude cctype .h»

t.oupper isn't the only useful character-handling function in the C library, Seetion 23,.5- describes them ,aUI and, gives examples of their use,

The %c conversion specification allow acanf andprintf 'to read and write single characrers:

s .... '·~ nf If.- ~~ _t..,c- nl~ Il'·c-· h )-, '.'

""'iI2JILJI.. - ~ '1:1 - ~ DC: ", , ,

printf(U"CU'f e,'h);,

t= rea.de a s in;gl e chaxact; er \it I /tr 'writes a" e,ingle character *1

acanf doesn't skip white-space characters before reading a character .. f the next unread character is ~_ space, then the variable ch in the previous example will contain a 'pace af~e[ acanf returns.rto force s canf to skip while space before reading a [character, put a space in its, format string j u . ,t before % c :

Recall from SeC]OI1! 3 .. 2 that a blank in ,a Be anf format '_ mug mean" I,,", kip zero or more white- pace charae ers,'

Since s'can.f doesn't normally skip white space, it's easy to detect the end 01'· an mpu'l line: check to see if the character just read is the new-line character .. For example, the following Joop 'will read and ignore all remaining characters in the current input line:

do {

aoanf (' 'II %e' II I &ch);

} while (ch 1= ~\n~);

Wben scanf is called the next time it will read tbe first character on the next input line.

: provides other 'y.-, I r ,. n ' writ single .harac t, r. - .particular '_ can use

1&1.1' the ge,'~ char ,.- nd put.chzrr functions ins 'd 0' - calling scanf and prin f. put.cha r write a , . .ing] "_ bar ct r:

put.chaz I( ch) ;

Each time g,et,ch,a,r is called i'~ rea; one .'11 racter, which it r turnx. In order to , . _v, tbi' cbara: ter, re 1l1UL u: e assi nr-' , nt to ,'lre )( in s . ~iil I):,

ch -- getlch,ar C); /'* reads a chazactie.r and st,ores i,t in ch * I

getcl1.ar' actu It returns an Lnt; value rather than ~" char valu (the I'ClaLOn will

_ i us d in later '-hap_,r )~ A r sult, ir n unu ,U,i;1 I or.' aria ~c,I _' .",' l ~-. ,,-

typ int rather than char i u ' iII b It ;"d to store a I, haracterread by'g'le,tc,har. Like acanf, g,etchar d, " sn' t skip hire-s 'P'c,~ I ,11 ac rsas it [1';. _I,.

U," g get char and put chaz (fir ther than scanf and pr ·nt~~ j saves tim when the 'pro r m i' ,e, uted, getlchar . d pU-_lchar ar [iIr st for' '," reasc n. irst they '[nulc'himp,lrth·o;scanf ,.n-,printf"bj"h e de igned n rear

,', 1""'; d f ,0=1 .... , ~ iO ,~" f _ cl d

311 rite many xm S II Willa m a varlelyl_o'ml" -I,,, '_ eeon ge-tch,ar' an

macroslP,'4t3 put.chaz __ c u~,WIl)I: imph m nt d as 'mi'",~' f ( additi u 'p I (.I.,

g'et char has aneth _ r advantage ' ,ver scanf: because "1 I: turns the ch _ . ,8,,I: r . at it rea ,getcha len hse lu, - ',f' i W I ldiorri , in' -1u in Io ps that earch for (I chr racn I or _' ". p 0- er all _-,' cu rene " or a _ haracu ;[,:- OD .ider the acari ~ loop hat we used' ~" ,i men I or : ,I' rput line:

do {

acanf ( .. %c III &ch)r;

} while (ch 1- \nJ) i

R _ \1 riting It hi 11 p usin ' getch,ar t. •

do {'

eh =. 9,e~c.har () i

} while (ch ,~== '\n ~ )1 ,;

Mo- ing he .' '111 of getc'l'- ·,r im th -I ntr Iling e .. res i In all - the 1,1,-,

ndense

Thi ]OIP rc ad a ~hnralc'er'- rei:" it in'. _ the vari bl ch, then te: ts i_- ch is no,

_' u l til th - ne r-Iine char "" ~ - tb _ ,lu "'I. " " '" tb, 10:1 bod I hi, hi' empt

i ~ executed tll, n I' 101 'P te t is perf rm, d once m r '~ can , ing 0 r, haracter to be re 1 ',C LLU' .don't even need be ch v ria le: \\1,- canju t COD1P re tbe return valu I,fgletchar with he D - line chars t [f:

7~3 C'ha'~a'cter Typ'ss 11411

/* skips rest of line *1

'.

t

The r-, mlting loop is awell-kn " D C idiom tha i c p ·"1: I but'- orth Iearninz. 'g,etc,ha,r is useful in loop that : kip char cters a . ell a loop that e arch for characters.t "0.0 Ider the -IOU.O' ing statement, which UJ·e - getchar to . - ip an indefinite number of ·.I]_ Ilk charact . rs:

When, th ' loop erminat Ige, t cha r encoun tered ..

A. ~

-, ~ careful if yuu mb getch,ar and scanf in the sarne program. scanf bas, a tendency t leave b, hind chara ters that it has "peeke at but not read I including the new-line I. haraeter, Consider what happ n ". if we try to read a number .... _ 'til then __ . - harac I :r"

pr'Lntif ('II Ent.er' ern integer.: III);. acanf ( U ~dllll, &i);

pz i.rrt f i( ~(Enl:er a comraand : n') ,;command ~ get,char () t

The I ~a11 of s canf v ill. leave behind any cb 'acters that weren t consumed durin _c the reading of i I including (but not limited to) th n·· !-lille character, g,etchar will etch the fir t leftover character, whih wai D 't wbat w had in mind.

PR'OGRAM Determining the Length 0-,8~' essage

o illn tn tie how characters ~ .. re read, lie' " write '~ program th I calculate th length of I~ Inc" sage, '- .fter "hie user enters the message ", _.h,' program di splay the length:

Enter a me,ssage: Brevity is, th'e soul ,of wit ., Your message 'wa;s, 27 character (s) Io'ng I.

The len th includ ."'. space and punctuation but not the new-Iiue character at the end 0 the messs gc .

W 'Il n- ,d a loopwho .. bor y react a character and Iucrements a C'OU'Dt, 'f. The

10' ( .ill term in at' '", " .. '11 I' a' e - - -1'1 ne ch aracter turn s up. We could 0' e either

acanf or getlcha,r to read characters: ,0 I C programmer: would cht o.~l_ ge't chaz. _',ing, straightfor ard whi Le I n P e might end up with h follow-

, ,42. ,Ch,aptsr 7 ,Ba,slc Type,s

prlnt r- (IJlIEnter a m,essa,ge: ~III ~ i ch = ge'tch.ar();

while (eh !.= '\nl), {

len 4o;'

lob = 'g'etohar (,) ;

retu.rn 0;

}

Recallingourdiscussi nof idioms ln 'I] Ing whd.Le l .p. and qet.chaz 'we reali e that tb - program can be horn ned:

,"ngfh2~,c 1* Oet,erminr=s the len'gtli cif a messa.g,e -ft./

in·t main ,(v,oid)

{

int lien::: 0;

printf (limEn ez a mess,age: n);~ while (getchar() 1= '\nl) le,n++ ~:

p,'rin'tf (uYc,ur message· was· ~d c'haracter (8.) long .. \n'~ " len) i

}

Computer', tend to be more restrieri than C when it come ':.' _ ~jthm tic. or a computer to perform SeU arirhme tic operation. the . peraads must u ... 'uaUy be 'Of the . arne e ize (the '. m ' number of bits) n be ton d in the same way,.··o·mputmay be able' 0 add two 16=bi! integer directf but not ':_ l'6 bi inf g' r and a 3,2-b'it Integ '0 r or a 32~bil integer and D,"--b,it ft ating-point number;

C on tiT other h d allo . -, the b sic tJ·" .t b mixed 'in expr j D I.

can combine integer, floating-point numbers, '(J1d ven character in' single . ixpr ision. 'The C compiler may then h . ve to generate instructi 011', that convert

IS me operand tOI different types ' o th t the hardware will be able tOI evaluat ' the expression. If we add a 1'6-b,il ahoz t. and, 32-bi'l int for e I. rnple, h, compiler will arrange .' or the ahort value to be cion erred to 32 bits. If we add an :int and D, float the compilerwill arrange for the int '01 be converted to fLoat; .". rmat, This. conVICI ion i' a little marie complic ted ". mice Lnt; and f' Loa t valm 's are stored in different way, "

Be .ause the compiler handles these conversions automatically without th programmers involvement the re known a: impl'icf conversions. C al: allow' the programmer 'to, perform e:rp,lic'it eonver. Ii'OIIS UI ing the 81':t operator, I'll discuss implicit conve rsion -, lir t, postponing . xplicit conversions until late in the section, Un ortunately, the rul .. '" for performing implicit conversion ~ :' ~ somewhat IClomprJICX. prim rily because " h,BS' 0 many different arithme tic typ:_ s.

Implicit conver ions are performed in 'the foIl wing situations:

When tbe operands in an arithrneti or logical expre sion don" have th r sam typ III (C pertorms 'wh~ t are know n a'·, th, U , .. uQ,I,(JTllJthmetic· -,OllV'BTSiOfI.S ..

• When the typ of the expre sion 0 tb righ ,id of an as ignment do _ sn _ t

match tb . type of be v riahle ,n th left sid riO

I. Wb nthe type 10 an argument in 3 function call d' ' .... n ~'t match the type of 1'111 -

d·· t

'corre '. po,n _ l.l1,g PlaT m,eer~

• When the type of the expression in a retur-n statement do rsn mat .h the function's Ii turn ty'p ,.

We 'll discuss the fir," two ca es I'IOW and save the uher for Chanter 9.,

The usual arithmetic conversions ar appl ied tl the op rand'. o most binary OIP' ratOT'S" including the arithmetic relatio al, and, equality op, raters. For example let's say "that f 11El· type f Loar and ~ ha ,tYPI into _ he usual arithmetic .. conversions win be ap Iied to the operand in th e press ion f + i,'e ause their typ: are n 't the same, Clearly it: safer to convert i to typef Loat; I, matching f 's type ra her than COil], crt f to typ' Lnt; (rn itching i ' type).. An 'in __ ger can alway be converted '0, f Loat.: the WIOr" t ilia can happen ", a mino los of precis ion, Coni erring IS floating-point number [01 Lnt., on the other hand would cost us the fractional part ofthe nun ber, War', still- we d get a comple ely meaningles result if the original number wer - larger than the large" t po' iible int gel or smaller than th ' smalle st integer;

The strategy behind the usual arithmetic conversionsu ',0 convert operand to the '-D, rrowest" typl~ that will safely accommodate b th v rlues, (i OU. ,bly peaking, one type is narrower than I: norher if it requir .. ' fewer byte '. tn ':, tore.) The typ ~ . of the operands can often be made to' match by . on ertins the operand of the narlower type to tne type f the other operand (tID act ~ known i l promo ~o_,). Among th most commo promotions are the i~ 'egral'p,r:omoti'ol's, which r onvert a charaete or short integer t. 'type Lnt; (or to unsigned Lrrt m some ca e ).

&

.

I

We- can divid ' the rut s for performing the usual arithmetic cion ersi n' into Ito' c "_.;:e', ~

• The',tJP' alle;,k"" (JperaJld is a jlOllti:,,_,_, ,_1tll'IU',e til. following diagram to p =Imul '- the . I erand " hose t- pie i ' narr- 'r:

long doubLe

r double

r

float

That is, jf I 'DI- r I _ as l,'-'P long doub'Le, ihen I "~l~' -, ho• ner operand to t pIC Lonq doub.l e. Otherwis .~.~ ~ I n cp rand ha type' douhl.e, e 111- -, rt the ther pe ~ nd to typ" doub L e. , thei . l' e, :_ one I p ran ba,' ype float~ convert the other operand to txe f loat.c Note that these rule cover mixrur 'fi teger and floating , __ es. if'onecoerand b lp longint fr exarnpl and th other hi typedoub l.e the long Lnt, operand is converted

doub.l e.

. I iI!i

Integra .. promotion ,nn

. a eh ' ;3." t rr short .' p .. rand , n, ,e typ ~ ..

. ,

J~' narro ' er:

una i.qned long in.

r

Lonq int

r

unsigned int

t Lnt;

l hen . IQne I. peen ~ C_'=_',,' ut It 0 . 'ur . nt, Wh"D .Lonq int and un;s,ign,@ld Lnt; h'~,I' 111· ram i 'Dgtb32 bits say . UI1~r 'I, e circumstances-jf ene ' . type long Lnt; and 'be other has ~y, e una i.qned into I nh j - .. cion "Ietted t I uris i.qned Lonq Lnt.,

'. hen . ..··,i ~ n : d I per' nd i ' I c nnbim d an un ign d op, .rand, th . igned operand

il converted ICO an un igned value .. - be onversi n inv lv -' adding or ~ ubtractin a

mul i=- le 0 11 + 11 h 'eli - n j" the lan I st representabl I \, alu : "th UD~ JUD', d tvoe.

Th~ ~ -, b ~

I .. ru~e C,' n cau' .' 'I, UI~' progrlamm1D" I'. rrOf' ~

UPP"'I tbal th _' int varia J i 11, the t lu ~JO and the uns Lqned int

ari JI' U 11, I' th - alue 1 O~ 1_'" . e lnpl i!. • cod u 'U ,ing tbe <: operator, se i ht

expect to get the n sult 1 true IIi Before t11_ comparison however I is con erred ',I unaf.qned int.m 'lie a nee I"· e ru rnber l:. 't Ii. P e <nled a an un Ian e integ r, lh, ". nverte value won't ' -]01• Instead, the value 4 oW' 4,.,16,1 296 is

dded 'a I, uming that ,,~I ,4 t;'I' 7 I,. i t th l" I, I~' ,·l uns ignled int . aIu' . - gi" ing

a converted 'fWU I'"' 4.' .

0" me I. ompil rs pr

, i m ed find unsien. {f~ . u __

'.,n un . ign . d numb r,

Hie au 7 tra " lbi '. D' it "I '~, t te u~, e unsignec

·,ibl,. and, especially D'-" Ie m ~ . Ure- with sizned in,t egers.

ohax c;

sho'r Lnt, 5; int i~

· I

uns.lgneCl int. 'U; long int 1;

un:signe _I long int ul; f,loat f ~

double d~

lang double Ld,

·
1 ~
·
1 -
U ==
1 - ~

.:L + c;

i + S;

t= G! is converted to, 1D - * I

/ '* sis, convez-t.ed to l.nt .. I

I i is C"onvert'sd to unsigned in't '*'/

/ '* u is convex - ad tOI long int 1: I

1* 1 i,B cD"nverted to unsig·n,ed IOlng int "* I

/'*' ul is co,nverted to f'loat ." /

1* f is convez't ed 't_ 0 doub l.e '*/

/'* d is ,conve~rted, to long double' /

H

'U, lL;

1 + u; ul ;; ul -+ I;, f' = f + ul;, d = d - f; Ld - Ld + d;

Conversion I uring Asslgnm ~I t

Th usual arithnu tic COin' ersi m don't appl to as signment. sst , C follei the

SlimPIII~ rul' h the e pression on fb!, right i .ofthc asaienrnent ,. I con ertec to th .. ,p' "the Ian bl on th :11 ,'t ide 'the varu ble's vne ~,~ , .. r Ieast ai wi e

the _.r tpre sion :, this , ill -, ork '. ithout a sna ~ For example:

phar' C; Lnt; i; flol t f; double: 'd;

/* ~ conve . -,led ~ , */
1, - Ci C .:LS, 0 ~I-
f _I /i- I I clcnve'rted, to float *1
- a, ;' 1 LS
d f /* f ~ , ad doub'Le ./
- ~, 18 convex 0)
f. Other cases are problerm ric. 'A ," ,j:_ ning a floating--p l:lot D.llDlb, r to ; n lot ,ger

ar]" ble dr Pi .ih fr. tL m I ,' - of the numb r::

Lnt, i;

i - 842.,91; i - -842,,, 97 i

1* i I now 8-2 */
18
/* i I ~B42 I
18 now M~ reov "'"1 ming . value to ,U variable of _- narrov e_r lyp_' will give a m anin less r _>0.11 (or w r 'e) if the . alue J' . u sid the rang of the variable "" Ilype,:

'C - 1.00i(}O ;; / .. "It WRON'G" *ft'*/
"
I 1" O,e2:0 1* * WRONG **. I
.r - ..
,
f - 1 Oel00 .. /**. 'WRONG ***1
,. I A "narr wing' assignment may eliclt a warnin,8 from the c mpiler or from tc ols such a . LLnt; ..

If's a good idea t append th f····· uffix o a floatin -poi nr c 0 . tam i, it - , ill b _: 8"/ igned t a f Loat. ' ariable "'.-, W 've been dlling since I~ b -'It r :

f ~ 3,;;14159If,;

I ithout th su Ix. th" 1-'( Ifl tonI 3" 14159 ,', uld have tye double Pl. ,'~i,' ij,

The rules I f r implicit . "on ersir In I in C'99 art somev bat diffe __ nt from the rule , in _Bool '~PEl '~8-2 e89", primarily b ~cau~~:~_" C9' . b "1 a idjti~n,aJl t_ p . ,B'o,o lonlg long' pe

t' od,d intezei n ype'"- and c ~Implle_ .. type. ;;

For the purp ' .. ' ~ f defininj con en in I~II- C9-c gi", each rnteg ype

inreg r I .n ersi n flank" - - . : .,~. at" the rs "i .. , •. m high ·1 tc lowe t:

l lon,g Lonq Lnt, uns Lqned ~ong Lonq int 2~ long Lnt; un,signe,d long int

a, Lnt., unsigned int

4. short. Lnt., unsigDleld. shoxt; int

5, char. ei'gned chaz, unaLqned char 6. B.001

For simplicity I'm Igm ring . xt ended integer types, and Dum 'rated type," ~

In pl,ac· 'of 8 ", s integral promotions ... 9" has "inte er prornoti " '. hich

involve convertins ,any I pe wbose rank L lies than int and unsigned in''C 0, intprvid ed that tll valu - of the typ~'-can " r presenn d u~ inu inti lor el '0

· d i t'

unsJ.gnecc, ~ni .,

A - in ICB9- the 'C99 rul "~,'r performing the usual arithmetic con er iions : an be i ided into two '. a' . ,:

• TIl'e "p',e o/,eitiler Op,fJli _ , tI' is I. 'flo-ti, g It]pe~, A long a', nei _her ope rand ha · . _ e mplex type, rhe rule, ' __ the. arne ... befor -,~ (Th . (:1 "D'eT'~ioll rules for com-

pili X . will ae d1i u~ ed in '_, ' _. n 27 ~ -,.

• ,. either IfJ.P ;,roorld type is It ,jlo\a,ti'1l;lg .. --p'le,., Fir, ~" perfe rm integer prom tion on both OPI~ an' -;0 If the. types of the two' operands I· re n IW the same, [be precess end .. Otherwise, 11·, . th fbU, wing rules stOPP,W.,g at the fir- '_ on . that , pplies:

• If both 'op· "and ~ hav _ .,jgne,d type'~ 'If both h,l' e un ~I: ne It pe ce 'n rert [be

I. 'IP rand wbo se type ball 1_" ser integ r . Ion 'cr ,ion rank tc 1:11. ty of the

I, P r, ~ d ", i h ,I reater rank.

- If th - UIL ian ed operan hi,' r nk greater or c_ qual t ' the rank of 'the typ· '. f the' ~.'ign,. d operai d'l' convert the' signed perand to the rype of the unsigned operand,

• ,~'tb_ ty, . , I. 1- the ign d perand I, - , pre' nt i U 0;- 'Lb values ' .. 1 be '._" p.:

of 'the unsigned operand, convert the unsigned opere "d to the' type 0&' the sign d ' pe~an .. _ .

• ' " there ~ ~ _' c n' bo h operands t· lb ' un I •. ' -

typ· ' of th I igned 'OP,·' rand

Incidentally all arithmetic typ '8 can be convert ,d to ~B'ooll ty .. I., The result of the conversion is Il if the origin.' 1 value I O· nth - I j ", the Ie. ul is I.

'. clorre '. pending ",' the

'ltholu,gl1 ' .~ implicit- onver ]0'8, ,' __ e CI n em ent, w som erirne: need gr_j' t, r d sree of control or type conversion. ror till: reason, Cpro'v~dc, iasts. A I' sst expres ion has the form

type,-n.{nne./p'· ifies U e t -'g tl " which the I pression should b. I eon erred,

TIl. ~.Illowwng example sbo ' he r t use e C ist expressio [,0 ompute the frac ina] pia-rtf a f Loat; zalue:

floatf~ frac paz i

fra't! p',art ~ f - (Lnt.) f;

Th: . cast e rpres ion (in't) r re pr esenr th I r lull' f on ing he due of f to ty e Lnt. I" "s usual arithm tic conversions th n requin that (int) f be eon .. verted ba k 1,0 type f oat; before the ubtrac i . n can 'I e pe rfi rm " L The differI rn I b tween f md (int) f i tiel ~ );. tional art -f f which dropped during the cast,

'. au t expr c " iOID·' enable us t d um nt typ I. on ersions Lh 'l wr ,Id lake place any ,1,1',':

i =. (Lnt ) f;

Tilley 181".. ena I·' U ro errule th xnnpih r nd rce i t do convt rsion hat e '", ant. Con rider the ~ ,Uwing . xampl .. :

f Loa.t, quot i.enc ,i

int dav i.dend, divislor;

11 4:8_:. I C' h- " 7 BI " '""'IIi

.', "ap,(isr L·,:aSIC 'YP,9,S

- . i[ I, no written, th r sult of' -' di i i n-_n int ~"r- '-, ill be j ,D'· rted _', fl,oat _ rm bef re bein . red in quot Le I' ,,-'" 'lbatJ- vant div1dlen,d ": id di visolr,n' . rted t· oat: b'.fo,'le_he ,'-i~ isi . n though, I I that we get ' mOf ' exa t ,~nl' -." r. ' ,C I' ,t e' ',r::··· .j. ID -~ 'illdo the -' k:

divisortloesnlne,- ~ .. L~,incel,a·tinlndividend[ float I '.~ the

compiler t onvert divisor t- f Loa t also.

Ineid :nt, UYlIl C regards ( l),P' -IlICl,PJ'J;e ) .. ~ _ unary ope r,~ tor, , nary ap aton

have high, r pr~. _,e, ·~n· - than lin _ vooerators IL' the' mpile _ interpr ts

(float) dividend I divisor

((float) dividend) / divl,so,r

quot.Lerrc - d i viden.d I (float) di visa· ;

,. are somenmes D=C·-·aJ' to avoid 0'.1.- ow, "'on'lider th fnllo ing example:

llong ";.

in,t j - 10010 i

Ii 1I.dl!., Ii!

1. :: ] !Ii J;

/. overflow may occur '. I

At first glance thi . tate menr llonk, fine, The /alu of] w j is ].0,0,0 .'0, _ nd i i

a Lenig" ',,0 Jt an, ea iiI. ton . slues ~~ thi' liz ri~'ht: T~ ~- -pr bl m is th Ib,~ .-

t ~ Q int . alue . are multiplied he -- ,I t . ill ha- e Lnt; '_' pe, Bu j "* j L too large to [' pI" nt . _n int on om nl __ chine " Ic,au' ·ina an 0 ".~ .- 0 .. Fortunately,

'U .. ' lin~ . .a 10'_ _'. ~ i_ _ the orobl . .':.

i =. ( long) j * j ,;

Sinlc_ the IC3"'t I IP erator takes prec denc - iver *'1 the fir·~' j i C'D' erted tJ long

[ pe, forcing Ul ' seeon -, j to, b . CI' lOY erted I-"~ , it N, te that '11:_. ratement

'.' urr,·, ':y tb -' time '_ . the

7.5 Type Definitions

In Section 5, . ., w .used the #d,efine dir cti e tOI create 111a'rO h" could be used as a Boolean type:

#·de'fine j8,QiO'L .int

&II The re's a better way to set upa Boote n type thou - h usins a - ature . '0 n ,- I a type deJinitio.fI:'

typedef lnt Bool;

~" otice that die name of the yp~ b 'in[g defined . -01 --' .. ' l st. 'ote 101 th It r-· . capi-

talized th.' word Boo'l.. Capitalizing th first letter . f a type n811 e i m t required; it .' jus a, con 'en ion that orne C prog I amnu [f' i em iloy ~

Using typledef f,O d line Blo"ol_an'Je[ the compil eru add 'Bool to he li: t I f type narm , that it recog liz ~ s. Bool can, n.OIW be 11 ed in the ' ami - _ ay as the built-in type n rmes= in variabl - declara . on LICIt t ! -"pr,e' ~ i 11 'I and clsewher . p, If[ xample [ we rniglr u se Bool to declar - variabl ~ s';

/ * aame a.s intfl a,g; * I

The compiler treats Boo,l __ S . I synonym for Lrrt.: thus, flag L real], nothing more than an [ordinary int variable,

, dv .'[ . ·t· _,' " -'1'- ·f· """"7 " .. Deflaitf "1 I

.' .. IVan, -ages, o[ =s pe .··e Dllons

Type definition , can rnakr a program more understandable (assuming that the programmer has been careful to choo: e rneaningful pe namest, For ;_ iample : up-

P.IOS~[ that the variable'S ca sh in and cash lout will be u to store dollar

[ ~

amounts, Declaring Dollars ,- ,

t.ypede f float Dollar,s; and then writing

i mo Ie informative than ju [ wri ing

Type definition call 1·0 III a .' e a program ea sier to modify, If we tater d, ide tb[~ Do L'La ra she uld really be defin d as doub Le, all we [lee de is chana th type definition:

150 Chapter 7 Ba'sic Types

The d - clarati: I,' '- ,f Dol Laxa v - labl -.' ne -€I n t -'ie '}1. ng d, ' jtbout the t, P . definition ' e ,I]ul need t " I at' _11 f Loat; arir bles that store dollar am unr lot n, . e sarily _- ,11 ',_c' __ Y t _ ' ~)I '_[ nd I hanze their " clarations.

Typ- definiti ns ,- ,'-I importan to I fo _- rmag -r[a~-1 ~ or gram- _ [On of b[ problem with moving pro" am from ne I r,.' . ~ pu er ' _ I [an' her is th lit:: P , m !j' have difi)', r nt ran _ In diff -rent rnachines '. ['" i i; an int v. _ i'_ Ib'l[e~, ' " 'i ignm ent like

i ~ 100000;

i fine on " maehir with .32-b[it integer , burl win fail on a machine Ith J6~bjl integer '.

R' r [ r at. r portability, ' -onsider u in, typedef 101 defin« 11' n II mes Io

Suppose that we'n ' writi g s prog .am th '1 n . d[ variable capa 11,' I", orin '

product quanti i -, in the range 0-50,~OOI.' ecould 1LI~,e Lonq variabl for [hi ,_ urpos e I sine ' ttl ' - re guaranteed [to b -' able to hold DU h, rs up to, at ] 8" t ,.1474 .,1.71 -'utw_;·dr,atberu:ein;t ariables since __ rirhi etic onLnt.valnes may b faster than oneratiom an Lonq values; Isc. int variables m,IY take up less "II.C

Inte ._,'_ of U"I ~ the int ' ',' .- .o d 'clare Iqu,~ n ii' < ,:: ri 'bJ' . I ,"e I. de - I,m-

vn ' uanti - t ; -,~

, md usc this type

~' rIare variabl s.:

Quantity 'q;

WI·- , t

ien we tran , port Imle program to

- .

the die ~nitwol1 0 '"'Qu,an ity~:

Thi te I hnique doesn't 1 ,01 i all our preble - ,., ut ortunately since changirn the definition, ,- QLlanti ty mai arre I til ' ',ay Quanti ty . uri_ bles are t the - I, ry le ~;.'I·, all '~_ pz i.rrt.f and acanf tha us 'Quanti ty ariables ' in D_ e', be _ b - - ~ ed . ith % dOD' en ,i I - '0' peci fi cation replacer !,' !Ii 1 d.

'i], , C[ library it 'elf u . typ[@,def tc C - at name: -or 'pe~ ',I can :

rrom one : imp II 'mentation 'to snothert tbesetypes ften nam[. that en ith

to such as ptrdiff_t. size_t,-, and w'char_t. The ~' a, t defini 'iO'D'" of thes typ " will, v ary ,- but h "re are ome typic 1 xample " :

typed1e£ Lonq int ptrdiff_ ,;' typed,lef uns,ignled lon.g int _s,ize~t ,; typedlef int wch,ar - 'I

In -991-ltb <stdint.h> hi, ·d r use typledef'tod_fillcD,ame.oriDt-l;

~s _ lint ~ h> he-ader-27.1 '_,pie· itha particular DILllll·C-r of hi .'. For Ie', ample int32_ t is - .C,· go . ._-~' integer

t)1' e . itb exactly - ,-, bit E Using the e tvnes i an e '- ... tiv , .. a t m 1_· __ progr _In· I - or p ~ abl I,.

7. The s· zeof Operat

], sizeof . perat r allrequired "to ~ It re valu I

,-~ro,'-, ~ I. rrnine hov muh - ·m··· 1~

.Th - I,. alue f th. exoresslon

ls an U[ sign d integer repres _'0: ing tbe numb r c bytes required to store ,3 :,aju, belonging t I tvoe ... name. ,Si,Z'90' (char ) is always 1 bu he size ot the other type may "ary~ On- a 3,~.-bi machine. sizeo,f (in,t) i normall 4 .. '., te thai

s i zeo is a rather unusual per O[ sin I , . th ornniler itself 'W] 1;1, uall,_

mine the valu 10:·, 8~z,eof .. tpre sion,

Th s i ,z eof I. perator can raj I b - 'PP~i. d ~ 'c n nts, ' _ ariahle 8., and ex pr ""

j D·, in . en: rial. 'i ~_ 1\1' I j I re int . ariables, th -, 8i zeo - (i)i hi ItO ,I: ~ ~ -hi·

machine .. _, i ", s i zeof (i + j ) . Wb,:n _ plle to an expn ssion=-ru . ed ito a

t.-p_~ -'izeo doesn't re uire PlaT,. nth . ,·U}, itL s i.z eof i ,. -, !L_ ..... ~_

S ize,of (i ) . low' ·ver",1 '1 "lenthc"CS may b . nl. edec , nyw,ay 'be ·1 u·e ,of operator

m ~'e~pjl I. I ul intet _l~ si ze,of i + j as I( S izelof i) I j ~ sic eof-a uD,ary OPI_ ~atlor~i- .·1: ,. pl~, ._ .' D I.· - vier the binary ,+ . pt. fa"" t· (f. . . 1t1l.· aid pn bl ms, I _I., - _,'~' u· e pa enthese in sLzeof 1_ xpre ·,11 n ...

Prin :n~_ a size'of alue 11· qui -.r·. I. re be we thetype I a si,zeof . ~,~Pl-_I-

ion j, .. _ n im .: ~ men i:· n-defined yp .. 1 t, '. ~ 3) i ae _ t,~ In C89- i 1 's best I", :iJ1-

rt th "', alu I.~ the ',_.- .. -~ , ion I a known ~ .. re b, . =- prin i j ., size_t i

guaranteed 'to, be an UJ]'- ign d inn , . er ryp _',<·0 it I, ,1£. - ,'I to cast f. Biz eo f ' .. p :'" ~ 'ion t una igned Lonq . the lar '. t I 1_ lei , __ I .J, nil md ili· '0 print it usin ~' ]1- % 1 U -,on er - ion:

- I

,..,.. ._.

I~ _er th itbOIl

, Io -I f - 11-

u .

• , .

Q- I,

i

,~ . - II

.iJ>Q"

"if", " I,:

I' 'Cti'OD 7.1 ' a,' '~ th',t 1)10, and "X HI- u--,_d 'to:, ritlell--l, ed int' " r·~ in 0 tal and he - notation .• 80 dn I \111"lte tOlrdin I . 'd) inte _ ers in 0 <al or hex ,,,,I t·, '01

You can u e %,0 and ~x ~o -'rint a sign - lnl_ g r as I n ,_ it- at " i n 'i nega '~:" ell

hes con ers io ause prin- f to II at u slzned inteaer a til ugh it were

un igned: Ul tb: - t « rd, pz i.rr 1 will assume 'that the I ign bi is "pari - f the num- 1 er'r magnitude, A" lena ~ ~ . the.', n bit i 0 there' '. 11 probk m, If th _ sign bi h I print.f ~ ill print an unexpectedly 1 :g -' number;

But wha - if th,~ number is 01 " ·altv· l' - 0, can I rite it in octal 0' - ble.· "ii

here's no dir ct . "ay rOI print a nega i e 'number in t - or hex, Fortunately the

need . is prett rare.You D,. ourse, ~.:. ,- herlu rtbe numbt r is neg tive

and print a minU1. sign yl ur sel f:

if (L <: O}I

printf("-%x"j -i); e Lae

pr2.ntf ( "f tx ", i)r;

. I' on ~ _'. preferen I, [0 the dcubfe 't ,'e~ f Loa.t; is tre tied

,I a second .. elas citizen, .... onsid r forir ranee, the dlscu n If fLoat. in Ker-

nighan ~ n Rin I' • e . TIi, ' Pre- .11~'nn'nin. ~ LCUl'! U,Q .," ': !~T1 m 'i, r .. :' n ~. -~ us j,ng

f Loat, j." to '- 11.' ~t -'ra' 'e i lara _ 1i~1T 't I r [-, I 1', often.. "r, .I, 'rO rna' hin '.

, , -

wher ' d- ubl -preci sion an thm ' ti i- part i cular] y Ie pensf 1 .. '~ C o riginaH , ,- man-

d edtha -11 fl ating-point arithmetic don, in ubl pre i', i 11. ( I _. and ( '991 h _VI eno 1. u h 1~ q uirement, )

ha do he adeeimal ' _,0' ·-i.n' 'C' 1 _ .. _,_ I 10 . _ Ilk I, 1-

~or'1' I[p. 1.: ]

he rade una! floating 'LiO sn nt begin wi h Ox Of' OX an must c ntain an exponent hil ]1 is - rec -' ded by th ' 1 -It· r P I[ p. : h· ,-' P , .I[ Ll rna ha _ I :d the constant nl,ay end ¥l~th f. F., 1 .' r L. Tt e expon nt j e pr' se d in del imal. but represent a powler of ~ ~ not pow r . f ] - '. Fcor -·x· mph Oxl . Bp3 repre ,. t thi 'D'U ber 1,,687_~ x ~ == 1'\E5~ "h. digit B '[li"POD"_', t the lit ane 11011. 'The B oec urs . the right of the p riod, sc e ch [ bJ I I'PI '" 01 a negati e pO'WI_T of

.:.,., Summing these p .1 ers I ~'_' ! ~-~ + 2,-4) yield" ,,6: 75.

HI • uti eimal floating / J" -'. 31.· prism 1_11y usen l for . pecifying 1-0 ' tant

that- require great p're,ci. ion I includin rnathem 'ti rl constanu u h ,ft:_ 'and 11. E_~e Dum . ,- , have a P-'· else binary [_ 'plf ."". n ti n, W] :rea~, a COli. t nt ritten in d 'cimal may -~ e subje t : , .in roun ing I.' I hen _D "_ r eo t inarv, HI' a-

"~Q', ~

, ".

A:

"affable,,19fl'gth a I'gU menr1 Usts, ~2S'. ,

de imal numbers __ re 1 0 useful "'; 'r' I eflnin -' con 1 ' , j - U:_R

1- th', - alues ofth - Jrurl' in the -c f Loa t . h> L:_ '~__ r, h "~ ,', t rants

write in hex, but difticult to write in d lmal.

I, do" III'S- %If to read ,do1lhl,e, aJUI __ but \f to pc-n it .. 1 [p .. 1-' ]

T "I is ~ ,I ugh ues [ n r answ er _- ~_".L 1lJ' '.' '_ that scanr und printf ar UDU etta! functiore in ' ( th -y aren restri t d Ito - -"" number ' ,. argument ._ , rosy that B canf and print 1- h'_ ve' variable-I neth 'gum rn Il ts, ',he functions with variahle-l ength 'UIIl, nt list c re _ aI I.' b c mpil _ r BTJ ': nge .fo I Loa 1- argument to be ronvened automaticallyto type doub.Le .. A ;.:1 re ult prin't f can' di· inguish berw __ n float and doub.l.e ar uments. Thi xplain \l %7f works for loth f Loat; and doubd.e ~argl ment ill " lls '''printf.

scan - . " 'n the 0_ her hand i 'P' ", ,d" p i'nt, , _I , a 1; tble, % f tel ~~. s, canf [,

stor , flo'at,_'lue, 'I the address pil. ed [0 it ~ bi]e %1 tell scanr to f, f- a dourrl.e vatu,' _ t th It addres '" he distincti n "'" l. 'en float and double i ' em -ial here " iven th ~ " rong e nr.i n Ipe ification, acanf WI-l li el ',' store the wron number of byt· .fJ10t 0 mention the act that Lb bu p urern for a f Loat; l , 't he sarnea [h,at fr a double I.

IQ': 'Yt'-b,:,t's, tb pr' per ,ra tOI prone I n I Ichar'., [pjJ I~,:~:.]

Tf I· ,_ . ,!I, n universally _L~e- t __ pronuncia ion. ' I me people PI nounce c'har in 'the same war" a the fm tsvllahle of charac _ r;" Oihe , s sa: "char," " in

QI~,

'h,eth' T. a eh rs et .

--- - - -

136]

~ it I 0 n '1 matter 'inc" th " ~i, n btl

will be zer . i ~ e pllan_, 'll _,_-'-bit I har I,' , 'I b, - ,e' -r: »e 'U ~r,b~ _ 1~ warn b

lable _- b' \1- una,igned char lyp w Conshk r tl f following example:

oh - ~ \' X"~'1,,;i.. '.' ..

~ -,,~' t

If en h_ s neen d cl re _ ,011'1" - " '1P chaz, lb c rnpiler In.' ch ,I e re tr' a~ iJ · I :1

n ny ,c, mpilers de . I ng a' ch i' u ed on I, a a. _ bar; .~ r,

Pi ble n. ut if ch i - r us d in on "1"',, hat re uire th

".,

compil r u I 'OtT 'lit alue t ~ n integer e're lik 1, to have f' uble 'he r ulr-

in, inteaer will be D gat~' e since cb ' .. Igu hi I i t: L

Her e '.. an tb - - situation: 'n ,',' me kin ot - . gr, rns il' custo ar to use chaz variablei to stnr one-b), ,in ocr .. If we're writing such or pro -r:- m, WI'~'n h " to I ecioe herher e ch varia 11_ haul be ,sign,ed char, '_ uns i.qned char, ju t 8,0- W'- must decide wheth r ordinar integer v, - iable ' should hav type int '.I' une Lqned Lrrt ,

QI: I I '00' 'I ,.' del" land 11'" 'h 'n"w~liD __ '~b~ racier ean be th. S, U linc!iife, d

eh r ' ten ' -- cD a us 'r ent 'r input and ~_ ~', the nter ke dee I I It __ ' PiT' gr'lim, read this _'-I I lcaria,ge ... -. turn chars -,il f' or ' " ' ret 1m plu, a lin , feed , [p .. 1,,','-

1154 ICh~ptBr ,7 Basic T~pes'

I part I_,' (-' herit age, it c ), -a s re . ros rille I' d ,1" it line .being rru ,d b a single lin -Ieed IC'- araeter, (In-I.: -: t x 11 .,~.=- I in ,~_ line- 1,-" I ha -

acter~ut no carriage rl [tm l~app_ ars at the [end ore a .b Iine.] he' lib r_ ry tl~ 1"31" r translating til _ u' r I, eypres int i line-t I' chara er. -_~' en I Pli@, ,~ sm r ' ,d "_' 1m a fil, , II!' UOI library t -an'late'~1 "1-_ '-'I.', nd- -Iine mark (whare ,'," it may he, into in J line ... feed character. TIll 'am tran ,f;Jirm~ti'~nl oc·ur-in rev ~ r ,-'wbe 1 1) put i. -'I; tten It, J1.,' creer ,II till' ile. ' see z ec ~'OD ,', .,1

de tail, .

Although file, e tram ]3"1. In' . eem COlD "u~:,i n ~".I Lhey • , rv - ,~ important pur-

,', 11' fr ~l th '" "

po':: msu ,aUn I1f' '. m' I 'm ' '1''lID ' . at n1,_~Y y, 'f, .I -- " 0 eraungs

"', _ 'I tIll r.,

'11_t lb' p~_o, ,ftbe\?':"I,a,pl' seq e ,"'~'[p~l-I,

A: The \ ? e' _"'p j_. related [: trigraph sequ n "~' I hieh ;-:e' ~11 with? '? If you' h uld dg.reptr :;equ9n~s ~25,3 pu ?? in, strinz, th _' ,_', I, P',' itn ~ I)' ilia! the compile I ',ill .,' st . e II f r the

b_,,.: inning fa trigr ph. R" ~l,c" c'_ the second l' by \ 11 1"'1 U ' pr '-Iem~

QI: _' Ige'tchari ,'I fa 'E Ir' - ~ou1d , I,

D ,dtarac" I, rs 11 [p. "]

A:, Although if .not ',' fa .. t I ge,tchar the scanf functloi i,: ,01[- flexible, A we

w prl II uslv the n%lc'l form ,[ ; trins causes sea f t 'I read til' nee _ in ut clu ...

U:, , it t ~_ f tb next non-whi ' - p' ce ,_barlactlor~" 1'·"1 acanf "I g'o _ Il rt I_ din character '. that are mixed in with orh - r ,." ind" of WItH,,! Let '-" ""YO that

. lIT input dats I ,I" ist f all' in eger then a, inale nonnumeri c ch at. r, I _ ~n

aneth I lnteg -r~, By u in , th,e f· rm t : Lring U td%lc%dll'. , e an g t scanf ' • r ead aJ I three items.

~Q::~,-ndler ,b,- ,t I~ir£un) stauees do th IDteglraJ prol r otill,o"O'D"e' fa, '18 "a ter er ,bort ID",',,-r' '" uDs,i,gned ,i,D.,t., [p, 1_,~

A: The intea al PIIU-, I U"D" yield : n 'Unsigned int if the int t Pi i ,n" , ~ f, c en ough to include ,ill possible values I f th -' ori ina] ryp .' .inc, ' ebaracn ns an ally eight bi [, long, they are , lim't alwa , converted to int, which i,l gu .. rani' sed

t be' 1 " t 16 bi ~ Ion ~"il a : Ib rt in, err an 1., " be en. erte It J ., _ t a

well, Un Igned short integers ar pf blenratic, If short integer have the ' am

gih ,rdin,', integer I ",'Y ,0 on " 11:6 bi machine). th :n unsigned ,11 rt

imeg r I 'wiU have to I· n ert d II( unsLqned Jbnt sin the L "I 1'_ un i -<IUIo"","_

hort in 'eger (6S,j31 IOn a. ] 6-bil machine Ii, larger [han the largest Lnt; I J,~~767).

Q,: ." It' :-11" l h,BP-~ ~nl,' if ,si 'rD ,8 lalU, tl a va_labl itb:::t u-t larl' , 'DOlt~-

t 0 d i,t?1 I[ ,I~, 14

'" _"

I ughlj speaking, if ,u, alue i ,I at int '6 al typ and the " ble j" uf an

UDI i ned type bees tra bit, are tbrnwll , '·'1,' n d t_ pe the

resul i. 'imple mentation .... d,efined.A signing a fl ann -point numb ',' [0 a, variable=-intr b ' [' fl atin -tbn.,1 II " 0 smallto h lid ,it pr ' UI ," I und fin, d " ha 'or: anyt]1ing can happen, including program tl rminatl m.

~~Q:: Wh,y doe CI bOithcr '101 pl[ioviile' 'type de6nili,oDSl? Isn It IdeBnlin· .1 II l!IIOOIL, macro just as '~od as, detlDin:R a BOQc,l 'type o.g t:yp,e,def'? [p, 14,91

A: There are tWOI imporL~nL differences between typle definitions and macro definitions. Fir t"type definitions ,are more powerful than macro definition .~ In particnIar, ,array and pointer 'ty'pesl can't be defined ,aSI macros, Suppose that we try. to usea macro Ito define a, "pointer to integer" type:

#aef'ine PTR_TO_IN'T 1n't *'

will become

after preprocessing, Unfortunately only p is a pointer; ,q and r are ordin,lry integer variables, Type definitions don' t have this, problem.

Second I t}'Pi!! die f names are I, bl,'bjil6ct to the same .' cope rule ,;I svariables: a typ@d~f name "defined inside a function bed:y wouldn't be recognized outside the function. Macro names- on the other hand, are replaced by the preproce ... or wherlever they a.ppear.

*Q::, YOiO ' aid til at 'CODlp'Uer '''''eBB nmany dete'rl1U1I'iBe 'lb,e 'yaJ'DI~ ,of a Eli i Z: ao f expre~, sion;;:"~ CaD'" a eomp,iler .lw:(I,,1 d,etermme the value' ,of asiz,S.Orf exp:fessilon?

[p. 151]

A: In C:S91,- yes, ]0 IC!99 however there's one exception, The compiler can't determine \!mi~eb~:e .. lenQth arra,s .8.S' the size of a variabl e-length an"aYi! becaus e ~be 'number of 1 .. 'Lem'cnts inthe array may change during the execution of [be program.

Exerci,ses

J ., _Gi~e the decimal value uf each of ,til If! foUQw~ng integer eonstams, (I) 077

(b) ex'??

l~) OX1l..BC

S:ection 7,,2,

2~ Which of the -following are not b;gaJ constants in Crl Classify each legal constaot ,a,s either integer lor £1olU ng,""polinL

I( IJ o JlO &.2,

(b) 3 2 ~ 1.E+'5

I(C) 1017 '9 a

(d) lOO ,000 (e) a. 97Be~2

3. Wbi, h ' f the foll wing· re 1]1' [ le.~d type, inC?

ahc.r una igned .J> rrt: (b) 51101."" float:

(c long doub.l e

1({jJI unad ned lcn,g

S ,oct-on 71131

,.

If c i ,3 rariable lOf· pe char b~ h lie 1 I' ,- I • n ,- in - statem n ,1, illegal?

(,a) i += c.r 1* i has type i.nt *' I

( c ~ 2 * c - 1;

( )1 pu .cha'r {C)I i

(J printf te,) ;

Se'- hich on, of tbl ~Dn, r ,in .. , is not a le~aJ WfJ1Y II write the number 16 ". Assum dl.aut the character el i ' '"CD,,),

alAI

(b) OblOO(]C101 01.01

,(d Ox4."l

e _ I Ul, 'olt wing item d la .]1ljf_hi h one I 'the type ',ch,ar .. , ahoxt; in' .,

I eng b the "l11IUe' t one guaranteed 'L b tar' e en ugh La sL, ,I", the Item,

(a 1 av: in' ml' nlh

I Davs in a yes 1

Mlnule~ I 'in ' __ day ,':.' ond in

7.,

acb'f the r -JI"wing bur cter 'cap - gi .the e uil ~ len octal eso p __ f smne tb,al

the haract r . i i _~' 'II .)¥ou I]]' Y wish l' con u.lt Appendi ' which ll 1 _h' numeri 1

codes for ' ·~,CII character .

, Iii \h
(b, \n
(c) \r
(I ) \t "

the equi alen h a"

Ope in; ~ 'bat i Ute' l

1 -! I~, uppo e that i i a aria I, . 1_ 'ly' tnt ]1 i' i· ble t pe long 'od k i ~ ,

p uus,i'91'le,d i LE" Iu iL i. llL ' t~ pe u~" the e :,p'J]" ssi n i + (lnt) j k,.,

, up.o·e ths i', I" ~ ~ .. p:: do,'uble.

l, pe in1:.~ f i" ariabl If I, pe -l,oa-

IYP I tbe ez pres: ion i I: f I dr,

I

I. Su po tb l i Is a ariahl .: typ in:' flOat ,I type double.E .plain 'hat cunve r if n: tal e place during lb. execun ' i' tatemem:

d = i ~ ff

Program',mingPtojeols' 157

~,3. Assume Lb~t a 'program contains the fuUuw'ing decimation' : ~har e = I~ \ 1 I ;

sllert ,8 = 2;

lnt i ~ ~3 'f

Lonq m ::: 5"

floa.t f .:::: 6,.5f;

doub'Le d = 7 +. 5 f

Give' the value Bud the' type of 1{:,B,ICll expre tsion listed below,

(n) c ... i (c'J f / C (e) f = d

(b), S + m, (d) Id I a tIl I( int:, 'f

1. Does the following statement always compute the fractional 'Part 'Of f correctly I( assuming III at f andf raC'_lP3 rt are float, variables)?

fra1c_' part == f ... ( in,t ) f;

If neu.what' the problem?

t~j'" Use typed'12f FlO create types named IntB, Int~',6", and Int32, Denne the tyope S"(\ tba[ taey represent 8 hit, )1(1BbiL. and 32 ... bit imeger on 'ylonr machine.

• I, The S[11lar'e'2 .. C' program of S·e,cl~DI1 6.3 will fail to' ually by printing strange 3lI1SWel1ii) jf i * i exceeds the maximum i,nt;vah.le., Run the progr"iul and determine the . mallest value of" n that cau es lfa.i'lllLIlf'e. TJFY ChilTI,gj' ng the type of i tn s hort ~nd running lLhe program again, (DOD'l forgel to update the conversion specifications in the call of pzi.nt f U 'Then

trylcng~ Fromthese experiments .. \vh~cd can yuu conclude abO'lJJrmo the number of birs lI.l~efl (10 store integer types on your machine?

2. Modify the 5quar,e2 . C!! progran1 of Section 6.3 '0 that iL pauses after every 24 squares and displays the following messa ae:

P'res:s Hnter t.o cont.dnue ... ,.,

After displayi n,g the nle·:S~tge,. I he program ShOldd use ge t chax to read a. character, get,dhar won't allow [he program [0 continue until the user presses the Eater ~ey;

J. Modify the su'm2 i c program o· Section 1'1'( to ," urn a series of double values,

'4. Write a program that translater an alph~bel],t: phone number into numeric rOlnn:

Entf.!Lr. phone nunW"er:, CALLATT 2.2551288,

(In case ,you don't have a telephone ocaJ!'by., here an! the letter 011 [11e keys: 2=AB,ICi,3=DEF", 4~m~ S;.....;1KL!~ 6o MNO~, 7~PR,S" tl'=TUV~, 9 'W"XY.,) [f the original phone number contains nenalphabetie character (d1~,j ~5 'or punctuation for example), leave them unchanged:

Rn.ter phone numb,'er:: 1·-8100-ICOL-.LEC-r' 1-SOO~:265-'53,28

You may assume that any letter , entered by the US'Bf' ale upper cage.

,5. In the S'CR_A8BLB Cro:s:wo.rd G,lme" plaYBr~ form words using small tiles, each containilll,g a 'I,el~~-' and iIJ facie value. TIle ':a:ce v,~du.e varies from one letter to another, based an the lettete .nldty., (Here MI" [he nloe values: l:AElLNOR,S,TU,. 2: 010- 3: BlMP~ 4,: FHVWY;. ,S: K., 8:, j')L I 0: IQZ,,) WriU~ &I Jn~d',gram that comrp,ules [be value ofa word by summing the value r' of its leners;

Ent,er a wo,rd~ pi'l:£al1 Scrabble value~ 12

¥ou.r program SbDW,d mUow any mixture of lower-case and Ll'Pl11W";.,ca;,!!j e let ters in the word, H itu: 'Use the t.ou,pp,er ~j,bT,ary func't:i"!Iln •.

Write a program tbl;,t PI':j n:ti tile values of 6 i zeof (i.nt 1, 9 i zeof ( short l' ~ ,s,izeaf (to"ng) 1 eiz,ec)f (tlo'at)'" isiz'e,of (double), and siz'eof lloing doublr=) .

ifi,

1.

'8.,,'

- ' ...

Modify Progf,anlming ProJect 61 from Chapter 31 so Lbat the user nU1lY add, sub'wact., mu h.iptIy~ or dl v ide tw'o fracti',on s fby enteri ng eith er ~ ~ -. * , ID'r I between the frac tiQiEl~Ii) ..

Modify Programming Project :8 from 'Chapler ,5 so d:uu the user- enters 3. lim~ u:sing the 12~ bour clock. The J.IlP[iIl will have the form hours : mimue« followed by either At p~ ~ or PM (either lower-case or upper-ease), Whi'te apace is allowed (but nlQi~ required) between the numerical time and tbe AMn?M iadicator; Examples of valid mfiut:

1=1.5'P

l,: 1,5P:M

1; 1,S.p

~: 15p!m

l~~S, p

1'~15 PM

1.:: 15< p

1,~ 1S pm

"YiDU ,may assume Ithat [be'iupul be one of these forms; there is, no need u) ~'~1it fur errors.

9. Write a program llial asks the user for a ll-Duur time, then displays the time in 24""hotlT fonn:

Ente'r a 12 -hour time: 9 ': 11 P~M E'g:u.iv,al,e'nt ,24-hour time~' 21:,11

See Pro,gr~tmmh:l,g PliOj 0et8 'or a desrc'rip.ti,on 0 " the i npu'~ fermat,

II O~ Wri~e' a p'HJ'gr~ml dlia[ eeun ts lchle number of vowels (a~ ell i. {J~ Dud, ,,~) ina sentence; Ente:,r a aent.enee s And tha.'t 18, the w'ay it ,is, .'

yo,ur aent.ence cont.a 1 ns 6 v,owela, ..

I l, Write, a .pnlgJ·,iDlJJ that takes a firs~ name and ~:as,l name entered by the user and displays tLhlast name, a comma- 13 id the t'int initial, llJ,nowr;d by La period:

"Enter a f·iEst .and last name: Llo'Yld FOlsdick Fos"di.ck ~ L ,Ii

The' user's m;pul may eonrain extra spaces before the first name, between the fir,sl and Ilast names, and aIlel" the JIst name,

12. W,dte ill program that evalnaees all e- presslon; En'ter an f!'xprecssion:: 1+:2:. 5· i J Va1u,e ~of ,expcr,eBs.iOtn'~ 1, lSI .. 5

The operands in the expression are floatlng-polm numbers: [he operators are +,~ - *,~ and /. The expression is evaluated from left to right (no operator takes precedence over any other opera 1,0.1"),

li3., Write a program that calculates the average word length for' a sentence:

Bn'ter a sentenc'18: It w'as, d,ej ,a vu all ,over a'ga.in ., ,Average 'wor,d Lenqt.h: .3~, 4

For simplicity, your program should consider a punctuation 'mark to be part of 1111e word to which it is attached, Displaythe average word length to one decimal place,

l4,., Wri.'te B. pro,gr,am that uses Newton's method to compute the square root of a. positive float. ing-point number:

Enter la, posi ti vie nu:nWer: 3,

~

S,quare r-oot; ::, 1 ,,?:3.2 015

Letx be the numberentered by the user, Newton's method requires an initial guess, y for the squar-e root of 1: (we'll [IS'e.. y '== I), Successive guesses He found by computing the average of y and~'(;/y. The following table shows how the sqnat~,e root of.3 would be found:::

Average of yandxl}"

x/)~

,3 ')

3 2

3 1.75

3 1~732]4

.3 1.73205

3 1.5

1 .. 714291 1,,73,196

1.732'05

2

1.75 1.,73,214

i!73205 1.,7J205

Note that the values of y get progressively closer '[0 the true square root of x,. Bar grealfit accuracy, YOlU' .progr,an1. should use variables of type doub.Le rather than f Loat; .. Have the program terminate when the ebsolnte value of the difference between the old value ofy and d1e new value of y iSI less; It ban the product of 'I,OOOOI and y~ Hint: Call [be f'abs Junction to find the absolute value of a doub l e. (You'Il need to include the <'m,ath ,,,h~ header ,all. the beginning of your program in order Co use fabs,.,)

l5~ Write ,3. program that computes the factorial of a positive integer:

En'ter ,at. posri.t.Lve i.nteger: 6

~

Factorial af 6: 720

(a) Use at shor-t; variable to store the value of 'the factorial. What is the Iargcstvalue of n

for' which the program correctly prints 'he factorial of n'? (b) Repeat part (a) using am .int variable instead.

(c) Repeat part (0) using a lo'og variable instead i

(d) Repeat part (a) [Ising a Lonq la.nSf variable instead (if your compiler supports the

lo.ng long type),

(e) Repeat part (;8). using afloat variable instead. (0 Repeat part (a), using a doub l e variable instead.

(rg) Repeat P31t (3). using a long doubl.e variable instead.

In cases (e)-{g)~ the program will display a close approxlmation ofthe factorial, not necessari II y the exact V3i~ ue,

Sign up to vote on this title
UsefulNot useful