-1

In the first code both of the printings are same, so as far as I understand the variables( a and b) share the same memory location.But in the second one it gives an error, what is the difference?

Also how (int &a = b )work? Arent we assigning the memory location to an integer by writing int &a = b?

int b = 9;
    int &a = b;
    cout<< &a << endl;
    cout<< &b << endl;

  int b = 9;
    int a = 5;
    &a = &b;
    cout<< &a << endl;
    cout<< &b << endl;
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
Crazy_Boy53
  • 241
  • 2
  • 4
  • 10
  • 3
    [What is a reference variable in C++? - Stack Overflow](https://stackoverflow.com/questions/2765999/what-is-a-reference-variable-in-c) – user202729 Oct 28 '18 at 14:52

3 Answers3

3

so as far as I understand the variables( a and b) share the same memory location.

No.

a is a reference variable. References are not objects, and are not necessarily stored in the memory at all. It is not possible to get the address of something that is not stored in memory. Taking the address of a reference variable will result in the address of the referred object.

Arent we assigning a memory location to an integer by writing int &a = b

No, we aren't. We are declaring a reference variable, which is initialized to refer to b.

But in the second one it gives an error

The result of the addressof operator is an rvalue. You cannot assign to an rvalue. In the first example, you never attempt to assign to the result of the addressof operator.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

&a = &b; doesn't do what you think it does.

&a is a temporary, an rvalue, a pointer to a. It cannot be assigned because it's not a variable that exists.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
0

In first code snippet

int &a = b; /* valid syntax */

a is reference to b i.e both a and b will be having same memory location or a is just another name of b, no seperate memory created for a it uses existing memory of b.

In the second code snippet,

int b = 9;
int a = 5;
&a = &b; /* invalid syntax */

the statement &a = &b; isn't valid as it results in r-value expression.

Achal
  • 11,821
  • 2
  • 15
  • 37