Thread: Repeating argument in functions.

  1. #1
    Registered User
    Join Date
    Mar 2006
    Location
    IL
    Posts
    23

    Repeating argument in functions.

    If you have ever scripted with Javascript you are aware of the arguments array that a function possesses. Basically, you could do something like this in Javascript:
    Code:
    //Define
    function myFunc()
    {
        for(i=0; i<myFunc.arguments.length; i++)
        {
            alert("Argument "+i+": "+myFunc.arguments[i])
        }
    }
    //Call
    myFunc("this is an arg")
    myFunc("so is this","and this","and this.")
    myFunc("here","are","several","args","with","no","specific","limit.")
    Anyway as you can see above, this function will basically display a message box alerting the user of each entered argument, despite that I did not define them specifically.

    Now I am looking to do this in C++ for an array building type thing, so my question is, how can I make a repeating argument (with a given data type of course).

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Variable length arguments.
    Check this out
    http://www.cprogramming.com/tutorial/lesson17.html
    Woop?

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Look up the stdargs mechanism (which comes from C). An example of the usage (assuming the variable arguments are ints, and the last in the list is zero) follows;

    Code:
    #include <stdarg.h>
    
    void sum(char *msg, ...);   /* function prototype */
    
    /* calculate sum of a 0 terminated list */
    void sum(char *msg, ...)
    {
       int total = 0;
       va_list ap;
       int arg;
       va_start(ap, msg);       /*   Set up so we can access variable argument list */
    
       while ((arg = va_arg(ap,int)) != 0) {      /* Loop over the arguments, assuming they are int */
          total += arg;
       }
       printf(msg, total);
       va_end(ap);   /*   Cleanup;  necessary before this function returns */
    }
    
    int main(void) {
       sum("The total of 1+2+3+4 is %d\n", 1,2,3,4,0);
       return 0;
    }
    One catch of the stdargs mechanism is that the type of the first argument must be specified, as the first argument is used by the va_start macro to set things up so the rest of the arguments can be accessed. (i.e. it is not possible to have a function of the form SomeFunction(...))

    Another catch is that it is not possible to simply get the number of arguments passed or the type of those arguments .... that information must either be known to the program, or some other scheme to recognise the last argument must be used. In the example above, it is assumed that all variable arguments are ints and the last argument given will have a value of zero. In functions like printf(), which use this mechanism, the format string provides information on the arguments that follow it. One serious gotcha is that undefined behaviour results if the function attempts to access more arguments than are passed, or treats any argument as a different type from what it actually is.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Another gotcha is that all type checking vanishes as soon as you use varargs.
    You should try and find a different approach in C++
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    I would use a vector (or similar container) if the types were all the same. If not, I would use Boost::any or Boost::variant.

  6. #6
    Registered User
    Join Date
    Mar 2006
    Location
    IL
    Posts
    23
    Ok, I have set it up to use the cstdarg header. Now I am having troubles converting it from a char to an "ItemClass *" (custom class). Here is the code I am using:
    Code:
    ItemClass** makeICPointerArray(int count, ... )
    {
    	va_list arguments;
    	va_start(arguments,count);
    	ItemClass** list=new ItemClass*[count];
    	for(int i=0; i<=count; i++)
    	{
    		list[i]=arguments[i];
    	}
    	va_end(arguments);
    	return list;
    }
    I guess my next question would be, how do I make it use something other than char for the other arguments?
    IDE and Compiler: Visual Studio C++ 2003

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    look at the example posted by grumpy. the parameters are extracted with the va_arg macro (which is where you supply the desired type).
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  8. #8
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    I think the technical term for this type of function is "variadic." Just thought it might help in a web search or something...
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  9. #9
    Registered User
    Join Date
    Mar 2006
    Location
    IL
    Posts
    23
    Quote Originally Posted by Sebastiani
    look at the example posted by grumpy. the parameters are extracted with the va_arg macro (which is where you supply the desired type).
    Thanks everyone, this has definately helped me a lot.
    IDE and Compiler: Visual Studio C++ 2003

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. An array of macro functions?
    By someprogr in forum C Programming
    Replies: 6
    Last Post: 01-28-2009, 07:05 PM
  2. Replies: 7
    Last Post: 01-21-2009, 02:27 PM
  3. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 09:45 PM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  5. Variable argument functions
    By quantum in forum C Programming
    Replies: 3
    Last Post: 12-19-2003, 10:52 AM