What operator is better (*) or (&) opeartors applied to a function argument?

Jan 6, 2011 at 10:06am
1
2
3
4
5
a)void Fx(int* I) {++*I;}
  void main()           {int I; Fx(&I);}

b)void Fy(int& I) {++I;}
  void main()     {int I; Fy(I);}


There seems to be no difference between these two.
Why not to use the latter one always?
Jan 6, 2011 at 11:42am
Pointers and references are just two different tools.
Pointers are useful for memory manipulations and references are useful with objects to be shared.
Jan 6, 2011 at 11:56am
Well, makes me wonder.
Jan 6, 2011 at 1:59pm
I can't find better words to describe the difference :-(

When you need to manipulate memory you are using pointers.
References can be refereed to as a special type of constant pointers. Once initialized, references keep the same address during lifespan. While pointers allow for any address to be stored.
Jan 6, 2011 at 3:43pm
I tend to do the following for function output:

- use return values for output first and foremost. Whenever possible/practical.
int Fx(int I) { return I + 1; }

- pass by pointer if you need to output an array:
1
2
3
4
5
void F(int* ar)
{
  ar[0] += 1;
  ar[1] += 2;
}


- pass by pointer if the output is optional, that way a null pointer can be provided:
1
2
3
4
5
void F(int* optionalout)
{
  if(optionalout)
    *optionalout = 5;
}


- otherwise, pass by reference (output is a single value, can't be returned, and is not optional)
Jan 6, 2011 at 4:04pm
Disch>pass by pointer if the output is optional

May I ask, what optional output is?
Is it the situation, when a function could return correct value only under conditions?
Or might it be the case when a function is able to construct different objects?
And... Is it more logical to use status enumerations or throw an exception, when output is optional?
Jan 6, 2011 at 4:29pm
Here's an example of funtions with optional parameters:
Windows Platform SDK CreateProcess: http://msdn.microsoft.com/en-us/library/ms682425%28v=vs.85%29.aspx
ANSI C time: http://pubs.opengroup.org/onlinepubs/007908799/xsh/time.html
Topic archived. No new replies allowed.