"Jeff Schwab" <je******@comcast.net> wrote in message
news:6d********************@comcast.com
Kurt Watzka wrote:
#include <iostream>
int main( )
{
int data[ 2 ] = { 1 };
std::cout << data[ 0 ] << '\n'
<< data[ 1 ] << '\n';
}
If data[1] is not 0, the compiler is broken.
On my compiler, data[ 1 ] is zero. Which does not match the
initializer { 1 }. So do you still think the initializer applies to
all elements of the array?
The rule is not that the first initialiser is repeated. The rule is that
anything not explicitly initialised is default-intialised, which means set
equal to zero in the case of an int. If the first and only initialiser
happens to be zero, then this means that everything is set to zero.
The matter is covered in the C++ standard in section 8.5. First we have the
definition of "default-initialisation":
"To default-initialize an object of type T means:
- if T is a non-POD class type (clause 9), the default constructor for T is
called (and the initialization is
ill-formed if T has no accessible default constructor);
- if T is an array type, each element is default-initialized;
- otherwise, the storage for the object is zero-initialized."
Next we have the definition of an "aggregate".
"An aggregate is an array or a class (clause 9) with no user-declared
constructors (12.1), no private or pro-tected
non-static data members (clause 11), no base classes (clause 10), and no
virtual functions (10.3)."
Finally, we have the relevant rules on the default intialisation of an
aggregate:
"If there are fewer initializers in the list than there are members in the
aggregate, then each member not
explicitly initialized shall be default-initialized (8.5).
[Example:
struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };
initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an
expression of the form
int(), that is, 0. ]"
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)