Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

union initialisation

Tags:

c++

c

unions

I'm attempting to globally initialise 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'll note that neither of temp.i or temp.t[...] actually give the correct item i initialised the union with. I'd imagine this would be avoided if I could manually initialise the integer member, but unfortunately I can't. I also can't change the ordering of elements within the struct (swapping the int and char order initialises everything properly) - they're actually provided by an external library. My question is this: how can I set the integer member of the structure globally, rather than the char[4] member (or, in this case, just the first element of the char[])?

EDIT: Also, is there a strictly-c++ solution to this problem? i.e. one where named struct initialisation doesn't work (because it doesn't exist in the language)?

like image 564
Ben Stott Avatar asked May 28 '11 10:05

Ben Stott


People also ask

How do you initialize a union?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can we initialize unions?

Initializing Union Variable union data { int var1; double var2; char var3; }; union data j = {10}; This statement initializes the union variable j or in other words, it initializes only the first member of the union variable j .

How many union members can be initialize?

A union can be initialized on its declaration. Because only one member can be used at a time, only one can be initialized. To avoid confusion, only the first member of the union can be initialized.

Can we initialize union in C?

C allows you to initialize a union in two ways: Initialize a union by initializing the first member of a union. Or initialize a union by assigning it to another union with the same type.


1 Answers

In C99 you can do this:

a temp = { .i=w };
like image 80
Šimon Tóth Avatar answered Sep 19 '22 16:09

Šimon Tóth