473,748 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

where are unions and bitfields particularly used ?

Hi,
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields(thoug h I have used
structures).I was just imagining where would these find
relevance.Thoug h both of these(bitfields and unions) are used where
space is a constraint(so I can assume always in embedded systems,where
memory is particularly less)and we want to save space/memory.

As far as I have read, there is no difference between structs an
unions apart for saving space(that would also imply how members are
accessed in unions compared to in structs).

Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.

I was of the impression that structures and unions were user defined
data types until I came to this defination of unions from K&R "Union
is a VARIABLE that may hold (at different times) objects of different
types and sizes, while the compiler keeping track of size and
alignment requirements."

So, is an union an user defined data type or a variable.

and why is it that "A union may only be initialized with a value of
the type of its first member" from K&R ??

TIA
rohit
Nov 14 '05 #1
23 2827
"rohit" <pr******@yahoo .com> wrote in message
news:93******** *************** **@posting.goog le.com...
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields(thoug h I have used
structures). [snip] Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.
The only time I can recall that I extensively used a union is where I had a
function which would return one of a number of data formats. Specifically,
this was part of a small DNS client library; having performed a query, this
function could be called repeatedly to iterate over the records in the
response, each one of which might be an IP address, a domain name, or
something else. The only direct advantage (as you noted) is saving space.

Bitfields are often used in non-portable code (where they represent some
particular layout of bits). You could use them if you have a number of
flags - but I generally #define the bit values and use a single "flags"
member.

[snip] So, is an union an user defined data type or a variable.
It's both. I read "variable" as a loose term meaning "something capable of
holding different values."
and why is it that "A union may only be initialized with a value of
the type of its first member" from K&R ??


Because there's no provision in the syntax/grammar of the language to
specify which member to initialise - although I think that is no longer the
case with C99.

Alex
Nov 14 '05 #2
"Alex" <me@privacy.net > writes:
"rohit" <pr******@yahoo .com> wrote in message
news:93******** *************** **@posting.goog le.com...
So, is an union an user defined data type or a variable.


It's both. I read "variable" as a loose term meaning "something
capable of holding different values."


This ambiguity often arises when a word that should really only be used
as an adjective is used as a noun. The adjective "union" doesn't have
this problem, i.e. "union type" and "union object" are both unambiguous.

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #3
rohit wrote:
Hi,
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields(thoug h I have used
structures).I was just imagining where would these find
relevance.Thoug h both of these(bitfields and unions) are used where
space is a constraint(so I can assume always in embedded systems,where
memory is particularly less)and we want to save space/memory.
Bit fields (in a struct) are used to access hardware or provide state
information about the structure.

As far as I have read, there is no difference between structs an
unions apart for saving space(that would also imply how members are
accessed in unions compared to in structs).
There is one big difference between unions and structs: a union will
allocate space for the largest item in the list. Also, compilers are
allowed to add space between fields.

Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.
Borlands' IDE uses unions for database fields. The have one variable
to define the kind of field and a union for the field categories.

I was of the impression that structures and unions were user defined
data types until I came to this defination of unions from K&R "Union
is a VARIABLE that may hold (at different times) objects of different
types and sizes, while the compiler keeping track of size and
alignment requirements."

So, is an union an user defined data type or a variable.
A union is a stencil showing how data is organized. This stencil is
used for instantiating variables or allocating memory.

and why is it that "A union may only be initialized with a value of
the type of its first member" from K&R ??
Probably to simplify compiler writing. Think about it, how does the
compiler know which data type in the union that the initialized data
is to represent?

TIA
rohit


One word about bitfields: The ordering, most significant bit or
least significant bit, is compiler dependent. Many people who work
on embbed systems or with individual bits, will often use the bit
arithmetic operators on an unsigned integral variable rather than
dealing with bitfields in a structure.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #4
On Mon, 10 May 2004, rohit wrote:
Hi,
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields(thoug h I have used
structures).I was just imagining where would these find
relevance.Thoug h both of these(bitfields and unions) are used where
space is a constraint(so I can assume always in embedded systems,where
memory is particularly less)and we want to save space/memory.

As far as I have read, there is no difference between structs an
unions apart for saving space(that would also imply how members are
accessed in unions compared to in structs).

Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.
Operating systems. The members of a list of resources where unions.
Actually they were structures that contained unions. Soemthing like:

struct device {
int type;
union {
/* a bunch of structures */
/* each structure contains */
/* the necessary information */
/* for one device */
}
}

