【问题标题】:About the size of unsigned char type in C++关于C++中unsigned char类型的大小
【发布时间】:2023-02-10 13:41:36
【问题描述】:

标准 C++ [3.9.1-1] 说

对于无符号字符类型,值表示的所有可能位模式都表示数字。

标准[18.3.2.4-(comment 197)]也说unsigned char的最大值相当于C中的UCHAR_MAX,在C标准[5.2.4.2.1]中定义为255。那么这是否意味着 C++ 中 unsigned char 类型的大小恰好是 8 位?

【问题讨论】:

  • 不必要。 UCHAR_MAX的最低最大值为255,是一个8位的charchar 可以是任意大小,只要它只使用 1 个字节即可。
  • @owacoder 不,sizeof(char) 保证为 1。但是,1 个字节可能大于 8 位。 :)

标签: c++


【解决方案1】:

来自 C11 5.2.4.2.1

下面给出的值应替换为适合在 #if 中使用的常量表达式 预处理指令。此外,除了 CHAR_BIT 和 MB_LEN_MAX, 以下应替换为与 an 具有相同类型的表达式 expression 是根据整数转换的相应类型的对象 促销活动。它们的实现定义值在幅度(绝对值)上应等于或大于所示值,并具有相同的符号。

(强调我的)

因此,该标准定义至少UCHAR_MAX 需要为 255,但可以大于该值。

我们对尺寸的保证是:

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

至少,数据类型的签名版本必须能够容纳:

  • char [-127, 127]
  • short [-32767, 32767]
  • int [-32767, 32767]
  • long [-2147483647, 2147483647]
  • long long [-9223372036854775807, 9223372036854775807]

【讨论】:

  • 谢谢。我得到了它。桌前没注意这些字眼。
  • 尺码整数类型不一定有这种关系。该标准对它们的范围提出了要求(例如INT_MAX &gt;= SHRT_MAX &amp;&amp; INT_MIN &lt;= SHRT_MIN),但在存在填充位的情况下,至少理论上可能有sizeof (int) &lt; sizeof (short)。 (这在实践中不太可能。)
  • @KeithThompson 实际上在 C++ 中我们有 3.9.1.2 There are five standard signed integer types : “signed char”, “short int”, “int”, “long int”, and “long long int”. In this list, each type provides at least as much storage as those preceding it in the list.
  • “char”、“signed char”和“unsigned char”是三种不同的类型,其中“char”可能是有符号或无符号的。因此 'char' 的范围是 [-128, 127] 或 {0, 255](假设是 8 位)
  • @DieterLücking 我将其更新为And at a minimum the signed versions of the data types must be able to hold:,根据标准,SCHAR_MIN 为 -127,SCHAR_MAX 为 +127
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-18
  • 2012-03-21
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多