In call by value, original value is not modified.In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().
#include<stdio.h> void change(int num) { printf("Before adding value inside function num=%d",num); num=num+100; printf("After adding value inside function num=%d ", num); } int main() { int x=100; printf("Before function call x=%d", x); change(x);//passing value in function printf("After function call x=%d", x); return 0; }
Before function call x=100 Before adding value inside function num=100 After adding value inside function num=200 After function call x=100
In call by reference, original value is modified because we pass reference (address).Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.
#include<stdio.h> void change(int *num) { printf("Before adding value inside function num=%d,*num); (*num) += 100; printf("After adding value inside function num=%d, *num); } int main() { int x=100; printf("Before function call x=%d, x); change(&x);//passing reference infunction printf("After function call x=%d ", x); return 0; }
Before function call x=100 Before adding value inside function num=100 After adding value inside function num=200 After function call x=200
Call By Value |
Call By Reference |
A copy of value is passed to the function | An address of value is passed to the function |
Changes made inside the function is not reflected on other functions | Changes made inside the function is reflected outside the function also |
Actual and formal arguments will be created in different memory location | Actual and formal arguments will be created |