How to call by reference and call by value ?!! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to call by reference and call by value ?!!

10th Oct 2019, 12:08 AM
David Owens
David Owens - avatar
11 Answers
+ 1
int main() { int a = 10, b = 20; swap1(a,b); printf("a=%d , b =%d",a,b); swap2(&a, &b); printf("a =%d, b =%d",a,b); return 0; } swap1(int x, int y) { int temp = x; x = y; y = temp; } swap2(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } The first printf will not print swapped values of a and b ....but the second printf will print the swapped values of a and b ....because swap1() function is called by value whereas swap2() function is called by reference as we passed address of a and b not their value directly, hence the changes made in swap2() function definition will going to reflect in the main function .
10th Oct 2019, 4:27 PM
Arpita
+ 4
David Owens calling by value will be better if you don't want to change value of already existing variable but need to use it wothin function.
10th Oct 2019, 1:04 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
Call by value : Void hope (int p) {} Call by Reference : Void move (int &p) {} Int main () { Int t = 6; hope(t); Move(t); } See when t goes into hope (call by value) the value of t Is copped to a another created variable p in the function and function will modify p not t When value goes into move the memory address of t is gone into p so there there is only one variable and no copy of t is copped and the function uses t only in form of p So better to call by reference
10th Oct 2019, 12:43 AM
Dev Pratap
Dev Pratap - avatar
+ 1
And by that i free more memory alright !!
10th Oct 2019, 12:52 AM
David Owens
David Owens - avatar
0
Yep
10th Oct 2019, 12:53 AM
Dev Pratap
Dev Pratap - avatar
0
But sometimes under circumstances calling by value is better
10th Oct 2019, 12:53 AM
Dev Pratap
Dev Pratap - avatar
0
Can u give me example !!
10th Oct 2019, 12:57 AM
David Owens
David Owens - avatar
10th Oct 2019, 1:00 AM
Dev Pratap
Dev Pratap - avatar
0
https://code.sololearn.com/cGjGljBh3E2K/?ref=app
10th Oct 2019, 1:01 AM
Dev Pratap
Dev Pratap - avatar
0
U r write
10th Oct 2019, 1:08 AM
Dev Pratap
Dev Pratap - avatar