Parameter Passing Techniques
When writing functions in C, one key concept every programmer must understand is how parameters are passed. This affects whether your function works with a copy of data or directly modifies the original variable.
In C, there are two main parameter passing techniques:
1. Pass by Value (Default in C)
Pass by value means the function receives a copy of the variable’s value. Any changes made inside the function do not affect the original variable.
#include <stdio.h> void changeValue(int a) { a = 50; } int main() { int x = 10; changeValue(x); printf("x = %d\n", x); // Output: x = 10 return 0; } Explanation: Here,a
is a copy ofx
. Changinga
doesn't impact the originalx
.
2. Pass by Reference (Using Pointers)
C does not support pass by reference directly, but you can simulate it using pointers. When you pass the address of a variable to a function, it can modify the original value.
#include <stdio.h> void changeValue(int *a) { *a = 50; } int main() { int x = 10; changeValue(&x); printf("x = %d\n", x); // Output: x = 50 return 0; }
Explanation: Here, a
is a pointer to x
. By dereferencing it with *a
, we modify the original variable.
What About Arrays?
In C, arrays are always passed by reference by default. When you pass an array to a function, it receives a pointer to the first element.
void updateArray(int arr[]) { arr[0] = 99; } int main() { int nums[3] = {1, 2, 3}; updateArray(nums); printf("%d\n", nums[0]); // Output: 99 return 0; }