The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

a const array of structs containing a union?

Hello!

Does anyone know how it is possible to declare and initialize a const array of structs containing a union?

eg.

typedef struct {
 int a;
 union {
  int b, c, d };
} foo;

foo const foo_list[] = {
 {1, { b = 2 }},
 {2, { c = 1 }},
 {1, { b = 5 }}
}

How does the syntax look for this? Is it even possible?

Thanks in advance!
Jon Doe Send private email
Tuesday, August 05, 2008
 
 
Not sure you can do this, as the initializer doesn't know which part of the union to use.
xampl
Tuesday, August 05, 2008
 
 
Just curious - did you give this even a cursory run through a compiler?

You have a limited ability to initialize a union. From the ISO C90 Standard 6.5.7:

"A brace-enclosed initializer for a union object initializes the member that appears first in the declaration list of the union type."

So, as long as you can get by initializing only using the first member of the union, you're OK.

However, it also says that "All unnamed structure or union members are ignored during initialization", which is news to me.  MSVC does not complain.

C99 supports what you're looking for directly (designated initializers), but C99 support is pretty limited - non-existent as far as Microsoft is concerned.
mwb
Tuesday, August 05, 2008
 
 
Hm, has it occurred to anyone that the example given is useless? All three members of the union are of the same type, which means that the union doesn't serve any purpose and it doesn't matter which element is used in the initialization (all three names refer to the same exact region of memory).

Now, if we had a more realistic example, such as:

    union U {
          int a;
          float b;
          void *c;
    };

    struct S {
          int x;
          char *y;
          union U z;
    };

you should be able to initialize an array of struct S's like this:

    static struct S[3] = {
          {1, "one", (union U)5},
          {2, "two", (union U)"five"},
          {3, "three", (union U)5.0}
    };

Of course, I haven't tried to compile or run this, so "caveat emptor."
Jeffrey Dutky Send private email
Tuesday, August 05, 2008
 
 
Thank you for all the responses.
It was an ill thought out and pointless example, I agree.

I did try to run a few variants through our compiler (dcc) but none worked. Anyway, I worked out an alternative solution, but thank you for the replies.
Jon Doe Send private email
Wednesday, August 06, 2008
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz