Can a Variable Number of Arguments Be Passed to a Function

Can a variable number of arguments be passed to a function?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

Variable number of arguments in C programmng

I want to use functions like sum(1,2,3) should return 6. i.e, no counter should be there

You could define a sentinel. In this case 0 might make sense.

/* Sums up as many int as required. 
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;

if (s)
{
va_list ap;

va_start(ap, i);

/* Pull the next int from the parameter list and if it is
equal 0 leave the while-loop: */
while ((i = va_arg(ap, int)))
{
s += i;
}

va_end(ap);
}

return s;
}

Call it like this:

int sum(int i, ...);

int main(void)
{
int s = sum(0); /* Gives 0. */

s = sum(1, 2, 3, 0); /* Gives 6. */
s = sum(-2, -1, 1, 2, 0); /* Gives 0. */
s = sum(1, 2, 3, 0, 4, 5, 6); /* Gives 6. */

s = sum(42); /* Gives undefined behaviour! */
}

The sum() function alternatively could also look like this (but would do one useless addition of 0):

/* Sums up as many int as required. 
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;

if (s)
{
va_list ap;

va_start(ap, i);

/* Pull the next int from the parameter list and if it is
equal 0 leave the do-loop: */
do
{
i = va_arg(ap, int);
s += i;
} while (i);

va_end(ap);
}

return s;
}

Passing variable arguments to another function that accepts a variable argument list

You can't do it directly; you have to create a function that takes a va_list:

#include <stdarg.h>

static void exampleV(int b, va_list args);

void exampleA(int a, int b, ...) // Renamed for consistency
{
va_list args;
do_something(a); // Use argument a somehow
va_start(args, b);
exampleV(b, args);
va_end(args);
}

void exampleB(int b, ...)
{
va_list args;
va_start(args, b);
exampleV(b, args);
va_end(args);
}

static void exampleV(int b, va_list args)
{
...whatever you planned to have exampleB do...
...except it calls neither va_start nor va_end...
}

Pass a variable number of arguments into a function

You can expand the array using a std::index_sequence

#include <iostream>
#include <utility>

struct A {
A(int a, int b) : x(a), y(b) {}
int x, y;
};

struct B {
B(int a, int b, int c) : x(a), y(b), z(c) {}
int x, y, z;
};

template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
T* element = new T(std::forward<TArgs>(MArgs)...);
return element;
}

template<typename T, typename U, size_t... I>
T* createElementFromArrayHelper(std::index_sequence<I...>, U* a){
return createElement<T>(a[I]...);
}

template<typename T, typename U, size_t N>
T* createElementFromArray(U (&a)[N]){
return createElementFromArrayHelper<T>(std::make_index_sequence<N>{}, a);
}

int main() {

int Aargs[] = { 1, 2 };
int Bargs[] = { 1, 2, 3 };

A* a = createElementFromArray<A>(Aargs);
B* b = createElementFromArray<B>(Bargs);

std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl;
std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl;

delete a;
delete b;

}

Is it possible to send a variable number of arguments to a JavaScript function?

Update: Since ES6, you can simply use the spread syntax when calling the function:

func(...arr);

Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:

function func(...args) {
args.forEach(arg => console.log(arg))
}

const values = ['a', 'b', 'c']
func(...values)
func(1, 2, 3)

And you can combine it with normal parameters, for example if you want to receive the first two arguments separately and the rest as an array:

function func(first, second, ...theRest) {
//...
}

And maybe is useful to you, that you can know how many arguments a function expects:

var test = function (one, two, three) {}; 
test.length == 3;

But anyway you can pass an arbitrary number of arguments...

The spread syntax is shorter and "sweeter" than apply and if you don't need to set the this value in the function call, this is the way to go.

Here is an apply example, which was the former way to do it:

var arr = ['a','b','c'];

function func() {
console.log(this); // 'test'
console.log(arguments.length); // 3

for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}

};

func.apply('test', arr);

Nowadays I only recommend using apply only if you need to pass an arbitrary number of arguments from an array and set the this value. apply takes is the this value as the first arguments, which will be used on the function invocation, if we use null in non-strict code, the this keyword will refer to the Global object (window) inside func, in strict mode, when explicitly using 'use strict' or in ES modules, null will be used.

Also note that the arguments object is not really an Array, you can convert it by:

var argsArray = Array.prototype.slice.call(arguments);

And in ES6:

const argsArray = [...arguments] // or Array.from(arguments)

But you rarely use the arguments object directly nowadays thanks to the spread syntax.

How to count the number of arguments passed to a function that accepts a variable number of arguments?

You can't. You have to manage for the caller to indicate the number of arguments somehow. You can:

  • Pass the number of arguments as the first variable
  • Require the last variable argument to be null, zero or whatever
  • Have the first argument describe what is expected (eg. the printf format string dictates what arguments should follow)

JavaScript variable number of arguments to function

Sure, just use the arguments object.

function foo() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}

Variable number of Arguments in C?

int ff(int num, ...)
{
va_list arguments;
int sum = 0;
va_start(arguments, num);
for (int x = 0; x < num; x++)
{
sum += va_arg(arguments, int);
}
va_end(arguments);

return sum;
}

//call
printf("%d\n", ff(3, 1, 2, 3));

va_list contains list of arguments in ..., in loop you get access one by one va_arg(arguments, int);



Related Topics



Leave a reply



Submit