Reputation: 727
I'm currently working with legacy C++ code, successfully compiled with gcc 2.9.X.
I've been asked to port this legacy code to gcc 3.4.X. Most of the errors were easily corrected, but this particular one puzzles me.
The context :
struct TMessage
{
THeader header;
TData data;
};
struct THeader
{
TEnum myEnum;
TBool validity;
};
What was done :
const TMessage init = {{0}};
/* Later in the code ... */
TMessage message = init;
My question(s) :
What is the meaning of the {{}} operator ? Does it initialize the first field (the header) to a binary 0 ? Does it initialize the first field of the first structure (the enum) to (literal) 0 ?
The 3.4.6 error I get is invalid conversion from 'int' to 'TEnum'
, either with one or two pairs of curly brackets.
How can I set my structure to a bunch of 0's without using memset ?
Thanks in advance.
Upvotes: 22
Views: 14358
Reputation: 1376
struct TMessage
struct THeader
TEnum myEnum
In this case you are initializing TEnum
with int
0
, which is incompatible conversion
.
So you must add casting like this:
const TMessage init = {{TEnum(0)}};
In C/C++, if you partially initialized
structure or array (only some of the first fields/elements), the rest will be initialized by the default constructor
(which is zero-initialization for primitive types). Compile error will occur if there is no default constructor or if the constructor is declared as private
.
Upvotes: 3
Reputation: 25553
It initialises all fields of the POD structure to 0.
Rationale:
const SomeStruct init = {Value};
Initialises the first field of SomeStruct to Value, the rest of the structure to zero (I forget the section in the standard, but it's there somewhere)
Thus:
const SomeOtherStruct init = {{Value}};
Initialises the first field of the first field of the structure (where the first field of the structure is itself a POD struct) to Value, and the rest of the first field to zero, and the rest of the structure to 0.
Additionally, this only isn't working because c++ forbids implicit conversion of int
to enum types, so you could do:
const SomeOtherStruct init = {{TEnum(0)}};
Upvotes: 25
Reputation: 70021
You can hink of it as a multi dimensional array (if that helps). You then reset two dimensions to 0 with that command. This works since (I assume) that the values within the struct can take 0 as a value.
Upvotes: 1