array[100] = {0} 如何将整个数组设置为 0? [英] how does array[100] = {0} set the entire array to 0?

查看:28
本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