C 语言规范是否保证 short 的大小始终是 char 的两倍?

Are there any guarantees made by the C language specification that the size of a short will always be double the size of a char?

根据我的研究,这些是我能找到的关于这些 built-in 整数数据类型的唯一保证:

在实践中,根据我的经验,short总是char的两倍大小,但这似乎并不是C语言规范做出的保证。好像16位char和16位short这样的场景还是可以的

这更像是一个好奇的问题,我意识到如果你真的需要整数数据类型的精确宽度,你最好使用 stdint.h header.

2021 年 6 月 6 日更新: 我不认为这个问题与 What platforms have something other than 8-bit char? 重复。我不是在问 char 的具体大小,而是 charshort 之间的比率,而不管两者的实际大小。至少对我来说,这些答案中的许多都以“重复”问题所没有的方式启发了我。我希望这也能帮助其他偶然发现它的人。

理论上,charshortint都可以有相同的大小。

很少有实现在实践中这样做(我不能说出任何名字;我想在上个世纪你可能已经找到了一些)

没有这样的保证。

C 标准将以下值指定为最小值:

#define CHAR_BIT                         8
#define CHAR_MAX    UCHAR_MAX or SCHAR_MAX
#define CHAR_MIN            0 or SCHAR_MIN
#define INT_MAX                     +32767
#define INT_MIN                     -32767
#define LONG_MAX               +2147483647
#define LONG_MIN               -2147483647
#define LLONG_MAX     +9223372036854775807
#define LLONG_MIN     -9223372036854775807
#define MB_LEN_MAX                       1
#define SCHAR_MAX                     +127
#define SCHAR_MIN                     -127
#define SHRT_MAX                    +32767
#define SHRT_MIN                    -32767
#define UCHAR_MAX                      255
#define USHRT_MAX                    65535
#define UINT_MAX                     65535
#define ULONG_MAX               4294967295
#define ULLONG_MAX    18446744073709551615

所以你可以有一个系统,其中 CHAR_BIT 是 16 并且 char 的 max/min 值与上述 short 和 [=13 的最小值相匹配=] 与上面没有变化,在这种情况下 charshort 将是相同的大小。

正如一些人已经指出的那样,规范不保证内置类型的“位宽”,如何定义这些取决于给定架构的编译器的实现。

也许更有趣的是它是如何在实践中使用的。事实上,“当前”架构的内置大小不遵循通常的 1-2-4-8 约定。 Analog Devices SHARC.

就是一个很好的例子(也是我有相当多个人经验的例子)

来自维基百科页面:

it knows nothing of 8-bit or 16-bit values since each address is used to point to a whole 32-bit word, not just an octet. It is thus neither little-endian nor big-endian, though a compiler may use either convention if it implements 64-bit data and/or some way to pack multiple 8-bit or 16-bit values into a single 32-bit word. Analog Devices chose to avoid the issue by using a 32-bit char in their C compiler.

32 位字符绝对可以称为“病态”情况,但它适用于广泛用于专业和专业音频应用程序的 SHARC。以 Universal Audio 的 Apollo 为例。