473,405 Members | 2,176 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Unions vs Classes

Some developers in my group are using UNIONS to define their data
types in a C++ program for an embedded system. Are there any pro and
cons in doing this when you can define a CLASS to do the same thing?

I guess there might be some additional overhead with CLASSES, but is
that really an issue with today's computers?
Jul 22 '05 #1
15 5245
David wrote:

Some developers in my group are using UNIONS to define their data
types in a C++ program for an embedded system. Are there any pro and
cons in doing this when you can define a CLASS to do the same thing?

'union' and 'class' do different things.
I guess there might be some additional overhead with CLASSES, but is
that really an issue with today's computers?


For todays desktop systems the memory savings by using a union
is seldome an issue. But embedded system are notorious short
on memory.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #2
David posted:
Some developers in my group are using UNIONS to define their data
types in a C++ program for an embedded system. Are there any pro and
cons in doing this when you can define a CLASS to do the same thing?

I guess there might be some additional overhead with CLASSES, but is
that really an issue with today's computers?


Let's say that
int = 32 bits

char = 8 bits

short = 16 bits
Take the following:

struct MonkeyStruct
{
int a;
char b;
short c;
};

struct MonkeyUnion
{
int a;
char b;
short c;
};
sizeof(MonkeyStruct) will be 56 bits.

sizeof(MonkeyUnion) will be 32 bits.
You can't simply just turn a class into a union or vice-versa! They're two
separate types of entity. Why would a union be in any way superior to a
struct? I myself can only think of two possible reasons:

A) Conserve memory

B) Neat memory tricks (like using a 4 char union to determine if a system is
LITTLEENDIN or BIGENDIN)

-JKop
Jul 22 '05 #3
"David" <ma**@david-eng.com> wrote in message
I guess there might be some additional overhead with CLASSES, but is
that really an issue with today's computers?


Depends on the memory. With a union you could reduce the sizeof by 25% or
50% or more. If you create many such classes, then the savings add up. On
the other hand, if you need a type field, you might be better off with
polymorphic classes (ie. virtual functions) as the virtual pointer is itself
a type field.
Jul 22 '05 #4

"JKop" <NU**@NULL.NULL> wrote in message
news:99*****************@news.indigo.ie...
David posted:

Let's say that
int = 32 bits

char = 8 bits

short = 16 bits
Take the following:

struct MonkeyStruct
{
int a;
char b;
short c;
};

struct MonkeyUnion
{
int a;
char b;
short c;
};
sizeof(MonkeyStruct) will be 56 bits.


Though its implemetation specific, this will most likely be 64, because a 16
short will probably require an alignment of mod 2.

Jul 22 '05 #5
Xenos wrote:
"JKop" <NU**@NULL.NULL> wrote in message
news:99*****************@news.indigo.ie...
David posted:

Let's say that
int = 32 bits

char = 8 bits

short = 16 bits
Take the following:

struct MonkeyStruct
{
int a;
char b;
short c;
};

struct MonkeyUnion
{
int a;
char b;
short c;
};
sizeof(MonkeyStruct) will be 56 bits.


Though its implemetation specific, this will most likely be 64,
because a 16 short will probably require an alignment of mod 2.


Even without the char, the size would probably be 64 bits, because the
the 4 byte int would need be aligned on a 4 byte boundary, and you have
to remember that the struct must also be usable in an array.

Jul 22 '05 #6
JKop <NU**@NULL.NULL> wrote in message news:<99*****************@news.indigo.ie>...
[snip]
Why would a union be in any way superior to a
struct? I myself can only think of two possible reasons:

A) Conserve memory

B) Neat memory tricks (like using a 4 char union to determine if a system is
LITTLEENDIN or BIGENDIN)


Are you intending to do something like put an integer in and
see what order the bytes come back out?

I'm doubting this last would be safe. You should not count on
how a compiler is going to squash things together in a union.
Socks
Jul 22 '05 #7
pu*********@hotmail.com wrote in message news:<c7**************************@posting.google. com>...
JKop <NU**@NULL.NULL> wrote in message news:<99*****************@news.indigo.ie>...
[snip]
Why would a union be in any way superior to a
struct? I myself can only think of two possible reasons:

A) Conserve memory

