Initializing the structure of the C / C ++ programming language?

I could initialize the structure using code:

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

but cannot:

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

why could I do this with the former, but could not with the latter with gcc, g ++, vc2008, vc6? In other words, why does the c / C ++ programming language not support this syntax?

thank.

+10
c ++ c struct
Nov 10 '09 at 1:37
source share
5 answers

The first statement creates a variable initialized with the given values, i.e. these values ​​are built in memory and stored directly in executable software at this variable address (for global) or are ready to copy memory (for stack variables).

The second statement of the second block is very different. Although it looks similar, it is an expression of purpose. This means that the RHS of the equals operator is an expression that is evaluated (regardless of what is in LHS = =) and then passed to the = operator. Without the proper context, {...} is irrelevant.

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, because there is an appropriate context for the compiler to find out what is in {...} .

In C ++ 11, the syntax is:

 struct_name_id = struct_type_id{ value1, value2, value3 }; 
+22
Nov 10 '09 at 1:45
source share

I don’t know why C initially didn’t support some kind of syntax for “reinitializing” the structure using something like a list of initializers - there are certain points when I would find it convenient. As Giuliano noted, C99 (and C ++ 0x) fixed it to a certain extent, but I often have to stick with the C90. When I want to do something like this, I sometimes do the following:

 struct foo const init_foo = { 1, 2, 3}; struct foo myFoo; // .... myFoo = init_foo; // reinitialize myFoo 
+4
Nov 10 '09 at 1:53
source share

You just need to specify the values ​​as such:

 struct_name_id = (struct struct_type_id){ value1, value2, value3 }; 
+2
Nov 10 '09 at 1:41
source share

Will this work for you?

 typedef struct name_id {int value1; int value2; int value3;} NAME_ID; name_id mynameid = {0,1,2}; 
0
Nov 10. '09 at 2:26
source share

I had a similar problem, and the solution to this was that I tried to initialize the structure outside the function (not using the initializer syntax, but with the entry obj.member = VALUE). This is a related issue, so posting here hoping someone with the same issue will land here.

0
Dec 19 '09 at 6:30 a.m. a.m.
source share



All Articles