In C, what is the correct syntax for declaring pointers?

后端 未结 8 1214
终归单人心
终归单人心 2020-11-27 20:32

I vaguely recall seeing this before in an answer to another question, but searching has failed to yield the answer.

I can\'t recall what is the proper way t

相关标签:
8条回答
  • 2020-11-27 20:58

    As a side note, I think it helps to understand the motivation behind the C declaration syntax, which is meant to mimic how the variable could be used. Some examples below:

    • char *x means that if you do *x, you get a char.
    • int f(int x) means that if you do e.g. f(0), you get an int.
    • const char *foo[3] means that if you do e.g. *foo[0] (which is the same as *(foo[0])), you get a const char. This implies that foo must be an array (of size 3 in this case) of pointers to const char.
    • unsigned int (*foo)[3] means that if you do e.g. (*foo)[0], you get an unsigned int. This implies that foo must be a pointer to an array of unsigned int (of size 3 in this case).

    Loosely, the general syntax is hence [what you get] [how you get it]. The trick is that this can be extended to [what you get] [how you get it], [how you get it], ... to declare multiple things at once. Hence, the following three declarations --

    int *p;
    int f(int x);
    int a[3];
    

    -- can be combined into a single line as follows (and yes, this even works for function declarations. They are not special in this regard):

    int *p, f(int x), a[3];
    
    0 讨论(0)
  • 2020-11-27 21:00

    I prefer the following style:

    Type *pointer;
    

    Why? Because it is consistent with the mindset the creators of the language tried to establish:

    "The syntax of the declaration for a variable mimics the syntax of expressions in which the variable might appear."

    (The C Programming Language by Brian W. Kernighan & Dennis M. Ritchie, ansi c version, page 94)

    It's easy to write FORTRAN in any language, but You always should write [programming language X] in [programming language X].

    0 讨论(0)
提交回复
热议问题