How to write an 8-bit clean program

Henry Spencer henry at utzoo.uucp
Sun Feb 11 12:21:10 AEST 1990


In article <1990Feb10.151053.16702 at is.uu.no> ra at is.uu.no (Robert Andersson) writes:
>In an 8-bit set some character will have values > 128.
>Is it kosher to store these values in char variables?

Well, there is of course the question of whether the variable is big enough
for the value, disregarding the sign issue.  However, that aside, the real
issue here is assigning a value which would fit if chars were unsigned but
isn't in the value space of a char which is signed.  This conversion has
implementation-defined results (section 3.2.1.2, Oct 88 draft).  It might
cause an overflow if somebody is being paranoid.  One would hope that
compilers which do that will quickly be fixed not to.

>Suppose you do it, then as long as you simply use char variables in
>simple assignments/test or as buffers, all is probably OK. As soon as
>you use the variable in arithmetic expressions or assigments to other
>types things become more muddy.

By definition, expression/conversion code which cares whether char is
signed or not is unportable.  The correct approach is to fix it, in
one way or another.

>So, the better way to do it might be to change all char variables in
>your program to unsigned char? But that opens another can of worms.
>Many compilers spit out warnings...

Moreover, on some machines you will take a serious efficiency hit for
this.  The right thing to do is to use "signed char" or "unsigned char"
in places where the code cares, and use "char" when it does not care.
Most of the time, cleanly-written code does not care.  Using chars as
characters -- rather than small integers -- seldom runs into sign issues
(although there are occasional hassles in table lookup and function calls).
Code which uses chars as small integers almost certainly should be using
"signed char" or "unsigned char" to explicitly indicate its needs.
-- 
SVR4:  every feature you ever |     Henry Spencer at U of Toronto Zoology
wanted, and plenty you didn't.| uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list