gpt4 book ai didi

我可以相信 sizeof(size_t) <= sizeof(unsigned long int) 总是正确的吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:33:13 24 4
gpt4 key购买 nike

我能相信吗sizeof(size_t) <= sizeof(unsigned long int)总是正确的,根据 C89 标准?

即,如果我使用 unsigned long,我不会失去值(value)其中 size_t是预期的,反之亦然。

最佳答案

也许是对 size_t 发生的事情的最好解释C89 中的整数类型是它的基本原理文档。仔细阅读本文档的第 3.4.4 节:

Sizeof and size_t for C89 (rationale)

第三段说:

The type of sizeof, whatever it is, is published (in the library header ) as size_t, since it is useful for the programmer to be able to refer to this type. This requirement implicitly restricts size_t to be a synonym for an existing unsigned integer type, thus quashing any notion that the largest declarable object might be too big to span even with an unsigned long.

这意味着,对于C89的关注,一般来说size_t与预先存在的 unsigned 相同整数类型,在 C89 中意味着 unsigned char, unsigned short, unsigned int, unsigned long 之一.
特别是,类型为 size_t 的每个值在 unsigned long 范围内.
通过阅读标准 C89 的规范,您还可以看到 sizeof(size_t)<=sizeof(long) .


现在,C99 的情况有点不同。该标准规定:

  1. 7.17 标准杆。 2 size_t是无符号整数类型。
  2. 7.17 标准杆。 4 用于 size_t 的类型[...] 的整数转换等级不应大于 signed long int 的整数转换等级
  3. ---------- 除非实现支持足够大的对象以使其成为必要。
  4. 6.2.5 标准杆。 8 对于任意两个符号相同但整数转换秩不同的整数类型(见6.3.1.1),整数转换秩较小的类型的取值范围是另一种类型取值的子范围。

    由于 signed long int整数转换排名unsigned long int相同,这意味着 size_t 的值范围包含在 unsigned long int 的值范围内.但是上面列表中的第 3 项为这条规则的异常(exception)情况敞开了大门。

因此,我们只能说,一个实现使 size_t 的值具有很高的意图。保持在 unsigned long int 的范围内.但我们不能完全确定

如果您想确定,可以执行以下过程来检查您的系统:

  1. 包括文件 <limits.h><stdint.h>为了访问有关您的实现的整数类型的信息。
  2. 比较常量ULONG_MAX (来自 <limits.h> )和 SIZE_MAX (来自 <stdint.h>)。

一个简短的程序是这样的:

 #include <stdio.h>
#include <limits.h>
#include <stdint.h>

int main(void) {
printf("Is the range of size_t containd in that of unsigned long?\n\n");
if (SIZE_MAX <= ULONG_MAX)
printf("Yes");
else
printf("No");
return 0;
}

关于我可以相信 sizeof(size_t) <= sizeof(unsigned long int) 总是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19329860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com