Pass by reference syntax | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Pass by reference syntax

In the c++ tutorial, it uses something like: void func(int *x){ *x = 20; } int main (){ int x = 5; func(&x); cout << x; } as an example of pass by reference instead of pass by value. Does this code do the same thing? void func(int &x){ x=20; } int main (){ int x = 5; func(x); cout << x; } What's the difference between the two? I know in the first one passes the address of x and the function is the pointer of x and changes x by dereference. But then how does the second one change the value of x?

13th Jan 2017, 1:21 AM
Cindy
1 Answer
+ 6
References are implemented using pointers internally but are "safer". They are like aliases .
13th Jan 2017, 4:09 AM
Karl T.
Karl T. - avatar