Point of Declaration

A name is considered to be declared immediately after its declarator but before its (optional) initializer. (For more information on declarators, see Declarators.) An enumerator is considered to be declared immediately after the identifier that names it but before its (optional) initializer.

Consider this example:

// point_of_declaration1.cpp
// compile with: /W1 
double dVar = 7.0;
int main()
{
   double dVar = dVar;   // C4700
}

If the point of declaration were after the initialization, then the local 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 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,     // error
    Clubs,               // error
    Hearts,              // error
    Diamonds             // error
};

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.

See Also

Reference

Scope