how does array[100] = {0} set the entire array to 0?(array[100] = {0} 如何将整个数组设置为 0?)
问题描述
编译器如何填充char array[100] = {0};
中的值?它背后的魔力是什么?
How does the compiler fill values in char array[100] = {0};
? What's the magic behind it?
我想知道编译器内部是如何初始化的.
I wanted to know how internally compiler initializes.
推荐答案
这不是魔法.
此代码在 C 中的行为在 C 规范的第 6.7.8.21 节(C 规范在线草案):对于没有指定值的元素,编译器将指向 NULL 的指针和算术类型初始化为零(并递归地将其应用于聚合).
The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).
此代码在 C++ 中的行为在 C++ 规范的第 8.5.1.7 节(C++ 规范在线草案):编译器聚合初始化没有指定值的元素.
The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.
另外,请注意,在 C++(但不是 C)中,您可以使用空的初始化列表,导致编译器聚合初始化数组的所有元素:
Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:
char array[100] = {};
至于当你这样做时编译器可能会生成什么样的代码,看看这个问题:来自数组 0-initialization 的奇怪程序集
As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization
这篇关于array[100] = {0} 如何将整个数组设置为 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:array[100] = {0} 如何将整个数组设置为 0?


- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01