Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

Is the enum private to the function?

void doSomething()
{
   enum cmds {
      A, B, C
   }
}
like image 855
BarryBones41 Avatar asked Jul 21 '16 18:07

BarryBones41


People also ask

What is the scope of enum?

In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.

What is the scope of enum in C?

In C, there is simply no rule for scope for enums and struct. The place where you define your enum doesn't have any importance. In C++, define something inside another something (like an enum in a class) make this something belong to the another something.

How do you declare an enum in a function?

The keyword 'enum' is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.

Can we declare enum inside main?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.


2 Answers

The enum cmds type and the enumeration members A, B, and C, are local to the function scope.

Note that while enumerations don't introduce a new scope for their member constants, they do get scoped within the containing scope, in this case the function body.

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 example code here on Coliru

like image 91
Colin D Bennett Avatar answered Sep 30 '22 19:09

Colin D Bennett


Like almost any other declaration, an enum type defined inside a block is local to that block.

In your case:

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

the block happens to be the outermost block of the function, but it doesn't have to be:

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

(Goto labels are the only entity in C that actually has function scope.)

like image 26
Keith Thompson Avatar answered Sep 30 '22 19:09

Keith Thompson