problem with safe-ctype.h

Herman ten Brugge Haj.Ten.Brugge@net.HCC.nl
Fri Dec 15 12:53:00 GMT 2000


Kaveh R. Ghazi wrote :
> 
>  > From: Herman ten Brugge <Haj.Ten.Brugge@net.HCC.nl> 
>  > 
>  > 2000-12-14 Herman A.J. ten Brugge <Haj.Ten.Brugge@net.HCC.nl>
>  > 
>  >         * safe-ctype.h: Make code work on all targets and not just on
>  >         targets where a char is 8 bits.
>  > 
>  > 
>  > -#define _sch_test(c, bit) (_sch_istable[(int)(unsigned char)(c)] & (bit))
>  > +#define _sch_test(c, bit) (_sch_istable[(c) & 0xff] & (bit))
>  > -#define TOUPPER(c) _sch_toupper[(int)(unsigned char)(c)]
>  > -#define TOLOWER(c) _sch_tolower[(int)(unsigned char)(c)]
>  > +#define TOUPPER(c) _sch_toupper[(c) & 0xff]
>  > +#define TOLOWER(c) _sch_tolower[(c) & 0xff]
> 
> The reason for these casts is to avoid problems when parameter `c' is
> a signed char.  If you pass in something > 127 you'll get a negative
> offset into the _sch_* arrays.
> 
> We used to have code to handle this in system.h before safe-ctype was
> put in libiberty.  Something like:
> 
>  > #define CTYPE_CONV(CH) \
>  > (sizeof(CH) == sizeof(int) ? (int)(CH) : (int)(unsigned char)(CH))
> 
> Then you'd wrap CTYPE_CONV around the `c' parameter in the ctype
> definitions.
> 
> Note: CTYPE_CONV is resolved at compile-time so you don't have
> multiple evaluation problems.
> 
> So e.g. if you #define TOUPPER _sch_toupper[CTYPE_CONV(c)] it should
> DTRT.  You may still need to & 0xff to truncate 32-bit chars into the
> right range, but CTYPE_CONV will also ensure that char 255 won't
> become negative.

I still don't understand. Sorry. What is the difference between:
'(int)(unsigned char)(c)' and '(c) & 0xff'
The following program does not abort:

int
main(int argc, char **argv)
{
	signed char a;

	for (a = -128 ; a < 127 ; a++)
		if (((int)(unsigned char)(a)) != ((a) & 0xff))
			abort();
	return 0;
}

The only problem I can see is for targets where we don't use 2's complement
(do they still exist?).

	Herman.


More information about the Gcc-patches mailing list