You pass an array to a function, very similarly as to how you would pass a non-array variable. There are two differences.
- You need to include square brackets after the array name so C++ knows its and array
- Realize that you are passing by reference.
void printRandom(int list[], int listSize);
int main()
{
int ARR_SIZE = 4;
int numbers[ARR_SIZE] = {2,4,6,8};
printRandom(numbers, ARR_SIZE);
return 0;
}
void printRandom(int list[], int listSize) {
srand(time(0));
int index = rand() % listSize;
cout << list[index];
}
The book recommends that you always pass the size of an array to your calling function, that way you don’t accidentally reference a point in memory past the size of the array. (This would generate an out of bounds error.)
Usually when you pass a variable, copy of that value is made. However, because arrays take up more space, the computer may not have the resources to handle that array. Secondly, it would take time to duplicate that value, so it is passed by reference instead, meaning any change to the value in your function is reflected in the calling function.
While this can lead to some unexpected results, especially when you are first learning, it gives a huge speed enhancement.
Let’s see an example of where a value is changed in a function and it is reflected in the calling function.
void changeValue(int list[]);
int main()
{
int ARR_SIZE = 4;
int numbers[ARR_SIZE] = {2,4,6,8};
cout << "Index 0:" << numbers[0] << endl;
changeValue(numbers);
cout << "Index 0:" << numbers[0] << endl;
return 0;
}
void changeValue(int list[]) {
list[0] = 10;
cout << "Index 0:" << list[0] << endl;
}
Preventing Changes to Array Arguments
Luckily C++ gives us a little trick we can use to prevent that from happening.
Just make the parameters a constant in the parameter list.
void changeValue(const int list[]) // ...
This will keep the array from changing in the function, but allow full access where the function is defined.
void changeValue(int list[]);
int main()
{
int ARR_SIZE = 4;
int numbers[ARR_SIZE] = {2,4,6,8};
cout << "Index 0:" << numbers[0] << endl;
changeValue(numbers);
cout << "Index 0:" << numbers[0] << endl;
return 0;
}
void changeValue(const int list[]) {
list[0] = 10;
cout << "Index 0:" << list[0] << endl;
}
If you try to run this section of code, you’ll now get an error when you try to compile it.
Returning an Array from a Function
C++ does not allow you to return an array. So how can you… well since arrays are passed by reference, and that allows you to modify the value in the called function, you can simply pass the array there.
C++ Arrays and Functions was originally found on Access 2 Learn