通常假设将对象初始化为所有位 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/