B) Neat memory tricks (like using a 4 char union to determine if a system is
LITTLEENDIN or BIGENDIN)


Are you intending to do something like put an integer in and
see what order the bytes come back out?


Given

union Int2Bytes{
int i;
char b[sizeof(int)];
};

I know you cannot write to .i and read from .b, but is it legal to do this?

int i = 0xaabbccdd;
char b = ((Int2Bytes*)&i)->b[0];

/david
Jul 22 '05 #8
On 15 Jun 2004 06:19:17 -0700, ma**@david-eng.com (David) wrote in
comp.lang.c++:
Some developers in my group are using UNIONS to define their data
types in a C++ program for an embedded system. Are there any pro and
cons in doing this when you can define a CLASS to do the same thing?

I guess there might be some additional overhead with CLASSES, but is
that really an issue with today's computers?


What do "today's computers" have to do with the embedded system?

It might make a vast difference if the target platform is an 8051 core
with 8K 8-bit bytes of code space and 128 (not K) 8-bit bytes of data
space on the one hand, and an ARM or PowerPC with many megabytes of
both.

Embedded systems vary so widely and by so many orders of magnitude
that the difference between common desk top computers and their
operating systems _almost_ seems trivial by comparison.

What do the developers who prefer unions state is the reason for
selecting them over classes?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #9
"Jack Klein" <ja*******@spamcop.net> wrote in message
What do the developers who prefer unions state is the reason for
selecting them over classes?


I've heard it's used extensively in low level programming. Also, if you
want to write an API and works in both C++ and C, then unions might be
right, as in the sockets class.
Jul 22 '05 #10
On Wed, 16 Jun 2004 04:09:02 GMT, "Siemel Naran"
<Si*********@REMOVE.att.net> wrote:
"Jack Klein" <ja*******@spamcop.net> wrote in message
What do the developers who prefer unions state is the reason for
selecting them over classes?


I've heard it's used extensively in low level programming. Also, if you
want to write an API and works in both C++ and C, then unions might be
right, as in the sockets class.


I have seen the situation of auto generate interface code that used
structs to hold different data and then collected these together
using unions and a type field. The client would inspect the type
field and then delve into the correct bit of the struct/union
combination.

This was actually consuming more space than a class hierarchy
and proper polymorphism. Since, the unions were as large as
the largest member. I suspect that paying the price of VPTRs
and using a class hierarchy (even with multiple inheritance) would
consume less space.

:) Chris.
Jul 22 '05 #11
posted:
JKop <NU**@NULL.NULL> wrote in message
news:<99*****************@news.indigo.ie>... [snip]
Why would a union be in any way superior to a
struct? I myself can only think of two possible reasons:

A) Conserve memory

B) Neat memory tricks (like using a 4 char union to determine if a
system is LITTLEENDIN or BIGENDIN)


Are you intending to do something like put an integer in and
see what order the bytes come back out?

I'm doubting this last would be safe. You should not count on
how a compiler is going to squash things together in a union.
Socks


union {

unsigned int FourBytes;

struct {
unsigned char Byte1;
unsigned char Byte2;
unsigned char Byte3;
unsigned char Byte4;
};
} blind;

