I am working through a c++ book/guide, but the pointers and references seem a little vague to me. This is coming from myself as a C# programmer and c# mindset that uses
foo(ref int x) and bar(out int y)
A small piece of code I wrote to show the memory position and memory position value, but I do not fully understand what each means, and in what context this is in.
int main()
{
int i = 50;
foo(&i);
cout << "\n\n" ;
foo(i);
getchar();
return 0;
}
void foo(int& bar) // & refer
{
cout << "refer";
cout << "\n&bar = " << &bar;
cout << "\nbar = " << bar;
}
void foo(int* bar)// * pointer
{
cout << "prefer";
cout << "\n&bar = " << &bar;
cout << "\nbar = " << bar;
}
output shows:
pointer
&bar = 0018FC30
bar = 0018FD04
refer
&bar = 0018FD04
bar = 50
What does & and * in each case mean, and how does it affect the output?
ofcourse, I have added all necessary methods into the .h file
UPDATE AFTER READING SOME ANSWERS
int i (values from pointer, aka points directly to variable)
- has a value = 50
- has an memory address = 0018FD04
pointer which points to int i
- has a value which is int i memory address = 0018FD04
- has its own memory address = 0018FC30
thus, to clarify, using a "refer" or "&bar" in the example actually creates a new variable which duplicates the int i
passed through in the foo(int& bar)
.
Instead of the new &bar
value containing the 50, it will have the memory address of the int i
.
TL;DR
foo(int bar)
receives the "value" of the variablefoo(int* bar)
receives the "value" of the variable, if changed, it will change the variable in the calling method.foo(int& bar)
receives the pointer/memory address of the variable.
I hope others find this as useful as I did, thank you all!