C Function Parameters
Parameters let you pass data into a function so it can operate on different values each time it's called. In C, arguments are passed by value by default, meaning the function receives a copy.
To let a function modify the caller's original variable, you must pass a pointer to it, a technique often called 'pass by reference' even though C only truly supports pass by value.
void func(int x); // pass by value
void func(int *x); // pass by pointerPass by value
When you pass a normal variable to a function, C copies its value into the parameter. Changes made inside the function do not affect the original variable.
Pass by pointer
Passing a pointer (an address) lets the function dereference it and modify the original variable directly, since it has access to the actual memory location.
#include <stdio.h>
void addOne(int x) {
x = x + 1;
}
int main() {
int a = 5;
addOne(a);
printf("%d\n", a);
return 0;
}5Since x is a copy of a, changing x inside addOne does not affect a.
#include <stdio.h>
void addOne(int *x) {
*x = *x + 1;
}
int main() {
int a = 5;
addOne(&a);
printf("%d\n", a);
return 0;
}6Passing &a lets addOne modify the original variable through the pointer.
Key points
- C passes arguments by value by default โ the function gets a copy.
- Pass a pointer to allow a function to modify the caller's variable.
- Arrays are effectively passed by reference since they decay to pointers.
- Function parameter names don't need to match the caller's variable names.
