Discussion Forum

Anonymous union inside a struct?

Next Thread | Thread List | Previous Thread Start a Thread | Settings

DetailsMessage
Read-Only
Author
Sam Liggin
Posted
30-Nov-2001 17:11 GMT
Toolset
C166
New! 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?
Read-Only
Author
Mike Kleshov
Posted
1-Dec-2001 16:07 GMT
Toolset
C166
New! RE: Anonymous union inside a struct?
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
Read-Only
Author
Norbert Paul
Posted
4-Dec-2001 14:49 GMT
Toolset
C166
New! RE: Anonymous union inside a struct?
Anonymous unions and structures are a Microsoft specific extension to C++. They are not even defined in standard C++.

Next Thread | Thread List | Previous Thread Start a Thread | Settings