# Structures Nested Inside Unions



## pcpro17 (Oct 9, 2006)

Hello. I have a bit-defined structure nested inside a union, as shown in the following example:

```
typedef union
{
   struct
   {
      UINT8 aa:1;
      UINT8 bb:1;
      UINT8 cc:1;
   } items;
   UINT8 yy;
   UINT8 zz;
} typeName_t;
```
Now I would expect from this code that if I did something along the lines of the following example in my application, that only those respective bits would be affected:


```
typeName_t fooBar;
fooBar.items.aa = 1;
fooBar.items.bb = 1;
fooBar.items.cc = 0;
```
However, what I am seeing is that whenever I set the value of any bit, all the bits are changed the same. So, for this example, the value of aa and bb would read back as 0, the last value written to that area (cc). Am I doing something wrong, or is this simply not supported by my GCC-based compiler? Thanks.


----------



## midders (Jan 1, 1970)

Not sure what your problem is, but why not just use flags with bitwise arithmetic? e.g.
#define FLAG001 0x01
#define FLAG010 0x02
#define FLAG100 0x04 // etc.
...
int a=0;
a=a|FLAG001; // set bit 1
a=a&!FLAG100; // unset bit 3

This is off the top of my head, so the code might need tweaking a bit.

Sláinte

midders


----------



## IMM (Feb 1, 2002)

This worked for me in VC6

```
typedef union
{
   struct
   {
      UINT8 aa:1;
      UINT8 bb:1;
      UINT8 cc:1;
   } items;
   UINT8 yy;
   UINT8 zz;
} typeName_t, *p_typeName_t;
////////////////////////////////////

typeName_t fooBar = {0};
fooBar.items.aa = 1;
fooBar.items.bb = 1;
fooBar.items.cc = 0;
```
The following seems to talk about unions and bitfields and gcc
http://www.coranac.com/documents/working-with-bits-and-bitfields/

I'm not sure if gcc would require extern C on the header stuff or not?

Would using a bitarray suit you better ?
http://en.wikipedia.org/wiki/Bit_array

Is it possible that what you are seeing is a quirk of whatever debugger you are using ?
If that is the case, you should be able to use _printf _or _cout<< _to debug the values if you use an initializer on fooBar as I did in the code above = {0};


----------

