What are the differences between a pointer variable and a reference variable in C++?

difference between pointer and reference variable in c++ with example
how is a const pointer similar and different from a reference variable
difference between pointer and reference with example
difference between variable and reference variable
difference between reference variable and normal variable in c++
difference between a pointer address and pointer value
difference between c and c++ pointers
what is the difference between a pointer and a reference type why are pointers considered unsafe

I know references are syntactic sugar, so code is easier to read and write.

But what are the differences?

  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, and must be assigned at initialization:

    int x = 5;
    int y = 6;
    int &r = x;
    
  2. A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack vs heap. This implies that there is a real address of a reference that the compiler will not tell you.

    int x = 0;
    int &r = x;
    int *p = &x;
    int *p2 = &r;
    assert(p == p2);
    
  3. You can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.

    int x = 0;
    int y = 0;
    int *p = &x;
    int *q = &y;
    int **pp = &p;
    pp = &q;//*pp = q
    **pp = 4;
    assert(y == 4);
    assert(x == 0);
    
  4. A pointer can be assigned nullptr directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference nullptr. Likewise, if you try hard enough, you can have a reference to a pointer, and then that reference can contain nullptr.

    int *p = nullptr;
    int &r = nullptr; <--- compiling error
    int &r = *p;  <--- likely no compiling error, especially if the nullptr is hidden behind a function call, yet it refers to a non-existent int at address 0
    
  5. Pointers can iterate over an array; you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.

  6. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a ..

  7. References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb)

  8. Const references can be bound to temporaries. Pointers cannot (not without some indirection):

    const int &x = int(12); //legal C++
    int *y = &int(12); //illegal to dereference a temporary.
    

    This makes const& safer for use in argument lists and so forth.

