Call by Value and Call by Reference in C
On this page (13sections)
Introduction
C passes function arguments by value — the called function receives a copy of each argument. To modify the caller’s variables from inside a function, you pass pointers (addresses). This pattern is often called call by reference in C textbooks, though technically C always passes the pointer by value.
Call by Value
Changes inside the function do not affect the original variable:
#include <stdio.h>
void increment(int n) {
n = n + 1;
printf("Inside function: %d\n", n);
}
int main(void) {
int x = 10;
increment(x);
printf("In main: %d\n", x);
return 0;
}
Sample Output
Inside function: 11
In main: 10
x in main remains 10 because only a copy was passed.
Call by Reference (Using Pointers)
Pass the address so the function can modify the original:
#include <stdio.h>
void increment(int *n) {
*n = *n + 1;
printf("Inside function: %d\n", *n);
}
int main(void) {
int x = 10;
increment(&x);
printf("In main: %d\n", x);
return 0;
}
Sample Output
Inside function: 11
In main: 11
Swap Example — Why Pointers Matter
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 5, y = 10;
printf("Before: x=%d, y=%d\n", x, y);
swap(&x, &y);
printf("After: x=%d, y=%d\n", x, y);
return 0;
}
Sample Output
Before: x=5, y=10
After: x=10, y=5
Without pointers, swap cannot change the caller’s variables. See the full Swap Using Pointers program.
Returning Values vs Using Pointers
| Approach | When to use |
|---|---|
| Return value | Single result (int square(int n)) |
| Pointer parameter | Modify caller’s variable or return multiple results |
| Return pointer | Return dynamically allocated data (caller must free) |
Arrays Are Passed by Reference Automatically
When you pass an array to a function, C passes a pointer to the first element — modifications inside the function affect the original array:
void doubleArray(int arr[], int size) {
for (int i = 0; i < size; i++)
arr[i] *= 2;
}
Best Practices
- Use pointers when the function must modify caller data.
- Mark read-only pointer parameters as
const char *strwhen not modifying. - Document which parameters are input-only vs output.
- Check for
NULLpointers before dereferencing.
Common Mistakes
- Forgetting
&when passing a variable for modification. - Dereferencing an uninitialized pointer.
- Returning address of a local variable (dangling pointer).
Related Pages
Continue learning with these related tutorials and programs:
- C Tutorials — Browse all C Tutorials.
- C Array — Concept hub — start with arrays before pointers.
- C Strings in C Programming — More in c concepts.
- C Functions — More in c concepts.