Array as a Function Parameter
Welcome back to our series on “Learning C++ step by step”! In our previous lessons, we learned how to store data in arrays and print them to the screen. But to write truly professional and modular code, you need to know how to move that data into functions.
Passing an array to a function allows you to perform complex tasks—like sorting, searching, or modifying data—without cluttering your main() program. In these lecture notes, we will break down the syntax, the “behind-the-scenes” memory logic, and the safety features C++ provides to keep your data secure.
Definitions: The Basics at a Glance
| Term | Simple Meaning |
|---|---|
| Formal Parameter | The placeholder in the function’s header that tells it to expect an array. |
| Pass by Reference | Giving a function access to the original data rather than a copy. |
Subscript Operator ([]) |
The square brackets used in the function header to signal that the input is an array. |
const Keyword |
A “security lock” that prevents a function from modifying the data you send it. |
| Base Address | The memory location of the very first element (index 0) of the array. |
1. The Core Rule: Arrays are “Pass by Reference”
The most important thing to remember is that in C++, arrays are always passed by reference.
- When you pass a simple variable (like an
int), the function usually gets a copy. - However, when you pass an array, the function gets the actual reference to the original array in memory.
The Impact: This means any change you make to the array elements inside the function (like setting them to zero) will permanently change the array in your main() program..
2. The Syntax: Defining the Function
When you write a function to accept an array, the formal parameter looks like this: void printArray(double arr[], int size).
- The Data Type: You must specify the type (e.g.,
doubleorint) of the components stored inside the array. - The Brackets: You use empty subscript operators
[]. You do not need to put a size inside these brackets; even if you do, the compiler will skip or ignore it. - The Name: You give the array a local name to use inside the function.
3. The “Size” Problem
A common challenge is that a function, by itself, has no way of knowing how many elements are in the array you sent it.
- The array’s size in
main()is out of the function’s “scope”. - The Solution: You must always pass the size as a separate integer parameter. Without the size, your loops inside the function won’t know when to stop.
4. How to Call the Function
To activate the function from your main() program, you simply use the name of the array without any brackets: describeArray(myValues, 4);.
What happens behind the scenes? When you use the array name alone, C++ sends the reference of the first index (index 0) to the function. Because arrays are stored contiguously (side-by-side), the function uses that starting point and the size you provided to navigate through every other element in the sequence.
5. Safety First: The const Keyword
Sometimes, you want a function to read your array (like printing it) but you don’t want it to change anything. Since arrays are passed by reference, an accidental change could ruin your data.
The Solution: Use the const keyword in the function header: void printArray(const int arr[], int size). If you try to modify a constant array inside the function, the compiler will throw an error (e.g., “assignment of read-only location”), preventing the change.
Based on the sources, here is the complete code implementation for passing an array to a function, demonstrating both the Pass by Reference nature of arrays and the use of the const keyword for protection.
Complete C++ Implementation: Passing Arrays to Functions
This code follows the logic described in the lecture, including the requirement to pass the array size separately and the effect of modifying array elements within a function.
#include <iostream>
using namespace std;
// Function Definition: Note empty brackets [] and separate 'size' parameter
void describeArray(double arr[], int size) {
cout << "Inside function: Modifying and printing elements..." << endl;
for (int i = 0; i < size; i++) {
// Arrays are passed by reference, so this change affects the original array
arr[i] = 1.1;
cout << "Element at index " << i << ": " << arr[i] << endl;
}
}
// Function with 'const' to prevent modification
void printOnly(const double arr[], int size) {
// arr = 5.5; // This line would cause a compiler error because of 'const'
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// 1. Initialization: Using a constant for size is recommended
const int SIZE = 4;
double values[SIZE] = {2.3, 4.5, 1.1, 6.7};
// 2. Printing array before function call
cout << "Original array in main:" << endl;
for (int i = 0; i < SIZE; i++) {
cout << values[i] << " ";
}
cout << "\n" << endl;
// 3. Function Call: Use ONLY the array name without brackets
// This passes the reference of the first index to the function
describeArray(values, SIZE);
// 4. Verification: The original array in main is now changed
cout << "\nArray in main after describeArray call (modified to 1.1):" << endl;
printOnly(values, SIZE);
return 0;
}
Key Technical Insights from the Implementation
- The Size Parameter: Because the function cannot “see” the size of the array declared in
main(it is out of scope), you must pass the size as a separate integer. - The Subscript Operator: In the function header, the empty brackets
arr[]signal that a reference to an array is being passed. While you can put a number inside these brackets, the compiler will skip or ignore it. - Reference Logic: When calling
describeArray(values, SIZE), you are not sending a copy. Instead, the reference of the first element (index 0) is sent. Because array memory is contiguous, the function can find all subsequent elements using this starting point. - Data Protection: If you want to ensure the function only “reads” the data and does not “modify” it, you must add the
constkeyword before the data type in the function header. Attempting to change aconstarray results in a “read-only location” error.
Interactive Elements: Try It Yourself!
- Point to Ponder: Why do you think C++ passes arrays by reference instead of making a copy? (Hint: Think about a massive array with 1 million elements!).
- Challenge 1: Write a function
squareElementsthat takes an array and multiplies every number by itself. Does the original array inmainchange?. - Challenge 2: Try to define an array with size 5 in a function header. What happens if you try to pass an array of size 10 to it? (Remember: the compiler ignores the number in the header!).
- Logic Test: If you pass an array to a function with the
constkeyword and try to setarr = 0;, what specific error do you think you will see?. - Multi-Array Task: Try to create a function that accepts two different arrays and their respective sizes. The function should return the product of each respective element of the two arrays. How many total parameters will your function need?.
Hint: Declare an array of the same size as the two arrays passed as parameters.
Engagement Boost: Let’s Chat!
- What’s your biggest C++ fear? Is it the syntax of functions or the idea of accidentally changing your original data?
- Question for the comments: Can you think of a real-life situation where “Passing by Reference” (sharing the original) is better than “Passing by Value” (making a copy)?
Ready to Master the Logic?
To see the live execution of these concepts and watch how memory addresses “jump” between indices:
- Watch the full video: C++ Array as Function Parameter | Lecture 36 for the complete visual walkthrough.
- Practice: Use our website links to download the sample code for the
constandreferenceexamples. - Subscribe: Stay updated as we move into 2D arrays and advanced pointers!
For official technical deep-dives on parameter passing, check out the official C++ Documentation.
Happy Coding!
