Asad Abbas <cyberstuden...@...> wrote:
> 
> While dealing with functions in C++.
> Generally, the C++ convention is the call-by-value.
> An exception is where arrays are passed as arguments,
> Arrays are called by reference by default.

No, they aren't.

It's possible to pass by reference in C++ by using the
reference operator.

It is hence possible to pass an array by reference, but
only explicitly...

  void foo(int (&array)[10])

If you try...

  void foo(int array[10])

...the parameter will 'decay' and be treated as...

  void foo(int *array)

This is _not_ the same thing as pass by reference. The array
will be treated as a pointer to an element. The pointer is
passed by value.

Even though it _looks_ like pass by reference, a further
difference can be seen in the loss of dimension. Observe...

  #include <iostream>
  
  using namespace std;
  
  void foo(int a[5])
  {
    for (int i = 0; i < 3; i++)
      cout << a[i] << '\n';
  }
  
  int main()
  {
    int a[3] = { 1, 2, 4 };
    foo(a);
  }

The program above should compile and run just fine because
the declaration of foo is treated exactly as if it were...

  void foo(int *a)

But change the declaration to use a reference...

  void foo(int (&a)[5])

...and you should see an error.

> Is ther any way to pass the arrays to the functions by
> value rather than reference?

People have mentioned wrapping in structs, but that is
not passing an array, that is passing a struct. There is
no way to pass an array by value in C++ (or C.)

-- 
Peter

Reply via email to