This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: cast to an enum does not throw errors even for invalid values
- From: John Love-Jensen <eljay at adobe dot com>
- To: Shriramana Sharma <samjnaa at gmail dot com>, MSX to GCC <gcc-help at gcc dot gnu dot org>
- Date: Tue, 22 May 2007 07:59:51 -0500
- Subject: Re: cast to an enum does not throw errors even for invalid values
Hi Shriramana,
> If an error is not called, I feel it defeats the very meaning of
> casting, to convert an object of one type to an object of another type.
> When there is no equivalent object of the target type, how can the
> casting happen?
It appears you have misunderstood what a cast operation means in this
situation. Both the C-style cast, and the static_cast.
It means that you, the programmer, have vouched that the value being cast is
appropriate for what is being cast to.
That, obviously, is NOT what you desire. You want some insurance that the
right hand value is checked and verified to be cast to the left hand BODY
value.
You should write and use this routine:
BODY ConvertToBODY(int i)
{
BODY result = SUN;
switch(i)
{
case SUN: result = SUN; break;
case MOON: result = MOON; break;
case STAR: result = STAR; break;
default: throw "out of BODY range error";
}
return result;
}
It is, perhaps, unfortunate that the compiler does not synthesize this for
you. But that's just not C++.
HTH,
--Eljay