Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (int)(unsigned char)(x) do in C?

Tags:

c

In ctype.h, line 20, __ismask is defined as:

#define __ismask(x) (_ctype[(int)(unsigned char)(x)])

What does (int)(unsigned char)(x) do? I guess it casts x to unsigned char (to retrieve the first byte only regardless of x), but then why is it cast to an int at the end?

like image 941
Tu Do Avatar asked Oct 01 '15 10:10

Tu Do


1 Answers

(unsigned char)(x) effectively computes an unsigned char with the value of x % (UCHAR_MAX + 1). This has the effect of giving a positive value (between 0 and UCHAR_MAX). With most implementations UCHAR_MAX has a value of 255 (although the standard permits an unsigned char to support a larger range, such implementations are uncommon).

Since the result of (unsigned char)(x) is guaranteed to be in the range supported by an int, the conversion to int will not change value.

Net effect is the least significant byte, with a positive value.

Some compilers give a warning when using a char (signed or not) type as an array index. The conversion to int shuts the compiler up.

like image 85
Peter Avatar answered Sep 27 '22 23:09

Peter