0
How to call by reference and call by value ?!!
11 odpowiedzi
+ 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 .
+ 6
Hello David , next time when you have any question please use searchbar. It'll save your time and avoid you from getting mfd.
Please refer these threads . If you don't understand then feel free to ask.
Happy learning my friend 😊
https://www.sololearn.com/discuss/125840/?ref=app
https://www.sololearn.com/discuss/1369622/?ref=app
https://www.sololearn.com/discuss/1072418/?ref=app
https://www.sololearn.com/discuss/195344/?ref=app
https://www.sololearn.com/discuss/84898/?ref=app
https://www.sololearn.com/discuss/519436/?ref=app
https://www.sololearn.com/discuss/221292/?ref=app
https://www.sololearn.com/discuss/344138/?ref=app
https://www.sololearn.com/discuss/199740/?ref=app
+ 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.
+ 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
+ 1
And by that i free more memory alright !!
0
Yep
0
But sometimes under circumstances calling by value is better
0
Can u give me example !!
0
https://code.sololearn.com/cGjGljBh3E2K/?ref=app
0
U r write