简体   繁体   English

下列结构和数组的所有成员是否都初始化为零?

[英]Are all members of following structs and arrays initialized with zero?

Furthermore, is there a difference between the initialization of the variables one and two, and the initialization of the varibles three and four? 此外,变量1和2的初始化与变量3和4的初始化之间是否有区别? Background of the Question is, that i get an compiler error in Visual Studio 6.0 with the initialization of variable two and four. 问题的背景是,在初始化变量2和4时,我在Visual Studio 6.0中遇到编译器错误。 With Visual Studio 2008 it compiles well. 使用Visual Studio 2008可以很好地进行编译。

struct stTest
{
  int a;
  char b[10];
};

stTest one = {0};
stTest two = {};
stTest three[10] = {0};
stTest four[10] = {};

Yes, all of them a required to be initialized with 0 by the language standard (C++98). 是的,所有语言标准(C ++ 98)都要求将其初始化为0。

Visual Studio 6 is known not to perform the proper handling of {} case: it doesn't even support {} syntax, if I remember correctly. 众所周知,Visual Studio 6无法正确处理{}情况:如果我没记错的话,它甚至不支持{}语法。

However, Visual Studio 6 is a pre-standard compiler. 但是,Visual Studio 6是标准的编译器。 It was released before the C++98 standard came out. 它是在C ++ 98标准发布之前发布的。

See Michael Burr's answer to a similar question . 参见迈克尔·伯(Michael Burr)对类似问题 的回答

The short answer is yes, but a little emphasis sometimes helps, eg , 简短的答案是肯定的,但有时稍加强调会有所帮助, 例如

stTest s = {0};

The initializations are the same. 初始化是相同的。 Visual Studio 2.0 is broken. Visual Studio 2.0已损坏。


Edit: 编辑:

Yes, they are initialized to zero. 是的,它们被初始化为零。

( Ripped from MSDN ) 从MSDN翻录

If I have a structure called tPoint ... 如果我有一个名为tPoint的结构...

    struct tPoint {   
        int x;   
        int y;
    };

... and I use it as follows ... ...我将其使用如下...

tPoint spot {10,20};

... I can expect that members x and y will be initialized. ...我可以期望成员x和y将被初始化。

As for your first question, I'd expect that the array b is not initialized because you only give one value for initialization. 关于第一个问题,我希望数组b不会被初始化,因为您只为初始化提供一个值。

You can initialize the values to zero by default: 您可以默认将值初始化为零:

struct stTest
{
  int a = 0;
  char b[10] = {0};
};

You can initialize the array like this: 您可以像这样初始化数组:

char i[10] = {0};
stTest one = {0, i};

As for why it compiles with VS 2008 and not VS 6.0, VS 2008 probably ignores the empty set and doesn't try to initialize anything. 至于为什么它使用VS 2008而不是VS 6.0进行编译,VS 2008可能会忽略空集,并且不尝试初始化任何内容。

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

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