-3

I am passing array elements to a function. This function adds 5 to each element of the array. I am also passing an integer and adding 5 to it... Even though it is a 'call by value' function the value of the integer dosn't change in main() (which is expected) but the array elements do change...

I wan't to know how and why?

#include <iostream>

using namespace std;

void change(int x[],int y);

int main()
{
    int sharan[]={1,2,3,4};
    int a=10;
    change(sharan,a);
    for(int j=0;j<4;j++)
    {
        cout<<sharan[j]<<endl;
    }
    cout<<endl<<"a is : "<<a;
    return(0);
}

void change(int x[],int y)
{
    for(int i=0;i<4;i++)
    {
        x[i]+=5;
    }
    y+=5;
}
Galik
  • 47,303
  • 4
  • 80
  • 117
Sharan Sondhi
  • 87
  • 1
  • 11
  • You need a pointer to change the value of the variable – Spikatrix Oct 02 '14 at 07:30
  • passing integer a and then adding 5 to y!!!!!!! – Sharan Sondhi Oct 02 '14 at 07:30
  • 1
    When you call `change(sharan,a)` a copy of the value of a is made and used inside the function. (The function assigns 5 to that copy which is fine but has nothing to do with the outside `a` which stays unaffected.) Declare the parameter `y` as a reference like this: `void change(int x[],int &y){ ... }`. Then y will become an alias for (not a copy of) of a and changes to y will be equivalent to changes of a. – Peter - Reinstate Monica Oct 02 '14 at 07:33

3 Answers3

5

Array decays to pointer,

void change(int x[],int y) is equivalent to void change (int *x, int y )

with x[i] += 5;

you're changing the content of address at x+i

y=5; inside change basically updates a local copy of y whose address wasn't passed, hence no modification in actual value of y after change exists

P0W
  • 46,614
  • 9
  • 72
  • 119
1

since array is always a reference type so any changes outside will affect the array in calling function too.

As you can see in your code :

change(sharan,a); // here `sharan` points the base address an you are passing it.
Rustam
  • 6,485
  • 1
  • 25
  • 25
1

C++ does not support passing raw arrays by value. When you try to pass them as such they are converted into a pointer to the array. For this reason if you modify the elements of the array then the change will be reflected in the calling function. In this case main().

Galik
  • 47,303
  • 4
  • 80
  • 117