473,406 Members | 2,352 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,406 software developers and data experts.

Good use for Unions

Hi guys I've been programming C++ for quite some time, but I have never used
unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards

Michael.
Jul 23 '05 #1
11 1377
Michael wrote:
Hi guys I've been programming C++ for quite some time, but I have never used
unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??


Look up "VARIANT" data type in Microsoft's OLE and COM documents.

V
Jul 23 '05 #2
I can't think of a very common case. However, in some recursive data
structures (e.g., trees), you might want each conceptual node to be either a
"real" node or a "nill" node. There are many different ways of implementing
such a data structure. Suppose you're *really* concerned about indirection
(i.e., you wish to avoid it). Then you might create a vector whose each
element an object of
struct node
{
bool m_real_node;

union m_true_node
{
real_node m_real_node;

nil_node m_nil_node;
}
};

So that's a case where you might use a union. As far as I understand, the
above (quite ugly) example should be used in very extreme circumstances (if
you're convinced this will actually improve performance), and you should
encapsulate the hell out of it into a container employing such nodes
internally.

By the way, I vaguely recall the above code working ~3 times as fast as a
version I wrote without unions (based on pointers, and using NULL to signify
a "nil" node) (of course, since I wrote them both, who knows what I might
have fudged, also, it's been years, and I can't recall the exact settings).
"Michael" <sl***********@hotmail.com> wrote in message
news:ct**********@hercules.btinternet.com...
Hi guys I've been programming C++ for quite some time, but I have never used unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards

Michael.

Jul 23 '05 #3

Michael wrote:
Hi guys I've been programming C++ for quite some time, but I have never used unions. I am trying to find a good exmaple of when they might be used. can anyone provide one??
Regards

Michael.


Force alignment of a buffer:

union {
char buffer[1000];
int dummy;
};

This forces the compiler to start 'buffer' at an integer boundary.
-shez-

Jul 23 '05 #4
If you're developing a specialized container class which houses builtin
data types as to provide your other interfaces with a common object to
pass around as data. For example;

class Data
{
union
{
char c;
int i;
float f;
};

type getType();
operator char();
operator int();
operator float();
};

et cetera.

Michael wrote:
Hi guys I've been programming C++ for quite some time, but I have never used
unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards

Michael.

Jul 23 '05 #5

"Michael" <sl***********@hotmail.com>, haber iletisinde şunları
yazdı:ct**********@hercules.btinternet.com...
Hi guys I've been programming C++ for quite some time, but I have never used unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards

Michael.


I use it for something like this for example.

union unionPw
{
int isPasswordSet;
char szPassword[16];
};

isPasswordSet = 0; // initialize
....
strcpy(szPassword, "password"); // isPasswordSet is set to a non-zero value
Jul 23 '05 #6
On 2005-01-26 11:14:47 -0500, "Aslan Kral" <as**********@yahoo.com> said:

"Michael" <sl***********@hotmail.com>, haber iletisinde þunlarý
yazdý:ct**********@hercules.btinternet.com...
Hi guys I've been programming C++ for quite some time, but I have never

used
unions. I am trying to find a good exmaple of when they might be used. can
anyone provide one??
Regards

Michael.


I use it for something like this for example.

union unionPw
{
int isPasswordSet;
char szPassword[16];
};

isPasswordSet = 0; // initialize
...
strcpy(szPassword, "password"); // isPasswordSet is set to a non-zero value


What happens if the first sizeof(int) bytes of "password" happens to be
a trap representation for int?

--
Clark S. Cox, III
cl*******@gmail.com

Jul 23 '05 #7

"Clark S. Cox III" <cl*******@gmail.com>, haber iletisinde şunları
yazdı:2005012613302816807%clarkcox3@gmailcom...
On 2005-01-26 11:14:47 -0500, "Aslan Kral" <as**********@yahoo.com> said:

I use it for something like this for example.

union unionPw
{
int isPasswordSet;
char szPassword[16];
};

isPasswordSet = 0; // initialize
...
strcpy(szPassword, "password"); // isPasswordSet is set to a non-zero
value
What happens if the first sizeof(int) bytes of "password" happens to be
a trap representation for int?

--
Clark S. Cox, III
cl*******@gmail.com


On Intel for sizeof(int)=4
before strcpy: isPasswordSet = 0
after strcpy: isPasswordSet = 0x73736171 ("pass")

So you can do something like this after strcpy:

if ( isPasswordSet )
{
....
}
else
{
....
}

What do you mean by "trap representation for int"?
Jul 23 '05 #8
"Aslan Kral" <as**********@yahoo.com> wrote in
news:35*************@individual.net:

"Clark S. Cox III" <cl*******@gmail.com>, haber iletisinde şunları
yazdı:2005012613302816807%clarkcox3@gmailcom...
On 2005-01-26 11:14:47 -0500, "Aslan Kral" <as**********@yahoo.com>
said:
>
> I use it for something like this for example.
>
> union unionPw
> {
> int isPasswordSet;
> char szPassword[16];
> };
>
> isPasswordSet = 0; // initialize
> ...
> strcpy(szPassword, "password"); // isPasswordSet is set to a
> non-zero
value

What happens if the first sizeof(int) bytes of "password" happens to
be a trap representation for int?

--
Clark S. Cox, III
cl*******@gmail.com


On Intel for sizeof(int)=4
before strcpy: isPasswordSet = 0
after strcpy: isPasswordSet = 0x73736171 ("pass")

So you can do something like this after strcpy:


No, you can't. It is undefined behaviour to read from any member of the
union that wasn't the last one that was set. Since the last thing you
set was szPassword, you may not read from isPasswordSet.
if ( isPasswordSet )
{
...
}
else
{
...
}

What do you mean by "trap representation for int"?


There may exist certain bit patterns for an int that represents an
invalid value. By attempting to use it, the CPU (or something else) may
cause some sort of trap causing your application to crash.

Jul 23 '05 #9

"Andre Kostur" <nn******@kostur.net>, haber iletisinde şunları
yazdı:Xn*******************************@207.35.177 .135...
What do you mean by "trap representation for int"?


There may exist certain bit patterns for an int that represents an
invalid value. By attempting to use it, the CPU (or something else) may
cause some sort of trap causing your application to crash.


How do you think it will be decoded as an opcode by the CPU?
It is just a value in the data segment.
Jul 23 '05 #10
"Aslan Kral" <as**********@yahoo.com> wrote in news:35qagpF4ntun2U1
@individual.net:

"Andre Kostur" <nn******@kostur.net>, haber iletisinde şunları
yazdı:Xn*******************************@207.35.177 .135...
> What do you mean by "trap representation for int"?


There may exist certain bit patterns for an int that represents an
invalid value. By attempting to use it, the CPU (or something else) may
cause some sort of trap causing your application to crash.


How do you think it will be decoded as an opcode by the CPU?
It is just a value in the data segment.


Doesn't need to be an executable opcode. It is theoretically possible that
on the UberCPU 9000 platform, in order to perform an operation on an int,
it needs to load it into a register. That register may have restrictions
on what constitutes a legal int. When you then load an invalid int
representation into that register, BOOM.
Jul 23 '05 #11

"Andre Kostur" <nn******@kostur.net>, haber iletisinde şunları
yazdı:Xn*******************************@207.35.177 .135...
"Aslan Kral" <as**********@yahoo.com> wrote in news:35qagpF4ntun2U1
@individual.net:

"Andre Kostur" <nn******@kostur.net>, haber iletisinde şunları
yazdı:Xn*******************************@207.35.177 .135... Doesn't need to be an executable opcode. It is theoretically possible

that on the UberCPU 9000 platform, in order to perform an operation on an int,
it needs to load it into a register. That register may have restrictions
on what constitutes a legal int. When you then load an invalid int
representation into that register, BOOM.


Hmm. I didn't know that. The value in my code was defined for a zero test.
Of course things like divide by zero exception or buffer overflow may happen
if you
are not careful. Other than those things I don't see any problem for Intel
platform.
That is not the subject. I was only giving a simple example. I don't it
creates such
problems.
Jul 23 '05 #12

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

Similar topics

15
by: David | last post by:
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...
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
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
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.