Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading