A reference is an alias for another variable.
int x = 10;
int& ref = x; // ref is a reference to x
ref = 20; // x is now 20
std::cout << x; // Output: 20
Passing by reference allows a function to modify the argument passed to it.
void increment(int& n) {
n++;
}
int num = 10;
increment(num);
std::cout << num; // Output: 11
A function can return a reference.
int& getElement(int arr[], int index) {
return arr[index];
}
int myArray[5] = {1, 2, 3, 4, 5};
getElement(myArray, 2) = 10; // Modifies the third element
std::cout << myArray[2]; // Output: 10
When you pass an array to a function, what is actually passed is a pointer to the first element of the array.
void printArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
}
}
int myArray[5] = {1, 2, 3, 4, 5};
printArray(myArray, 5); // Output: 1 2 3 4 5
You can pass an array by reference to ensure the size information is retained.
template<size_t N>
void printArray(const int (&arr)[N]) {
for (size_t i = 0; i < N; ++i) {
std::cout << arr[i] << " ";
}
}
int myArray[5] = {1, 2, 3, 4, 5};
printArray(myArray); // Output: 1 2 3 4 5
For multidimensional arrays, you need to specify the size of all dimensions except the first.
void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < 3; ++j) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
int my2DArray[2][3] = {{1, 2, 3}, {4, 5, 6}};
print2DArray(my2DArray, 2);
// Output:
// 1 2 3
// 4 5 6