Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2006-01-06 14:52:43


Chris Cleeland wrote:
> On Fri, 6 Jan 2006, Peter Dimov wrote:
>
>> Chris Cleeland wrote:
>>> Whatever is necessary. If the args were shorts (signed or
>>> unsigned), the interface is representing that the following would be
>>> legal:
>>>
>>> asio::ipv4::address my_address(322, 798, 0, 1024);
>>>
>>> And we know that's not correct.
>>
>> If the arguments are unsigned chars, you (the author of the
>> function) have no way of knowing whether it's correct, because you
>> won't see 322 or 798.
>
> I'm missing the point of what you're saying. If the args are
> unsigned chars, there is no need for the author of the function to
> check the range b/c the range is implicit in the type. Hopefully
> pedantic compilers will issue warnings regarding loss of precision
> via implicit conversion catching errors like this at compile time
> rather than at execution time.

If the interface takes unsigned char, passing 322 will result in the
function receiving 66. This may generate a compiler warning, or it may not.
Even if it does generate a warning, an explicit static_cast to unsigned char
(because the programmer thinks that the value is in range) will silence it.

If the interface takes an int, passing 322 will result in the function
receiving 322. The function can now handle this error in an appropriate
manner. Callers that pass an unsigned char are neither helped nor harmed by
the interface taking an int. Callers that pass an int that is out of range
potentially lose an easy to ignore warning and gain runtime error detection.

So it's a set of tradeoffs. If the interface takes shorts, there is both a
warning and a possibility of runtime error detection.

In summary, what I'm saying is that in C/C++, using unsigned char for an
argument with a range 0..255 is not inherently superior to the alternatives.
(It would be in a range-checked language.)


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