Difference Between Call by Value And Call by Reference
Call by Value Vs Call by Reference
On this page we will discuss about difference between call by value and call by reference. On this page we will also write program for both to understand the difference between them in detail. These are the methods to pass parameter in a function.Hence understanding call by value and call by reference is very important to understand the basics of functionin C++.
Difference Between Call by Value And Call by Reference
Call By Value | Call By Reference |
---|---|
In this passing the value of Variable. | In this passing the address of Variable. |
Can’t change the value of actual argument using formal argument. | Can change the value of actual argument using formal argument. |
No pointers are used. | Pointers are used. |
It requires more memory. | It requires less memory. |
It is less sufficient. | It is more sufficient. |
Call by Value
Example
#include <iostream> using namespace std; void swap (int, int); int main () //caller function { int a = 2, b = 3; swap (a, b); //fun_call cout << "In calle:after swapping a=" << a << " b=" << b; } void swap (int a, int b) { b = (a + b) - (a = b); //swap logic in a single line cout << "In called:after swapping a=" << a << " b=" << b; cout << endl; }
Output:
In calle:after swapping a:2 b:3 In called:after swapping a:3 b:2
- Here ‘a’ ,’b’ in main function is different from ‘a’,’b’ from swap() function.
- Just data is copied, both are having different scopes and different memory locations
- Hence changes in the swap() ‘a’, ‘b’ will not affect the main ‘a’, ‘b’
call by address
- Sending the address of variables from caller to calle function is called call-by-address
- Any changes made in function definition will also affect the change in the caller function
Example
#include <iostream> using namespace std; void swap (int *x, int *y) { int swap; swap = *x; *x = *y; *y = swap; } int main () { int x = 2, y = 3; cout << "Value of x before swap is: " << x << endl; cout << "Value of y before swap is: " << y << endl; swap (&x, &y); cout << "Value of x is: " << x << endl; cout << "Value of y is: " << y << endl; return 0; }
Value of x before swap is: 2 Value of y before swap is: 3 Value of x is: 3 Value of y is: 2
- In this address of main() ‘a’, ‘b’ is passed to swap() and stored in pointers ‘c’, ‘d’
- Hence * c,*d points to a,b respectively and having same locations
- Here a and *c and b and *d both are the same, any changes in either caller or called function will reflect other
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment