1

Why references can not be reinitialized in C++ while pointers can be reinitialized?

int x=5;
int y=6;
int *p1;
p1 = &x;
p1 = &y; //re-initializing the pointer but same can not be done with references
int &r1 =x;//can be initialized only once
Geek
  • 26,489
  • 43
  • 149
  • 227

1 Answers1

1

There's no obvious syntax. You can't use the normal = syntax; that sets the value the underlying pointer of the reference. Perhaps you could think up a syntax like this:

&my_reference = new_value;

But that's kind of strange and awkward.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • That's not possible in any form. `&variable` is always a rvalue, and rvalues can't be the left operand of an assignment. – Nbr44 Apr 17 '13 at 05:43
  • @Nbr44 I think you mean rvalue, since the name lvalue stems from that it usually stands on the left hand side of an assignment. – Agentlien Apr 17 '13 at 05:45
  • Ooopsies, rvalue indeed ! Thanks ! – Nbr44 Apr 17 '13 at 05:45
  • @Nbr44: I know it's not possible. I was saying such a feature was left out of the language at least partially because of the lack of obvious syntax. I then listed a possible sample of what it *could* look like, but then pointed out that it would be, in my words, “strange and awkward,” which I claimed is why it was not chosen. I never stated that this was supported syntax. – icktoofay Apr 17 '13 at 06:00
  • Alright, I misunderstood - my apologies ! I think there's also quite a technical aspect to why it was left out though. I can't see that kind of mechanism working well with the C/C++ internal side... – Nbr44 Apr 17 '13 at 06:17