C++ Arrays: C++ Array to Function
Syntax
void functionName(dataType arrayName[], int arraySize);
Example
#include <iostream>
using namespace std;
void printArray(int arr[], int size);
int main() {
int myArr[5] = {3, 1, 4, 1, 5};
int arrSize = 5;
printArray(myArr, arrSize);
return 0;
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
}
Output
3 1 4 1 5```
## Explanation
In this example, we have defined an integer array `myArr` with 5 elements. We have also defined a variable `arrSize` to hold the size of the array.
We then call the `printArray()` function and pass in the `myArr` array and `arrSize` as arguments.
The `printArray()` function iterates through each element of the array using a for loop and prints it out to the console.
## Use
Passing arrays as arguments to functions is a common use case in C++. This allows you to reuse a function for different arrays without having to write a separate function for each one.
## Important Points
- Arrays are always passed to functions using pointers.
- The size of the array must be passed to the function as a separate argument.
- When passing arrays to functions, the original array is not modified unless you explicitly write code to do so.
## Summary
In this tutorial, we learned how to pass arrays as arguments to functions in C++. We also reviewed the syntax, example, output, explanation, use, important points, and summary of C++ Array to Function.