简体   繁体   English

C / C ++中的数组初始化

[英]array initialization in C/C++

这段代码初始化所有主要C中的阵列的所有元素和C ++编译或不?

int arr[100] = {0};

In all compilers. 在所有编译器中。 This is guaranteed by the C Standard and the C++ Standard. 这由C标准和C ++标准保证。

For example, for C here is the relevant paragraph: 例如,对于C,这是相关段落:

(C99, 6.7.8p21) "If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration." (C99,6.7.8p21)“如果括号括起的列表中的初始值设定项少于聚合的元素或成员,或者用于初始化已知大小的数组的字符串文字中的字符数少于其中的元素。对于数组,聚合的其余部分应与具有静态存储持续时间的对象隐式初始化。“

and

(C99, 6.7.8p10) "If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then: [...] if it has arithmetic type, it is initialized to (positive or unsigned) zero; [...]" (C99,6.7.8p10)“如果没有显式初始化具有自动存储持续时间的对象,则其值是不确定的。如果没有显式初始化具有静态存储持续时间的对象,则:[...]如果它具有算术类型,它被初始化为(正或无符号)零; [...]“

If the array happens to be an array of structs, you'll quickly run into problems. 如果数组恰好是一个结构数组那么你很快就会遇到问题。 Heck, you can't even do a single struct. 哎呀,你甚至不能做一个结构。

This simple example shows that two major compilers (gcc and msvc) do not follow the specifications as quoted in ouah's answer (gcc seemingly, from its warning, and msvc from its error msg). 这个简单的示例显示了两个主要的编译器(gcc和msvc) 没有遵循ouah的答案中所引用的规范(gcc 看似来自其警告,msvc来自其错误msg)。

Consider this source, foo.c / foo.cpp: 考虑这个源,foo.c / foo.cpp:

void foo(void) {
   struct A {
      int i;
      int j;
   };
   struct A single = {0};
}

Compile, with both gcc and g++: 用gcc和g ++编译:

$ gcc -Wall -W -c foo.c
foo.c: In function 'foo':
foo.c:6:14: warning: missing initializer
foo.c:6:14: warning: (near initialization for 'single.j')

$ g++ -Wall -W -c foo.cpp
foo.cpp: In function 'void foo()':
foo.cpp:6:27: warning: missing initializer for member 'foo()::A::j'

The same warnings are given for arrays. 对阵列给出了相同的警告。 This gcc is only two years old: gcc --version --> gcc (GCC) 4.5.3 . 这个gcc只有两年了: gcc --version - > gcc (GCC) 4.5.3

Plain {} without the 0 works fine in gcc, including for arrays. 没有0的普通{}在gcc中工作正常,包括数组。 And you could always compile with -w (lower case) to disable all warnings. 并且您始终可以使用-w (小写)进行编译以禁用所有警告。

But MSVS 2012 has the equal and opposite problem with this example (including arrays). 但MSVS 2012与此示例(包括数组)存在相同且相反的问题

It likes {0}, and treats {} as an error : 喜欢 {0},并将{}视为错误

Error C2059: syntax error : '}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM