Variable-length argument lists

Source: Internet
Author: User

The best example of variable-length argument lists function is printf ()

The proper declaration for printf () is

Int printf (char * format ,...)

Where the declaration... means that the number and types of these arguments may vary. The declaration... can only appear at the end of an argument list, ourMainprintfIs declared

Int minprintf (char * FMT ,...)

Since we will not return the Character CountPrintfDoes.

the tricky bit is how minprintf walks along the argument list when the list doesn' t even have a name. the standard header contains a set of macro definitions that define how to step through an argument
list. the implementation of this header will vary from machine to machine, but the interface it presents is uniform.

the type va_list is used to declare a variable that will refer to each argument in turn; in minprintf , this variable is call aP . for "argument Pointer" the macro va_start initialize aP to
point to the first unnamed argument. it must be called once before aP is used. there must be at least one named argument; the final argument is used by va_start to get started. each call of va_arg Returns one argument
and steps aP to the next; va_arg uses a type name to determine what type to return and how big a step to take. finally, va_end does whatever cleanup is necessary. it must be called before the function returns.

The properties form the basis of our simplifiedPrintf:

 
[Code = C/C ++] # include <stdarg. h> void minprintf (char * FMT ,...) {va_list AP; char * P, * sval; int ival; double dval; va_start (AP, FMT); // make AP point to first unnamed Arg for (P = FMT; * P; P ++) {If (* P! = '%') {Putchar (* P); continue;} switch (* ++ p) {Case 'D': ival = va_arg (AP, INT ); printf ("% d", ival); break; Case 'F': dval = va_arg (AP, double); printf ("% F", dval); break; case's ': For (sval = va_arg (AP, char *); * sval; sval ++) {putchar (* sval);} break; default: putchar (* P); break;} va_end (AP); // clean up when done} [/Code]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.