Passing Array as Parameters - C++ Arrays

Passing array as parameters in C++?
What is passing by reference?

Explanation

In C++ while Passing array as parameters only the address of the array element is passed. So it is "passing by reference" so that the actual array element will get changed. Even though the array is passed as reference "&" symbol is not used instead the "[]" is used to in the parameter name.

Example :



#include <iostream.h>
#include <iomanip.h>
int sum(int[]);
void main()
{
int arr[5] = {1,3,5,2,5};
cout << "Sum of the array elements is::" << sum(arr);
}
int sum(int a[])
{
int sum1 = 0;
int i;
for (i = 0; i < 5; i++)
{
sum1 += a[i];
}
return sum1;
}

Result :

Sum of the array elements is::16

In the above passing array as parameters example the sum of the array "arr" is evaluated using the function "sum" by passing the parameters using the "passing by reference" method.

C++ Tutorial


Ask Questions

Ask Question