Connecting Tech Pros Worldwide Help | Site Map

& vs ptr

Steve
Guest
 
Posts: n/a
#1: Jul 22 '05
what is the difference between passing by & and passing by pointer
for example
doSomething(int & address);
doSomething(int * ptr);
thanks


Victor Bazarov
Guest
 
Posts: n/a
#2: Jul 22 '05

re: & vs ptr


Steve wrote:[color=blue]
> what is the difference between passing by & and passing by pointer
> for example
> doSomething(int & address);[/color]

Why "address"? A reference is not an address, it's an alias.
[color=blue]
> doSomething(int * ptr);[/color]

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
Closed Thread