lookaside
lookaside

Reputation: 357

Why does C have separate name spaces for tags and identifiers?

From cppreference:

1) Label name space: all identifiers declared as labels.

2) Tag names: all identifiers declared as names of structs, unions and enumerated types.

3) Member names: all identifiers declared as members of any one struct or union. Every struct and union introduces its own name space of this kind.

4) All other identifiers, called ordinary identifiers to distinguish from (1-3) (function names, object names, typedef names, enumeration constants).

This allows for code like this (among other things):

struct Point { int x, y; };
struct Point Point;

This code seems somewhat unclear to me as Point can refer to both a type and an instance of a struct. What was the motivation behind having separate name spaces for tags and other identifiers?

Upvotes: 5

Views: 546

Answers (1)

John Bollinger
John Bollinger

Reputation: 181114

The actual question posed is

What was the motivation behind having separate name spaces for tags and other identifiers?

This can be answered only by reference to the standard committee's rationale document, which in fact does address the matter, however briefly:

Pre-C89 implementations varied considerably in the number of separate name spaces maintained. The position adopted in the Standard is to permit as many separate name spaces as can be distinguished by context, except that all tags (struct, union, and enum) comprise a single name space.

(C99 rationale document,* section 6.2.3)

Thus, it is explicitly intentional that code such as

struct point { int point; } point = { .point = 0 };
goto point;
point:
return point.point;

is permitted. My interpretation of the rationale is that the intention was to be unrestrictive, though it remains unclear why the different kinds of tags were not given separate namespaces. This could not have been accidental, so one or more parties represented on the committee must have opposed separate tag namespaces, and they managed to prevail. Such opposition could very well have been for business instead of technical reasons.


*As far as I am aware, there is no rationale document for the C2011 standard. At least, not yet.

Upvotes: 4

Related Questions