Suppose I have a function foo
:
int foo(int a, int b)
{
return a b;
}
Can I in any way call foo
with an array and have each elements of the array act as one parameter?
e.g:
int arr[2] = {1, 2};
foo(arr); // Should return 3
In JavaScript I can do:
let arr = [1, 2];
foo(...arr); // Returns 3
Is there anything similar in C?
CodePudding user response:
No, this is not possible. You will have to call the function foo
like this:
int arr[2] = { 1, 2 };
foo( arr[0], arr[1] );
However, it is possible to redefine the function foo
like this:
int foo( int arr[2] )
{
return arr[0] arr[1];
}
Now, you can call the function foo
like this:
int arr[2] = { 1, 2 };
foo( arr );
CodePudding user response:
You can pass an array to a function, but in doing so it decays to a pointer so you don't know what the size is. You would need to pass the size as a separate parameter, then your function can loop through the elements.
int foo(int *arr, int len)
{
int i, sum;
for(i=0, sum=0; i<len; i ) {
sum = arr[i];
}
return sum;
}
Then you can call it like this:
int arr[2] = {1, 2};
foo(arr, 2);
Or, assuming the array was declared locally:
foo(arr, sizeof(arr)/sizeof(*arr));
CodePudding user response:
Only by writing out the references longhand:
foo(arr[0], arr[1]);