When calling a function, C determines whether the function works on a copy of the argument’s data or directly on the original data in memory. This distinction is known as the parameter passing method.
1. Passing by Value (Default Method)
Pass by value is the default method in C for simple variables (like int, float, char).
- Mechanism: When the function is called, the value of the argument is copied into the function’s parameter.
- Effect: The function operates on the copy. Any changes made to the parameter inside the function do not affect the original variable in the calling function.
Example: Pass by Value
void increment_value(int num) {
num = num + 10; // Only changes the local copy 'num'
printf("Inside function: %d\n", num);
}
int main() {
int x = 5;
increment_value(x);
printf("Outside function: %d\n", x); // x is still 5
return 0;
}
2. Passing by Reference (Using Pointers)
Pass by reference is achieved in C by explicitly passing the memory address of the variable (using the & operator) instead of the value. The function receives a pointer to the original data.
- Mechanism: The function receives a pointer (
dataType *) to the original variable. Inside the function, the dereference operator (*) is used to access and modify the original variable. - Effect: Any modification made via the pointer directly alters the original variable in the calling function.
Example: Pass by Reference (Swapping Values)
A classic use case is swapping two variables, which cannot be done with pass-by-value.
// Function signature accepts the addresses of two integers
void swap_values(int *a, int *b) {
int temp = *a; // Read the value at address 'a'
*a = *b; // Change the value at address 'a'
*b = temp; // Change the value at address 'b'
}
int main() {
int num1 = 10;
int num2 = 20;
// Call the function, passing the memory addresses (&num1, &num2)
swap_values(&num1, &num2);
printf("num1: %d, num2: %d\n", num1, num2); // Output: num1: 20, num2: 10
return 0;
}
3. Multiple Return Values (Pointers)
Since a C function can only have one explicit return value, pointers provide the standard mechanism to “return” multiple values to the caller by modifying variables passed by reference.
Scenario: A function needs to calculate both the sum and the average of two numbers.
// The function returns the sum (via return), and modifies 'avg_ptr' (via pointer)
void calculate_stats(int x, int y, float *avg_ptr) {
int sum = x + y;
*avg_ptr = (float)sum / 2.0f; // Write the calculated average back to the original address
}
int main() {
int a = 10, b = 30;
float average;
// Pass the address of 'average' to the function
calculate_stats(a, b, &average);
printf("Average calculated: %.2f\n", average);
// Output: Average calculated: 20.00
return 0;
}
