Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of double curly braces initializing a C-struct?

Tags:

c++

c

struct

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.

like image 419
Isaac Clarke Avatar asked Jun 06 '11 11:06

Isaac Clarke


1 Answers

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)}};
like image 158
James Avatar answered Oct 23 '22 17:10

James