Difference Between Call by Value and Call by Reference in C (With Pointers)
Comprehending this distinction between call-by-value and call-by-reference helps to shed light on how C functions receive arguments and change the state of the calling function. From a strict point of view, C passes all arguments by value, but the difference between call by value and call by reference could be taken as a distinction between ordinary value parameters and pointer parameters. Call By Value: a function makes an independent copy of the argument passed to it, so that the modification of the argument within the function does not affect the original variable in the caller's scope. Simulated Call By Reference: the caller passes the address of a variable (&x) to a pointer parameter, and the function dereferences the pointer and changes the original memory location of the caller, but it does not copy any big structs.
Difference Between Call by Value and Call by Reference in C — Technical Overview
Comprehending this distinction between call-by-value and call-by-reference helps to shed light on how C functions receive arguments and change the state of the calling function. From a strict point of view, C passes all arguments by value, but the difference between call by value and call by reference could be taken as a distinction between ordinary value parameters and pointer parameters. Call By Value: a function makes an independent copy of the argument passed to it, so that the modification of the argument within the function does not affect the original variable in the caller's scope. Simulated Call By Reference: the caller passes the address of a variable (&x) to a pointer parameter, and the function dereferences the pointer and changes the original memory location of the caller, but it does not copy any big structs.
#include <stdio.h>
void swap_by_ptr(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void) {
int x = 10, y = 20;
swap_by_ptr(&x, &y);
printf("After pointer swap: x=%d, y=%d\n", x, y);
return 0;
}
Runnable C example
#include <stdio.h>
void swap_by_ptr(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void) {
int x = 10, y = 20;
swap_by_ptr(&x, &y);
printf("After pointer swap: x=%d, y=%d\n", x, y);
return 0;
}Expected Output
After pointer swap: x=20, y=10