C structs don't define types?

前端 未结 10 2215
离开以前
离开以前 2021-01-21 06:54

I\'ve just started learning C with a professional Java background and some (if no too much) C++ knowledge, and I was astonished that this doesn\'t work in C:

str         


        
10条回答
  •  醉话见心
    2021-01-21 07:05

    In C there is no confusion between

    struct Point {
        int x;
        int y;
    };
    

    and

    union Point {
        int x;
        int y;
    };
    

    which are two different types called struct Point and union Point respectively.

    The C99 standard section 6.7.2.1 states:

    6 Structure and union specifiers have the same form. The keywords struct and union indicate that the type being specified is, respectively, a structure type or a union type.

    7 The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit.

    So it most unequivocally declares a type. The syntax for type names in C is given in sections 6.7.6 and includes the specifier-qualifier-list from 6.7.2, which takes the form of struct-or-union identifier.

    Does this code works in C99? Or is this a "C++ thing"?

    No, C99 does not decide to promote structure types over enum types and union types with the same name. It is a "C++ thing", as struct and classes are mostly the same thing in C++, and classes are important to C++.

提交回复
热议问题