Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In what scope is a struct member identifier put?

The C spec says

There are four kinds of scopes: function, file, block, and function prototype.

Now if I do the following outside any function

struct A {
  int x;
};

My understanding is that the identifier x is visible at file-scope. And that we use a namespace syntax to access the member, as the spec says

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)

Let's make this more clearer by adding a function

struct A {
  int x;
};

void f(void) {
  int i;
}

Then the identifiers, scopes and namespaces participating in this program's representation are (N/A is "not applicable"):

file scope
==========================================
Ordinary  |  Members A  |  Tags  |  Labels
------------------------------------------
 f        | x           | A      | N/A
          |             |        |


function scope of f
=========================================
Ordinary  |  Members ? |  Tags  |  Labels
-----------------------------------------
 N/A      | N/A        | N/A    |
          |            |        |


block scope #1
=========================================
Ordinary  |  Members ? |  Tags  |  Labels
-----------------------------------------
 i        |            |        | N/A
          |            |        |

And the scope hierarchy is "block scope #1" -> "function scope of f" -> "file scope".

I once talked with a C compiler writer, and he said that x is not into any scope. Can anyone please explain how this would work? How could we refer to x in any way at all then? Further quotation (emphasize mine):

An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter.

The same identifier can denote different entities at different points in the program.

For each different entity that an identifier designates, the identifier is visible (i.e., can be used) only within a region of program text called its scope.

If we say that a member of a struct has no scope, then it is not visible and therefor cannot be used. But obviously, we can use struct members. Am I missing anything?

like image 390
Johannes Schaub - litb Avatar asked Mar 11 '11 17:03

Johannes Schaub - litb


1 Answers

As the standard says, it's in a separate name space created for the struct type. This rule was added in C89, I think. Once upon a time, all member names shared a single name space.

Maybe the compiler writer was being pedantic; a name space is not the same as a scope. A struct definition does not introduce a scope as it doesn't hold variables; it holds members.

like image 178
Fred Foo Avatar answered Sep 28 '22 07:09

Fred Foo