📜  按值致电与按引用致电之间的区别

📅  最后修改于: 2021-05-25 19:44:31             🧑  作者: Mango

可以通过两种方式调用函数:按值调用按引用调用。通常,通过作为参数传递给它们的值的类型来区分这两种方式。

传递给函数的参数称为实际参数,而通过函数接收到的参数被称为形式参数

按值调用:在此参数传递方法中,将实际参数的值复制到函数的形式参数中,并将两种类型的参数存储在不同的存储位置中。因此,在函数内部进行的任何更改都不会反映在调用者的实际参数中。

按引用调用:实际参数和形式参数都指向相同的位置,因此在函数内部所做的任何更改实际上都会反映在调用者的实际参数中。

Call By Value Call By Reference
While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”. While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References.
In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function. In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function.
With this method, the changes made to the dummy variables in the called function have no effect on the values of actual variables in the calling function. With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.
// C program to illustrate
// call by value

#include 

// Function Prototype
void swapx(int x, int y);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass by Values
    swapx(a, b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Swap functions that swaps
// two values
void swapx(int x, int y)
{
    int t;

    t = x;
    x = y;
    y = t;

    printf("x=%d y=%d\n", x, y);
}


Output:
x=20 y=10
a=10 b=20
// C program to illustrate
// Call by Reference

#include 

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
    int a = 10, b = 20;

    // Pass reference
    swapx(&a, &b);

    printf("a=%d b=%d\n", a, b);

    return 0;
}

// Function to swap two variables
// by references
void swapx(int* x, int* y)
{
    int t;

    t = *x;
    *x = *y;
    *y = t;

    printf("x=%d y=%d\n", *x, *y);
}

Output:
x=20 y=10
a=20 b=10
Thus actual values of a and b remain unchanged even after exchanging the values of x and y. Thus actual values of a and b get changed after exchanging values of x and y.
In call by values we cannot alter the values of actual variables through function calls. In call by reference we can alter the values of variables through function calls.
Values of variables are passes by Simple technique. Pointer variables are necessary to define to store the address values of variables.


注意:
在C语言中,我们使用指针来实现按引用调用。在C++中,我们可以使用指针或引用来进行按引用传递。在Java,原始类型作为值传递,非原始类型始终是引用。

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。