Prime #### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime #### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# Call by Value Vs Call by Reference (Difference Between)

## Call by Value Vs Call by Reference

### Call by value

• Sending the values of variables from caller to calle function is called call-by-refernce
• Any changes made in function defination will not affect in caller fucntion

#### Example

`#includevoid swap(int,int);main()//caller function{int a=2,b=3;swap(a,b);//fun_callcout<<"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 /*a+b=5b=5-(a=3)//a changes to 3 b changes b=5-3=2*/cout<<"In called:after swapping a="<<a<<" b="<<b;}`  o/p

`In calle:after swapping a:2 b:3In 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’

• 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

`#includeusing namespace std;void swap(int*,int*);main()//caller function{int a=2,b=3;swap(&a,&b);//fun_callcout<<"In calle:after swapping a="<<a<<" b="<<b<<endl;//a,b changes}void swap(int *c,int *d){*d=(*c+*d)-(*c=*d);//swap logic in a single line /*a+b=5b=5-(a=3)//a changes to 3 b changes b=5-3=2*/cout<<"In called:after swapping a="<<a<<" b="<<b<<endl;}`

O/P

`In calle: after swapping a:3 b:2In called: after swapping a:3 b: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