Home > Software engineering >  Whats the difference between reference to an array and array as a parameters in functions?
Whats the difference between reference to an array and array as a parameters in functions?

Time:12-18

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?

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?

CodePudding user response:

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 (provided that the corresponding parameter has the qualifier const) like for example

f( { 1, 2, 3 } );

Here is a demonstration program

#include <iostream>

void f( const int ( &a )[] )
{
    std::cout << "void f( const int ( & )[] ) called.\n";
}

void f( const int ( &a )[2] )
{
    std::cout << "void f( const int ( & )[2] ) called.\n";
}

void f( const int a[] )
{
    std::cout << "void f( const int [] ) called.\n";
}


int main()
{
    f( { 1, 2, 3 } );
}

The program output is

void f( const int ( & )[] ) called.

CodePudding user response:

Since you cannot pass arrays by value (a C restriction that C inherits) any declaration of a parameter as an array will 'decay' into a pointer (losing its size). So the declaration

void f__(char t[5])

is identical to

void f__(char *t)

Everything else follows from this -- within the body of f__, t has a pointer type, NOT an array type. So any auto inferencing from it will be based on that pointer type.

  • Related