typedef a struct before it's declared

前端 未结 7 1939
死守一世寂寞
死守一世寂寞 2020-12-09 15:14

I\'m not a beginner, I\'m very familiar with the following idiom:

typedef struct Foo_ Foo;// I know typedef struct Foo Foo is fine, I\'m just trying to make          


        
7条回答
  •  眼角桃花
    2020-12-09 15:53

    This is covered in 6.7.2.3p8:

    6.7.2.3 Tags

    Semantics
    [...]

    8 - If a type specifier of the form struct-or-union identifier occurs other than as [a struct-or-union definition] or [a struct-or-union declaration], and no other declaration of the identifier as a tag is visible, then it declares an incomplete structure or union type, and declares the identifier as the tag of that type.

    The type specifier struct Foo in typedef struct Foo Foo is not in a definition (struct Foo {...};) or a declaration (struct Foo;) so it falls under 6.7.2.3p8.

    Note that there's nothing special about a typedef; you could also e.g. write

    struct A { struct Foo *p; };
    

    and a previous definition or declaration is not required to be visible.

    However, in a function declaration or definition:

    void foo(struct Foo *p);
    

    if struct Foo is not previously declared then the scope of the declaration will just be the function declaration or definition, and it will not be type-compatible with any subsequent declaration or definition of Foo.

提交回复
热议问题