eolas/zk/C_is_call_by_value.md

67 lines
1.3 KiB
Markdown
Raw Normal View History

2026-01-19 17:06:41 +00:00
---
tags:
- C
---
2026-01-17 18:57:02 +00:00
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
```