当前位置: 首页 > 文档资料 > C++ 中文教程 >

Call by Value

优质
小牛编辑
126浏览
2023-12-01

将参数传递给函数的value call by value方法将参数的实际值复制到函数的形式参数中。 在这种情况下,对函数内部参数所做的更改不会对参数产生影响。

默认情况下,C ++使用call by value来传递参数。 通常,这意味着函数内的代码不能改变用于调用函数的参数。 考虑函数swap()定义如下。

// function definition to swap the values.
void swap(int x, int y) {
   int temp;
   temp = x; /* save the value of x */
   x = y;    /* put y into x */
   y = temp; /* put x into y */
   return;
}

现在,让我们通过传递实际值来调用函数swap() ,如下例所示 -

#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;
   // calling a function to swap the values.
   swap(a, b);
   cout << "After swap, value of a :" << a << endl;
   cout << "After swap, value of b :" << b << endl;
   return 0;
}

当上面的代码放在一个文件中,编译和执行时,它会产生以下结果 -

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

这表明尽管在函数内部已经更改了值,但值没有变化。