Search code examples
c++arraysfunctionarguments

How to make passing an array by reference optional in C++ function?


Is there a way to pass default value to array which is passed by reference to a function so that passing it is not necessary?

I have a function like this:

void foo(int (&arr) [3])
{
    //some code...
}

Then i tried this:

void foo(int (&arr) [3] = nullptr)
{
    //some code...
}

but it obvoiusly didn't work because reference cannot be nullptr and it is not even an array.

EDIT: I would like not to use std::array if possible, and I also need to know the size of passed array without passing its size which is why I didn't do this: int (*arr)[3].


Solution

  • In C++, you cannot directly pass a default value to an array passed by reference. However, you can achieve a similar effect by overloading the function with a version that accepts a default array and calls the original function with it.

    Here is a Code

    void foo(int (&arr)[3]){}
    
    void foo()
    {
        int defaultArr[3] = {1, 2, 3};
        foo(defaultArr);
    }
    int main()
    {
        int arr[3] = {2, 1, 4};
        foo(arr); 
    
        foo();     
        return 0;
    }