Pass an Array by reference to function in C++

This tutorial will discuss about a unique way to pass an array by reference to function in C++.

Many times, we encounter a situation, where we need to pass a fixed size array to a function. For that we need to pass two data points in the function,

  • The data type of elements in array.
  • The size of array.

Although, we can pass the array as a pointer, and the size of array as second argument, but that would decay the array to pointer, and therefore that is not the best solution. Instead of that, we will pass the array as a reference without decaying it.

Suppose we have an array,

int arr[5] = {23, 34, 78, 23, 21};

Now we want this array to a function as a reference. For that we need to provide the array information in the function declaration, like this,

template <typename T, size_t size>
void display(T (&arr)[size])
{
    // some code
}

Here, we passed the data type and size of array as template parameters, which will be automatically deduced from the argument. The signature T (&arr)[size], tells the function that the incoming parameter is an array of type T, and the size of array is the second template parameter size. Let’s see an example, where we will pass an array in a function as a reference, and print each value of array.

Let’s see the complete example,

#include <iostream>

// Pass an Array by reference to a function
template <typename T, size_t size>
void display(T (&arr)[size])
{
    // print the contents of array
    for(int i = 0; i < size; i++)
    {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

int main()
{
    int arr[5] = {23, 34, 78, 23, 21};

    // Pass an array by reference in function
    display(arr);

    return 0;
}

Output :

23 34 78 23 21

Summary

Today we learned about several ways to pass an array by reference to function in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top