I am studying C using "C Programming: a Modern Approach" by K.N.King. Quoting the book,
Each structure represents a new scope; any names declared in that scope won't conflict with other names in a program. (In C terminology, we say that each structure has a separate name space for its members.)
I never really thought about structure member's identifier before. But to think about it, it was surprising that use of same identifiers as local variables don't hide other identifiers although it should.
So I took a look at name space
in C, and read C99 standard documents. In section 6.2.3, the standard declares name space of structure members as follows.
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);
What really bothers me is what each structure or union has a separate name space for its members
means.
I'm seeking clarification on the concept of separate namespaces for members in C structures and unions. Specifically, does the notion of each structure or union having a separate namespace for its members mean that (a) every variable of a particular structure has its own namespace, or (b) each structure (or union) tag has its own namespace when defined?
For example, when creating structure variables like struct s var_a, var_b;
, I'm interested in understanding whether each variable (var_a
and var_b
) has its own namespace.
Each structure type has its own name space, not each structure variable.
There are four categories of name spaces in C: labels, tags, members, and ordinary identifiers. There are infinitely many name spaces, in theory, since each structure and union type has its own member name space and there is no limit on the number of structure and union types.
(History trivia: A precursor to the C language did not have separate name spaces for members. All structures shared a single name space for their member names, so you could not have structures with same-named members at different offsets in the structure layout.)