Function with infinite number of parameters

Once in a rare while you need a function which can accept infinite number of arguments. Most programmers only rarely learn this trick which can be useful at times. When you want to process an infinite number of parameters, here are the tricks to use: PHP This is rather simple in PHP as PHP doesn’t [...]

Once in a rare while you need a function which can accept infinite number of arguments. Most programmers only rarely learn this trick which can be useful at times. When you want to process an infinite number of parameters, here are the tricks to use:

PHP
This is rather simple in PHP as PHP doesn’t restrict the arguments that can be passed. You can pass 10 arguments to a function accepting 2, PHP will just ignore the rest 8

There is a function named fun_get_args() inbuilt into PHP that allows you to get the list arguments as an array

function bcaddall($add)
{ $num = 0;
$args = func_get_args();
foreach($args as $arg)
{
$num = bcadd($num, $arg);
}
return $num;
}


Visual Basic.NET

In VB.net, there is a special Paramlist datatype

Public Function Concat(ByVal ParamArray Args() As String) As String

Dim objSB As New Text.StringBuilder

For i As Integer = 0 To Args.GetUpperBound(0)
objSB.Append(Args(i))
Next

Return objSB.ToString

End Function

Console.WriteLine(Concat())
Console.WriteLine(Concat("a"))
Console.WriteLine(Concat("xyz", "123", "3453"))
Console.WriteLine(Concat("a", "b", "c", "d", "e", "f", "g"))

To explain the above function, ParamArgs stores arguments of string type into a string array. So now you've got an array of strings that were passed as arguments. What you do with it is completely upto you.

C++
Doing this in C++ is a little complicated. Its bloody complicated.
First you define the function parameters as char *vstrcat(const char *first, ...)The last ellipses means that the function will accept an infinite number of arguments of the previous argument

char *vstrcat(const char *first, ...)
{
size_t len;
char *retbuf;
va_list argp;
char *p;

if(first == NULL)
return NULL;

len = strlen(first);//This stores the length of first argument

va_start(argp, first);//starts initialization of traversing argument loop

while((p = va_arg(argp, char *)) != NULL)//va_arg is used to access the next argument value
len += strlen(p);

va_end(argp);//stop using arg as argument loop

retbuf = malloc(len + 1); /* +1 for trailing \0. This line declares a string long enough to hold the concatenated string. len was calculated by looping through all the arguments and adding their lengths

if(retbuf == NULL)
return NULL; /* error */

(void)strcpy(retbuf, first);

va_start(argp, first); /* restart; 2nd scan */

while((p = va_arg(argp, char *)) != NULL)
(void)strcat(retbuf, p);

va_end(argp);

return retbuf;
}

As I said pretty complicated