Application of Union in C

B

Ben C

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.
 
C

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top