Struct initialization of the C/C++ programming language?

The first statement creates a variable initialized to the given values, i.e., these values are built in memory and stored directly in the program executable in that variable address (for globals) or ready for memory copy (for stack variables).

The second statement of the second block is very different. Although it looks similar, it is an assign expression. It means that the RHS of the equals operator is an expression that is evaluated (independently of what is in the LHS of =), and then passed to the = operator. Without proper context, {...} doesn’t have any meaning.

In C99, you can do this:

struct_name_id = (struct struct_type_id){ value1, value2, value3 };

Now the RHS of the equals operator is a valid expression, since there is proper context for the compiler to know what is in {...}.

In C++11, the syntax is:

struct_name_id = struct_type_id{ value1, value2, value3 };

Leave a Comment