C++ function call by value

Using call by value method, only the copies of actual arguments is passed to the called function. By default, C++ uses call by value to pass arguments . The call by value method  of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. In general, this means that code within a function cannot alter the arguments used to call the function. Following code defines how call by values take place:

// function definition to swap the values.

void swap(int x, int y)

{

int temp;

temp = x; /* store the value of x */

x = y;    /* insert y into x */

y = temp; /* insert x into y */

return;

}

Now let us call the function swap() by passing actual values as in the following example:

#include <iostream>

// function declaration

void swap(int x, int y);

int main ()

{

// variable declaration:

int a = 5;

int b = 10;

cout << ” Value of a before swaping :” << a << endl;

cout << ” Value of b before swapping :” << b << endl;

// calling a function to swap the values.

swap(a, b);

cout << ” Value of a after swapping :” << a << endl;

cout << ” Value of b after swapping :” << b << endl;

return 0;

}

When the above code is put together in a file, compiled and executed, it produces following result:

Value of a before swapping: 5

Value of b before swapping: 10

Value of a after swapping : 5

Value of b after swapping : 10

Which shows that there is no change in the values though they had been changed inside the function.