C structs don't define types?

前端 未结 10 2323
离开以前
离开以前 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 06:54

    So...

    Point           a tag
    struct Point    a type
    
    typedef struct {
        . . .
    } Point_t;
    
    Point_t         a type
    

    I often see a why? written between the lines. After all, it does seem perfectly reasonable to just say Point x;, so why can't you?

    As it happens, early implementations of C established a separate name space for tags vs other identifiers.There are actually 4 name spaces1. Once the language was defined this way, it was then not possible to allow the struct tag to be used as a type because then all existing code with name collisions between ordinary identifiers and tags would be suddenly in error.


    1. The 4 name spaces are:
    -- label names (disambiguated by the syntax of the label declaration and use);
    -- the tags of structures, unions, and enumerations (disambiguated by following any) of the keywords struct, union, or enum);
    -- the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
    -- all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants)

提交回复
热议问题