0

Possible Duplicate:
Difference between pointer variable and reference variable in C++

I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways...

Whats the difference between

int a = 0; 
int &b = a; 

and

int a = 0
int *p = &a; 

Obviously, p holds the address of a, but b is a reference to a, meaning I can change the value of a with b. But I can also do the same thing with p. So what are advantages or disadvantages?

Community
  • 1
  • 1
Dalton Conley
  • 1,599
  • 2
  • 28
  • 36

2 Answers2

2
  • A reference must always be initialized
  • A reference can't be null
  • Once initialized, a reference can't be changed to be an alias of a different object.
Brent Writes Code
  • 19,075
  • 7
  • 52
  • 56
Cătălin Pitiș
  • 14,123
  • 2
  • 39
  • 62
0

I think it comes down to how you plan to use the variables afterwards in your program. Both statements appear to do the same thing (in this limited scope).

The first approach seems to be (in my opinion) poor programming practice since it may not be obvious later in the program that changing the value of b also changes the value of a. In the second, at least it is known that p is a pointer, so you should expect the side effects that come with changing the value to which it points.

Nick
  • 145
  • 6