Connection initialization

I am trying to globally initialize a union, as in the following example:

#include <cstdio> typedef union { char t[4]; int i; } a; enum { w = 5000, x, y, z }; a temp = {w}; int main() { printf("%d %d %d %d %d\n", temp.t[0],temp.t[1],temp.t[2],temp.t[3],temp.i); return 0; } 

However, if you run the code, you will notice that neither temp.i nor temp.t [...] actually give the correct element i, initialized by the union. I would suggest that this could be avoided if I could manually initialize the integer member, but unfortunately I cannot. I also can’t change the ordering of the elements inside the structure (int and char swap order initializes everything correctly) - they are actually provided by an external library. My question is this: how can I set the integer member of the structure globally and not the char [4] member (or, in this case, only the first char [] element)?

EDIT: Also, is there a strict c ++ solution for this problem? that is, where named structure initialization does not work (because it does not exist in the language)?

+7
source share
4 answers

Would you like to do this:

 a temp = {i: w}; 

This should work for both gcc and g++ .

+7
source

In C99, you can do this:

 a temp = { .i=w }; 
+11
source

In C99, you can use named initialization, as in:

 ax = { .i = 10 }; 

There are several suggestions for using the non-standard gcc extension, but I would avoid this if C encoding:

 ax = { i : 10 }; 

You can use the function to initialize:

 inline a initialize( int value ) { // probably choose a better name a tmp; tmp.i = value; return a; } 

and then use:

 ax = initialize( 10 ); 

The compiler will optimize the copies.

If you are running C ++, you can provide a constructor for your union type:

 /*typedef*/ union u { // typedef is not required in general in C++ char bytes[sizeof(int)]; int i; u( int i = 0 ) : i(i) {} } /*u*/; ux( 5 ); 
+7
source

You can initialize an integer element as follows:

 a temp = { .i = w }; 
+6
source

All Articles