Parameter Passing Types
What is parameter passing in C?
In C programming, parameter passing is the process of passing values from a calling function to a called function.
There are two commonly discussed parameter-passing methods:
1. Call by Value
2. Call by Reference (implemented in C using pointers)
Note: Strictly speaking, C uses pass by value for all function arguments. What is commonly called call by reference in C is achieved by passing pointer values.
Call by value
Definition: In call by value, a copy of the actual argument is passed to the function. Changes made to the formal parameter do not affect the original variable.Example: C Program to swap two numbers using call by value
#include <stdio.h>
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int x = 10, y = 20;
swap(x, y);
printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
Output:
x = 10
y = 20
Explanation: The function swaps only the copies of x and y. The original variables remain unchanged.
Call by reference using pointers
Definition: In the commonly used C teaching terminology, call by reference means passing the addresses of variables to a function so that it can modify the original variables through pointers.Example: C Program to swap two numbers using pointers
#include <stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x = 10, y = 20;
swap(&x, &y);
printf("x = %d\n", x);
printf("y = %d\n", y);
return 0;
}
Output:
x = 20
y = 10
Explanation
- &x passes the address of x.
- &y passes the address of y.
- int *a and int *b receive copies of those addresses.
- *a and *b access and modify the original variables.
How does it work?
- swap(&x, &y) passes the addresses of x and y.
- The pointer parameters a and b store those addresses.
- *a accesses x, and *b accesses y.
- The function exchanges the values at those addresses.
This is often called call by reference in introductory teaching, but technically C still passes the pointer arguments by value. The function uses those pointers to modify the caller's objects.
Difference between call by value and call by reference
| Feature | Call by Value | Call by Reference (using pointers in C) |
|---|---|---|
| What is passed? | Copy of the value | Address of the variable |
| Pointer required? | No | Yes, for this technique |
| Original variables modified? | No, not through the copied parameters | Yes, through dereferencing |
| Function call example | swap(x, y); | swap(&x, &y); |
| Function parameters | int a, int b | int *a, int *b |