What is the difference between call by value and call by reference in C?
In call by value the function gets a copy of the variable, so the original value does not change. In call by reference we pass the address (a pointer), so the function can change the original value.
#include <stdio.h>
void byValue(int n) { n = 100; }
void byAddress(int *n) { *n = 100; }
int main(void) {
int a = 1, b = 1;
byValue(a);
byAddress(&b);
printf("%d %d\n", a, b);
return 0;
}
Output:
Output of the above program is
1 100
See the full chapter Call by Value and Reference.
Learn more about the similar topics:
| Tutorials |
|---|
| C Functions |
| C Function Arguments and Return Value |
| C Call by Value and Call by Reference |
| C Recursion |
| C Scope and Storage Classes |
| Exercises & Assignments |
|---|
| Write a C program to find the factorial of a number using recursion |
| Write a C program to swap two numbers using a function and pointers |