What of the below is wrong please?
It is my understanding that a pointer represents an address of something of some type.
So, int i = 18
, a pointer to it is int *pI = &i;
The following 2 declarations are valid
void foo (int &something) // Will accept an address of something
void bar (int *something) // Will accept a pointer to something
When we declare a function as
void bar (int *something)
We better send a pointer to something. Indeed, foo(pI)
works.
Following the same logic, when looking at
void foo (int &something)
We should send it an address of something pointing to an int as an argument, so then:
Why is foo(&i)
wrong?
void foo (int &something) // Will accept an address of something
This is incorrect: int&
is a reference, a concept that is similar to pointers in certain ways, but not at all identical.
References are similar to pointers in that a value can be changed through a reference, just like it can be changed through a pointer. However, there is no such thing as "null reference", while NULL pointers are very common.
When you call a function that takes a reference, you simply pass the variable the reference to which you are taking - no &
operator is required:
void foo (something); // "something" must be a variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With