Search code examples
c++arrayscall-by-value

Changing Array elements by call by value


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;
}

Solution

  • 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