Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we define enum inside a function?

Tags:

c++

enums

We can define class/struct inside a function. Can we also define enum and union inside a function?

void fun() {
    enum {BIG, MID, SMALL};
    // other code.
}

I can compile the code with gcc 4.8.2, but I'm not sure if it's legal.

like image 350
for_stack Avatar asked Apr 21 '16 10:04

for_stack


People also ask

How do you declare an enum in a function?

To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary).

Can we define enum inside a method?

The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.

Can we define enum inside a class?

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

Can we define enum inside a method in C#?

You cannot define a Class, Enum, or Struct inside a method; that's just the way the C# language is implemented.


1 Answers

Yes, it is perfectly ok to define an enum inside a function. Your code portrays perfectly legal anonymous enum declaration.

Structs and classes may be declared within a function as well (and may also be anonymous). The only limitation with types that are declared within a function (rather than at namespace or class scope) is that they cannot be used as template parameters.

more information on Enumeration

C++11 onwards

Well the limitation regarding template parameters has been changed since C++ 11, for more information on template parameters can be found on link Template Parameters

like image 145
Tejendra Avatar answered Oct 12 '22 03:10

Tejendra