How to explain C pointers (declaration vs. unary operators) to a beginner?

The reason why the shorthand:

int *bar = &foo;

in your example can be confusing is that it’s easy to misread it as being equivalent to:

int *bar;
*bar = &foo;    // error: use of uninitialized pointer bar!

when it actually means:

int *bar;
bar = &foo;

Written out like this, with the variable declaration and assignment separated, there is no such potential for confusion, and the use ↔ declaration parallelism described in your K&R quote works perfectly:

  • The first line declares a variable bar, such that *bar is an int.

  • The second line assigns the address of foo to bar, making *bar (an int) an alias for foo (also an int).

When introducing C pointer syntax to beginners, it may be helpful to initially stick to this style of separating pointer declarations from assignments, and only introduce the combined shorthand syntax (with appropriate warnings about its potential for confusion) once the basic concepts of pointer use in C have been adequately internalized.

Leave a Comment