Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat are the differences between a pointer variable and a reference variable in C++?
    primarykey
    data
    text
    <p>I know references are syntactic sugar, so code is easier to read and write.</p> <p>But what are the differences?</p> <hr> <p>Summary from answers and links below:</p> <ol> <li>A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding.</li> <li>Pointers can point nowhere (<code>NULL</code>), whereas a reference always refers to an object.</li> <li>You can't take the address of a reference like you can with pointers.</li> <li>There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in <code>&amp;obj + 5</code>).</li> </ol> <p>To clarify a misconception:</p> <blockquote> <p><em>The C++ standard is very careful to avoid dictating how a compiler may implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:</em></p> <pre><code>int &amp;ri = i; </code></pre> <p><strong><em>if it's not optimized away entirely</em></strong>, <em>allocates the same amount of storage as a pointer, and places the address of <code>i</code> into that storage.</em></p> </blockquote> <p><strong><em>So, a pointer and a reference both use the same amount of memory.</em></strong></p> <p>As a general rule,</p> <ul> <li>Use references in function parameters and return types to provide useful and self-documenting interfaces.</li> <li>Use pointers for implementing algorithms and data structures.</li> </ul> <p>Interesting read:</p> <ul> <li>My all-time favorite <a href="http://yosefk.com/c++fqa/ref.html" rel="noreferrer">C++ FAQ lite</a>.</li> <li><a href="http://www.embedded.com/electronics-blogs/programming-pointers/4023307/References-vs-Pointers" rel="noreferrer">References vs. Pointers</a>.</li> <li><a href="http://www.embedded.com/electronics-blogs/programming-pointers/4024641/An-Introduction-to-References" rel="noreferrer">An Introduction to References</a>.</li> <li><a href="http://www.embedded.com/electronics-blogs/programming-pointers/4023290/References-and-const" rel="noreferrer">References and const</a>.</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload