Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
why we pass arrays in functions parameter in c++


What I have tried:

C++
<pre lang="C++">
why we pass array in function parameter
Posted
Updated 27-Jul-23 1:19am

Quote:
Why we pass arrays in functions parameter in C++

Usually, it is because we need to process the array in the function.
Your question barely make sense.
 
Share this answer
 
When writing code for a function you have three options for handling the data it is going to process :
1. The data is passed into the function.
2. The data is externally accessible meaning it can be global.
3 If the function is a method of a class the data can be a member of the class.
 
Share this answer
 
Because the function needs to process the data the array contains.

When you call a function, you pass it a copy of the parameter - this is called "pass by value".
In the case of an integer, a copy of the integer is passed:
C++
int Double(int x) { return x * 2; }
...
int a = Double(666);
int b = Double(a);
The function doesn't to be changed to process the different results.

But what if I want to process an unknown number of integers? I can't write a different function for each possible number of parameters you might need - so we pass an array of integers instead:
C++
int Sum (int arr[], int count)
   {
   int tot = 0;
   for (int i = 0; i < count; i++)
      {
      tot += arr[i];
      }
   return tot;
   }
Now I can call it with any array of integers I want:
C++
int a[5] = {1, 2, 3, 4, 5};
int b[3] = {101; 201; 301};
int x = Sum(a, 5);
int y = Sum(b, 3);


Make sense?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900