Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>C++ adopts the C syntax. As revealed in "<a href="http://cm.bell-labs.com/cm/cs/who/dmr/chist.html" rel="nofollow noreferrer">The Development of the C Language</a>" (by Dennis Ritchie) C uses <code>*</code> for pointers in type declarations because it was decided that type syntax should follow use.</p> <blockquote> <p>For each object of [a compound type], there was already a way to mention the underlying object: index the array, call the function, use the indirection operator [<code>*</code>] on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,</p> <pre><code>int i, *pi, **ppi; </code></pre> <p>declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that i, *pi, and **ppi all yield an int type when used in an expression. </blockquote></p> <p>Here's a more complex example:</p> <pre><code>int *(*foo)[4][]; </code></pre> <p>This declaration means an expression <code>*(*foo)[4][0]</code> has type <code>int</code>, and from that (and that <code>[]</code> has higher precedence than unary <code>*</code>) you can decode the type: foo is a pointer to an array of size 4 of array of pointers to ints.</p> <p>This syntax was adopted in C++ for compatibility with C. Also, don't forget that C++ has a use for &amp; in declarations.</p> <pre><code>int &amp; b = a; </code></pre> <p>The above line means a reference variable refering to another variable of type <code>int</code>. The difference between a reference and pointer roughly is that references are initialized only, and you can not change where they point, and finally they are always dereferenced automatically.</p> <pre><code>int x = 5, y = 10; int&amp; r = x; int sum = r + y; // you do not need to say '*r' automatically dereferenced. r = y; // WRONG, 'r' can only have one thing pointing at during its life, only at its infancy ;) </code></pre>
 

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