Boost logo

Boost :

From: Dill, John (john-dill_at_[hidden])
Date: 2004-04-20 17:43:54


"Rob Stewart" <stewart_at_[hidden]> wrote in message news:<200404202049.i3KKnwe25029_at_[hidden]>...
> From: "Dill, John" <john-dill_at_[hidden]>
> > "Rob Stewart" <stewart_at_[hidden]> wrote in message news:<200404201905.i3KJ55e08992_at_[hidden]>...
> > > From: "Dill, John" <john-dill_at_[hidden]>
> > > >
> > > > I am wondering about the use-case of numeric_cast in this sample.
> > > >
> > > > unsigned char uchar_max = std::numeric_limits<unsigned char>::max();
> > > > char schar_value = 0;
> > > >
> > > > try {
> > > > schar_value = boost::numeric_cast<char>( uchar_max );
> > > > }
> > > > catch ( boost::bad_numeric_cast )
> > > > { std::cout << "Overflow occurred..." << std::endl; }
> > > >
> > > > When I execute this sample, I don't get the exception. What's
> > > > the background on this behavior? I'm using gcc 3.3.1.
> > >
> > > Your char is unsigned.
> >
> > I'd like to know why conceptually the exception isn't thrown.
>
> As I said, in too few words, is that your "char" is unsigned, so
> "char" and "unsigned char" are essentially the same type.
> Technically, they are distinct types (for overloading purposes,
> for example), but they are both unsigned and the same size, so:
>
> assert(std::numeric_limits<char>::max()
> == std::numeric_limits<unsigned char>::max());
>
> on your system.

Actually that is not the case. The max defined for unsigned char is 255, while for char is 127. Actually, char is supposedly equivalent to signed char, not to unsigned char.

> > Why is it beneficial to have unsigned T to signed T overflows
> > not be detected? It is not just char, but short, int, and long
> > as well.
>
> Now that's another story. Changing "unsigned char" to
> "unsigned" and "char" to "int" should cause an exception. If
> that's not happening, I don't understand since
> std::numeric_limits<unsigned>::max() is greater than
> std::numeric_limits<int>::max().

Actually, I think those type conversions shouldn't cause an exception. Converting char to int for example should be no problem since the range of char is within the range of int. Should be similar for unsigned char and unsigned.
 
> > If this was the intended behavior, then what is the reasoning
> > behind it?
>
> What you describe isn't the intended behavior other than the char
> problem.

I think it is a problem when you have an unsigned char, range 0 to 255, put into a char, range -128 to 127, when you are converting an unsigned char value of 255 (the numeric_limits::max()) into a [signed] char. It is an overflow problem, and it doesn't generate an exception. From what you seem to say, this should be a bug.

Best,
John


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk