What exactly does this mean?

I have an assignment that asks me to "Make sure to pass the array as a constant reference parameter"....I don't really know what it means by that. I currently have a function which creates a 3x3 array...I know you can't make functions return arrays, so how would I be able to pass this array into another function?
You can pass an array as an argument to a function.
Your professor is asking you to make sure to pass it as const, so that the function cannot (morally) modify it.

1
2
3
4
5
6
7
8
9
void print( const int a[ 3 ][ 3 ] )
  {
  for (int i = 0; i < 3; i++)
    {
    for (int j = 0; j < 3; j++)
      cout << setw( 5 ) << a[ i ][ j ] << " ";
    cout << "\n";
    }
  }

Hope this helps.
> "Make sure to pass the array as a constant reference parameter"
> What exactly does this mean?

Hmm.. What does it mean?

I've discovered that when people say 'const reference to T', they really mean 'reference to const T'.
For example, if someone said const int& is a ''const reference to int' what was intended was that it is a 'reference to const int'.

using the same interpretation, perhaps something like this is what is expected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum { N = 3 } ;

typedef int array_type[N][N] ;

void function( const array_type& array )
{
    std::cout << N*N << " == " << sizeof(array)/sizeof(int) << '\n' ;
    // ...
}

int main()
{
    int a[N][N] = { {1,2,3}, {4,5,6}, {7,8,9} } ;
    // ...
    function(a) ;
}


simply put. const means it cannot change.

Some times arrays can be large, so passing copies of arrays is not efficient ie. use more ram.

it is good practice to pass an array by reference, meaning tell the function where to find the array in ram, rather pass the function a copy of the array which takes more space...

the thing is, passing by ref means u can change the contents of the array.
by making it constant u can no longer change anything in the array.

i assume he just wants you to manipulate the array without changing the contents.

if you have multiple functions to manipulate the array, the ORIGINAL array values will change as you call different functions. Thus we want to keep the original while we work with it. so we make it constant.
+1 Duoas
Topic archived. No new replies allowed.