Rabu, 02 Desember 2015

Stdarg

A function may be called with a varying number of arguments of  varying types.  The include file <stdarg.h> declares a type va_list and defines three macros for stepping through a list of arguments whose number and types are not known to the called function.

stdarg.h Types
Name           :   va_list
Description       :  type for iterating arguments


Macro functions
va_start            :  Initialize a variable argument list (macro )
va_arg              :  Retrieve next argument (macro )
va_end             :  End using variable argument list (macro )
va_copy           : Copy variable argument list (macro )

 - va_start()
The va_start() macro initializes ap for subsequent use by va_arg() and va_end(), and must be called first.

-  va_arg()
The va_arg() macro expands to an expression that has the type and value of the next argument in the call

- va_end()
Each invocation of va_start() must be matched by a corresponding invocation of va_end() in the same function.
 
-va_copy()
The va_copy() macro copies the (previously initialized) variable argument list src to dest.

-The function "foo" takes a string of format characters and prints out the argument associated with each format character based on the type.

=Example=

  #include <stdio.h>
  #include <stdarg.h>

       void
       foo(char *fmt, ...)
       {
           va_list ap;
           int d;
           char c, *s;

           va_start(ap, fmt);
           while (*fmt)
               switch (*fmt++) {
               case 's':              /* string */
                   s = va_arg(ap, char *);
                   printf("string %s\n", s);
                   break;
               case 'd':              /* int */
                   d = va_arg(ap, int);
                   printf("int %d\n", d);
                   break;
               case 'c':              /* char */
                   /* need a cast here since va_arg only
                      takes fully promoted types */
                   c = (char) va_arg(ap, int);
                   printf("char %c\n", c);
                   break;
               }
           va_end(ap);
       }

Tidak ada komentar:

Posting Komentar