简体   繁体   English

关于C ++中unsigned char类型的大小

[英]About the size of unsigned char type in C++

The standard C++ [3.9.1-1] says that 标准C ++ [3.9.1-1]说明了这一点

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]. 标准[18.3.2.4-(注释197)]也表示无符号字符的最大值等于C中的UCHAR_MAX ,在C标准[5.2.4.2.1]中定义为255。 So does this mean the size of unsigned char type in C++ is exactly 8 bits? 那么这是否意味着C ++中unsigned char类型的大小恰好是8位?

From C11 5.2.4.2.1 从C11 5.2.4.2.1开始

The values given below shall be replaced by constant expressions suitable for use in #if preprocessing directives. 下面给出的值应替换为适用于#if预处理指令的常量表达式。 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. 此外,除了CHAR_BIT和MB_LEN_MAX之外,以下内容应替换为与根据整数提升转换的对应类型的对象的表达式具有相同类型的表达式。 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. 因此,该标准定义了UCHAR_MAX至少需要为255但可能大UCHAR_MAX值。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM