By reference or by pointer

G

Guest

What is the difference between passing argument by reference or by pointer?
Is there any difference in terms of PERFORMANCE ?
When and why one of these method (by reference or by pointer) should be
preferred?

THX.


typedef struct{
int X,Y,Z}TMyStructure;

void Function1(TMyStructure &xyz)
{
xyz.X = 123;
.. . .
}

void Function2(TMyStructure *xyz)
{
xyz->X = 123;
.. . .
}
 
G

Gernot Frisch

typedef struct{
int X,Y,Z}TMyStructure;

void Function1(TMyStructure &xyz)
{
xyz.X = 123;
. . .
}

void Function2(TMyStructure *xyz)
{
xyz->X = 123;
. . .
}


It's a question of style. I use references for input, pointers for
output, but do as you like.
-Gernot
 
J

John Harrison

What is the difference between passing argument by reference or by pointer?
Is there any difference in terms of PERFORMANCE ?

If you use a reference then the compiler has a slightly easier job of
optimising your code. This is because it knows that a reference will always
refer to the same object, but a pointer can be changed to point somewhere
else.

john
 
P

Peter Koch Larsen

What is the difference between passing argument by reference or by
pointer?
Is there any difference in terms of PERFORMANCE ?
When and why one of these method (by reference or by pointer) should be
preferred?

THX.


typedef struct{
int X,Y,Z}TMyStructure;

void Function1(TMyStructure &xyz)
{
xyz.X = 123;
. . .
}

void Function2(TMyStructure *xyz)
{
xyz->X = 123;
. . .
}

Use a reference whenever possible, and a pointer (perhaps a smart one) only
if you can not. If the above code is correct, you should have used a
reference. Change it as below and a pointer is correct.

void Function2(TMyStructure *xyz)
{
if (xyz)
{
. . .
}
}
 
M

Method Man

What is the difference between passing argument by reference or by pointer?
Is there any difference in terms of PERFORMANCE ?
When and why one of these method (by reference or by pointer) should be
preferred?

THX.


typedef struct{
int X,Y,Z}TMyStructure;

void Function1(TMyStructure &xyz)
{
xyz.X = 123;
. . .
}

void Function2(TMyStructure *xyz)
{
xyz->X = 123;
. . .
}

In C, function parameters were not allowed to be passed in by reference
(using &). The feature was added for C++ to make code easier to read. So
performance wise, I beleive they should be the same.
 

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,183
Messages
2,570,967
Members
47,520
Latest member
KrisMacono

Latest Threads

Top