+ 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; } ;)
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/
+ 2
thanks for your time! explaining this
+ 1
who the hell downvoted this?đŁđŁđ·đ€đ
+ 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.
+ 1
đżgood thoughtsđ€
0
You're welcome. That was actually a good question, since the difference is not really clear.