This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Anonymous union inside a struct?

The C complier doesn't like this piece of source code:
-------------------------
struct MyUart {
union {
unsigned char rx; // read
unsigned char tx; // write
};
unsigned char control; // r/w
};

volatile struct MyUart far* const UART = 0x101010;

unsigned char ReadByte( void )
{
while ( (UART->control & 0x01) == 0 )
{}
return UART->rx;
}
--------------------
I get the following error:
UNION.C(15): error C70: rx: undefined member

However, I get no error at line #13 on the reference to UART->control. Is there something I'm overlooking?

  • I don't have the C standard within my reach at the moment, but I'm pretty sure that anonymous unions were introduced in C++, not in C. So there is an obvious way of making the piece of code work:

    struct MyUart {
    	union {
    		unsigned char rx; // read
    		unsigned char tx; // write
    	} data;
    	unsigned char control; // r/w
    };
    
    volatile struct MyUart far* const UART = 0x101010;
    
    unsigned char ReadByte( void )
    {
    	while ( (UART->control & 0x01) == 0 ) ;
    	return UART->data.rx;
    }
    
    Another thing to be concerned about is alignment of structure members in memory. By default, they are aligned at word boundaries.
    Regards,
    Mike

  • Anonymous unions and structures are a Microsoft specific extension to C++. They are not even defined in standard C++.