CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 1999
    Location
    Italy
    Posts
    39

    void func(p1,p2,p3,...?)

    Is it possible to create a C or C++ function with a variable number of parameters?

    Many thanks for your help.
    Antonio.

    _______

  2. #2
    Join Date
    May 1999
    Location
    Antwerp, Belgium
    Posts
    136

    Re: void func(p1,p2,p3,...?)

    Yes you can. This is an example I found in the VC++ Help :

    int average(int first, ...)
    {
    int count = 0;
    int sum = 0;
    int i = first;
    va_list marker;

    va_start(marker, first);
    while(i != -1)
    {
    sum += i;
    count++;
    i = va_arg(marker, int);
    }
    return (sum ? (sum / count) : 0 );
    }




    Other examples are the c-routines printf, sprintf, ...


  3. #3
    Join Date
    May 1999
    Location
    Antwerp, Belgium
    Posts
    136

    Re: void func(p1,p2,p3,...?)

    Yes you can. This is an example I found in the VC++ Help :

    int average(int first, ...)
    {
    int count = 0;
    int sum = 0;
    int i = first;
    va_list marker;

    va_start(marker, first);
    while(i != -1)
    {
    sum += i;
    count++;
    i = va_arg(marker, int);
    }
    va_end(marker);
    return (sum ? (sum / count) : 0 );
    }




    Other examples are the c-routines printf, sprintf, ...


  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: void func(p1,p2,p3,...?)

    Yes. Most C or C++ textbooks explains this technique. Alternately, do a search on "varargs.h" to get a rundown on how this is done.

    Regards,

    Paul McKenzie


  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: void func(p1,p2,p3,...?)

    You're forgetting the most important part: the header:

    #include <varargs.h> for UNIX

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

    Regards,

    Paul McKenzie


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured