cast to an enum does not throw errors even for invalid values

Ian Lance Taylor iant@google.com
Fri May 25 14:38:00 GMT 2007


Shriramana Sharma <samjnaa@gmail.com> writes:

> Consider:
> 
> enum BODY { SUN, MOON, STAR } ;
> enum PLANET { EARTH, VENUS, MARS, PLUTO } ;
> int main ( void )
> {
>   BODY body ;
>   // body = 1 ;                           // gives error. expected.
>   // body = EARTH ;                       // gives error. expected.
>   body = (BODY) 1 ;                       // no error. expected.
>   body = (BODY) EARTH ;                   // no error. expected.
>   body = static_cast < BODY > ( 1 ) ;     // no error. expected.
>   body = static_cast < BODY > ( EARTH ) ; // no error. expected.
>   body = (BODY) 3 ;                       // no error. unexpected.
>   body = (BODY) PLUTO ;                   // no error. unexpected.
>   body = static_cast < BODY > ( 3 ) ;     // no error. unexpected.
>   body = static_cast < BODY > ( PLUTO ) ; // no error. unexpected.
> }
> 
> I feel that the compiler should detect it when a value being casted to
> an enum does not have an equivalent enum identifier. i.e. in the above
> case, 3 and PLUTO (equivalent to 3 from the PLANET enum) do not have an
> equivalent identifier in the BODY enum. But still the compiler does not
> call an error. Even negative integers are "casted" to the target enum
> without an error.

These conversions are permitted by the C++ language.  gcc could give a
warning, but not an error, and certainly not a runtime error.

Ian



More information about the Gcc-help mailing list