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

标签 c language-lawyer undefined-behavior calloc

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

  • 所有位都为零可能不是指针的有效表示,甚至是空指针,尽管所有常见的现代系统都使用它。
  • 所有位都为零可能不是 float 的合法表示,尽管它在 IEEE 兼容系统上。

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

#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.

关于所有位 0 都可以是整数的陷阱表示吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47055947/

相关文章:

c - 如何编写用于分析的 MPI 库

C - 序列化技术

c++ - C++11 之前的初始化列表中同一变量的多个突变是否未定义行为

c++ - 为 sfinae : does the language allow it? 使用别名模板

c - 在同一语句中使用多个递增/递减

c - (i + 1) < ii 和 (i + 1) > ii 怎么可能都为真?

c++ - 是否可以将 C 风格的 api 回调/处理程序适应 C++ 以进行类相关的动态创建?

c++ - 为什么在重定向 stdout 和 stdin 时 Python 的行为不符合预期?

c++ - C++ 中的存储重用

c++ - std::string 作为成员函数参数的奇怪行为