Thursday, September 13, 2012

Miscellaneous – X – Variable Arguments.



Header File  <stdarg.h> provide Macros that implement variable argument lists.

void va_start(va_list ap, lastfix);
type va_arg(va_list ap, type);
void va_end(va_list ap);

The va_arg, va_end, and va_start macros provide a portable way to access these
argument lists.

va_start sets ap to point to the first of the variable arguments being passed to the function.

va_arg expands to an expression that has the same type and value as the next argument being passed .

Because of default promotions, you can't use char, unsigned char, or float types with va_arg.

va_end helps the called function perform a normal return.



#include <stdio.h>
#include <stdarg.h> //Header file for variable argument

  int Addition( int num, ... )
      {
           va_list args;   // Variable to store the arguments
           int sum = 0,i;
           va_start ( args, num );           // Initializing arguments
           for (i=0;i<num;i++)        // Loop until all no of args
                   sum += va_arg ( args, int ); // Adds
           va_end ( args );                  // Clear the list
           return sum;                      // Returns the average
      }
  void main()
      {
           printf("%d",Addition ( 3, 12, 22, 40 ));
      }



#include <stdio.h>
#include <stdarg.h> //Header file for variable argument


  void PrintChar(char *ch, ...)
      {
           va_list argc;
           char arg;
           va_start(ap, msg);
           while ((arg = va_arg(argc,char)) !='0')
              {
                   printf("%c ",arg);
              }
           va_end(ap);
      }

  void main()
      {
           clrscr();
           PrintChar("The Character %c\n", 'a','b','c','d','0');
           getch();
      }

No comments: