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

前端 未结 23 938
渐次进展
渐次进展 2020-11-30 18:08

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 alre

23条回答
  •  孤街浪徒
    2020-11-30 18:33

    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.

提交回复
热议问题