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

Whats the difference between reference to an array and array as a parameters in functions?

What is the difference between functions, which have reference to an array:

// reference to array
void f_(char (&t)[5]) {
    auto t2 = t;
}

and simply array:

// just array
void f__(char t[5]) {
    auto t2 = t;
}

as a parameters?

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

The calling code is:

char cArray[] = "TEST";
f_(cArray);
f__(cArray);

char (&rcArr)[5] = cArray;
f_(rcArr);
f__(rcArr);

In both cases t2 is char*, but in first function my VS2019 is showing that t inside function has type char(&t)[] and t inside second function has type char*.

So after all, is there any practical difference between those functions?

>Solution :

You can specify a complete array type parameter as for example

void f( int ( &a )[N] );

and within the function you will know the number of elements in the passed array.

When the function is declared like

void f( int a[] );

then the compiler adjusts the function declaration like

void f( int *a );

and you are unable to determine the number of elements in the passed array. So you need to specify a second parameter like

void f( int *a, size_t n );

Also functions with a referenced array parameter type may be overloaded. For example these two declarations

void f( int ( &a )[] );

and

void f( int ( &a )[2] );

declare two different functions.

And functions with a referenced array parameter type may be called with a braced list like for example

f( { 1, 2, 3 } );
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