0

Possible Duplicate:
What are the differences between pointer variable and reference variable in C++?
Pointer vs. Reference

To do a call-by-reference in C++, I think I could use either of those two:

int f(int *x);
int g(int &x);

They would be called like so:

int *w;
f(w);
g(*w);

int y;
f(&y);
g(y);

Is there a difference in the functions f and g? I should be able to work with x as an int* pointer and *x as an int inside both functions. So what is the difference?

Community
  • 1
  • 1
Martin Ueding
  • 8,245
  • 6
  • 46
  • 92
  • 4
    The former is a pointer, the latter is a reference. There is a huge difference between the two. (Also removed the C tag since references don't exist in C) – netcoder Dec 20 '12 at 15:52
  • This may help you : [differences between pointer variable and reference](http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c-) – Passepartout Dec 20 '12 at 15:54

2 Answers2

3

Most of this is a matter of taste. There is one important difference though. A pointer (*) can have a null value whereas a reference cannot be null and always must refer to a valid object.

Will
  • 4,585
  • 1
  • 26
  • 48
2

The reference can't be NULL, so you don't have to check that. Otherwise, it's probably just syntactic sugar (at least for simple use cases). Check the disassembly of your program to see.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469