call-by-value

Can someone explain to me what is a call-by-value?
And is the below code fragment a function call to myfun an example of call-by-value?
Any help is greatly appreciated!

1
2
3
4
5
6
7
8
9
10
11
void myfun (double xl]) 
{
  ... do something with x...
}

int main() 
{
  ...
  double x[]={3.0, 1.5, 1.1}; myfun (x);
  ...
}

Call by value means that when you pass an argument in c/c++ it's a copy of the original value that is passed not the original object. It's the default function for all build-in objects (char, int, float, double etc) meaning that if you use a function and its argument is of build-in type you cannot change the value of the argument:

1
2
3
4
int x = 0;
void fun(int x) //a copy of x (here x = 0) is passed here
{x++;} //x inside fun is increased by 1
//x is again 0 here 


I am guessing this is for an array: double xl] meaning double x[]?
Well arrays although build-in type are an exception. They cannot be passed by value but rather by reference (meaning by pointer in c)
You are actually passing the address of the first element of x by using x[]. So every change you made there is affecting the original object. Only elements of arrays can be passed by value (which makes no surprise since elements of an array are build-in types!)

Hope it helped
closed account (1vRz3TCk)
Well arrays although build-in type are an exception. They cannot be passed by value but rather by reference (meaning by pointer in c)
Technically the same thing is happening. The thing to know is that whenever the name of an array is evaluated it is implicitly converted to a point to the first element in the array. So when an array is used as an argument to a function, the compiler implicitly converts it to a pointer and then this pointer is copied (call-by-value) into the function. If you make changes to the pointer itself they will only change the local pointer in the function not the point at the calling point. If you dereference the local copy of the pointer it will be pointing to the same array outside of the function.
Yea just change your parameter to double* x . Then you can pass the the arrays starting address in memory to the function like myfun (x);

You can then treat x as if it is just an array. Even if x is a pointer to the array in myfun, there is no extra syntax required.

If you do not want to change the array, simply make the parameter a const double*
Last edited on
closed account (zb0S216C)
Arrays can be passed by reference, too. They are what's known as a reference-to-an-array. The downside to these is that the length of the array must be known. Here's one:

1
2
3
4
5
int array[3] = {...};

const int(&r_arr)[3] (array);

std::cout << r_arr[0] << std::endl;


I use these whenever possible. They are quite safe an'all since they tell you the length of the array referred to by it.

[Above code compiles with MinGW]

Wazzak
Last edited on
Topic archived. No new replies allowed.