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

前端 未结 23 868
渐次进展
渐次进展 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:14

    I saw this question a few days ago, and then happened to be reading the explanation of Go's type declaration on the Go Blog. It starts off by giving an account of C type declarations, which seems like a useful resource to add to this thread, even though I think that there are more complete answers already given.

    C took an unusual and clever approach to declaration syntax. Instead of describing the types with special syntax, one writes an expression involving the item being declared, and states what type that expression will have. Thus

    int x;
    

    declares x to be an int: the expression 'x' will have type int. In general, to figure out how to write the type of a new variable, write an expression involving that variable that evaluates to a basic type, then put the basic type on the left and the expression on the right.

    Thus, the declarations

    int *p;
    int a[3];
    

    state that p is a pointer to int because '*p' has type int, and that a is an array of ints because a[3] (ignoring the particular index value, which is punned to be the size of the array) has type int.

    (It goes on to describe how to extend this understanding to function pointers etc)

    This is a way that I've not thought about it before, but it seems like a pretty straightforward way of accounting for the overloading of the syntax.

提交回复
热议问题