The code when then use a switch based on the type. If the type was
PRINTER then use the structure within the union that represented a printer
resource. If the type was HARDDRIVE then use the structure within the
union that represented a hard drive resource. Et cetera.
I was of the impression that structures and unions were user defined
data types until I came to this defination of unions from K&R "Union
is a VARIABLE that may hold (at different times) objects of different
types and sizes, while the compiler keeping track of size and
alignment requirements."

So, is an union an user defined data type or a variable.

and why is it that "A union may only be initialized with a value of
the type of its first member" from K&R ??

TIA
rohit


--
Send e-mail to: darrell at cs dot toronto dot edu
Don't send e-mail to vi************@ whitehouse.gov
Nov 14 '05 #5
"rohit" <pr******@yahoo .com> wrote
Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.


I 've used bitfields for bitmaps of deleted records, when implementing B+ tree
indexes,to save space when storing the index(we 're talking about BIG
indexes), since coincidentialy every block could fit 16 of my records(fixed
size).Of course something like that could be implemented just with bit
operations and masking on 2 chars. Now the only case that I had to use a union
was in flex and bison files.

--
Pascal Adoniou

Nov 14 '05 #6
rohit wrote:

[...]
Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.


Example of a situation where I've used a union:
I have a bunch of CGI's (C code that generates the content of webpages).
To prevent cluttering that code with HTML constructs (and creating a
maintenance nightmare) I've written a library that does the actual
HTML-generating and exports a more high-level interface to the CGI's.
Some CGI's need to produce form controls so I would like to have an
interface like

lib_add_formctr l(T_formctrl* ctrl, [some general parameters]);

and not

lib_add_textctr l([all the text control parameters]);
lib_add_radioct rl([all the radio control paramters]);
...

T_formctrl is a struct that contains (among some other parameters) a
union and a type indicator (which is a value from an enum):

typedef struct
{
e_formctrl_type type;
union
{
T_textctrl text;
T_radioctrl radio;
...
} u;
} T_formctrl;

where the type of each union member is a struct with the parameters
specific for that type of form control.
To prevent cluttering the CGI's with the code to fill a variable of this
type I've also made some 'factory functions' in the library so you can
create a form control with just one function call:

T_formctrl ctrl;
lib_make_textct rl(&ctrl, [parameters for a text control]);
lib_add_formctr l(&ctrl, [some general parameters]);

Not that special but this also permits me to create other very
convenient high level interface functions. For example the requirements
wanted a table where the cells of a row can contain form controls for
editing or inputting data. Now I can make an interface like

lib_edittable_a ddrow(int nbCtrls, T_formctrl* ctrl1, ...);

which permits me to output any combination of form control types and any
number of form controls. The library takes care of the drawing details.

In OO terms you might call T_formctrl an abstract base class and
T_textctrl, T_radioctrl, ... the concrete subclasses.

I can't think of another way that can give me this kind of flexibility
with such a concise interface but I'm just a newbie (started my first
job six months ago) still learning every day and this group has readers
with many years of experience :)

--
Dirk

