If an enumeration is declared in a function, what is the scope?

Is enumeration private to a function?

void doSomething()
{
   enum cmds {
      A, B, C
   }
}
+4
source share
4 answers

The type enum cmdsand elements of the enumeration A, Band Care local to the scope of functions.

Note that while enumerations do not introduce a new scope for their member constants, they fall into scope, in this case the body of the function.

int doSomething(void)
{
    enum cmds {
        A, B, C  // 0, 1, 2
    };

    return C;  // returns 2
}

int anotherThing(void)
{
    enum cmds {
        C, D, E  // 0, 1, 2
    };
    return C;  // returns 0
}

Run the sample code here at Coliru

+3
source

Enumerations do not introduce a new scope.

Refer to this .

+1
source

, enum, , .

:

void doSomething()
{
   enum cmds {
      A, B, C
   }
}

, :

void doSomething(void) {
    if (condition) {
        enum cmds {A, B, C};
        // The type and constants are visible here ...
    }
    // ... but not here.
}

( Goto C, .)

+1
source

As you pointed out in this question, enum cmdwhich you identified can only be used in this function . But if you define enum in the header, you can use all the enumeration elements in any c file that includes this header.

This is the same as a regular variable, but sometimes an element can be used as marco(in fact, it's just an integer). This is very convenient in some cases.

0
source

Source: https://habr.com/ru/post/1648691/


All Articles