什么是C = {0}长版本? [英] What is the long version of ={0} in C?

查看:108
本文介绍了什么是C = {0}长版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在问这个问题:


  

= {0} 是一个捷径什么再code?


所以,经过多次搜索,并通过我的C书翻找我知道这与集合初始化但如果我想写这个code的更长的版本做的一切。下面是从程序的实际code,以防万一。

 静态字符VID [25] [100] = {0};


解决方案

长的版本是一个循环,初始化数组的所有成员:

 的for(int i = 0; I< ARRAY_SIZE ++ I)
{
    myArray的[I] = 0;
}

,编译器可能会产生对 memset的功能,这可以或可以不包含此幼稚循环的一个更优化的版本。

的呼叫

但像迪特里希指出,在这个例子你在问题中所示,你声明静态阵列。这使事情变得有点复杂。未初始化静态数据被放置在可执行文件的特别部分叫做的.bss 部分,是由两个C和C ++标准要求是默认初始化为零。如果你明确初始化的数据,链接器把它的可执行文件的。数据部分。明确初始化为0是一个有点特殊情况。智能链接器会忽略显式的初始化,并将数据存储在的.bss 部分。阿呆接头可仍放置在数据中的。数据部分。因此,它可能会更好的的显式零初始化静态链接的对象。

I have been asked this question:

= { 0 } is a "shortcut" for what longer code?

So after many searches and rummaging through my C book I know everything that it does with aggregate initialization but what if I wanted to write the longer version of this code. Here is the actual code from the program just in case

static char vid[25][100] = { 0 } ;

解决方案

The long version is a loop that initializes all of the members of the array:

for (int i = 0; i < ARRAY_SIZE; ++i)
{
    myArray[i] = 0;
}

The compiler will probably generate a call to the memset function, which may or may not contain a more optimized version of this naive loop.

But like Dietrich points out, in the example you've shown in the question, you're declaring a static array. That makes things a bit more complicated. Uninitialized static data is placed in a special section of the executable called the .bss section and is required by both the C and C++ standards to be default-initialized to zero. If you explicitly initialize the data, the linker puts it in the .data section of the executable. Explicitly initializing to 0 is a bit of a special case. Smart linkers will omit the explicit initializer and place the data in the .bss section. Dumb linkers may still place the data in the .data section. So it's probably better not to explicitly zero-initialize objects with static linkage.

这篇关于什么是C = {0}长版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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