更新时间:2022-10-27 12:49:01
长的版本是一个循环,初始化数组的所有成员:
的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.