J't is ~h,(1 use.r who ,!j'h.rJu/d p''fJratn'etrizQ P,(QCSriuti9SJ, not 'heir cr-eaitors.

<stldarg ". h», ,<stdlib" h» and -et.Lme I! h>-th,e only IC89 headers fh .. at W" ren't covered in p' e ious chapters-e-are unlike any other in the tandard library", The <:s,tdarg . h>, header (Section 6. -~) makes 11 po, lble t'D' wri e function with a vari able number '.f arguments, <: s td!l i-n OJ h,:> (Section 210 ,~2) is an assortment of functions that don't fit into one of the other headers. The -e t.Lme . h> header (Sectlon 26.~ I) all ows program to work TN itb dates and times,

26.1 The <st.,darg. h> Heade'r: Vaia l A,rg me:' s

tJP" va_arg (va_list ap" t)''P);

void va_~plytva_list de,st~, va_.1.ist ere) ;"' void va end (va list ap);

- ~

void va star't (va Ld at; ap , }}I"I'lnN) ~

- ~ -

Function .snch as printf and acanf have an unusual property: hey allow any number of argumenn ~ The abiliry t ' handle a varia ble number of arguments j m 1 limited 'to library function ,,3, it turn cut. 'The <st.darg'" h> headier pro ~ides the tools we '1.1 nee ' to write OUf own function wltb variable-length argument lists. <: 8 t.da.rg" h,> declares one typ,c (v,aI_l Ls t) an [define se eral macros. In C8·91 , there are 'three macro ~ nam d va_start.,. va~,arg", and va_enid .. which can be,

eD) thought of a~ fun cti ons with the' prototypes shoi n ab ,IV,!!. C9'9 add a function ... li ke macro named va_copy.


To see how these neeros work ·'e use them to write a function named max~int that finds the maximum of OTCJ~ number of in eger argument . Here' how we might call the function:

The firStt argument specifies bow m:IDY addititolDaJ arguments will fono"t~ . his call IOf max i n it will return 30 (ttu~ large: t of the numbers 10-, dO;; and 20)1.

Here", the definition ofilia max. int fu nctio 11:

