& vs ptr

S

Steve

what is the difference between passing by & and passing by pointer
for example
doSomething(int & address);
doSomething(int * ptr);
thanks
 
V

Victor Bazarov

Steve said:
what is the difference between passing by & and passing by pointer
for example
doSomething(int & address);

Why "address"? A reference is not an address, it's an alias.
doSomething(int * ptr);

Basically the same difference as in declaring a reference versus
declaring a pointer

int main() {
double d;
double& rd = d;
double* pd = &d;
}

Performance-wise, they are often the same. Logically, they are,
because pointers can be null, references can't, so when I receive
an argument by address (a pointer by value), I need to test it for
being non-null before using. I don't have to do that with references.

Of course, the syntax is different for accessing the object. If you
have a reference, you just use its name to get to the object. If you
have a pointer you need to dereference it using the * operator. Also,
a reference like you described can only refer to a single object, but
a pointer could be the pointer to the first element of an array of
several objects and you may get to other elements of that array by
means of the indexing operator ([])...

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,174
Messages
2,570,940
Members
47,485
Latest member
Andrewayne909

Latest Threads

Top