Where in a declaration may a storage class specifier be placed?

前端 未结 3 756
天命终不由人
天命终不由人 2020-12-14 02:07

For example, let\'s consider the static storage class specifier. Here are a few examples of both valid and ill-formed uses of this storage class specifier:

3条回答
  •  Happy的楠姐
    2020-12-14 02:48

    In summary, anywhere in the declaration specifier (See section 7.1 in the ISO/IEC 14882-2012), ie before the *. Qualifiers after the * are associated with the pointer declarator, not the type specifier, and static doesn't make sense within the context of a pointer declarator.

    Consider the following cases: You can declare a normal int and a pointer to an int in the same declaration list, like this:

    int a, *b;
    

    this is because the type specifier is int, then you have two declarations using that type specifier int, a, and a pointer declarator *a which declares a pointer to int. Now consider:

    int a, static b;  // error
    int a, *static b; // error
    int a, static *b; // error
    

    which should look wrong (as they are), and the reason (as defined in sections 7.1 and 8.1) is because C and C++ require that your storage specifiers go with your type specifier, not in your declarator. So now it should be clear that that the following is also wrong, since the above three are also wrong:

    int *static a; // error
    

    Your last example,

    typedef int* pointer;
    static pointer j;    // valid
    pointer static k;    // valid
    

    are both valid and both equivalent because the pointer type is defined as a type specifier and you can put your type specifier and storage specifeir in any order. Note that they are both equivalent and would be equivalent to saying

    static int *j;
    static int *k;
    

    or

    int static *j;
    int static *k;
    

提交回复
热议问题