This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]