按引用调用和按值调用之间的差异

可能重复:
值参数和参考参数之间的差异?

按引用调用和按值调用之间有什么区别?

在C中,没有通过引用的调用。 你可以得到的最接近的地方是获取一个地址,并传递该地址的副本(按价值 – 见下文)。

在C ++中,按引用调用传递对象的引用(原始对象的别名)。 通常这将作为对象的地址实现,但不能保证。

按值调用意味着获取某种值,并将该值的副本传递给该函数。

基本区别在于,当您按值传递参数时,该函数仅接收原始对象的副本 ,因此它无法执行任何操作来影响原始对象。 通过引用传递,它获得对原始对象的引用,因此它可以访问原始对象,而不是它的副本 – 除非它是const引用,它可以修改原始对象(例如)。

简而言之, 通过引用调用函数可以修改其参数:

def f(x): x := x + 1 print(x) x := 1 f(x) /* Now, x is 2 */ print(x) 

在“按引用调用”中,上面将打印2次两次。

按值调用是指函数接收传递给它的参数的副本,因此调用者不会看到任何修改。 使用上面定义的f(x) ,按值调用将是:

 x := 1 f(x) /* x is 1 in the caller */ print(x) 

在上面的f(x) ,打印调用将打印2 ,但是只修改f()得到的x的副本,因此在调用者中, x仍然是1,而第二个print()打印1

 Call by value: 1 2 3 4 5 6 7 void foo( int x ) { cout << x << endl; x = 4; } int someVar = 5; foo( someVar ); The value 5 is pushed onto the stack and foo is called. Inside foo(), 5 is popped off the stack and output. x = 4 modifies the stack copy, which is then thrown away when the function returns. 1 2 3 4 5 6 7 void foo( int& x ) { cout << x << endl; x = 4; } int someVar = 5; foo( someVar ); The address of someVar is pushed onto the stack and foo is called. Inside foo, the address is popped off the stack and the integer stored at that address is output. x = 4 modifies the memory referred to by the address, which means that when foo() returns, someVar now has the value 4. Contrast the above code to 1 2 3 4 5 6 7 void foo( int* x ) { cout << *x << endl; *x = 4; } int someVar = 5; foo( &someVar ); This code does the exact same thing as my reference example, it's just the syntax is a bit different: note the &someVar where foo is called, and note the *x in foo() to refer to the integer value. 

在通过引用调用时,您将获得变量的实例。 更改函数的参数后,在这种情况下,您的变量将在调用方法中更改。 在按值调用时,您将获得实例的副本。 在这种情况下,参数变量的变化不会影响调用方法中的变量

传递给函数的参数可以是两种类型,即1.传递的值2.传递的地址

第一种类型是指按值调用,第二种类型是指按引用调用。 例如,考虑program1

  main() { int x=50, y=70; interchange(x,y); printf(“x=%dy=%d”,x,y); } interchange(x1,y1) int x1,y1; { int z1; z1=x1; x1=y1; y1=z1; printf(“x1=%d y1=%d”,x1,y1); } 

这里函数交换的值按值传递。

考虑program2

 main() { int x=50, y=70; interchange(&x,&y); printf(“x=%dy=%d”,x,y); } interchange(x1,y1) int *x1,*y1; { int z1; z1=*x1; *x1=*y1; *y1=z1; printf(“*x=%d *y=%d”,x1,y1); } 

这里函数通过引用调用。 换句话说,使用符号&传递地址,并使用符号*访问该值。

通过分析program1和program2的输出可以看出它们之间的主要区别。

按值调用的program1的输出是

 x1=70 y1=50 x=50 y=70 

但是通过引用调用的program2的输出是

 *x=70 *y=50 x=70 y=50 

这是因为在按值调用的情况下,值被传递给名为swap的函数,并且值互换并打印为

 x1=70 y1=50 

并且因为没有返回值,因此x和y的原始值就像在main函数中那样

 x=50 y=70 got printed.