This blog is under construction

Saturday, 5 May 2012

va_list, va_start, va_arg, va_end

Header file:
    stdarg.h

Synopsis:
     va_list obj;
     va_start(va_list obj, lastarg);
     type va_arg(va_list obj, type);
     va_end(va_list obj);

Description:
    
va_list variable argument list.  It is used by the macros va_start(), va_arg() and va_end().
va_start It initializes obj for the subsequent call of va_arg() and va_end().  This should be called first.  And the lastarg is the last argument that is present before the variable argument list.
va_arg It returns the next argument.
va_end It is called after processing all the arguments.





Sample program for va_list, va_start, va_arg and va_end in C:



  #include<stdio.h>
  #include<stdarg.h>
  #include<string.h>
  #include<stdlib.h>
  char *res;
  char *str_append(char *format, ...) {
        va_list obj;
        char *str;
        va_start(obj, format);
        str = va_arg(obj, char *);
        strcpy(res, format);
        while (1) {
                strcat(res, str);
                if (strcmp(str, "end") == 0)
                        break;
                str = va_arg(obj, char *);
        }
        va_end(obj);
        return res;
  }

  int main() {
        res = calloc(1, 100);
        res = str_append("hello", "world", "12345", "end");
        printf("Output:%s\n", res);
        return 0;
  }





  Output:
  jp@jp-VirtualBox:~/cpgms/stdarg$ ./a.out
  Output:helloworld12345end


1 comment: