call by value c

This commit is contained in:
Thomas Bishop 2026-01-17 18:57:02 +00:00
parent 2ba5bfb2f3
commit f55f6f6ad6

64
zk/C_is_call_by_value.md Normal file
View file

@ -0,0 +1,64 @@
When you pass a value into a C function as an argument it creates a copy of the
value that is stored outside of the function (the parameter value). This value
is modified by the function.
Changes to that value within function scope are not reflected in the main scope
- the values that were passed in as arguments..
Say the function returns the value it modifies. The modified version will only
be accessible from the function, the original main scope value will be the same
as it was when the value entered the function.
This is why [pointers](./Pointers_in_C.md) are used in cases where you want a
function to change the value of a variable in main scope.
## Demonstration
```c
void swap (int a, int b) {
int t = a;
a = b;
b = t;
printf("a = %d, b = %d", a, b);
}
```
With this form of the function we get:
```c
int main(){
int a = 21;
int b = 17;
swap(a,b);
printf("a = %d, b = %d", a, b);
}
// a = 17, b = 21
// a = 21, b = 17
```
Refactoring the function to use pointers gives us:
```c
void swap (int *pointer_a, int *pointer_b) {
int t = *pointer_a;
*pointer_a = *pointer_b;
*pointer_b = t;
}
```
Now that we are using pointers, we can pass in the main scope variables:
```c
swap(&a, &b);
```
Which will cause the main function to return what we expect:
```txt
a = 17, b = 21
```
While the non-pointerized version of the function enshrines **call by value**,
the pointerized version enshrines **call by reference**.