所有位 0 都可以是整数的陷阱表示吗?

Can all bits 0 be a trap representation for integers?

通常假设将对象初始化为所有位 0 是将其所有成员设置为 0 的简单方法。对于非整数类型,标准不保证这一点:

整数呢?以下代码是否完整定义:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    int *p = calloc(sizeof(*p), 1);
    if (p) {
        printf("%d\n", *p);
        memset(p, 0, sizeof(*p));
        printf("%d\n", *p);
        free(p);
    }
    return 0;
}

来自C Standard, 6.2.6.2, Integer Types

For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.

陷阱表示的定义是,C11 6.2.6.1/5:

Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

这意味着陷阱表示必须是无效值。

在二进制补码的情况下,int 的所有二进制组合都是有效值,因此陷阱表示是不可能的。

在虚构的补码系统的情况下,如果不支持负零,则可以将值 0xFFFFFFFF(假设 32 位 int)设为陷阱表示。同样,在一个虚构的有符号星等系统上,值 0x80000000 可以用作陷阱表示。

在更狂野的虚构系统中,整数可能具有填充位,然后此类填充位可用于保存陷阱表示。

在任何这些情况下,二进制表示 0 始终是一个值。许多 C 标准都依赖于此,例如具有静态存储持续时间的对象的初始化、calloc() 函数、结构中填充字节的值等。在所有这些中,结果不应是陷阱表示。

请注意,如果您不是极度虚构系统的程序员,none 无需担心。可能存在一些奇怪的实验性计算机,其中存在这种情况。您甚至可能会找到可以向您介绍他们的人。

如果您正在设计与此类异国情调的、很可能是虚构的系统的兼容性,您应该详细记录为什么您的产品需要这种兼容性。因为你的老板可能想知道你为什么要花很多时间设计与现实世界中实际上不存在的计算机的兼容性。