By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,037 Members | 2,065 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,037 IT Pros & Developers. It's quick & easy.

Application of Union in C

P: n/a
I want what is the application of union in C.Please explain

Apr 19 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 2006-04-19, balasam <bk*****@gmail.com> wrote:
I want what is the application of union in C.Please explain


They're quite often used for a sort of "polymorphism".

For example, if you were writing an interpreter for a dynamically typed
language, you might represent values in the language using unions like
this:

enum value_type
{
INT,
REAL,
STRING,
OBJECT
};

struct value
{
enum value_type type;

union
{
int val_int;
double val_real;
char *val_string;
struct object *val_object;
}
value;
};

All values are instances of "struct value", but that can represent an
int, a double, a char or an object.
Apr 19 '06 #2

P: n/a
CJ
A common use for union is to ease breaking up a STREAM of input, in the
example below breaking an int value read into two short values.

/* tunion.c */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/* Usage: tunion <binfile */
int
main(int argc,char *argv[])
{
union {
unsigned ii;
struct {
short high;
short low;
} word;
} decode;

printf("sizeof(decode) = %d\n",sizeof(decode));
printf("sizeof(decode.ii) = %d\n",sizeof(decode.ii));
printf("sizeof(decode.word) = %d\n",sizeof(decode.word));
printf("sizeof(decode.word.high) =
%d\n",sizeof(decode.word.high));
printf("sizeof(decode.word.low) =
%d\n",sizeof(decode.word.low));

/* Reads 0x01020304 from stdin */
read(0,&decode.ii,sizeof(decode.ii));

printf("high word = %04hx\n",decode.word.high);
printf("low word = %04hx\n",decode.word.low);

/* Reads 0x04030201 from stdin */
read(0,&decode.ii,sizeof(decode.ii));

printf("high word = %04hx\n",decode.word.high);
printf("low word = %04hx\n",decode.word.low);
}

Redirecting a file containing eight bytes, below, you can use the union
variable decode to get direct access to the two 16 bit words of the int
value read.

binfile contains: "^A^B^C^D^D^C^B^A" (quotes not in file)

CJ

Apr 21 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.