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.
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).
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.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
You cannot define a Class, Enum, or Struct inside a method; that's just the way the C# language is implemented.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With