(PGP keyID: 0x448BC5DD - http://www.gnupg.org - http://www.pgp.com)

..oO° Never, ever leapfrog a unicorn. °Oo.
Nov 14 '05 #7
On 10 May 2004 02:10:37 -0700, in comp.lang.c , pr******@yahoo. com (rohit)
wrote:
Hi,
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields


Unions are jolly handy if you have polymorphous data. A commonplace
example is the data in a spreadsheet - it can be text, numbers, formulas,
graphics and so on, all mixed together.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #8
Edd
rohit wrote:
Hi,
In my couple of years of experience, I have never found a single
instance where I needed to use unions and bitfields(thoug h I have used
structures).I was just imagining where would these find
relevance.Thoug h both of these(bitfields and unions) are used where
space is a constraint(so I can assume always in embedded systems,where
memory is particularly less)and we want to save space/memory.

As far as I have read, there is no difference between structs an
unions apart for saving space(that would also imply how members are
accessed in unions compared to in structs).

Can someone just give a couple of examples/scenario's where these have
actually been used or need to be used.

I've used unions similar to this one a few times:

union MyVector
{
struct
{
float x, y, z;
};
float v[3];
};

I can then fill the vector using a loop whose body indexes elements of v, or
if I wish to access or write a particular component I could use somevector.x
rather than somevector.v[0]. The former just seems more intuitive to me.

Another example that I can think of for unions off the top of my head
involves the Quicktime file format. Each atom is described by 4 bytes. So
assuming that on your system sizeof(int)==4, it may be convenient to define
the following union:

union QT_ATOM_TAG
{
char name[4];
int id;
};

In the format description, a 4 letter-code is used to indicate an atom-type,
but for comparisons and so forth, it's probably easier to use the integer
version.
It's a pretty localised example, but there are uses for unions. I've never
really used bit-fields, though.
Edd

Nov 14 '05 #9
> Operating systems. The members of a list of resources where unions.
Actually they were structures that contained unions. Soemthing like:

struct device {
int type;
union {
/* a bunch of structures */
/* each structure contains */
/* the necessary information */
/* for one device */


Is it more common to overlay structures in unions OR having a
structure which has unions as members.Also unions use much less memory
compared to structures(I can understand the situation when if we would
have used a structure of structures instead of a union of structures,
and at a single time only one of the structures is valid like this
example above, we are amounting to memory bloat) as they I suppose do
not have alignment problems and so do not require any padding to be
done.

One more clarification >>
I know that its illegal to take the address of a register variable
using the & operator.But this small example
#include <stdio.h>
int main()
{
register int i=10;
int *ptr;

ptr = &i;
printf("Value of ptr == %d\n",*ptr);
return 0;
}
when compiled
gcc -pedantic -ansi test_register.c -o test -Wall
test_register.c : In function `main':
test_register.c :7: warning: address of register variable `i' requested

../test
Value of ptr == 10

Gives just a warning though I can get the executable.

Also register variables are by default auto variables,I cannot declare
it as an external variable.
This small example proves that :

#include <stdio.h>
register int i=10;
int main()
{
int *ptr;

ptr = &i;
printf("Value of ptr == %d\n",*ptr);
return 0;
}

and compiling it
gcc -pedantic -ansi test_register.c -o test -Wall
test_register.c :2: register name not specified for `i'
test_register.c : In function `main':
test_register.c :7: warning: address of register variable `i' requested

and the binary is not generated.

How am i able to take the value of the regiter variable.I was thinking
of using register storage class for variables of which I wont be
concerned with the address and if I accidently try to acess the
address the compiler should stop me as an error condition.

TIA
rohit
Nov 14 '05 #10

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

Similar topics

15
5280
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 thing? I guess there might be some additional overhead with CLASSES, but is that really an issue with today's computers?
9
3093
by: Neil Zanella | last post by:
Hello, Some programmers like to use a coding convention where all names of variables that are pointers start with the letter p (and sometimes even use similar conventions for strings and other numeric data types). Do such programmers also have conventions for naming structures and unions (e.g. do they like their names to begin with s and u, so that, when the . operator is used, it is clear whether a structure or union is being accessed...
8
1907
by: Régis Troadec | last post by:
Hi all, I follow c.l.c. for only a short time and I would like to know why there isn't anything concerning bitfields among the FAQs. Is it because ... 1. of portability issues? 2. bitfields aren't enough useful to be discussed? 3. of the low frequency of questions concerning this topic? 4. of anything else?...
19
14809
by: Mehta Shailendrakumar | last post by:
Hi, I would like to know why array of bitfields is not possible. Is there any relation with processor architecture for this? Thank you for your time. Regards, Shailendra
18
1782
by: chump1708 | last post by:
union u { struct st { int i : 4; int j : 4; int k : 4; int l; // or int l:4 }st; int i;
18
4726
by: richard_l | last post by:
Hello All, I am writing an application which receives a word which is a bitmap. I have created a word typedef which contains a bitfield defining each bit. however, I was wondering however if it would be better to write a macro to access each bit instead of the bitfield. I have read the C-FAQ on bit fields, but was wondering if there were any advantages/disadvantages to using bit shifting. To my mind I think using bitfields are more...
4
1765
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; };
9
19257
by: cman | last post by:
Who can explain to me what bitfields are and how to use them in practice? I would need a fairly detailed explaination, I would be a newbie to advanced C programming features. What are the advantages of using bitfields? cman
11
2017
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 unions . My questions are : 1. Is it dangerous to use unions ? Is it worth the trouble if I want to save memory ? Are they error prone ? 2. I read that it is not possible to access more than 1 member at any instant from a union. What does this...
0
8823
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9530
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9363
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9312
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.