Why is it possible to declare a struct and a non-struct with the same name?

后端 未结 4 1623
旧巷少年郎
旧巷少年郎 2021-01-03 00:11

Apparently,

For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope

4条回答
  •  一生所求
    2021-01-03 00:44

    I'm just curious what the initial reason was? Without understanding, it seems like an example of bad language design, that causes ambiguity and is confusing.

    In C it's a first implementation of name spaces. Identifiers live in different name spaces and the idea is they can have the same name if they are declared in different name spaces. Name space for structure tags and ordinary identifiers are not the only two name spaces in C. There are four name spaces in C:

    (C99, 6.2.3 Name spaces of identifiers p1) "Thus, there are separate name spaces for various categories of identifiers, as follows:

    — label names (disambiguated by the syntax of the label declaration and use);

    — the tags of structures, unions, and enumerations (disambiguated by following any24) 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)."

提交回复
热议问题