Difference Between Pointer and Reference (with Comparison Chart , References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference. A pointer to a class/struct uses -> to access it's members whereas a reference uses a.. A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address as the item it references. References cannot be stuffed into an array, whereas pointers can be.

What's a C++ reference (for C programmers)

A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, ie the compiler will apply the * operator for you.

All references must be initialized with a non-null value or compilation will fail. It's neither possible to get the address of a reference - the address operator will return the address of the referenced value instead - nor is it possible to do arithmetics on references.

C programmers might dislike C++ references as it will no longer be obvious when indirection happens or if an argument gets passed by value or by pointer without looking at function signatures.

C++ programmers might dislike using pointers as they are considered unsafe - although references aren't really any safer than constant pointers except in the most trivial cases - lack the convenience of automatic indirection and carry a different semantic connotation.

Consider the following statement from the C++ FAQ:

Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.

But if a reference really were the object, how could there be dangling references? In unmanaged languages, it's impossible for references to be any 'safer' than pointers - there generally just isn't a way to reliably alias values across scope boundaries!

Why I consider C++ references useful

Coming from a C background, C++ references may look like a somewhat silly concept, but one should still use them instead of pointers where possible: Automatic indirection is convenient, and references become especially useful when dealing with RAII - but not because of any perceived safety advantage, but rather because they make writing idiomatic code less awkward.

RAII is one of the central concepts of C++, but it interacts non-trivially with copying semantics. Passing objects by reference avoids these issues as no copying is involved. If references were not present in the language, you'd have to use pointers instead, which are more cumbersome to use, thus violating the language design principle that the best-practice solution should be easier than the alternatives.

C++ References, A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a  Arithmetic operation. Reference does not offer any arithmetic operations, whereas numerous operations can be performed on pointers. We can use the address of an object pointed by a reference and do pointer arithmetics. But this is pointer arithmetic, not reference arithmetic. c.

If you want to be really pedantic, there is one thing you can do with a reference that you can't do with a pointer: extend the lifetime of a temporary object. In C++ if you bind a const reference to a temporary object, the lifetime of that object becomes the lifetime of the reference.

std::string s1 = "123";
std::string s2 = "456";

std::string s3_copy = s1 + s2;
const std::string& s3_reference = s1 + s2;

In this example s3_copy copies the temporary object that is a result of the concatenation. Whereas s3_reference in essence becomes the temporary object. It's really a reference to a temporary object that now has the same lifetime as the reference.

If you try this without the const it should fail to compile. You cannot bind a non-const reference to a temporary object, nor can you take its address for that matter.

Pointers in C Programming with examples, What are the differences between a pointer variable and a reference variable? const int &x = int(12); //legal C++ int *y = &int(12); //illegal to dereference a  The key difference between a pointer and a reference is that a pointer is a variable which stores the address of the memory location of another variable while a reference is a variable that refers to another variable. The two mechanisms, the pointer and reference, have different syntax and usage.

Apart from syntactic sugar, a reference is a const pointer (not pointer to a const). You must establish what it refers to when you declare the reference variable, and you cannot change it later.

Update: now that I think about it some more, there is an important difference.

A const pointer's target can be replaced by taking its address and using a const cast.

A reference's target cannot be replaced in any way short of UB.

This should permit the compiler to do more optimization on a reference.

References vs. Pointers, The main difference between C++ Reference vs Pointer is that one is referring to another variable while the latter is storing the address of a variable. References  The main differences between pointers and reference parameters are −. References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.

Contrary to popular opinion, it is possible to have a reference that is NULL.

int * p = NULL;
int & r = *p;
r = 1;  // crash! (if you're lucky)

Granted, it is much harder to do with a reference - but if you manage it, you'll tear your hair out trying to find it. References are not inherently safe in C++!

Technically this is an invalid reference, not a null reference. C++ doesn't support null references as a concept as you might find in other languages. There are other kinds of invalid references as well. Any invalid reference raises the spectre of undefined behavior, just as using an invalid pointer would.

The actual error is in the dereferencing of the NULL pointer, prior to the assignment to a reference. But I'm not aware of any compilers that will generate any errors on that condition - the error propagates to a point further along in the code. That's what makes this problem so insidious. Most of the time, if you dereference a NULL pointer, you crash right at that spot and it doesn't take much debugging to figure it out.

My example above is short and contrived. Here's a more real-world example.

class MyClass
{
    ...
    virtual void DoSomething(int,int,int,int,int);
};

void Foo(const MyClass & bar)
{
    ...
    bar.DoSomething(i1,i2,i3,i4,i5);  // crash occurs here due to memory access violation - obvious why?
}

MyClass * GetInstance()
{
    if (somecondition)
        return NULL;
    ...
}

MyClass * p = GetInstance();
Foo(*p);

I want to reiterate that the only way to get a null reference is through malformed code, and once you have it you're getting undefined behavior. It never makes sense to check for a null reference; for example you can try if(&bar==NULL)... but the compiler might optimize the statement out of existence! A valid reference can never be NULL so from the compiler's view the comparison is always false, and it is free to eliminate the if clause as dead code - this is the essence of undefined behavior.

The proper way to stay out of trouble is to avoid dereferencing a NULL pointer to create a reference. Here's an automated way to accomplish this.

template<typename T>
T& deref(T* p)
{
    if (p == NULL)
        throw std::invalid_argument(std::string("NULL reference"));
    return *p;
}

MyClass * p = GetInstance();
Foo(deref(p));

For an older look at this problem from someone with better writing skills, see Null References from Jim Hyslop and Herb Sutter.

For another example of the dangers of dereferencing a null pointer see Exposing undefined behavior when trying to port code to another platform by Raymond Chen.

Pointers vs References in C++, What are the differences between a pointer variable and a reference variable in C++?. A pointer can be re-assigned:int x = 5; int y = 6; int *p;  May 18, 2016 Leave a Comment The “pointer” and “reference” both are used to point or refer an another variable. But, the basic difference among both of them is that a pointer variable points to a variable whose memory location is stored in it. The reference variable is an alias for a variable which is assigned to it.

What is difference between a pointer and reference parameter in C++?, This contains seven differences between pointer and reference. The basic difference among both of them is that a pointer variable points to a  Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be dereferenced with * operator to access the memory location it points to. References : A reference variable is an alias, that is, another name for an already existing variable.

Differences between pointers and references in C++, Yet it is also true the for some languages other than C++ there are sometimes NULL The declaration of a reference variable contains base type followed by  A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable.

What are the differences between a pointer variable and a reference , In C++, references provide many of the same capabilities as pointers. The difference between pointer and reference declarations is noteworthy, but it's not the basis for deciding to use This function returns a reference to local variable i. The main difference between pointer and reference is that pointer is a variable that holds the address of another variable while reference is an alias to access an already existing variable. C++ is an enhancement of the C language. It is also considered as a superset of C.

Comments
  • I think point 2 should be "A pointer is allowed to be NULL but a reference is not. Only malformed code can create a NULL reference and its behavior is undefined."
  • Pointers are just another type of object, and like any object in C++, they can be a variable. References on the other hand are never objects, only variables.
  • This compiles without warnings: int &x = *(int*)0; on gcc. Reference can indeed point to NULL.
  • reference is a variable alias
  • I like how the very first sentence is a total fallacy. References have their own semantics.
  • ...but dereferencing NULL is undefined. For example, you can't test if a reference is NULL (e.g., &ref == NULL).
  • Number 2 is not true. A references is not simply "another name for the same variable." References may be passed to functions, stored in classes, etc. in a manner very similar to pointers. They exist independently from the variables they point to.
  • Brian, the stack is not relevant. References and pointers do not have to take space on the stack. They can both be allocated on the heap.
  • Brian, the fact that a variable (in this case a pointer or reference) requires space does not mean it requires space on the stack. Pointers and references may not only point to the heap, they may actually be allocated on the heap.
  • another important diff: references cannot be stuffed into an array
  • @kriss: No, you can also get a dangling reference by returning an automatic variable by reference.
  • @kriss: It's virtually impossible for a compiler to detect in the general case. Consider a member function that returns a reference to a class member variable: that's safe and should not be forbidden by the compiler. Then a caller that has an automatic instance of that class, calls that member function, and returns the reference. Presto: dangling reference. And yes, it's going to cause trouble, @kriss: that's my point. Many people claim that an advantage of references over pointers is that references are always valid, but it just isn't so.