+ 4

explain difference between these 2 codes

#include <iostream> using namespace std; void myFunc(int *x) { *x = 100; } int main() { int var = 20; myFunc(&var); cout << var; } and..... #include <iostream> using namespace std; //diffrent point & void myFunc(int &x) { x = 100; } int main() { int var = 20; myFunc(var); //different point var cout << var; } ;)

17th Feb 2018, 4:14 AM
Jay Jay
Jay Jay - avatar
6 Answers
+ 1
In the 1st code you pass a pointer, in the 2nd code you pass a reference. They behave a bit different. As you can see by passing a reference you can directly access the value without dereferencing (*x = 100 in 1st code). But you can't iterate a reference, whereas you can iterate a pointer (so that it points to the next memory block) here is an article about the differences and a short guideline when to use what kind of passing a memory address: https://www.geeksforgeeks.org/passing-by-pointer-vs-passing-by-reference-in-c/
17th Feb 2018, 10:33 AM
Alex
Alex - avatar
+ 2
thanks for your time! explaining this
17th Feb 2018, 10:35 AM
Jay Jay
Jay Jay - avatar
+ 1
who the hell downvoted this?đŸ˜ŁđŸ˜ŁđŸ˜·đŸ€’đŸ˜”
14th Mar 2018, 10:45 AM
Jay Jay
Jay Jay - avatar
+ 1
I guess it was someone who thinks it makes me sad. Maybe this person was sad because I didn't do his homework for him. Good that I don't care if someone dislikes my posts or codes. I'm happy when someone corrects my mistakes, but I couldn't care less about someone downvoting me for no reason at all.
14th Mar 2018, 11:19 AM
Alex
Alex - avatar
+ 1
🗿good thoughtsđŸ€—
14th Mar 2018, 11:25 AM
Jay Jay
Jay Jay - avatar
0
You're welcome. That was actually a good question, since the difference is not really clear.
17th Feb 2018, 10:36 AM
Alex
Alex - avatar