A name is considered declared immediately after its declarator but prior to its (optional) initializer. (For more information on declarators, see Chapter 7.) An enumerator is considered declared immediately after the identifier that names it but prior to its (optional) initializer.
Consider this example:
double dVar = 7.0;
int main()
{
double dVar = dVar;
}
If the point of declaration were after the initialization, then dVar would be initialized to 7.0, the value of the global variable dVar. However, since that is not the case, dVar is initialized to an undefined value.
Enumerators follow the same rule. However, enumerators are exported to the enclosing scope of the enumeration. In the following example, the enumerators Spades, Clubs, Hearts, and Diamonds are declared. Because the enumerators are exported to the enclosing scope, they are considered to have global scope. The identifiers in the following example are already defined in global scope.
Consider the following code:
const int Spades = 1, Clubs = 2, Hearts = 3, Diamonds = 4;
enum Suits
{
Spades = Spades,
Clubs,
Hearts,
Diamonds
};
Because the identifiers in the preceding code are already defined in global scope, an error message is generated.
Note:
Using the same name to refer to more than one program element—for example, an enumerator and an object—is considered poor programming practice and should be avoided. In the preceding example, this practice causes an error.