C++ Call by value

C++ Functions

For passing parameters to a function,Call by valuethe method copies the actual values of the arguments to the function's formal parameters. In this case, modifying the formal parameters inside the function does not affect the actual arguments.

By default, C++ usesCall by valuemethod to pass parameters. Generally speaking, this means that the code inside the function does not modify the actual arguments used to call the function. Functionswap()The definition is 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 by passing actual arguments.swap():

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 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 results:

交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 100
交换后,b 的值: 200

The above example shows that although the values of a and b were changed inside the function, the actual values of a and b did not change.

C++ Functions

other extensions