 | Discussion Forum |  |
|
|
how many mem does union cost?Next Thread | Thread List | Previous Thread Start a Thread | Settings | Details | Message |
|---|
Read-Only Author Freddy Zhang Posted 26-Jun-2001 23:21 GMT Toolset C51 |  how many mem does union cost? Freddy Zhang struct structSeperate { unsigned char uaHigh; unsigned char uaLow; }; union OneIntorTwoBytes { unsigned int un; struct structSeperate ua; };
void AFunction() { OneIntorTwoBytes unionMy; ... ...unionMy...// ... }
In the above example, Could you please explain how many bytes of free mem will be allocated for AFunction()? How many bytes of free mem will be allocated for the whole module? | | Read-Only Author Jon Ward Posted 27-Jun-2001 01:11 GMT Toolset C51 |  RE: how many mem does union cost? Jon Ward The unionMy variable (which is a union) will take 2 bytes.
I don't know how much space is used by your function.
Jon
| | Read-Only Author Andrew Neil Posted 27-Jun-2001 09:20 GMT Toolset C51 |  RE: how many mem does union cost? Andrew Neil Don't forget those <pre> and </pre> tags!
This is a popular way to access individual bytes of a larger data type, but don't forget that it's non-portable - as it relies entirely upon the byte ordering of the Compiler/Target. There may also be alignment issues with some larger data types.
You might want to try something like:
struct structSeperate
{
#if defined __C51__
unsigned char uaHigh;
unsigned char uaLow;
#elif defined SOME_OTHER_COMPILER
unsigned char uaLow;
unsigned char uaHigh;
#else
#error Unknown byte ordering
#endif
};
union OneIntorTwoBytes
{
unsigned int un;
struct structSeperate ua;
};
On the subject of unions, alignment and Keil Gotchas!, you should also check these Knowledge base articles: http://www.keil.com/support/docs/928.htm http://www.keil.com/support/docs/1279.htm | | Read-Only Author Andrew Neil Posted 27-Jun-2001 09:41 GMT Toolset C51 |  RE: how many mem does union cost? Andrew Neil The only time a Union (or struct) will "cost" you extra memory beyond the size of its contents is if the compiler inserts any extra "padding" bytes for alignment. AFAIK, Keil C51, being targetted on an 8-bit architecture, doesn't add padding.
Padding is usually only added on larger word-size machines, which don't like objects crossing word boundaries; eg, 16-bit objects starting on odd addresses for 16- or 32-bit machines; 32-bit objects starting on non-multiple-of-4 addresses on 32-bit machines.
There is usually some sort of "pack" option to overrinde the padding, at the cost of access efficiency. | |
Next Thread | Thread List | Previous Thread Start a Thread | Settings |
|