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)?
Ben stott
source share