Calling the function sum(int [], arr_size)
in the statement
total = sum((int []){1,2,3,4,5}, 5);
a Compound Literal (int []){1,2,3,4,5}
is passed as argument. It is clear that the length of array is determined by numbers of elements in literal(which is of-course 5
here). Then what is the need of passing 5
as another argument?
can't we define above function as
sum(int []) {....}
and then calling it as
total = sum((int []){1,2,3,4,5})
?
You can define sum
that way and call it as shown in your example, but in that case you will not be able to determine the size of the array inside the function.
What you could do is declare sum
as
int sum(int (*a)[5])
{
...
}
and then call it as
total = sum(&(int []){1,2,3,4,5});
But in this case you will be restricted to arrays of size 5
only. If you want to have a function that works with arrays of any size, you have to either pass the size from outside or reserve some sort of "terminator" element in your array