C++ function parameter passing (three types of parameter passing)

There are three types of function parameter passing: passing by value, passing by pointer and passing by reference. The latter two functions are similar.
Passing Value After the
parameter is passed to the function, it is only a local variable. Modifying this variable cannot change the value of the actual parameter, that is, this is a one-way pass.

void add(int x)
{
    
    
x++;
}
int main()
{
    
    
int b=1;
add(b);//函数完成后b的值不变
}

Passing pointers In
theory, what is passed into the function is also a value, but this value is essentially an address, so modifying this pointer cannot affect the external pointer, that is, the formation and the actual parameter are two independent pointers.
However, before the address pointed to by the formal parameter is changed, the value in the address saved by the pointer is modified by the address saved in the pointer.

void test(int* x)
{
    
    
    *x += 5;
}
int main()
{
    
    
    int a = 0;
    int* b = &a;
    test(b);
    cout << *b << " " << a;//结果是5 5
}

Passing by
reference Passing by reference means passing the address of the parameter. Modifying the content in this address will naturally modify the outside parameter.

void add1(int& x)
{
    
    
    x += 5;
}
int main()
{
    
    
    int a = 1;
    int* b = &a;
    add1(a);
    cout << *b << " " << a;//结果是6 6
}

Summary:
The storage unit of the formal parameter is allocated when the function is called
. The actual parameter can be a constant, variable or expression
. The type of the actual parameter must match the formal parameter
. The parameter value is passed when the value is passed, that is, one-way transfer
. Pass by reference Two-way transfer can be achieved
. Often quoted as a parameter can ensure the safety of the actual parameter data
. Passing by reference is more efficient than passing by value (this will be discussed later)

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/113732502