Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the size of unsigned char type in C++

Tags:

c++

The standard C++ [3.9.1-1] says that

For unsigned character types, all possible bit patterns of the value representation represent numbers.

The standard [18.3.2.4-(comment 197)] also says that the maximum value of unsigned char are equivalent to UCHAR_MAX in C, which is defined as 255 in C standard [5.2.4.2.1]. So does this mean the size of unsigned char type in C++ is exactly 8 bits?

like image 871
xskxzr Avatar asked Sep 25 '15 15:09

xskxzr


People also ask

What is sizeof unsigned char in C?

For unsigned character types, all possible bit patterns of the value representation represent numbers. The standard [18.3. 2.4-(comment 197)] also says that the maximum value of unsigned char are equivalent to UCHAR_MAX in C, which is defined as 255 in C standard [5.2. 4.2. 1].

How big is a unsigned char?

The unsigned char datatype encodes numbers from 0 to 255.

What is the value of unsigned char?

Character values of type unsigned char have a range from 0 to 0xFF hexadecimal. A signed char has range 0x80 to 0x7F. These ranges translate to 0 to 255 decimal, and -128 to +127 decimal, respectively.


1 Answers

From C11 5.2.4.2.1

The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR_BIT and MB_LEN_MAX, the following shall be replaced by expressions that have the same type as would an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.

(emphasis mine)

So the standard defines that at a minimum UCHAR_MAX needs to be 255 but it can be greater than that.

The guarantees that we have on size are:

sizeof(char) = 1 and sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

And at a minimum the signed versions of the data types must be able to hold:

  • char [-127, 127]
  • short [-32767, 32767]
  • int [-32767, 32767]
  • long [-2147483647, 2147483647]
  • long long [-9223372036854775807, 9223372036854775807]
like image 147
NathanOliver Avatar answered Sep 29 '22 07:09

NathanOliver