Easy Tutorial
❮ Cpp Member Operators Cpp Loops ❯

C++ Call by Value

C++ Functions

The call by value method of passing parameters 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 actual parameter.

By default, C++ uses the call by value method to pass parameters. Generally, this means that code within a function cannot alter the arguments used to call the function. The function swap() is defined as follows:

// Function definition
void swap(int x, int y)
{
   int temp;

   temp = x; /* Save the value of x */
   x = y;    /* Assign y to x */
   y = temp; /* Assign x to y */

   return;
}

Now, let's call the function swap() by passing actual parameters:

Example

#include <iostream>
using namespace std;

// Function declaration
void swap(int x, int y);

int main ()
{
   // Local variable declaration
   int a = 100;
   int b = 200;

   cout << "Before swap, value of a :" << a << endl;
   cout << "Before swap, value of b :" << b << endl;

   // Call the function to swap values
   swap(a, b);

   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 100
After swap, value of b : 200

The above example demonstrates that although the values of a and b are changed inside the function, the actual values of a and b remain unchanged.

C++ Functions

❮ Cpp Member Operators Cpp Loops ❯