In C Language, "call by value" and "call by reference" are two different ways to pass arguments to functions.
Functions can accept arguments either by value or by reference.
In call by value, a copy of the actual parameter's value is passed to the function.
Any changes made to the parameter within the function do not affect the original value of the argument.
Typically used for passing primitive data types like integers, floats, characters, etc.
#include <stdio.h> void increment(int x) { x++; printf("Inside function: x = %d\n", x); } int main() { int num = 5; printf("Before function call: num = %d\n", num); increment(num); printf("After function call: num = %d\n", num); return 0; }
the value of "num" remains unchanged outside the function despite being modified inside the "increment()" function because the changes were made to a copy of "num".
Before function call: num = 5 Inside function: x = 6 After function call: num = 5
#include <stdio.h> void swap(int a, int b) { int temp = a; a = b; b = temp; printf("Inside swap function: a = %d, b = %d\n", a, b); } int main() { int x = 5, y = 10; printf("Before swap: x = %d, y = %d\n", x, y); swap(x, y); printf("After swap: x = %d, y = %d\n", x, y); return 0; }
although "a" and "b" are swapped inside the "swap()" function, the actual variables "x" and "y" in the "main()" function remain unchanged. This is because "a" and "b" are copies of "x" and "y" respectively.
Before swap: x = 5, y = 10 Inside swap function: a = 10, b = 5 After swap: x = 5, y = 10
#include <stdio.h> void increment(int *x) { (*x)++; printf("Inside function: *x = %d\n", *x); } int main() { int num = 5; printf("Before function call: num = %d\n", num); increment(&num); printf("After function call: num = %d\n", num); return 0; }
the value of "num" is modified directly within the "increment()" function because the address of num was passed to it. Thus, the changes made inside the function are reflected in the original variable "num".
In call by reference, the memory address (pointer) of the actual parameter is passed to the function.
Any changes made to the parameter within the function directly affect the original value of the argument.
Typically used for passing arrays or structures where passing a copy of the entire data would be inefficient.
Before function call: num = 5 Inside function: *x = 6 After function call: num = 6
"x" and "y" are swapped successfully inside the "swap()" function because their addresses are passed (by reference) to the function. As a result, the changes made inside the function are reflected in the original variables "x" and "y".
#include <stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; printf("Inside swap function: *a = %d, *b = %d\n", *a, *b); } int main() { int x = 5, y = 10; printf("Before swap: x = %d, y = %d\n", x, y); swap(&x, &y); printf("After swap: x = %d, y = %d\n", x, y); return 0; }
Before swap: x = 5, y = 10 Inside swap function: *a = 10, *b = 5 After swap: x = 10, y = 5