I have had the recent pleasure to explain pointers to a C programming beginner and stumbled upon the following difficulty. It might not seem like an issue at all if you already know how to use pointers, but try to look at the following example with a clear mind:
int foo = 1;
int *bar = &foo;
printf("%p\n", (void *)&foo);
printf("%i\n", *bar);
To the absolute beginner the output might be surprising. In line 2 he/she had just declared *bar to be &foo, but in line 4 it turns out *bar is actually foo instead of &foo!
The confusion, you might say, stems from the ambiguity of the * symbol: In line 2 it is used to declare a pointer. In line 4 it is used as an unary operator which fetches the value the pointer points at. Two different things, right?
However, this "explanation" doesn't help a beginner at all. It introduces a new concept by pointing out a subtle discrepancy. This can't be the right way to teach it.
So, how did Kernighan and Ritchie explain it?
The unary operator * is the indirection or dereferencing operator; when applied to a pointer, it accesses the object the pointer points to. […]
The declaration of the pointer ip,
int *ip
is intended as a mnemonic; it says that the expression*ip
is an int. The syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear.
int *ip
should be read like "*ip
will return an int
"? But why then doesn't the assignment after the declaration follow that pattern? What if a beginner wants to initialize the variable? int *ip = 1
(read: *ip
will return an int
and the int
is 1
) won't work as expected. The conceptual model just doesn't seem coherent. Am I missing something here?
Edit: It tried to summarize the answers here.
*
in a declaration is a token meaning "declare a pointer", in expressions it's the dereference operator, and that these two represent different things that happen to have the same symbol (same as the multiplication operator - same symbol, different meaning). It's confusing, but anything different than the actual state of affairs is going to be even worse.int* bar
makes it more obvious that the star is actually part of the type, not part of the identifier. Of course this runs you into different problems with unintuitive stuff likeint* a, b
.*
can have two different meanings depending on context. Just like the same letter can be pronounced differently depending on the word it's in which makes it hard to learn to speak many languages. If every single concept/operation had its own symbol we'd need much larger keyboards, so symbols are recycled when it makes sense to do so.int* p
), while warning your student against using multiple declarations in the same line when pointers are involved. When the student has completely understood the concept of pointers, explain to the student that theint *p
is syntax is equivalent and then explain the problem with multiple declarations.