[Understanding C Language] Why should we distinguish between passing by address and passing by value?

 

Table of contents

What is pass-by-value?

 Why is there an address?

How to choose between pass-by-value and pass-by-address?

 Example:

Advantages and disadvantages of passing by value:

Advantages and disadvantages of address transfer: 


        The [Understanding C Language] column is mainly used to share Shui Mo’s superficial understanding of C. Here you may get inspiration by seeing some solutions to problems that have troubled you for a long time.


What is pass-by-value?

         ​ ​ ​ Let’s look at a piece of code first:

e.g.1


#include<stdio.h>

int Add(int x, int y)
{
	int z = 0;

	z = x + y;

	return z;

}


int main()
{
	int a = 10;
	int b = 20;
	int c = 0;

	c = Add(a, b);

	printf("%d ", c);

	return 0;
}

        For this code, we can easily find that the function Add only needs to get the values ​​​​of a and b, then add them and return them. There is no need to modify a and b themselves.

        Passing by value means that when data is passed to the formal parameters of a function, what is actually passed is a copy of the data rather than the data itself. During the value transfer process, the value of the variable itself will not be modified, only a copy of the data value is passed to the formal parameter of the function, that is, only the data is operated on and the data is not changed.

         being summed up inside the function, not changing the value of the formal parameter or actual parameter. (In fact, changing the formal parameters has no effect on the actual parameters)

        why? ——> Changing a copy of the original data will not affect the original data.

        If you want to understand in detail the operation of the function when passing parameters, you can read:

[C Language] Creation and Destruction of Function Stack Frame Space - CSDN Blogicon-default.png?t=N7T8https://blog.csdn.net/2301_79465388/article/details/134256464?spm=1001.2014 .3001.5501

 Why is there an address?

But in fact some problems cannot be solved only by passing values, for example:

 

 (Exchange the values ​​of a and b)

         why?

        When we press F10 to start debugging, turn on monitoring:

         We found that the addresses of a and x, and the addresses of b and y, are different. (In fact, it is easy to understand: because x is a copy of a and y is a copy of b)

        How to solve this problem and realize the exchange of a and b?

        At this time, consider passing the addresses of a and b into the function swap():

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>

void swap(int* pa,int* pb)
{
	int tem = *pa;
	*pa = *pb;
	*pb = tem;
}

int main()
{
	int a = 0;
	int b = 0;
	scanf("%d %d", &a, &b);

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

	swap(&a, &b);
		
	printf("%d %d\n", a, b);
	return 0;

}

        In this way, the exchange of a and b can be achieved:

How to choose between pass-by-value and pass-by-address?

         In fact, address passing seems to be more special than address passing, because it establishes a real connection between the formal and actual parameters of the function, and the value of the variable of the calling function can be changed in the called function, that is to say:

        If the function only needs the value of the variable of the calling function to implement the calculation, call by value can be used.

        If you want to modify the value of the variable in the calling function inside the function, you need to call it by address.

 Example:

e.g.2

        When we want to solve problems in life, we will write a program, but for the readability and neatness of the program, we often create functions and pass parameters to the functions:

        In fact, it is not only solving mathematical problems, but also some of our own behaviors are the process of calling functions by value!

        Here’s an interesting analogy:

        When you get a math test question, aren’t you just a “function”? When you receive information from the test paper, the calculation process you write down, and even the final answer you arrive at, are not all based on the values ​​of the test paper (actual parameters), and the final values ​​of the formal parameters (formal parameters) are returned to the marking teacher. (Main calling function)?

e.g.3

When we implement passing parameters to an array, our needs generally fall into two situations:

       1. Complete the function call without changing the value of the array;

        2. While completing the function call, change the value of the array;

But I believe you already know that array parameters are passed by address.

        In this case, what are the tips?

        The first situation:

        For example: to find the length of an array and return the length value, we can use const to modify the array name that we do not want to change:


#include<stdio.h>

char* my_strcpy(char* p1, const char* p2)
{
	char* s = p1;
	while (*p1++ = *p2++)
	{
		;
	}
	return s;
}


int main()
{
	char str1[20] = "xxxxxxxxxxxxxx";
	char str2[] = "hello";

	char* p = my_strcpy(str1, str2);

	printf("%s\n", p);


	return 0;
}

         Code analysis: This code simulates the strcpy function;

        The while statement is a very clever way of writing, and it can be implemented in one statement:

        Assignment, self-increment, and judgment of multiple functions.

        (This also reflects the compact and rigorous style of C language)


 

        The second situation:

        That is, to get the address of the array normally and operate, for example:

        Operate on an array, changing the values ​​of its elements:

        

void initBoard(char Board[ROWS][COLS], int rows, int cols, char set)
{
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			Board[i][j] = set;
		}
	}
}

         Code analysis: This code initializes a two-dimensional array and is relatively easy to understand.


Advantages and disadvantages of passing by value:

advantage:

        ​ ​ 1. To prevent accidental modification of data, the value-passing method can ensure that the caller and the callee use different memory spaces.

shortcoming:

        ​ ​ 1. Large memory overhead: passing by value requires copying the entire actual parameter value into the formal parameter

        2. Low efficiency:

        3. Unable to modify actual parameters

Advantages and disadvantages of address transfer: 

advantage:

        ​ ​ 1. When the function is called, the address is passed, which saves memory space;

        2. It makes it more convenient for the function to modify the value of the variable in the context in which it is called;

shortcoming:

        ​ ​ 1. Modifying the value of a variable within a function may produce unexpected results, so the use of address transfer needs to be handled with caution;

        (You can define constant variables and constants to avoid this)

       


over


Reprinting without the author's consent is prohibited

Guess you like

Origin blog.csdn.net/2301_79465388/article/details/134365452