int n=10;
ADD1 (n);
1. General formal Parameters
void add1 (int v1)
{
v1+=1;/has no effect on arguments
}
This is the most common form parameter, and the formal parameter is only a copy of the argument, and any action on the formal parameter does not modify the value of the argument. The action on V1 in the example only modifies a copy of the argument. The argument does not change
int *p=&n;
ADD2 (p);//p is a pointer to n
or direct ADD2 (&n)
2. Pointer parameter
void add2 (int *p)
{
*p+=1;//The actual argument is changed
p+=1;//has no effect on arguments
(*p) ++;//arguments are changed
}
Using pointers as the parameters of a function, only the action on the object that the pointer refers to will change the value of the argument. There is also a more secure and natural way to implement change arguments-reference parameters.
When executing add2 (&n), the system adds P "in a row of ADD2 in the memory allocation table, with a new address and a value of &n. Operation *p, that is, in the operation of N. Kind of like a reference, *p is an alias for n
int a=1,b=2;
Swap (A,B);
3, reference parameters
void swap (int &a,int &b)
{
int temp=a;
A=b; Will change the value of the argument
B=temp; Will change the value of the argument
}
A reference parameter is directly associated with the object to which it is bound, rather than a copy of those objects. So this method can modify the value of the argument and is more intuitive.
the formal parameters and arguments of a function have the following characteristics:
1. Parametric allocates memory cells only when called, releasing the allocated memory cells at the end of the call. Therefore, the formal parameters are valid only within the function. When a function call finishes returning the calling function, the parameter variable is no longer available.
2. Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, they must have a definite value to pass the value to the formal parameter when the function call is made. Therefore, the actual parameters should be given a definite value by means of assignment, input and so on.
3. Arguments and formal parameters should be strictly consistent in quantity, type, or in order, or a type mismatch error will occur.
4. The data transfer occurring in the function call is one-way. That is, the value of the argument can only be passed to the formal parameter, and the value of the parameter cannot be transferred back to the argument. Therefore, during a function call, the value of the formal parameter changes, and the value in the argument does not change. So you need to modify it manually.