Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

Header File stdarg.h Category Variable Argument List Routines Prototype void va_start(va_list ap, last i!

"# type va_arg(va_list ap, type"# void va_end(va_list ap"# $es%ription &mplement a variable argument list. 'ome C un%tions, su%h as v print and vprint , ta(e variable argument lists in addition to ta(ing a number o i!ed ((no)n" parameters. *he va_arg, va_end, and va_start ma%ros provide a portable )ay to a%%ess these argument lists. *hey are used or stepping through a list o arguments )hen the %alled un%tion does not (no) the number and types o the arguments being passed. *he header ile stdarg.h de%lares one type (va_list" and three ma%ros (va_start, va_arg, and va_end". va_list+ *his array holds in ormation needed by va_arg and va_end. ,hen a %alled un%tion ta(es a variable argument list, it de%lares a variable ap o type va_list. va_start+ *his routine (implemented as a ma%ro" sets ap to point to the irst o the variable arguments being passed to the un%tion. va_start must be used be ore the irst %all to va_arg or va_end. va_start ta(es t)o parameters+ ap and last i!. (ap is e!plained under va_list in the pre%eding paragraph# last i! is the name o the last i!ed parameter being passed to the %alled un%tion." va_arg+ *his routine (also implemented as a ma%ro" e!pands to an e!pression that has the same type and value as the ne!t argument being passed (one o the variable arguments". *he variable ap to va_arg should be the same ap that va_start initiali-ed. .ote+ /e%ause o de ault promotions, you %annot use %har, unsigned %har, or loat types )ith va_arg. *he irst time va_arg is used, it returns the irst argument in the list. 0a%h su%%essive time va_arg is used, it returns the ne!t argument in the list. &t does this by irst dere eren%ing ap, and then in%rementing ap to point to the ollo)ing item. va_arg uses the type to both per orm the dere eren%e and to lo%ate the ollo)ing item. 0a%h su%%essive time va_arg is invo(ed, it modi ies ap to point to the ne!t argument in the list. va_end+ *his ma%ro helps the %alled un%tion per orm a normal return. va_end might modi y ap in

su%h a )ay that it %annot be used unless va_start is re%alled. va_end should be %alled a ter va_arg has read all the arguments# ailure to do so might %ause strange, unde ined behavior in your program. Return Value va_start and va_end return no values# va_arg returns the %urrent argument in the list (the one that ap is pointing to". 0!ample+ 1in%lude 2stdio.h3 1in%lude 2stdarg.h3 45 %al%ulate sum o a 6 terminated list 54 void sum(%har 5msg, ..." 7 int total 8 6# va_list ap# int arg# va_start(ap, msg"# )hile ((arg 8 va_arg(ap,int"" 98 6" 7 total :8 arg# ; print (msg, total"# va_end(ap"# ; int main(void" 7 sum(<*he total o =:>:?:@ is AdBn<, =,>,?,@,6"# return 6# ;

You might also like