Re: casting to unsigned char for is*() and to*() functions



On Thu, 30 Jun 2005 06:46:03 -0700, James Daughtry wrote:

>> The reason you need the cast is that converting directly
>> from plain `char' to `int' might not produce what toupper()
>> needs.
> Does the standard guarantee that casting signed char with a negative,
> non-EOF value, to unsigned char will produce the expected character?

Strictly, no.

> It
> seems to me that unless this guarantee is provided, the cast would give
> you defined behavior but garbage results. That's only marginally better
> than undefined behavior. As such, wouldn't it be better to simply avoid
> the operation if the value is out of range?

This is a muddy area. In practical terms the likelihood of it failing is
remote and the pain of implementing it portably (assuming that is possible
at all) is too great. So we just assume that it works. Really the onus is
on anybody writing or developing under an implementation where this
doesn't work to think long and hard about what they are doing. On
architectures where there can be an issue (such as non 2's complement
ones) there is a simple fix for the implementation - make plain char an
unsigned type.

And no, a wrong local result is nowhere near as bad as undefined
behaviour, the former can affect results for a particualr value and
anything dependent on it, the latter can make the entire program
unpredictable.

> if (c == EOF || (c >= 0 && c <= UCHAR_MAX))

c == EOF is a dangerous operation when c can be an unsigned type.

Lawrence
.



Relevant Pages