bubble
bubble

Reputation: 3526

When do we say that two identifiers have same scope?

The C standard defines that two identifiers have same scope if and only if their scope terminates at the same point. And goes on further to state that:

Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

Does it mean that two identifiers are formally called to have same scope even if the beginning of their scope doesn't match ?

Upvotes: 2

Views: 173

Answers (2)

MasterMind
MasterMind

Reputation: 61

It is understandable that you get confused. However, this is actually only a matter of definition. In the latest committee draft of the C99 Standard in paragraph 6.2.1:

item 2:

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.

and item 6:

Two identifiers have the same scope if and only if their scopes terminate at the same point.

So as you can see the term "same scope" is a matter of definition and does not mean that the scope starts at the same location or that the region of the program in which an object is kwown is exactly the same. Therefore, also as mentioned in the previous answer:

{
    int a;
    int b;
}

To summarize: Yes, the variables a and b have their scope starting at different points, but because their scope ends at the same point, they are according to the C standards definition said to have the "same scope".

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477100

Yes, that's a reasonable way of thinking about it. Otherwise no two identifiers would have the same scope!

{
    int a;
    int b;
}

In the above, the scopes of a and b begin at different points, but surely we want to think of them as being in the same scope!

Upvotes: 5

Related Questions