int max_int (in·t n., i', OJ OJ)


v'a_,st,art (,aJP'" n] j'

largest ~ va arg(apt int) i

l!!!!!llllll!!! .

,f air (i = '1;' i <' n ,; i +-+ ) ( curr,e'n't = v,a=arg(ap~ in,t);' ,i f (cuz r-ent; ,;> 1 argesLt ) large,s't ,= c'urr'eIl.'t;

via ...... 'end (ap) ; return, larg'est. i

'The '. "" symbol in the parameter li·t (known as Ian etl'ipsi_.) indicates that the parameter n is followed by a variable number (lif additional paremeters.

The body of m,ax_int begins wirh the declaration of a variable QDf type va list,:


v,a,_ ,i,:St: ap;

V,B start

~ . __

Declaring such a variable is mandatory for max_in't to! be. able 'to aeces " the ~guments that follow n.

The statement

indicates where the variab e-length part of the argamen t I ist begins tin this eft, e, after n), A function with a variable number of arguments mll' t hove arleei t one "normal" pu,runet'cr' the ell ipsis always goes at the em 'Of the param Iter Iis after the ast normalparameter,

va_.rgl Ihe statement

lar'ges,t ,~ v,a~ar9 (ap , intl;

fe ehes max int's second argument the I. De after n) assign I it to la,r;'g'e'St, and :au~oimadcal1y ad ances to the next argument. The word in t indicates tha VIe expec m,ax_in·L,'\9 second ~g~J'ment' 0 have int type. The statement

J:\ .. ~



.~ ,LL\

current = va arg (.ap. i' It:) ;'

· t""

max n I',

Don't ror et dl,_ t va _ ,rig at'- ili,Y' advances t the next ar ume -_t aft -'-r f ching th currenton j HI ~.'_·cc use o- thi p pC'J' I e co 1'1' t ave I ritte n max ' nt's I'I'_ I in the foU Iwing W~ - ,:

for (i - 1; i c n; i++)

if (va_arg (ap , Lnt.) ::> largest ,)1 1ar'gest - vs_arg (ap # in _ , ;

I ft., WRONG W'.*!

Th statem n

'V'a_end ( ap) ~

i r quired t ,I In' U . e -f' the fun ion return ',f iru tea I of returnin J the

functien might can va_,st'la- t and trave se the ar nment Iisr ._., n.)

T;~ va clopy aere c nie Br'c I va 1st U,·' I dest I al

va li,s )". The usefulness -' v,a_co'py lies in the a ths muhiple calls of

va arg D_l ' I " '. made usin ere efr ~ it s c oied ,~-c [I dest- thus oro-


ces ilngs me orme a gume nts .. _,aWnfJ va_ copyallo .. functioi ,t rem mber

w '-. it " in h _ argumen U' ·0 _b tile . later r 'urn I~ . the' ._am· p . in' lID reexmme an argument ran possibly the ,-' - gu I' th 1 follov it) ..

Each call 0 . via ~ start IOf va_ COpiy must be pair -, end ..

"e l th :~JI' I-','U" t nn ,~ I ' '0' '", 'in I~ 111 n~' v· a '~r'g mu p qr

'_ _ 1.:1 _ I ,ill I· 1 rr' I I I " 'I - 1.1!!ljj _ 1· . 11-1 ' .. ~ ~ .1 _ I . " i£U'

between the cal of va_,s t art (lor va _c opyl and the matehi . call of v,a end.

Whe'n a function 'wi h 'V' -1_ bl argument Ut L 1 _ Iled the le'oml Hie perfor (h,

def ult ~gum. n' - 'ifl-m " ions '. n _I -. ,,' I 'n'l, tf J I ' ' l'~ II he I 11ip i ~ 1n

chaz D. shlort argumen I, .1 promot d to Lnt , nd float alu .. _ pro-

m: lied t ldoub1 le'j I I -Ieq_u·· tly, i' . I sn' t I .,i ,..' nse to P' ' '.' '_ 1:_lu_h

char. s,h,ortr float' va a. . g- since srzu tent -of,I'-' prj' -, ~,>n-'ill n 1& bat e lone of thOl, e type ,.,

hle Ar,gllmen

- ,U ie- r Iis ,t ", an illh rent] 't 7 rop., ·iti ' -~,

" (I '.' ho ,··_an:· rou·, it, IC,aD b . to ' , .'

m ' Is to pzi.n f and seen . Otb r rnn ti n' . ith variah le ,are

-',_Ilud]y sensiti _ ' ,~ The prim,', dlfficul _ is that a fune ti ·n 'ith 1_' variabl: al:_' n n list basi n _ w~ _y o determir C the number 0 argum nts or their types .. This information musi be p , .1 I, '. -, i the un 'in Imdl r ~ sum ' __ b the func ior "mla~' int

'-ieli ,IS; I .,n the fir I argu ment (I - • ,p J - i fy how m-- ,y addition . W ~I it

vfprintf vlPrintf vspr'intf


'n,tIl' I~JD'I

at 0 urnes that th ~ guments scan II rely "ll the form '

m nts and the type '0_ each,

Another pr blem ha t ith P , ,in" NOLL a- an argument, NULL is [1,\1""

, Uy defined to represent O. When '01 it: passed to, a functi n with 8 :- ariabl argnme it 1i,',t. I the 'c ompile '"",', urn,' , that il J e resen ,aw lntr 'l~ther~' n 'I -- ay it :_ _ n II that e want it tn repr ~ " t th - null p i nte r; Th solution is t add', ce - '~rlt = ing (v,oi,d *)NULL r (voi,d_ *) min. ead a'-NULL,. (See tb Q& -, seeri n at the end ,,' Cb- pi er 17 ' r m, r di -'U""i'D f 'bi - in

unction 'ucl1 a, pr:hntf and , tbe number ,fad -it]1 nal argu-

in vfprio' f (F LE *' Festric't stream!

cons eha.r *' re'strict format"

va_l '- -,t a g) • .. Q10 .. ~.>

int vprintf (canst char' l' res't1?ict: form,at,

va_lis arg) ,I ,'1 <stddo" h

i.at: vsnprintf rchax lr>f,S'st,rict B size_t rr,

canst ella!: * re,st:ci~ fO,l~at"

va_list, ,arg) l )''['1 <stdj_cJ .. h>

Lrrt ;\rsprint£' (char w re tria: ,6 J

cons I char * restriet format,

va~lis,t arg) ;' from oGstd.io,. ,;>

The vfprintf. vpr-i.nt.f and 'vsprintf ~u:n_ .ions (the 'v .. "pri,ntf funetions' ) belong lOI < S t,d,i 0 .' h>~ W 're di cussing them in thi ~ section because they'r invariably used in It; njuncti ,[I with them, en .. , In <stdarg .. h» '99'1-d the vsnprintf function,

The v ...... pr.intf function :-J' _"I ,'I,'ly related t~ fpxintf- printf- and

apz'Lntf. Unlike these ,~ II, "[Hl " however; the v.. .. p:tintf functior , have ,8

-', ad number of argum nts, Each funeti 'D ' ), I ,[ .'~ ~gument U' , - VEL 1 i st val ue 'I

which implies that it ' - ill be alled b a fun lion j "v' iabl argume nL Ii "t - practie -'I the v: ... p'rin'tf functions are used primarily or writing 'w, wrapper" funetin, fait .aCIC' pt a variable 'Dum ,I J ar uments which are then p ssed to a v~,,,,,printf function.

As an example, let's "", thaf ¥I" f'_ working Oil __ rogram th need [, ill, pJ,~,y

~-rr 'f ~,'_io sages from time i 0 time. We'd like each J ',' I, rage to b ~giD 'wi ~, a pr-fl, f the form

where nil for the fir t ,_ rrc r rne a, e an merea es b,- ":R f r each subs equent error, -0 malo '[ ea '. 'r I,' pr iduce ( rrnr message' ,ween" rite _ function named er.ro.rf that s similar to printf,- but ad ,** ErIor n: _ the beginning f

its output and always writes [0 5,t,aerr instead of at.dout . We'!]J have e::~r'r(:rFf call 'v'fprintf to domost of the' uchJ,ltl output, Here's what erx'orf 'might look like:

int errorf (c.anst char .. form,a.t, ., .. )1


nuw_err,ors++ ;

fprintf (s,t,der-T, ml ** ELrror- %d: 'I', num errors); va_sti3lrt(ap~ format);

n = vfpriott (S1:,de:rr, ta.rmat~, ap1 i/ va end- (ap,) ;

fpri:n'tf (- :e;,tderr, mil \:n IIII) ;

I.leturn n s


The wrapper functioll-erY'orf, ion our exampie=-i -, responsible for calling va~st,a_rt prior to calling the sr. .. printf function and for calling va_end after the v. .... printf function returns, The wrapper function isallowed to call vil......,;arg one or more times, before calling the 'v: ... .pri.nt.f function,

vS'nprin't" The vsnprin,tf function wall added to the e90 version of <stdi,o ,,'h>., It

corresponds to snprint.f (discussed in Section 22,"8)~ which is also La IC99 tunction,

., The v'U~sc,anf Functions

'int: vfsc:anf (FILE *r',e,stltict st:r'eam,

conat char .. I",f!stric,t fO'Z7l1'at f

va~liB t a:rg); froru c:stdio ,mh:::-,

Lnt: vs,canf (canst char '* xeecx i ct: fO'rffl'at,~

v,g __ l 1st a;~g); .,,"(JUl' es't d i.c ~ h>

int v8{Jc'anf (canst char '* F,estri-ct 5,

const c,h,al,;'" * .l·;estrict ornl'at


va_list arg); frosn <stdia., }1,>

V'fs'canf v.s1canf vsscen:

'C'99 add, a set of "VIIII.scanf function .. ~ '£0. the <sttClio,. h~ header, ~fsa:anfvacanf .. and vnscan f are equivalent [0. fs£canf~ acanf, and jaaoanfi, respectively, except that they have- a va_list parameter through 'which a variable argument list can be pas ed, Like the v .. ~p,rin,tf functions, each v~",.s,'c,anf func'{jon is designed to be called by a wrapper function (bat accepts a variable number of arguments. which it 'then 'P"a.$.ses tn 'tbt!v ",-", .. 8 c anf function. The wrapper function is responsible for calling va_,s'bart prior to calling the v,"",,,s,canr tunc ion and for calling v·a.~,end after [hie v~~.;sc,an,f function reUJJFIl ~".

<st:,dlib jI' hs serves as I_I c tch-all fer functi ns that I lon' fit into any of the other he aders, The - unctions in < a, tid.l ib .. h:>, fall into eight grtrup'::

iii II II'

, Umel1.C conversion _ un, - no '

Pseudo-randr m sequ: nc ~ g _c neration function:

Memory-managemen functions Communication with the environment Searching and sorting uti ities

Inte,ger arithmetic func i . ns

Multib te/wide-character conv 'f~ 1 In un 'lion


We')] 10k ,It each group inurn wrtl1 thre _' exc ~ I' .~: ns. the emorj man gemem function' 'he mul tibytel - ~ d -chars _CLet C' ,n~_ I - . ion fune ti. __ -" and tht' mult b_ t,_l wide- tringcon en io I functh n ,~,

The memory-m nag I . nt functi .. n,. (ma,ll,€)c':- ca110c reallol€ and

fre'e)r permit a program to allo 031 a block of m'e mory and 'then later releasr it Of change it, ize, Chapter 17 d.-'· cribesall four U.DICbon· in s orne detail,

The multibyte/wide- haracter con ersi , function ali' U-" to

multibyte Icbaractler to a wide rC,har',_ ,'_- r Dr _ e- rersa Th. mul ib ,tel convers ion fu -'CtiOD" perform · ilar : ··-n· wide strings BI' b ~ -[ up' of fun ~ti ~n >, are I ·S ussed in'


'. 'Ill

double .a" ,Iof (Icanst char *np,tr); int at,oi (con,st cha r npltr);

long i~t atol (conat; cha: *nptr);

lcu:r1g io'ng int a,,-oll tCODs't ella ;t ~t );

dl:ouble strtcd (conat, cMar ' restrict lptr,

ha'r *. r,est~.J.c endpt r} ,

floiat :str~o, (canst ,cha.r e t i.at: npt:r,

ahas: *' rest i.at: len -!pt, j I

long double strtDld tconet: char iii" .re -t i t: nj:2tr, char Itlt' rest:.rict endptr);

long lnt s.trtol(c:o s_ Crlar' , €IS :r:ict npt ,

E:har"** tee J:iC1 endp z , int b- se) ,;

strtcd ;s1'r"ol strtoul

IGn,g long in' strtc)ll (e'o1l9't ella, :it ~~estrict npt , cbar ** xeecr ie endptx,

in b - . ,e) ;

'unsigned llong int sbrteul (

const; chax !It res,' ric' _, nptr,

I har ,''II: restriet_ndptr" int base);unS.igl:1ed' long long Ltit: t.rto '11 ( const char ,.. restr~ct npt: r

c,aar' ** re,strict e'n,dpt" in't base) i

Th . . functi ,. . f i r'lI...,

,I' Dllm:·'D,c'ouve·JI 108 ,- ']1(;;'(10'1}, olr "",trto,g I_'I nVlersJO]l functio ", I .... UJII_y Ie

,<D WDI in . 89) con, rt trill','" I containin numb- - in chan cte r t their

,'quiV~]cc-Dt numeric v lues, Three . ' thes i func ions are fairh old, another three were a d d wh D the C8,9 land f' WI' . [I 11'[ d and 'e m, re were added in C99.

AU the numeric 1(:', '. ersie n functieas-e-whe her new' lor old-woe _ in mu .,h,

he same W3_'. Ea h nc ion remp to eon en stria 'p ',in' ed 101 I' ,- the nptr param ter) to a number, Each function skip whkte-spa· ~ ehara ,t ·r" at rbe beginRing 0 th string, ~ 'I .. ub equent chara ter . I p,_ rto numb -, I (p~' :,-"" ~y' ezin-

ning t . itb ',~ plus I r mime .ign " and ".,' 'P'!l a'l the' -', char. ter Itb:_ r I~ an t be pan of tb numb, r~ In addition caleb functl n n tur.ns Z'_.. if no conver 'lion can b per-

I mned 'the . tring i, . mpty r the i haracte I 'D,O'-- in· any initi I bite ace don -l have the form the function is looking for),

Tb- old function ' I atof ,atoi and aco l.) I,'. - vert a string to a doub.l.e.

Lrrt., or long int alue, r espec ively .. Unfortunately these funetic ns lack lally ul'ay t stndicat .... how lllCh f ,I strina "5,1'_' msumed during '. I_ onven ion, -~f'eI ver, th .,' functions ba-' ~ n~I".~Y t. indicat - that ,~ con - rsi n was unsuccei ful, (Some implementation of'tbese function may mdify tb - errno variable '. hen it c over ion fails but that .. no' guaranteed.

T~be.:89 functions ts'tr'to',d" et,rtol and ,s,trtoul) ale more 'Sopbi'Jt'I' C,·,' I:,d. ~, r one thing" tb ". indi - ate where the conversion stop '.' b ,_. "~_ lOll1l the variable that andpt.r points to. (Th :, cond argument clan . e I . null pain e.r if

w, re nol intere ted in ,b_ r _ the ion ersion C de I.) 10 I h ; beth r a func ., _

wa·[ abJ . to c .. n"·Dme t.1 e entire ,.'. "g-, we can jns ... stwhelher _ .. '. variable points te a null ch . . c er, If DIO CO'D', ersion coul be performed the vsriabl th t endpt.z' points 1," i . given be la]u,e I n,ptr (a~' I long a endpt.z isn r a DU]] P inter), 'What"s more, s,t,!;tol and at rr.ou'l bav . a blase argument that specifie 'I th-

- .. e 0'" tbe number b ing . onverted .. AU base b-1I1 " an 13,6 (inclu i e are , upported,

B,.",!-' e ing mor-e versa tile than ' .old functions, strtod, ,strt,ol" and

strtoul ar . better a die acting, :[tQE<. E_, ch function tors ERAN'GE in errno if a conversion produce a valuelJ]" t' outsid 'the range 0" the fUDe' ~.OD, return

Y,P '" dditir In, I strtod unctir [I returns plus or mimu lfC'GB VALI=, the

,0;:: 1 imi t.s . h:>' mI1CI'OS ~.2:3~2 atoll s,frtof s,t;rtald'

strtall Si"rtoull

at,r'tol and at.zt.ou.I functions return the smallest or largest values of 'heir respective 1"ClLU'Jl] ~1pl_~. I, strto~ returns either LON(~=MIN or LONG=MA!C~ and strt!t),ul returns ULONG, MAX.)


C99 add.. the ,at,oIL, strt'o,f1 str'told, s'trtoll, and ,st,rt,oull

function ~ a to 11 [, the arne a [be a t'o,l foo,cti{)'fJ',. except thar i'L convert a string to a Lonq long int value, at rt.of and strtol,d are the same as Ertr't'QldL, exe p'r that th~y CID')lVtS'rt a string to' a float '0_ lo,ng ,deiJble, v;a]Uie I re pective ~y. S, It r. toll is the ~. arne as s tr t,ol except that it converts a string tID at Lonq long int value. strtoull i the same ,a~ str·toulll except that it converts It string 1'0 a1:1 unsigned long long' Lnt; value, IC'99 alSIO m ...... ·." ,,,_, small change to [be floating-point numeric onversioa functionsrthe ' rring passed ito s.trtod (as well as lt~ Ill, weer COUS~J1g strt,of and s,trtold Jllay contain a he tadeolmal floating-point number, Lnfini'ty~ or NaN",

'The following program convert I: '. tring to nnme rile arm by applymg each of the six numeric conversion functions that exist 1:11 C:8lg,. After calling tbe ,st"L'to,d" strtol; and ,s,trto'ul funetio - e; the program also bows whether each eonver-

·,i,on produced a valid ric ult and whether it 'was able to eonsume the entire string.

The progrEtm abtai'[ls the inpuf string from the command line"

# incl ude <,e:r'~no, ~ h»

" i~,clude cstdio,., 11~

#i.nclu,d.e' '<stdli,b" h»

p,rintf (II "19 %,S\11.IIII•

errno ! = E:RARGE ? II Yes, '1'1:, I~~,NIO

;t'ptr =,::= "\ tJ t ? IIlR ¥es ~i' :: UN~ mi "

i"nt mai.n (i.nt ,dll:gC, char *argv [] ~I


cha.r '*p t r i'

if ( ar'gc 1 ~ :a) {

prirrtf ( llu8~a'ge: tnID1W,convst.ring\n}II)I; Ii!:xi_'t (EXIT_FAIL'ORE:) ,~


print-t ( II :FunctiDn

, t--:,J!:' II'

p,r:lnl,,;,.;·_L ~ --- =-=~-

p,rintf' ( lIIat.of

. . tf t III -~, •

plr~.n \ . a"L,.IOl.,

pri.nt'f ( III a,tol

R'e;turn Value\n'~I) ;' === - _-- _-=-- \n ~~I ), ;

%9\D Ii " atolf' (argv [11 ), '} ;

Q ·d\···· II . . i, .'. [1]' ) '\

'6 ··.,n ,~ aito1 ~argv. ~ ;'

%ld\n\n II" atol (argv [1.] )I} ;

print·f ("Func,tion R,e'turn Value

'''String Cons,umed'?\nll

V- -:I, 11.' d' -. II?

.~, II .. ,..'.!!,

!I~I - - - - - ~ - '""'"


erma - 0, print:f ( tm str.t,cIO CHK_VAL'ID;

er'rno :' 0; print:1: !( 1Ls,tr'tol


e Y'''iF'r''iI r'iIo.- - 10'

£, ..... .Ji-"'~ ,_ . ~

p,r,'in,t-f r Ils,t:rtoul CHI(, "VALrID ,f


[f 300000liQIOOO is the command-line argument, the output of the program might have the following appearance:


Rettl_rn ValulC!

atof atoi atol

3e+09 ~'14'?A c,_]lt':.:11 '7-

'" ',' ~,~ ,ID~ ,

F t' I unc' a.on

Return Value

_B'trtcd stx'boJl ertr"toul

3@+'D91 214748364'7 3100,000010100

Ye;s No YI~,s

Yes Yes Yes

On many machines, the number -000000000 i~ too large to represent as ;211 1_0101 in'LegerJ although it's valid as an unsigned JO,[]I,g integer, Til ' ,a.ted~ and ,a, col functiODII-' had no 'way 0 indicate that the number repr 'sente,d by their argument was out of range, In the output Sh,OWD, rh returned l4'148 _',I '47 th elarge t long integer l, but 'the C standard deesn'tguarantee this b ehavi or. The strt,ou-l funetion performed the eonver sion eorrectl y:, s, t r·t'oll returned 214 7 ~ .8,316 : 7 ('[he standard requires It '£Q return the largest long in1Ieg,_ r) and stored ERANiGE- in ,errnlQI.

If 1,23 " 456 i,- the command-line argument, the output -wiU be


t · ,a~ 01

at.o l

123 . ,1-5,16 12]



Return Value

V l"d-? a 1. ,.

S"tz;:in,g Cdns.um~,d?

~trt.cd ertrt'c,l et:,rl:oul

12l .. 4,516 123


Y@U3 Yes: 'Yles

Yes Nel


_ n six function reared thi . smna as a i ,aU,d number 4Jth, ug th the inteser 1\1'1]'_'-


tion ,- toppe I It tb d __ imal ,in. e'9 rt:oll ' __ - d st,rt_oul '

able to indicate that th y didn "1, m_- let ;_,.I_ _ ~:D some tho string,

I ro'o is the command-liae argum _ n 15 th 'DD u will ' ,


t I a! OJ.


o 0,


Function Return Value

srt ted 0

etrtol '0

str oul 10

Ye,g Y,es 'I,ea

No 'No


~ ll the f In~'tion' l oked ,at th l uter _ and immediately r -turned ~ ern. I "he stro.

"~ -_I, ti ,0' I dido '- hang ,BrID,e but ' ,,' I," _ tell th t Db "nt, r,_ m

til ~ f,Olel th,i;1!t the fODICti'DD: didn t CDiD ,,orne th _ string,

, ~ III

I U -, C __ 'IIIl_...., __ JIIJ

int rand (v.eid) ;

ve i.d srand (,un,si I' ',e,d _.

Th' ran,d and ,9rand _ unction Pi o,,~ th _ I_' D[ '_ r _ti 'n I ,,-' pseu m nnm-

bers. These fun nons are u'" ul in Jm1Jt tl 0 progra l and g,_ -L_ -pl :ying PJl - gram ' (_,~ .- imul .~, a d lc - [On or the d _ aI in' I rd game, for 11.- 'pl· , ~

rand Bach ne i,~ , I;_ '_Dd rand return a r. iberbetween 10 an' RAND t4AX a

macro defined in <:stldlib .h,».' ae [JUDi ers return d by rand aren ' actuall_

rl~~n lerm f I-Y re-' n: r 1- ' fr m -a L -,:- - valu . ., " ubi ': ' ,~,e( b ,'Ie er-

rand appe[aI, I ' 0 produ .' ~ ,an nor lated _que'Il-!Ie et n umber . ,.

sra- dI ICal1i:-Jg s'rantt, U:PI . "",_ the " - .' alu ' J1' , zand, 1 rand is ialle I prior _

s rand, th, [V ' ue i 'I fl' umed t . be 1,,[1, h seed val -'. d:_'I!, rmines . p~ _.1 ieul

[.equence pseudo-rand £'_ nU.Rlb 'I::' ~ srand allow '0-, to .' ·11(:,'1 whi h _ .'. ,';_ lIL' _'

" [ant

A pr gram that alwa:ys uses the same ' "I,d value wi]] ,alw'_y~1 get the same se uene 0 number frl __ zarid, Thi 'I"operty can sometimes b use 1l1:1 e nn. -, m behai fl,' the' m way" ,11 time it .... run.. - .ing testing ea ier, However we 'LLs,ually '_ ant r'and [0 .pr du " a diffi rent - quenee e .' b ' ime th, - pr 'gram is, run.

A po·. -playin pr gr am - ,I wa' .deal the sam- ,.ard i '[0 [ likely I. '--, popu-

til!n\E! ~lInctiQn "28,,3 1,1.) The easiest way tiC 'randomize I' the see values i 0 call W, time funeti n

'hl-h returns - numbe '1 me d, .the . urrent __ te end bID P" ins t.ime·

(I ' arn value to ,Brand make I .]7 behavior of rand ,Dry from one run to the ne I. ',e the '9uessc lan, 'guess2 ii cpr_gram I S __ tion 1. ii_ I [0' examples 0 this te·· -bn--qu e.


-'-·'1 -,_'.'

," .' -'

'-The. "'. - t- dl- _J! b- '1-. ,Uea",#iI'--: ~ .. , G"-_::__e'-'~I~"!lI1 Utii',i.' .. ~:aIS"· ,tie <:8' -'-_:_' .2 " ~ n> nl~.,(, ,LI'S" ,i ' ". ·,n'Eiro .jl!l!fd~~,

The fD!11Iowi_ng, program rlis:p'~~ay,sl he firs fi, e values returned by dllC rand funetion, then allows the user 'to, choose a new seed value, The process repe at , until the user enters zero as the I seed,

i inC!l ude ~,S tdilO, ,. h> '# Lne.Lude <; s l:dl ih . h >,

in t mil in (voi"d)1


Lnt; i g,eed. '~

--- - , - - ,

p'ri.nt,f (~~Thie prolgram 1d[,isplays thle first f:iv"12 v'alues of U

n xand. \IlI111) f'

f,or It; ") {

fer (i ~ 0; i < 5: i++)

:printf- ( II!I i'd, J~" ran'd, ( ) J ,;

printf ( u \n\n'1i )1 I

p,rin.-tf (IIIE,nte~r n,19W seed value (0 to, termina - el ; aoanf I( II %·d ~~" ,-seed) t'

if (seed == 0':

br1eak;: ,srand ,( seed,) ;

'11)1 ..



Tbi,sJ p,r,cgram di:sp,la;ys 'the fir,s't five valu,es of zand, 1:8042'89'383 B4H;91308:9' 1,681692'117 17146369,15 1~H;?I""93i

En'ter Qle'w seed v,al ue (0, tOI t.ernuna t Ie l : 1010 61'1741240 611.'911301 S161Ei,B7479 lO'3SUi531,S84 801009'ISSIS

Ente,r ns'w;' see:d v,alul~ (0 to t:.ermin,a,tAe:') ~ 1

1804289383 946930$B6 1611692777 1714636915 1!5?747793

There are many w_'y:s to write the ,ran,rj function SDI there's DO guarentee ilia every version of rand will generate the number shown here, Note' Jma:l ehoo ,i:o,l 1 ns the I eed give '- the same sequenc , of numbers as not specifying 'die seed lIt all,

void an,art (void) ;

.int, at·eJri t_ (void (,w f:une) (void) " ;

va'd exit~2nt eta us) I va'd' EKit (inc SEa us);

chaz *get,env (canst char wnamIB);' in system (c>ens' C! .ar *'8· ring) ;

The functions ln this ,if up provid a ~nmp] inti rface 0 the op ratinz ~ ,-' tem, ,'- 0, ring program .fo I, t· rrnin re -; h r no In ~ U_, _r'~ li:[J,rm" llv, a d return I I, It 'w- code' to the 0P' T ting . _" te '_' ~ (.1 r [, 11 in~ ,rmati-In r. I ,m '" ' ll, r C., ment, and 13 execute Pi rating Y 'Item ·onlm,and',;,~ On' f the functions _..Exit~

i a I d ilion.

endt Perle rming th ',ull,exi t (' u), II wh r _ in program i n rmal ly e, Diva1'e~fi'~

ti th ~ .. th' ii' ~ t d n I

, ex ',111 uig tr ,- ternent ~e :.urn n i' 1111 ma i.n: "-I' pr gram termmates, n u u

G 'ift ret rod the op ,ratin,_g ry t m ,ru raru I" I. <stdlib, ~ h> lef --I ihe mae-

to's EXIT FA-LURE and EXIT' SU(!CES,9 hieh c~ n be used sarsurnent to


exi t, 'TIt .onl ath r . ' rt ... ,,01 ". . ument to ex.i, t' 0, ,- h i -h has the s ,- .' m 'rut-

ing ~- EXIT_S,UCCE:SS R turning tatus ther w __ n J ',I' • l,,'c J nu n- 't n.cc1e':. ,ari1- - p rtable to. aU op . rating , ystems,

ate,x,n " - _Ilt ' pr gr m t, rmiaate , it u IU 11,,' pet ~ - I". ro. I . _.Ie' . on ," b _ HInd th .

, rene in_'lu' tog nu hingI mtput buffer that', I nlain unwritt n data, ']o,ing- 'I' n tream : '" and ',1.',- ti 11,8' :- rnporary til, W-' Inay have amy. Ci '(~'L an-up" ac lin rh t " d lik a program t - rf mn ;al terminati ' . Tb a.texi t fu ; ion ~ ll,· - U, t "register". ., " ti '11 to ne c~ lIe,' upon pr gram .ermin io'n. 1i I regist -r'r a fun, lion om" cleanup, for e .ample - e -Iou_),d c U at exd.t; 3.; follov s:

at exd t (c l.eanup] ;


hen pas " fun ti n pointer 1(10 a ~ E!.xitcll h sn re tll ' I I inter ,"Iway for funm

refe I. DC,~ "_he prog m 1 ,~ r tl, rrnin normallv ( ia a c _II I, f ex.Lt; or a return:tat'em~nt in 111_ main funcnont, any function registered with atexit

"ill b - called autornt · _ ally. (If [- r m n ~ n nion ". bJI '. -'-, n regL tere -t th '_ · c

_ aIl~d in the r~ 1",,' 0 "the order in ' . hi h Irhl'_' I, regi - tered, I

The Exit Iune i" ,'0 Is slmilar to exit" - u.. vet Exi t doe n t call rundon - lb~ l hav been r obi I, r, d v llh at exd t, 11 r d s it c U ~ ny ignal handl -F,' pI'1 i - u 1,- passed ro the signal 00' i i Is Exi t noe - rr t nee ssarilv fh h outpu buffer" clo e open ream ,r I, lete temp rary ill .. ~whether thee

cti . 'Dr P __ - orme d 'j lrnple 'ID, ,nbll]I' n-defin ' .

abort is - j -: imilar t exit,ut I, ~ 1 "11'_ it causes abnormal pr)1 ram ~ rmi-

nation.. unc ions registered ith a.t exi t air en't called, Depending n the implement ation i rn y b· h. c . e 1I1al, U U - UI·'· rs containing un ritt n da IJ ~ _ . 'R'''t flushed, trearns aren't 1~1- )~",' nd temp lEary file~ ~ ~ -n tid let tl abort re W1', an implem -nltUilJl=de ned: t 'rtu: cod irrdi [B11n,g unsuec ~ ful termin rion.

'1'"81 inc . - [ tn> provic e 'I 1 • en / I'lrun n, : . I set of ~ b~

describe 'the u, r' I chara or" ris/ "1:' These . trin ., typi,t:';' J~y ln' lDd - ~h p'_ th r be

ea ~, hed whenth user runs .program, th,- tye of the u r' terminal (in the ' a--

I r 11_ multi-u - t'· tern and s, I n~ F r rnple _ "h -th, - izht l _1_

... - gle'tenv

PATH= lusr/lcc!al/bJin ,~, Ihin .' /u,s,r Ibin; .

n . onment, ': fin th


char *p ~ ge I env ( U PATH'I") i

I 0, point I the string U Iller /l,ocal/bin: Iba.B ~ /usr/,bi.n.: .. II. e C',Ir'fuJ with getenv: it·tum', a pointer Ito a staricail ,_U c ed string thai may h chang d l a 1 t r can (If the f nr ti D.

·system The ISly,stem function 110 ro __ '.__ I 0 . un an nber p l,gTtaD1 (pos 'ihJ.

an operating system C' rnmand). The argumen to. ,system is " string containing ~1 c'mmeln,l ,1" ,11- . . ne tb, t we' l enter ~ I the I' _., ating ", ste ] _' "mp~, nr example ,uppo' that -. e fie WT]tiug a pro. "am, tb, r need, a lu mg of th file in

th. current dire '_Iry~ _' __ . '. III L all syste'm m th . follot ingw '~f:

hi. all in 01' the UN' . I ommand 1 S "0.1' [0 rite ,. Jr in . th . ur-

r·, _ ''1 direc 011' m!. the file n,: m d myfiles~

te return ."_ UJ' '_' sys'telTl j, implement Itl n-d fin d. syste'm . p" all-

return tbe termination status c' Idle from the program tb,at we a 'ked it to IUD:; It ',1-

ing 'tins v due allow tl,·, '~O C I ~ he her Ie,. 'ram --1(_ '"I pr ., . ',. " I. .:. "11 i D'

ays tern with ," I null p. inc r a '. -'. ja,1 me ming: the function returns ,~ non' ro

v lue ·f '~, comme n pl' ser ~, .avail: b~ .,

vo.i.d *bae rr'ch tccns vo'id *key" cons

I t rob 'i t I

,B1 Z'B nmernr f S ltZ2', 61. z.e ~'

- . ~

int ('COMpa r) {eflnst of

cons vodd

o Ld

* a,se"


vo:id qs 'rt (void ""base f s ise t nmemb , sizff!_ size,

am (*c,om ar)' (const vlo~d 'I, Icons I void 1t')) ;

bseareh Tb bsear'ch -, notion .' archei a· rt d . iT _ for' particular Wb -nD,sear·ch i'" Icall ~.d tlll,_ k,ey parameter pain, l the kev, base p ints to the arrav nmemb i the numb [I{ "elements in the : , YI size i the size t eaeh ele-

mnt (in b~ tes), ' II!. compar i· a.~ inter lJ . is n fun,' tioa, Th mpari-

,f.. 'II " • '[1 ~"II ... , _I d' ;I- ']I,." d oni ,L

0[1 run ti In 1" rOO] ar to me '. me requir ,- q,sorD': wn . n pa ',' -'. pmnt 'rs to tn"

and ,_I .ay element (in th, n erder) the uncti '0 mus . renu ,eg '[J,' ~-" ~ r.,

Of positi .' integer depending O'U wi e'1 :r the key is I ess than equal 'to, or greater

than the arrai el menr, bse,arch re urn inter ' '. an Jement that m~ tche the

- -

k y~:, . _ it doesn't find a match, b,EU!!'arc-b . r _-' rns null po~nt. r.

Alth 1b1gb tho Ctan : I_d doesn t reqair it to oeu!,src'h normall u e tb binary search gorithm '0 search the arn _ 'j; bs,earch ill I' compare !I, th I -y -:- ith the ·l~'men.t in rbe middle I . f 'til C. alra.·. :;, if there I a match, the fun tiOIB r turns, IT lhe key is smallertlu IU" middle element bSlearch Iimirs L '.'-' ch , 'befit hal f of [be ~ ~ _ loY" if the , . ,'I is 1 ".- g,er~ b,s e arc'h .. earches only th lasthalf of tb

arrav, bSlearch rene ~. 'h" egy until it I,d,. th ke~ I. = run u,- of elemenn

to " earch, h. . '. -0 'this t chnique -. baea.rch i, quite _1-t---e,Mchin,g an, array f

1'00. elem nt Fe_ ui " . n1y 10 '. mparis ··ID. I • " m' '. rching an . _. I a- I f

,OO!;I D element requires no mer tb.' G cotnpari ons,

qsort Secti n 1'7.7 discuss _- 111 q;sloxot fun tion 'whicb can ~,' r1' any am _ ~

hsearchnl 3, but '_ ean _ w' y~ use qao rn.t

am Y P ior to ~. king bs aaz ch ~ .. , search it.

OUf next program omputei the air mile ge tre rn e '-'or· City to vari U··, inter-

~ .... 1 ,".' TI first asl .'L ter a citv nam th ·AI ~ - .~A

n:aUIODw cmes, _ le program st a .'<, me usert .' en !er a c rty' name, '. en ~PM

th . ~ mileage . that .. it)';,:

Enter ci ty' name: Sh,anghai

Shanghai is 7371 m11129 f_~',om New Y,ork ~ity.,

.. pro - ~ml1 will ':]l '-i ly/mile' ~ g- p '. , " r . arri 'yo Bv usiu

I' earch the ,array for a ci _ name the prngn m c 1- sily nd th mileage ~ (Mileag are fro ,. J"rJDpl>a e. om.

bscarch 10 >- respondin

#in,clud.e ,~stdio~, h~ #'i:nlc'lu,d:e <,Bt,ldli,b .. h> #i,nci ud.l€ -e string .. h>

stru,c·t IC!ity_' info {, char *ci'ty;

int miles;'

) ;

in '~ comp ~ re ~ ci, t i ea (cons t vof, d*' key _pt:r' ~ canst vod.d *element_ptr)';:

int main (volid)


char city name[B~] i


,Ert:ru.ct ci,ty_infc *p't-r;

conat; at.ruct; ,city' '-nfo milleag'E! I[] ~

{ (1'Berlin II, ~ ·965), {'~B:uenos ,Aires·l,.

( tr Cairo, U , 5601,2 } lI( {I~ Cal cut.t.a In. II

{ II Cape Tawnu• '77'Ei,4}, {ulcaracas U j

[ II' Chi caqo it , 713 } ~ {"I H'Q,ng Kong ill ~'

{ II'H,QDolulull " 9,64}, {I~ I,s'tanbul ~I ,~

5297} I 7,·:918} , 2~32} ,

80514J " 49'75} ,I

sbs labs


.( ~IILi9blon'll t

( ~~ Los Arlgeles ~~ j {~~MJ!!xico' City~l! ~ { ii~MClSOOWII'.,

{1~Riol d@ Janel'rolfl, r mm San ,Franci B'C.a n ~

{ I1II S tOlckhol m'~ "

{ ~~ Tok.yo u ~

{ I1II tifa-s h"ingtloI], III' ,t

3364}, {" Londonu ~' 2451} I {nM'.anil,a,u i

~2 0 94 I. {II! :["\'hi~)ntrealll ,

41665} I {III Pari,s III ,I'

4B17} ~ {~~Rlomeu ~

2,5 '11 } I' {~~ Sha,ngrh,a. i U ,

392,4,}~, ,{ III S'ydn,ey'~ , &1401 },' ,(: ~~'W'lars,awH ,~

20IS}] ;

34 58:~' " B4 '5'13 ~, " 3210 l ~' lfi2i&} ~ 42Bl~

! ,r

13,7.1} ,

9933} f' 4,),44 J '

pri·ntf "'~',Ent:e:r ,[!_i-ey namee lili); soanf I( II ,g,O ![~ \n]1 II I city ~na'me) ;

pltr .;;;;; bsearch ('Cit:Y_D!ame', mileag'e,

sizeof (mil.,'e,agle) I ,s;,iz,eof I(mfle"a,ge [Qi'] " r B,izecf CmiJlLeag,e [0]: ') " It::ompar'G ,ei tiles:) ;


if (pt.r ! = NULLI ')I

.printf (1lllls i.s ,td miles fro,m Ne/w 'Ylor'k C,ity~ \nlt, city name, pltr-~'mile5');


prin~t..f ( ~. %:s, wasm n t. found '. \:1'1 U j ~i ty n,ame;'), :



int l[!oJmpare~cilt.ie:s (eonst void ·kiey~·'tr f) canst void *elelm.'en,t~t:r)



r'eturn strcmp (' (char'it) key pt.r,

~ ~-

((S"t.t!U,ct, c~ity~i.nflo .') 'B1en'tH~n!I'·_p'l:.rll -,city} ;

imt abs(int j);

ille..ng int labs I{ long int j);

long long int 11abs (long. liang int jJ';

di y. t di v I( i:nt nurne r- int denom):

Idiv~t Idtv(lonq tnt numez I lon,g int: denomr • 12div t ~ldivtleng long in~ nl1me~",

long long int denom},..

'The abs funetion returns 'the i _ bsolute v,alu,c of an Lnt, value'; the Labs runctilon returns the absolute value of a long' int value,

The di v function dividesl its nrstargument by it" second, eturning a di 11 t value, div_t is, a structure 'that contains both a quotient memb r (named quat) and a remainder member (rle'm)", Fair example, if' ana is 11 di V t v,ari,8bme,~ . e could write

ana == di v ( 5 II ,;2);

prilut f ( I!'I Qqc:rtilent: \·d R;emain,aer~: %d\n ~J~, ana ~ Q?U~OI't~. €Ins ~ r'emJ ,~




. _ Die ]-.1 Member~, of the t en: Structure

The Ldiv function is similar but works, with long i ntegers: i' returns an ldi v~ t structure which also has quot; lind l!,em'menlber ~ (Tbe rd.i v_t ad Ld.i v ~ t types are-declared in <:stdlib ""h~.)

C'9Y provides two additi ·In.,a~ function, , The Ll.aba function return the abso ...

lute value of a long lon.g m·t value. Ildi v is I irnilmr to d,i v and ldi Vi exc pt that it divides two' long long int values and returns ,a,1ll 11d.iv~'t structure. '(TI1,e ll,di v~·t type was als . added in e99 .. )

The e t Lme .. .h» headier provide>: functions for determining the time (including the date)", 'peTfornliog arithmetic on time values and fomn Hi- g time for d'· play" Before 'w, .' explore these function 1 however, we' need to discusi ho:w times are stored, <time" h> provides three types, each of which represent a different way to store 3, time:

I. cLook t.: lA, time value measured in "elock ricks"

• time=t:: A- compact, encoded llm,f! fmd datal: (a celendar ,.~'Dile).

• fft rue t t'Hl: A ti me that has been dJvi llled lnte seconds, minutes, hours, and so onto A value of type ,struet cm i often called a hro,keN'~ld(Jlwn time. Ta -,ie .26.1 sbow,S the members. Qf the tm structure. AU members arc 0"( type in:t .

MilJ:ilDNnl "blue'

Mrali'lI.uft '.D-l,'l'e

't.m, sec Seconds m~er the minute 0

'tulmin MiDules after the heur 0

tm hour Hours since midnight 0

tm~mday D'IY 0_ the rnomh l

"t m, mon .Mcu:nh. .since J anuary 0


't'm_. year Years since t9rJO 0

tm_wday D'I)'I$ since Sunday 0 ,6

tm~yd!ay D'a)" since January I 0 365

tm i·edat D,a.~ light S,avmng -_ [me fi,a, ~t- oft

t . ll01\\I' '~or [WO extra '~"I'~',3pi seconds, r In C99, the mmmum value is 6n. ttpo j live it D,ay Ii gb L S~ryin:t Time is i 1m] I~ rf~l:'l~ .Z ero if H~ ", net in effee t, and neg;il:tiy.c if this ~nformaWinL1 is wnklu'lwll1J.

5'9 23 31 Il

These types are used lor different pUlllo'se !' A c.l,olck_t value is good IOlnJ;y' for representing a time duration; time~ t and- at ruct; em ealues IC·· [] '. 'tore' an entire date and ime. tim,e_t V8~l1eS are fghtly encoded" I. ,0 [he,Y occupy liuJe space s t .rue t t m. values req ulre much more space, cut they r-e often easier to worl with, The C standard states that c Lock t and time t must be "arithmetic types," but leaves it ,at that. We: don'te en knuw if clo"ck_·t and ti,m,e_t value, are stored as integers or floating-point numbers,

We re now ready to look at the 'functions in -ct; ime' ,.' h>~ which fall into two groups: ti me Ina nipulatioa functions and time ,(:0.0;- en;iun functiona,

clock t clock'uo~d);

double a,i I ft ime ('tJ:ID,e ' timel, time t mkt ·mletstruct tm 1< Lmep ti'rn. t tim - (, .frne t; *tLme~),

t "timeO);


clock The c Lock fun ti 'n return ,cl,o,ck t - alu repr entin he proc ssor ti - e used by the program ince execution e nn. ro 1 onvert this alue to econds, we an di ide it :y CLIO'CKS_P'ER_jSEIC:~ In iero 1 lefined in time ~ h>~

, hen c Lock iL u' ~ l'u determin ho· I H' OJ P 'ogr ,- - '8 b - en running, it\

I 'US'OlllJI to call it twice: I DC' at the --eJnnin.g of main' ,d once ju t bef I-e the Pi -( '. c., - 111 terrninates :

#.inC!lude 'cat,dio"h> #:include ct:lme .. h>

ill" maa.n I{void),


clock :~ star't_clock ~ clock () ;

p'rintf ( ~ Pro'ceSBor -time used ~ ;-·9 Bec .. \n II •

(c'lock() - start~clo,c,k) I (double) ICLOCKS PER_SE,C);' r~turn 10;


Th-' [I . r th ini ial call ,~clock i th __ th - p:t tJ - ,ill u _ :. ,me pel. I' -

.re It rea 'he. main- [h - n , •. 0 hidden t'start-up C c' "de" . ruling c l.ock

[at t1 lei _ c ;<'11 ning of rna In " II _ 1111 in. ho 10 h tim th

b t we can subtra ~t it ], ' , ~

Th [ .'. standard a, s only th r c lac: k~t i ", an an th metl C:' t ~ e: th ' . _ -p 0

(~LOC'KS,_PBR~SEe is unspec ~ -i,-' I result the f ie of 1I ", ,j"., -

me '. ary from one i rnplem 'nt.': ti n 0 ,a'nother~ making it 1 ifficnlt t· I ispla usin g

p r i nt£. 110 ,,1- ·'e 111 pr 1 m.vour example . - rt CLIO(~KSi PER SE C "I.

eg, doub l e forcina Lh! mire -r' ,jl ,n "t . ha e r' pe doub.Le In ". '. 'I· I the rp of

CLOCIK ' ...... PER _ S E C i M, speei Led " be clock t .. but c 1 0 ck_ t i , '[ill an imple-

- . . ," ,,... 1 -

m· 'ot ·n-. I • nl ·'e,.

tlilme The time, func "on r turns the current _"al mdar time,

ulI p inl-el., itim.e also store U:- cale ndar time in the '11

poin I~ '. F ,'_ im,e' a -lint L - tun ,~I time in t - t

quirk, but it ive co I "; tb\ plion of . ritin . : dther

t fme (L.cu,r_t!me) "

wher cu,r_time i vari bl of typ imls:__t ..

d~tftim,e' The di f f ti me unction r tar, th - di ,f~ renee ~ erween I: i me 0 (tbl . "ai~ II':_ r

tim t and t.dmea measured inseconda Thus.te compute tln ctual running tim of _ program (n.1 t the processor tinu ') w' could o.e th follo ing code':

tinclude <std10.h~ #,include <·time ilh>

in - 'main, (v,oid)


t~me' t start_time == time [NOLL) i

pzL nt; f ( II Runn :l.ng time: %9 sec" \n ~~ , diffti'me (ti'me (NULL)" start t me)l) ~ return 0;'


mktlrne I 'e mkt im,9 uncti 'M en .' u a brok D ... do D time .ll. 'red iu the. I., uetun

that it, argumen p,in£. t ,int _ c_ Jend, -tim .. which it then returm . etr '-~ mkn i.me 2_cUU ts the member f th tructu - I" OC" ,Iridin, '10 the follo- in rules:

I. mkt ime chan e any mernbe ho " . rn l -- ithin their legs

. ee 'Tab,le 26, J). These alterations may in tum rec uire change . 0 other mern ... bei ,.lftm_. sec l' t 1- -g for example, mkt:Lme r: duces i '·0 th proper rangr (0-591), ad . 't; Ih· e IT,a mtnutesto tm~min~ tm mi,n i, n -\ ~

large mkt I' me re'i ue it no add th exrra nour tn i m hour, I~ -_~ ~:L·· 1:-

tb: pro es H1 1_ ontinue r "I th tm~mda'y" tm_mon., d m_year mem-

b .(S •

• , ter adju ring the 0 .be'fI1J· mber r the stru lUI III n ss "--J mktime

se s tm~w"da,y (d,a:y ofth. wI·-k) ani t.m _ylday' (day ofth arl to th 'ir,cor re -t VaiUIC. ~'ere I. n. :_ - ,aD Ile, -, I fJ initl Iize tb, values O"' tm ........ wday . m tm_yday before calling, mkt Lme: it ignores tb original values of ~bc·,e members,

mkt ama's abiJity IJ· I adjust the memb (I: of a tm structure makes it u eful for rime-relate arirhrn tile A_', xarnpl let ',- us mktime l' " ns'c- ~r I he followi . question: 1 the ~ .. l-, Iympie begin on July .17 and end J,6· I ,S later, wb t i' rth ending da J J1' W. Ill .. " ~I~ "'Ioring July' 7c 201.;. in a t.m structure:

I " m mda)(' ~ 27;'

t. em m~,""'" :' ~.,

. .. II.... _.~. '~';';.I.I;,£, !elf

t" t;:m__Y'f!ar = 1.12;

/* ,July -1', I'~ ,2,012 ok I

, 'e 11 ' 1 o Initializ Ith - other member f the ~ trueture xcept ·tm wday and

tm _yd,ay) , 0 10'C ur . tha 1 h.ey d - n l am und fi d :,alu-~ I tb 1 . ul_ a c:

an rwer:

t.t:m aee = Q; t~tmmin := '0;

t, . tm_bour = 0, t.tm isds ; -1;

L. tm=.m.day += 16,~

. hat lea e. 4,_·· in m_md,ay which i·.· I .u rs -:' .. 1-· h': me ber, Callin c

mktime, will bring the membr r .. of 'the struerur ~ ack illt lb· dr proper r . g.e'· :

mktime' &t) ;

Wi-U discard mkt Lme I. rerum valu .,~, cinc€ 0 e're inter, . & . _, on] "." [he' functi Q_ "

",. ton t. Tbe elevant member o~t now ba:~ .. the 'UI alu ... s:

Me,nhel· t.m mday

- '

tm mon



tm_wda,y tm;__yd.ay

VallI,' j ,

l' ]12

o 224



12 August ~O L':' Sundae

. Sib day of the year

'lme COnveti~-.on I I uncti

char; asctime(cG.t struct tm* im ptr); char c im,e (CfDl1St time t *timer); struct_ m 'grrJ ime (sollat tim,e_ *1 imer) ;

stl:uct tm -localtime I{lmonst t.Lme II '* imer);

ad ae 't strfti me (.ch~.r 'll' rnetir i ot: a, size_t maxs:ize" conat; char res x i.et: forrna.t,

en t st ucc tm * restr.iGt . ime:ptr);

The time C.D rsion . nction m i possible tc 0'1". err calenc r time t _ brnk· a-down timet They can also COD ,'" times (cal ndar OL brok n ... down) 'rQ rring f rm, The following figure shows b '. thes , unction are related:


Calendar time

__ ""_,,.........-_~ BI'iOken ... dol' . n tims' trn

l,o(]a,l time

Th figure inelud th mktime _Unction -- hich the I standard classifi " ""', , rill' nipul lion fun tion rather than ~ "con er ion" unction,

The 9111ti.me lind Localt.Lme func~i' ·n'}, are similar, Wb n pas.· _d a poin er tJ',_, ," "I,eDI lar time ooth return a poi I er 1 I "l.tFUC' U r ~Qntainill_ til equiv I -1 ent broken-down ime, LocaLt ime p,rt JJ"' a L'~ I time- while 'gm,ti.me's return

value i, expire' ,I e', in UT - ,I,' ,'. ·1 ina _ niven al Fim J~ Th return valu of

gmtime ' nd Loca'lt.Lme point 01 a -,I" ticalh illocated struemre that may be changed by a later call of eith er funeri n.

Th aact.fme "'[I II tim) Iuncti ,n r turn: pt in er to, null-termine ed " tring of the :fO[I11

g:mtime Ilacalitimle

con uructed fr m 'h ' broken-de I ,',' n time oointed ~, it argum nr,

ciilmle The Cit ime fUD ti - n r tum" a p dnter t . a tring escribing a Jocal tim . If

cur tim'e l' a" ariable of" ty-- tim,e t" the c'all

- """""

c time· ( &cur_t ime )

asc,tim - (Loca Lt Ime (&cur_ti.me) ')1

The rerum value of aact.drae ruld ct.ime poln ,[ a sta ically alloe, bed string

that rna' be chan zed b I, t I .[ eith r fun·li' n

strtl:imle Til - strftime _;ounction,~ like the aact.Lme function, I,. n errs a broken n tim to.string form, nli e -as,ct:ime. hov _ ,.r, it . i ,e,"' IU, " gr' 1'1 eal '

spr:iro - rUnctiOlfilr.22.8 '. ntr ol over ho the tim' is orrna ed. In f et, strftime r_~ mble sprin. f

in that it writes charaeters int', a string S (the fut ,wrgUJD_·nt ace r in ,00 for-

mat strin ,- (til. third ar_ umn ~I. The orrn ' ',' io~ rna, c intain . rdinary 1, h rae ter (whi _ h are cepit d info s unchang - d) along, 'with the convers i011 specifier ,hO\V11 in . hi 26~2 (, 'bi >ch are re 1 1'. ce b_ tb ludic I·' strin L'" The 1-1' argument p int- to a t m strucuir - \ _ hich i U CI. as the .- urce ,1_" ldat, and time in " rrnation, The se ond ar ument i Ii limit on me number ,'f ch =3£'1'--,' that t an tored in s.


The strftime function- unlik the other fun tionsin <time ,. h~ is sen ,iti- -e to sec urrent loc M. ' hanging the' LC~ TIME, r ateg 1'-_' mav - ectthcbeh - 101" of the 1 onversion - peei fier:' .. The examples in Table 261.': are ,: tric ]31 ~ r tb,e n ell I icale: in t German l "- ~JI_ ~ the repl __ cement 1'1: I . %-A [ ." ghl e Die'n,sta,'g in tead of Tue:sday.

bl " 1_99· aadard spell 'I, ut the e ·~_·'Ict r plac ment urm s f r. mn . I" '" the I' I}ver Ion sp eiflei s in the II, C "m I 1I(8J, '. ,S,r.: didn t '0 inu • this l,f( ] of det iLJ, abl 26,.3 list the e I-on ersion ~p eifier and the tring they're replaced by'~

C al '0 adds lrJ number of strfti-m,e on I~r ~ on speei 'iers ': 1 TL_ble _, .

. hows, Ollie of the J~ on' for the ,ad f ti una I conv r " ion s cifiers is the desire to . uppo . the lS, ' ',,60 I standard,

" 1~lJble 2Ifi,;;2 Conversion Specifiers or the !B t ref t i mle-lL[(llctLon

%:a '~A, %b 'tB

~n UI:o,....

_ ,LI








%FT \';gt



CI. , ,

"S ltr

%j !k'M ~,M t,nt :\p

IA ' -t ·ij;'r


ID ,tt .~

~'Tt >-g I

%ut %0 %vt %\~.

%W tx %x %y %y ,:at


'g.. !,. -~ '!!ill

Abbreviated weekday name (16.8.,. S un) Ft1'U we1ekday nl,tlf1ne (e.g., IS1IDday, Abbrev iated month name (e,.g ... Jun) Full month narne (e'.g. June')

-ompleu~ day and time (e.g, Sun JUIJ J 1.'7; 48 :: 34 2007) Year di'fided by J 00 and U1LHlcIHed to an integer (,00-99)

'Day 'of month (101-31)

Equivalent to :%m/,ld/ %y.

Day of month (l~31J'; [I single digit l I preceded by tl . pace Eqnivaleru hO %Y = %m ~ %'d

Last LWI) digits 0-1 lS,Q 8160:L week-based year (000==99) E8,Q 860:1 ~. eek- be "led year

Eq Wvaicll,l LO %h

Hour' an 24"'ROIur clock ("0 DEE=2:3) Hour on ] 2,.._bour clock (0 1~ 12, DI:!y of ye-ar ,,0 01 1-3, 16 ti')

M,cJnth (Ol~121)

Minute I( 0 Cl- 591

New-line character

J\MIPM de "ignalor (AM: or PM)

112-hour clock Lime (e .g; (liS: 4: 8 ';: ]; 4 PM) Equlvalem 10 %B; iN

Sec ond (0 0,-6 1): max] mum value in C'99 is 60 Horizontal-tab character

E .~uiv',a],eJl to "M~' %'M : PaS

rSlo' '8,601 ,~'ee:kdi;ly It 1-71; Mnnday If\ ~

_ eek II umber (00-.5 ],); firsl Sunda)' 11 beginning 0 week 1 15,'0 86'01 week number (Ol~53J

',-ee'kday (O'_6)~ S ulnd~),y is 0

Week number (to 0-53): first Monda:y is be~i [11'111;0 ~ nf week 1 Complete date (e.g.-, 016/03/07)

Complete tlme (e.g., 17 :' 4 8· ~ 34)

Las t tWOI dtg it; o-f year" 10 a='" 51 9')


Offset from UTe lnIS,'Q860 l formal [e.g., - os~ (] or +0200) Time zone rUU11e or abbrevlatlon (,eO\,S,.~ ESI~I)



Table 2(i~J Replacement Strin,g-, ~~r 8/t rf time Conversion Specifiers in ~he' ~~ C 111m Locale

COlu~,e,rs;o" %a


",l:b %8 ,%·c

!lip %T

'x %X

!z." D~

R ' "1'1:; rl II"""t Firsl three characters nf tA

O'D~ f If ,Sunday 'II . II~ Monda:y II~ ' •• '.'. t, II~ Sa tur,day II

First three charn'CleJ 0_- %8

One of II' J"anuaryU, mil Fenrll,ary ~II ," ,. ,. ,. ~ II D'Bc,e,mhe,r III Equivalent to u t,a. ·~~b %e %T '%Y'!I

One of II JU4 1I1I Of 1IIIPMI111

Equivalent to It % I ':, ~:M ~ liS %'Pl f~

Equivalent to III %m/ %'dl %y II

Bquivalenr u IT


ISO 18801 lis an intsfrnatio,nal s andard that de:BcrlbIB'S way's, o"f reprleslB'nting dates and tlmes, It was o"riglinaUy' pubUshed in 198,8 land' later updated In ,20010 and: 200'4, ACQO,rdlng 'to thIs stan dard t dates and lilmes are elnt~re~y numeric {LIs. mlclnttls, are no represented by' name,s) and hours are '8!XprIBss,ed u9,ing he 24-t.lolur cllo'ck.

There' are a number cd ~SIOI 8601 date and t'ime forma,ts, seme ,of which ara dire~ctily supper ad Diy B tr£ t Lme ,co.nver:ston speciti:er.s in 'C,9:9~ The prjlmary 1,8:0 e5'01 date form?lt ('YYYY--MAt1-D'D) and this pnrnary !t~mle' format (,hh':m,m~:ss) corre,slPc,nd '0 the %PL and iT c,onversi'Olnl specifi,IS'.rs,; r'Bsjpec1ti'vellYi

11910 ,86011 has a sys;tem, of Inum,beri,ngl the, weeks, ,of a yelar; this systeml is sup"" po,rted b'y th!e %'gl %G~ and tV c'onV'erslon spec:ifi1ers,. W'es'ks beg]n on Mloln __ 'r"~ anld we's,k 1 is the week Icantailning he first Thursd,ay of the yS8t C'lonsequerrtI1y! 'the fir.st few Ica,ys 'of Jlanuary (as many aSI three'), m'ay cs'ong tOI 'I:he last week olf the pr,Bvious y'ear. Fo,r e')("a,mpl,e. consider ths calendar 'fot Ja,nuary ,2011 :

Il -UB

2 ]0 20111 2011


2011 201 I

] 4 ,5 lIS 7 S 9
1U ml J--1 13 14 1 I Hl'
I1 18 19 '::0 2~ 2,")' 23
2 "I _6 17 :g 29 30
.... -
31 JanlU8,ry6 ~s th,e frilrst Thursday' of the yelatr, 501 the we,e:k of January H is week 1_ J'8'nualry 1 ,and ,January 2 be,~ong! to the last w,e1ek I(Wlrsk 52.) o,f the previ,ou:s year~ F:or these tw,a dates, ,strf, ime Wi~11 re'plllBce "'.9 by 101 %G by 2,010'1' and %v by 5,2~ INote that the last few days of D'scember wiill~ semenmes betong to wa,ek 1 of the fc,llllowling' year; thlis happens, whenever ID,Bc,ember 29,30 or 31 is ,8 Monday.

The %z corwerslon i,pleclifllelr corresponds, to the ISOI 86'01 tJlme zone ,speoilfica .. tJl0n,. -hnmm means, 'the'! a II:me zone ~91 h,h hours and mm minutes beh~nd IU~C': the s,tr~ng. +h,hmm' ind~cfat8s the amount by' which a "me' zone is aheadl,o,f UTe.,

: om - di, 'I)-Ie . I'"D' f c tt, in

- -_ - ~

s trf time conversion I peci ers, s- 'OOt' i [I speci fier c that begin with an E or 0

modifier cause tl replacement t b, P rformed Lt io.- '1 altern tiv format that d. pends ,'_'0 the urren I '.~ le, II an alt srna "', . representation do '.0 t eXISt in the c urre III 1 I 'aJ '~ th . modifier has nJO eff t. (In the II' C III I cale, E . nd a are i" nored, I

_ '. ble 2ti .. 4li . , W' that en allo 'e 1£0, ha e E or 10 mn ifi.· rs,

Displayin ~ the Date and Ime

Let' sJay we' Deed a program' hat I "ispJa'y the _ nrrent d tie an _ time, The ,p'rogrld1~ fir· t . tep, of COUl. e i, t .... call e t. ime fuuc " , n [I I.' lain the calendar time. The

Table 216,,~4 E- and Q ee Modified 'Conversion Specifiers for the s tr£ t i:mtf!

Functlon (C991 only)

%B·,e !kEC %Ex %EX %Ey lEY %0(1

Alternative date and time le_plresefl'tadon

'amlf: ,ofhUile ,'ear (~6rlod)r In alternative r:epre.eDt2tioo, A]temahVle date rep[ese'ntation

Alternative time representation

Offset from, tEe (y't!,Rr on~'y) in alternative repir~s~n'ta:tiorJl Full altemaii ve year repres ~'ntl.tion

Day of luondl" 1J~,ing alternati ve numeric sYll1holl:s, (filled wid1leaJdin,g zeros OT' wi,tll J,oading spaces H'there :is no alternati e s,yruboiI for zero) D'ay ofmonth U '·iin,g ahernatlve numeric symbols (fi Iled with ~eading "paces)

I .. tour on 24-hol!lr eloek, ILl~inl, alternative nu merie symbols Hour on ~.2-bom clock, using alternative numeric symbols MDnth" us,ing ;lllrn,at'ivcnLun,cric symbols

M inure, using alternative numeric symbols

Second, using alternati e numeric s:)rmboh

ISO, ,8'00 It w~,kdny as a number in a]temalbVe repre entatiou,~ 'when;, Mlenday is, I

Week number, using alternative numerics')rrrJibols

ISO 8,60 J week number" u~lng alternative numeric symbols Weekday as anumber, using al ernatlve numeric sYll1bo.b; 'Week number using allternicluv " numerie symbel

Last two digitI· '_ year- using alternative numeric s,ymboi··




tOI ·%-'Om %-O.M %OS tou

%Otl %OV %ow tow


second step is, to convert the lime U) string form and print i.t The eo lest wa.y to do

h d· ," ]1 'I III ~ . . ,. .

!-. I,.:"J-":,-",I I' :-.':-, --:- ,_.,.L., '.' - " 1-" ,.-1-' -,_!I!- -,,-_ ',- J._,. I 1"'1-- 1,_'" ,-'I iliii 1.,1-- ',_' '_"'I _or; .'-, l~,

tne secon step 1.S to em ott me, w __ .1C1 return n pomter to a Long contammg 3.

date' and ti 1]1e~ then piC1S.· this poin'tfrr to put s or pri nt f.~

So far, ;so good, But what if we W'8J]'t the program to dis play the dale and time in a particnlarway? Let S I'S'SUDle that we need the following format, where 106 is '~ll month and 03 is the d,ay lor the month:


The ct.Ime function always use [be arne format for the date and time, 5'0, it's no help, The ,strftime function is better; ostng it- WI!: can almost aehieve the appearance that we want Lrnfortnnately, srt.rftime won't let US, di:splay a" onedi,gJt hour' without ,8 Ieadlag zero. AJS:Qr1 strftim,e u'les,AM and PM instead 'of ,ell. and p.

W11Ie:n IBtrft.im!e isn'tgood enough, we have another alternative: convertthe calendar time to a broken-down time, then extract die relevant lnformatlon from the t.m structure and format it ourselves using printf or- ,8 imilar function, We might even use str'fti'm,e todo omit! of the fonnauing before having other functions complete the job.

Tile following program Illustrsres the options. It displays the CUl'TOOl dab~i and rime in til-nee formats: the one used by ct.Lme. one close tOI what we 'wunlt (created using ,strftim,e)1 and th.- desired format (created using printf)j The ctime version is easy to dOI~ th . B,trftim@ version is a llnle harder, and 'the p,rint'f version i ' the most difficult,

#ino.1..udle' <:: s,tdio '. h.> .- include <t_ime_h:>

:lot main (void)'


,time cu -- ent -== time (NOLL,,) i

s truot; tm *pt r;

char dat,9_time [21] ~

tnt llour,;

char lant_or _Jlm ;'

I" Print dat e and t.Lme U:1 dJ!faul': fo' - ma ~ 111 I PU~$(ctime(~cllrrent)) :

1* P',r~nt dat.e and tJ.me~ using ,sitz:ftime to format .. / s'trftiule '(date_tim1e, sizleo'f (d,ate_timeJ ,"

lI~m~!jd~%Y '%1': \M%p\nU, Loca.lt ime{&curr'lent) ) ; puts (date_time)' 'f

1* Print dat e and t.Lme , u ingpr"lntf t.o format *1 ptr .==- lo'cal'ti.me (&current:) ,

hORr ....... pt.r->t:m_haurJ;

if (ho'ur <= 11)

am ....... or~m ~ 'al; el~e {

hoc r. '""= .12;

am _or _pm -= , p II ;'


if (hour =;;;; a) hou'r ~ 12 i

printf(~II%.,2d-\ 2d-%d %2d,,%,~2d~c\n~', p,tr'->' m_mo,n + 1, ptr~~tm mday, ptr- tm yea~ + 1'00, houl ,

- --

pt.r--c-tm min, am or n,m) i'

~ ~ "",_r-

return 0;


Sun Jun 3 ~1:4B:34 2007

06-03-2001 05:49PM

06-03-2007 5:4Bp

IQ· &--; A·

" . I '_ _'

Q: Altbou. ~ <st,d1ib I h> P -0 -ld Dumb -r' IO_~ fun ... ti,OB~ tha 0011 -r'ltnn

. 0 numbrs _] er _ don appear II b ,', :ll Iunetlens lh t co-' , I I -~ number It. , -'tring~ .. ~ What no es?


:$~ :- llil

• '_'. 1111

Q & A 701

Some C libraries ~ upply functions ith name 11k i toa that c nvert number re

uinzs, in' the e fun" ti 0, j ~. [ gre Jdc tb uzh: lb." ar _ n t rart r

tandard and 'won - t - e portable, TIl b est - a, [0 p :r orm tI11_" kind . f conversion i

t call une tion ~ uch ~~'S s-p r i,r t ilia', rir s t iaue output int u n t:

char str' [2 0] ;

illt i,

I'· wri' es i into

he s, ring str -/

II ~'d II _ ~) .. ,

~ . , ~ I

NI t· nly j , spr int f portabl e bu it 1 [ proi , il I . pp Ullin e of he number,

- at deal of control over the

- -

e dl _N ripfjoD 0:' tb s t!rt:acJL anetl I 1 . ,a' '~llo - 11;-

mentt •. CrUlD '; Ii!: a he tad -, ~- - - aI O-J, [~_11 -pol t nambe . I r'

., tb I~I t' I tb -- '. [ '1-' 1

1[:' . _I. '01_ -m,.; 0,1 ' - e r: - D g,m[ .. I-'r",or; pi.. -,

11 '.1'1.- cimal A ating-p Ii., numb r b -,: In -- irhox Ir OXc llowed b 1[1' IOf' more hexadecim __ l di i' p ~ ,,;,jlll inclu I'll, . d cimal-p int bar;w. ter), and then

pibl_ a lnan e_, c nen ~, ", - ~ hie HI -" th n ICbup' . r 7

Ion of h ·xad. cirnal floatin C ms tants, which h,- '\1[- imilar=bin DI- - identicul=-

.. rm t. Infinit I th _onnIN'F or INF "NITY~ "_ n' . U' tl:.: 1,[[ rs mn b

. ,

lower ~ a· . I.' ," L, re __ I esen - db, the strina NAN . - g' in igno i - g.--, [ ) p'.' fbl

d ~y a, pair -f oarenthes I. I ~ '11, p enrhe '-I ma b . mpt r Lb. ~' IDa:

I. ntain . ri IS, of charact rs, h re h ell ter is " Iener digit, or underre The en aeter ~ may ,- _ used It r specify 0 e rf tb blts '. - ih bin ._ r prleent 'lion If the N,_ N value, bui th IT e : __ -t meaning II: ~ -, pi -, marion-defined. The sam, kind of character seqnence=-whicli the C99 stand '''d calls an ll" barnan uncl'on ""28.4·,eq_ul,.f1,'-ll-, als .' It, I 'in call: th 'nan fun li 'n ..

~-"Q" L, '.' .'

._ !I


1 ...... 1

c·IJ exit til) lar_~ fie Ii - [ pr,.-

, estat ml nt re t- rn I'l,;' in, ma.i,D,i .

Then H~·-.'I' iss De . Fir" . h, 'D I I. ma i n unction return" the' H' etirne If i ....

local variable - nds I assuming IL] ,:' ,- th" h e automatic ston ge dur ' i .. n, as the , ill unle ,'II th ~ - re I '! lared -, b s l:a tic ;o~. hi [h isn l true · - , e eX'l t. un ti n

11 called, A pl oblem wilJ I ceu r if a:ll1,Y action lh~1t tak:. plac at program termina[j ,u-8uh as '_ allin a fun-til II pr ii, u I, regi t r d using aL~; t I r flu hin

['10 output stream buff! r=-require II '. e . 0 the se ariables, In particular, a

program rnizht h.a- aJI,~" s et.vbu d In ,,' main's c ariable: a' a

bu er .. · hus 'in rare ca es. pr IgT 11'1 m ivbeha- impr 'p .. rl_ if il attempt [ tJ rerum from main bu.' w, )Irk 'i it call .' lexi t: ins , .

he oihe - L,UI. ill I ' n, y in ' ' hie Ir m.a1n . h:- Ie

return type other than .i nt; if an implenn rnarica ' the ' .~. grammer

to do so In thes cin umstanc ,~th) 11 exi, (IZ·) i a" n ~.. aril executins rlst,urn ,1.1;' in main. In fa rt, th - sta I rn J1 rs,turn'l ,; rna be lllega' . i rna in i d . Iared to return -:. -01 t ,.,~~, r .' anu JI- I ..




Is there II Iltio"nSlUp between '_,~ e labar'tfu -dOD and ,SlGAB,R,T siigD_JIl? [p~, 68'8]

-\,e'-,., A call ,of abor-t actually rai ses the SI!GlffiRT signal, If there's DOl handler fair S,I'G.A;BRT~, th f program terminaret abnormally as deserit I in ,Section'lti,2. If a handler has been installed for S,I'G~_BRT (by a call 101" 'the sig',nal function), tbe handler Is call ed, If the handler returns, th prog am then terminates abnormallv, However" ifthe handler doesn 't return (it call. longjlmp .. , for example), then the program. do sn't tl rminau ".

IQ:, "-by do,_b,e ,tI,i'v Bnd, Idi,v .fUOICiH'OD:, exist?' Cant.: w,e ,lOft use tile I and 'ft; opera't'ors,? [p, 6-.·2]

A: div and! 1.div aren't quite the same as l and ~. Recall from Seetiond .. 1 thar applying I and % to negativ operand doesn'tgive a portable result in C8J91., If i or j 'is negative, whether the value of i I j, Ji round' . up 101' dow" is irnplementatio ... defined. las is the sign of i % j ," The answers computed by' di v land, Ldd v, on the other h -'ld? don't depend ")0 the in1 . dementation. Th quotient is rounded toward ZeJDI;, the remainder is, computed according to the' formula ,n == q x d +, f" where n 'is

th t. ~ ..... 'II l.. + iII,'lI.., . iii d Ii h d Ii ~ d '., .. 'II.., i d I~

e ongmai mmoer, 'q 18 me quouent.: ' 18 tne I.· tvisor; an r IS we remain er. -iere

are a few exa I ~ ples:

n ,d ,q r
l' ,3 2 ]
~1 3 ·-2 -1
7 -3 -2 I
·-7 2 ~1 ,a'i T~, C99'.- 111e / and % ope ators are guaranteed to produce the san e IeS,UJt a ,div and l,div.

Effici ney is the other reason that di v and Idi v Ie' "t MIni" machm '" have an instruction that can compute both the quotient and remainder Sal catlin,g div or Idi v may be fa Iter than using the I "and ~ operator separately,

Q ...• ~ •. ~_-, Wbe~D d' o'e' .. i£\' ,I'''''' a, D-~ g,'m- - D o· ',. , he 1f"ITin ...... 'liM"i!!!!i f"un- -, - ;fIilti-'""oc-n ""om- ,,0 r~ - -10- I J p-' L19,1tl

_ _ ,.1,:--, __ 11;' 1- ._:_ ... Di IUI,I~ _III II;,~. ~. ~~I ':I"ll~"JI~U[~' _ .L __ .'," ~I. "'I; t~,&l .. ;,. _til, _:_"iI' B--""UJI

A: Then' me gmtim@ stands for Greenwich Mean Time (GMT) referring to th locat (solar) rime at the R.oyallObservatory in Greenwich England .. rn l,8,8,ltl 'GMT W,[S adopted 3i' an international reference time- 'with other lime zone, e pressed hours £, behind GMT-~ or "ahead of' GMT .. '~ In 19172,~ Ceordinated Univer al Time

(UTIC)-a sys.em based nnatomic clock rather than solar obscrvarions=-rcplaccd G1vIT as, the international ime reference, By adding 0.- ea ~ second" once every

lew y,ear,~ UTI , is kept synchromzed 'with 'GMT to within 0,.'91 second, so, fo !_' H bUll

.1' he m'o.l~ ,~: 'P'fA'-;;, s·· -e' time *Ie,~i!£' 'fl,'rllQl.m- Ie." n- ~'~ th ,!iii! "W·'~ '0, ~y. '. '~':ii!iIr :tr'fII"lII'!I:'! "'-"II 'I!"I~ Ii d.' P'D' ,. IP'!' ~,III

U/ .. , .. i;Jdl _ '~\.t.IL. lULU .. " ILIJIl.. __ DliJl~~ - I l~. ",~ t ~., a I ILj~~ iU·~ '. ~ l_ \.il1d.i1~

I,. Rewrite the m~_int function ·0 that, instead of passing the number of integers I, the 'first argLlm.l_ nt, we mu t supph~ 0 a~ the hl' I IJfgumentHint~· max __ int mu l have at iel~ t 01

E "

, XerC'S&15

"normal" parameter, so YOII C311"t re movie 'fhe pafQJJ111~e;teT' n, Iustead, assume [hat 'il[ represents 10111'e' of the numbers tobe compared.

2. W-ri'me ,3 ,~~d rnpll fi],ed, versi Ollll of p r,in1lE f in \vbi,ch the only eonversion pacification is %d I and ,IDJ 'mgnm,e1l1s after the first are assumed to have in,t type .. U the function encounters a , character that 5 not immediately followed by a dcharacter, h. shou d ignore both characters. The function should use calls of put char to produce ,aU output. YO/Ill ,Inlay assume that the' ~ mnar string doe m't eontain escape . equences,

3. Extend the fu,ncti.on. of Bxerci . e 2 SO dlat It allows (W'DI conversion ·pecific,alion5: %d and ~s. Each %d in 'tile fOrnll,t string rndiCliltles an tnt ar,gum~nl~1 and each %8 indic2JJ~tes a (:::har' * (Sllring) argument,

4.; W rite a function named di sp 1 ay' that takes ,any number of arguments, The first arl;nn:re,m must be au integer, The re~ll,~iDinl arguments will be strings, The first argument specifies llfJJW ma:ny !1U:rIOg:s tile C,aI] contains, The tunctlon win prinrtlre string I , OJ[] Itt single fjne~, with adjaoenlt strings separated by one space. For example, [me calli

diapla:y (4',~ iI Sp,ecialll ~ II Ag'lent III f IllIilD,al,e ~~ It u C',oop,er II ) ,;

\yillp,roduceJ the following output:

Sp'l8cial Agefn.t [Ja.l~ COapH!r

;'" Wri:l5 the fonowilng funcnilon:

char '*'v(~rt rcat (cons t char '* f I.r ,19 t ~

), .,

• -~, If

AU arguments o-f'vstr'ca:t are ass umed tOI be ·,trin,gs.,. except ror the 1a t argnmene, which mu's'[ be a nun PiOl:111fCr (cas'[ to char- '~ype) .. 'The function returns a pointer to a dynami,caJJy allocated striag 'CDl1tai,nJjn& the ,concate~uttio1ill of the arguments. vstrc,ct shoutd return II nu]~ poimer if not enough memory is available, Hins: 1-.1 ave V,Bt rea t go ihroo,g,h the M~Ulments twice: Ole,€: to determine the amount 'of Me1110ry required for the returned string and once to IcoRY [be argumems ill1to 'me string,

6,. W,rite the t·oUOtwine 'u[JJlC:li,[Jn~

_ -

char '*max_pai.r (in't. num_Plairs", "' .... )1;

The argJluneu,ts of'maxJ1air are assumed Ito be II pairs" of integers and strings: the value of nu,m_p,~irs indicates how many pain \\dU [cHow. 'CA, pair consists of an in'tlfguluemn followed by a char 'iAr' argumen.'~l.The function searches the integers to -md the largest nne~, i1 then returns the strin,g argument that follows it. 'Con rider the 'ffioUowing can:

max_pel i r (!l, lSO, lI'~Se.infeldl1,~ l.E~HJ"" III I Love Lu,cye ~

39, , 'T,he ,Holneymolone~"9 ", 21 <0 ,f II All intbe F,a.milyllll, 8 6' , 11m T,:ti,~ S'Ei'prano a I'il 1

The hn~es't int ilrgumenl is 2. :~O~ so tJlIle flJln!C~ioD returns tl All in t.he Famil YU.J which foUow,s it in the argument HS'l.

SBc~-t· -'"110' n- '2' 6· , '2.1

. .'.··.1 1 .. _ 1'"-" .iI ... ..:...

1m 7. Explain the meaning of the fo]J[fWin,g S' atemem, assuming that value is a variable of type Lonq in t ,and p is I variable of type char it:

va l.ue ;;;;;_ st,r.tlol (p~ 'PI If 10) ~

8,. Write a starement that randernly assign IDIil',' of the numbers 7- ] l ~ -~ 5., or 19 I(] the variable IL

'ei 91,. Welte 1ft function that returns a rmtndam douhl.e value d in the range 0.11' <. d <: 1.0.

to.., Convert the '~oUO'\vin_g ealls 0_· atoi, at.of., and at o.lLjnto calls of strtol, str'tlcl'l' and s,trtol1~, respectively,

(a) a1'l:oi Lstr) ~bJ at.al (:str) (e) atoll (s,tr)

J ~., Although ~he bs:,earch function 'is normally used 'with a. sorted ;arrs,)\, it \viB sornetimes work curr-eicl~Y wi fu 3J] ,arr,ay thsr ~~ t1n~)I partially sorted, Wh,m'llco'ndi'lion mtU;,IL an artm:y sathrfy to guarantee that bsasa-'I"ch ,_ nrks properly fer ,3 particular key? Hint: The answer appears 111 ~ he C standard,

S· ·t~'·· -n '116' ,3-:-'

_ eCII,O 11 ~,_: "Ii.:c I

l2. Writ,e' a fiu]c'[ion that, when passed 0; year, return ,B timB_tvalue represeming 12,~OO a.m, HD the first day of "hat ye~lri'

~ J. Section .26.3 described some 'of the [S'OI 8.60 I date and time formats. Here aile a, fe\v more: (I) Year followed by d3,), OIl' yeM:YYYY~DDDI,~ where D',DD is at number between nOli and ,Jo,6

I( 11) Year, week. nnd day of 'we,el:~~1lYY-W,,~u'~D~, where ,·n!,j hi a mneber between Oland' 53 and,l) lis a digit between 1 llhrough 7', beginning with MoncbJy and ending vvith Sun .. day

(c) 'Combined date and time: YY'YY ~MM-DD'T'h",:,""J'I:A:~\~

'Give s tr,ftime strings thaI curre:;pund to each of these fOrnl3.ts.

81 I. I ,H) W'rm te ~ prO'IT31f111 'Lh~u calls lbe z'and function 1000 Ii mes, printing the 10,w-order bh of each v,aJlJel it returns (0 11" the return value ~'., even, ~ if it's odd),. Do you see amy patterns? (O~tert 'lJle ~I~)l few bit, of zand's return v,~JUlJ.~ aren't especially random.)

(b) Bow c,an W~ lmprove thc randornness of'rand fOT generating numbers within a small range?

2. OW-rite aprogram '(hill tests the atexit function, The program should have two function Un adtHlion tOI ma,in1t O'De of whicb prints tThat IS a,ll, and the other f,a.lks,L Use the a't ,ex i 'I: function to reli,s~ler both to be called fii'l pregrnm termination, Mak,e' 'I Ute [hey'~re called in the proper order, S,'ll tha:l we see the mL!" sage !fh,il't'I:S all, folks,!. 100 me screen.

• 3.Wri~e a program 'tba.'l uses [he clock function to measure how long i,[ takes 'qsort to sort an wTay of 11000 ioteg'eT [ha.l are origina lly l n reverse order, Run tile program for may. of ] 00[10 and 1 00000 integers us well,

CI' 4.Wri[e' a program 'Khal premp the user for a dare' (month, d.ruty~ and yearl and an integer n, then prints the date thu,t'I S, n days later

;5, Write a <p'rogr~1m lh;4:~ prompts !the user to enter two dates, the, l prints the difference between them, measured in dB,Y' l~ HIllt: Use lhemkt; i me and d i'f f time functions,

to 6. Write 1)..1lgT,O.1l1I'S, Ulllt display the current date Mid time in leach ef the ~nno'wing format. Use ,s~trftime to do ~IU or most of the formatting,

(a) ,Siunday r June ]. f' 2007 to 5 : 4,flp

(b) ,S'lln, J Jun 07 1'7;; 4,8

(c) 06/03/07 5 : 48': 34· ,PM

Sign up to vote on this title
UsefulNot useful