int main(void)
{
blind.FourBytes = 0x1F1F1F1F;

//Now, check each individual byte

if (Byte1 ==
}

I did this before in a program I was writing. Can't remember why I did it,
or which numbers I used! I'd still have it tucked away in my archive though
(Actually, just right now as I'm writing this I thought of the reason, I was
encoding digital audio to be sent down to a CD-Writer, and had to know the
ENDINESS).
-JKop
Jul 22 '05 #12
"Chris Hill" <ne***@plantain.org.uk> wrote in message
This was actually consuming more space than a class hierarchy
and proper polymorphism. Since, the unions were as large as
the largest member. I suspect that paying the price of VPTRs
and using a class hierarchy (even with multiple inheritance) would
consume less space.


Furthermore the VPTR way is probably faster than a switch-case on the type
field.
Jul 22 '05 #13
JKop wrote:
union {
unsigned int FourBytes;

struct {
unsigned char Byte1;
unsigned char Byte2;
unsigned char Byte3;
unsigned char Byte4;
};
} blind;

int main(void)
{
blind.FourBytes = 0x1F1F1F1F;
//Now, check each individual byte
if (Byte1 ==

I did this before in a program I was writing. ...


While using unions is generally machine specific anyway the above is
especially "bad" because it makes many assumptions (like ints are 4 bytes).
Jul 22 '05 #14
da********@warpmail.net (David Rubin) wrote in message news:<82*************************@posting.google.c om>...
[puppet sock moaning about in-one-var-out-the-other unions snipped]
Given

union Int2Bytes{
int i;
char b[sizeof(int)];
};

I know you cannot write to .i and read from .b,
You can, it's just that it is not portable, and probably even
not reliable. Some things that could bust it:
- Different hardware
- Different OS (even new version)
- Different version of the compiler
- Different address of loading the code into memory
- Long list of weird things that could happen on specialist platforms
but is it legal to do this?

int i = 0xaabbccdd;
char b = ((Int2Bytes*)&i)->b[0];


I'm pretty confused by that. What's it supposed to do?
Lessee, you've got the address of an int variable, and
you've cast that as a pointer to an undeclared union,
and you've tried to reference the zeroeth char in the
"b" data element of that undeclared union. I'd say,
that this *might* compile, but the results won't be good.
The best you could hope for would be some kind of memory
access violation. The worst would be that char b contains
garbage and you don't realize it.
Socks
Jul 22 '05 #15
pu*********@hotmail.com wrote in message news:<c7**************************@posting.google. com>...
da********@warpmail.net (David Rubin) wrote in message news:<82*************************@posting.google.c om>...
[puppet sock moaning about in-one-var-out-the-other unions snipped]
Given

union Int2Bytes{
int i;
char b[sizeof(int)];
};

I know you cannot write to .i and read from .b,
You can, it's just that it is not portable, and probably even
not reliable. Some things that could bust it:
- Different hardware
- Different OS (even new version)
- Different version of the compiler
- Different address of loading the code into memory
- Long list of weird things that could happen on specialist platforms


Hence, "cannot". Yes, you *can* abuse unions like this, but it is not
guaranteed to work, as you point out.
but is it legal to do this?

int i = 0xaabbccdd;
char b = ((Int2Bytes*)&i)->b[0];


I'm pretty confused by that. What's it supposed to do?
Lessee, you've got the address of an int variable, and
you've cast that as a pointer to an undeclared union,
and you've tried to reference the zeroeth char in the
"b" data element of that undeclared union. I'd say,
that this *might* compile,


Will definitely compile.
but the results won't be good.
No. Well, maybe. This seems to work much better for me if the union
members are unsigned.
The best you could hope for would be some kind of memory
access violation.
No, AFAIK. 'i' is allocated on the stack, and you should be able to
dereference 'b' anywhere as it is an array of 'char'. But the fact is
that the union is aligned to 'int', so there shouldn't be a problem
anyway.
The worst would be that char b contains
garbage and you don't realize it.
Socks


'b[0]' must be the first byte of the representation of 'i' AFAICT. The
question is whether this is guaranteed by the standard. We have
established that "writing and reading" from (different members of) a
union is UB, but what about "casting and reading" as described above?

/david
Jul 22 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: muser | last post by:
sorry to post so soon after having posted before. I'm using a union and I've read that a union can only hold a value of one member at a time. The following function uses a union, but i don't know...
6
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
16
by: Tim Cambrant | last post by:
Hi. I was reading up a bit on the features of C I seldom use, and I came across unions. I understand the concept, and that all the contained variables etc. share the same memory. Thus, when a new...
23
by: rohit | last post by:
Hi, In my couple of years of experience, I have never found a single instance where I needed to use unions and bitfields(though I have used structures).I was just imagining where would these find...
4
by: uralmutlu | last post by:
Hi, I was wandering if I can have classes in unions? I basically have source code in a format very similar to: union example { ClassA variable1; ClassB variable2; };
67
by: bluejack | last post by:
A recent post asking for help with unions reminded me of this component of the C language that I have only used a couple of times, and those almost entirely out of personal whim -- Unions for the...
11
by: pereges | last post by:
Hello, can some one please guide me a little into using unions. I read about unions in K & R but I am finding it difficult to apply to my problem at hand. I want to save up some space by using...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.