doesn't execute as I want it
This question already has an answer here:
Pass by value creates a copy of the argument. It is this copy that is changed in the function
void add(int x){
x = x+1;
}
Thus the change you make is made to the copy and not the variable in your main
scope (that you are expecting to see changed).
If you want to change a variable within a function by passing it as a parameter you cannot pass by value. You could change your function to pass by pointer like this
void add(int* x){
*x = *x + 1;
}
and pass the address of an integer to the function like this
int y=3;
add(&y);
within main()
The pointer is still passed by value so it is a copy of the pointer that is being acted on, but this doesn't matter as you are not changing the pointer itself, you are changing the value of the variable it points to.
This function:
void add(int x) {
x = x + 1;
}
Essentially says this: create a function named add
, that returns nothing ( void
), and takes a single integer argument x
. Then you call the function:
y = 3;
add(y);
This says "Set the variable named y
to 3. Now call the add()
function passing as an argument the current value of y
, namely 3. This is no different from
add(3);
The argument x
is entirely local to the function add()
. It exists only inside the function, and does not affect anything outside it.
So your function dutifully adds 1 to the number you gave it, and then throws it away. Just like you told it to.
C has no "pass by reference" like other languages, where you can tell a function to act on a variable itself rather than its current value. It does, however, have pointers, which can accomplish similar things.
All function arguments in C are passed by value. That means that the parameter (in this case, x
defined in add
) is initialized to a copy of the value of the argument (in this case, y
, which has the value 3
).
Since x
is a local variable, executing
x = x + 1;
changes the value of x
, but that change has no effect after the function returns and x
no longer exists.
Note that the argument doesn't have to be the name of a variable. You can legally call your function like this:
add(42);
x
is initialized to 42
-- but x = x + 1
certainly isn't going to change the value of 42
.
If you want to modify the value, you can have the function return the new value:
int add(int x) {
return x + 1;
}
The caller can do anything it likes with the result, including assigning it back to the variable:
int y = 3;
y = add(y);
Or you can pass the address of the object you want to modify:
int add(int *x) {
*x = *x + 1;
}
and then the caller can do this:
int y = 3;
add(&y);
This is still pass-by-value, but the value being passed is a pointer value, the address of x
. It's how we can emulate pass-by-reference in C.
上一篇: 什么是在C中传递的byValue和byReference参数?
下一篇: 没有按照我的要求执行