0 votes
in C Plus Plus by
What are the differences between a pointer variable and a reference variable in C++?

1 Answer

0 votes
by
  1. A pointer can be re-assigned:

    int x = 5;
    int y = 6;
    int *p;
    p = &x;
    p = &y;
    *p = 10;
    assert(x == 5);
    assert(y == 10);
    

    A reference cannot be re-bound, and must be bound at initialization:

    int x = 5;
    int y = 6;
    int &q; // error
    int &r = x;
    
  2. A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary & operator and a certain amount of space that can be measured with the sizeof operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.

    int x = 0;
    <span style="border:0px; box-sizing:inherit; color:var(--highlight-keyword); font-family

Related questions

+1 vote
asked Jan 20, 2021 in C Plus Plus by SakshiSharma
+1 vote
asked Jan 2, 2020 in C Plus Plus by GeorgeBell
0 votes
asked Jan 6, 2021 in C Plus Plus by GeorgeBell
...