We're going to talk to you about some of the knowledge about parameter passing in the C language.
1. Problem Introduction
Please write out the printing results of the following program.
#include
Add an integer to 10
void add_by_10 (int a) {
A = a + 10;
}
int main (int argc, char *argv[]) {
int a = 2;
Add_by_10 (a);
printf ("A=%d\n", a);
The above program is very simple, we define a function add_by_10, its function is to implement the integer plus 10, and then called in the main function, because a initial value of 2, when the function is called after the value of a becomes 12.
Is that really the case? If you compile and execute this program, you will find that the result of the printing is "a = 2".
Why is that? This is completely different from what you think.
2. Problem analysis
And then we'll go along with you to analyze why this is the result.
In the previous article we have said that the definition of a variable is actually from the 4G memory bar to take space, such as you define an int a, its essential meaning is to take a new 4G memory strip from your 4-byte size of space, as shown below, the yellow part of the space is a, others can not use ha.
We will further this problem, in fact, the system in allocating memory, is the function as the basic unit, such as the program defined in question 1, we have two functions, main and ADD_BY_10, so the system will first assign memory to these two functions, The variables inside the two functions then take memory in the memory space to which the respective function belongs.
A portion of the 4G memory strip is part of the main function (yellow area), and some areas are part of the ADD_BY_10 function (orange area), as shown below:
An int A is defined in the main function, so this a will take 4 bytes of space (black area) from the main area and assign a value of 2. In addition, there is a parameter int a in the ADD_BY_10 function, so this a will also take 4 bytes of space (gray area) from the Add_by_10 area, as shown below:
When executing the line add_by_10 (a) in the main function, the value of the main function A is assigned to the parameter a of the ADD_BY_10 function, as follows:
In the ADD_BY_10 function, after adding 10 to the A variable to which it belongs, a becomes 12, as follows:
After the ADD_BY_10 function call is finished, the add_by_10 memory space is freed.
From the above step by step analysis, you can see, in fact, the main function of a has always been 2, and there is no change, and change is only a value in the ADD_BY_10 function. So that's why you finally see the result: "A= 2" instead of "a= 12".
Think: How can you achieve the "a = 12" result?
Analysis of the principle of parameter transfer in C language (value transfer)