Properties of enumeration and enumerators C++

Here we will discuss some the properties of enumeration and enumerators,if you do not know what are they visit the link given below.

Link :C++ enum :unscoped enumeartion
 
Property One::Enumeration scope

The scoping rule still applies in enumeration.If the enumeration has a local scope then the enumerators of that enum can only be accessed in the local area.And of course global scope enum can be accessed from anywhere within the file.

Link :Local scope and global scope
 

enum { size=10 ,
array_size=20.3 ,
max_size=49.00 ,
char_size=8
};

int main( )
{
cout<< size << ” ” << char_size ;

{
enum { loc=7 , loc_size=90 }; //local scope enum

cout << array_size << endl //fine
<< loc_size ; //fine
}

cout << max_size ; //fine

cout << loc ; //error!! local scope

return 0 ;
}

Property 2:Enumerators type is ‘const int’

All the types of enumerators in any enum type is “cont int” type.You cannot change the type of enumerators.And since the type is a “const int” type,we cannot change the value of the enumerators later again.Once it has been assigned a value the enumerator is fixated to that value for it’s life time.If the enumerators were not assigned any value ,in this case also we cannot change it’s value later.

enum { size=10 ,
array_size=20.3 ,
max_size=49.00 ,
char_size=8
} ;

enum evalue { eval1 , eval2 , eval3=-99 , eval4 };

int main( )
{
array_size=67 ; //error
size=78; //error

eval1=12 ; // error

return 0 ;
}

Since we cannot change the value of enumerator,it doesn’t mean we cannot use it to assign to another variable or enumerator.Consider the example below.

int i1=array_size ;//ok

evalue eval5=eval1 ; //ok
evalue eval6=evalue::eval2; //ok

The second and third code declare new enumerators of type ‘evalue’.Note we are initializing newly created enumerators here,not trying to change it’s value,so the ‘const int’ type rule(unchangingness) is still followed.


Property 3:Enumerators cannot have same name.

Enumerators belonging to different or same enum type cannot have the same name.Using the same name for different enumerators create conflict with the previously defined enumerators.

num { size=10 ,
array_size=20.3 ,
max_size=49.00 ,
char_size=8
} ;

enum data_size { char_size , //error!! previously defined
int_size };

This is also one of the difference enum has with user-defined type,where different structure can have members with same name.


Limitations of C type enum

One of the limitations of C type enumeration is that the type of enumerators is fix to integer type.We cannot change it’s type whatsoever.However,this limitation is overcome by C++11 scoped enumeration which allow defining enumerators of different types.Not only that,C++11 enum has lot of other useful properties which makes it worth using to write a better program.



Leave a Reply

Your email address will not be published. Required fields are marked *