Viku
Viku

Reputation: 2973

Variable-Length Parameter Lists

/* va_arg example */
#include <stdio.h>
#include <stdarg.h>

void PrintLines ( char* first, ...)
{
  char* str;
  va_list vl;

  str=first;

  va_start(vl,first);

  do {
    str=va_arg(vl,char*);
    if
    printf ("%s\n",str);

     } while (str!=NULL);

  va_end(vl);
}

int main ()
{
  PrintLines ("First","Second","Third","Fourth",NULL);
  return 0;
}

Can we call the PrintLines function like this PrintLines("First","Second","Third",6,NULL); having integer as part of the variable argument list. If yes can anyone please explain how to do that?

Upvotes: 1

Views: 1407

Answers (2)

Rainfield
Rainfield

Reputation: 1212

Consider variadic templates in C++ 11. I know it can do this, but never used it before.

Upvotes: 1

pbhd
pbhd

Reputation: 4467

so for your case you just would do it hardcoded, like:

void PrintLines ( char* first, ...)
  ...
  str1=va_arg(vl,char*);
  str2=va_arg(vl,char*);
  str3=va_arg(vl,char*);
  int4=va_arg(vl,int);

  va_end(vl);
}

But I think that's not what you want: You sometimes may want to call PrintLines with an integer at pos 4, and sometimes with a string. Then you have to tell it what that thing at pos 4 is, because how should this poor function find out wether 112312123 is a integer or a address of a string? So you have to supply some type-info to this function, maybe similar like it's done in printf and friends: The first arg contains a string describing the rest of the arguments. Maybe something like vsprintf will do a perfect job for you?

Upvotes: 3

Related Questions