在 C99 中,第 6.5.3.4 节:
2 The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. ...4 The value of the result is implementation-defined, and its type (an unsigned integer type) is
size_t
, defined in<stddef.h>
(and other headers).
在 C++14 中,第 5.3.3 节:
1 The
sizeof
operator yields the number of bytes in the object representation of its operand. ... The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined.
唯一的保证值是 sizeof(char)
, sizeof(unsigned char)
和sizeof(signed char)
这是其中之一。
然而,“对象表示中的字节数”对我来说似乎是铁定的。例如,在 C99 §6.2.6.1 中:
4 Values stored in non-bit-field objects of any other object type consist of n × CHAR_BIT bits, where n is the size of an object of that type, in bytes. ...
既然它看起来定义得很好,那么为什么它是实现定义的呢?
<小时/>你们中的许多人似乎都误解了我的问题。我从未说过:
A)类型的大小在所有系统上都已定义或相同,
B)实现定义意味着它可以返回“随机值”
我在这里得到的是n * CHAR_BITS
是一个固定的公式。公式本身在实现之间不能改变。是的,一个int
可以是4字节或8字节。我明白了。但在所有实现之间,该值必须 n * CHAR_BITS
.
最佳答案
sizeof
的结果是实现定义的,因为各种基本类型的大小是实现定义的。我们对 C++ 中类型大小的唯一保证是
sizeof(char) = 1 and sizeof(char) <= sizeof(short) <= sizeof(int) <=
sizeof(long) <= sizeof(long long)
每种类型都有一个最小值,它必须支持 C11 [附件 E(资料性)实现限制]/1
[...]The minimum magnitudes shown shall be replaced by implementation-defined magnitudes with the same sign.[...]
#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
因此,根据标准,int
必须能够存储可以以 16 位存储的数字,但它可以更大,在当今的大多数系统上它是 32 位。
What I'm getting at here is that
n * CHAR_BITS
is a fixed formula. The formula itself can't changed between implementations. Yes, an int may be 4 bytes or 8 bytes. I get that. But between all implementations, the value mustn * CHAR_BITS
.
您是正确的,但 n
根据 C99 §6.2.6.1 定义为
where
n
is the size of an object of that type
强调我的
因此公式可能是固定的,但 n
不是固定的,同一系统上的不同实现可以使用不同的 n
值。
关于c++ - 为什么要定义sizeof实现的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37750904/