0% found this document useful (0 votes)
778 views8 pages

Union in C PDF

Unions in C allow storing different data types in the same memory location. Only one member can be accessed at a time. Structures allocate separate memory for each member, while unions share the same memory location for all members. Bit fields allow defining structure members using bits to optimize memory usage.

Uploaded by

mirziauddin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
778 views8 pages

Union in C PDF

Unions in C allow storing different data types in the same memory location. Only one member can be accessed at a time. Structures allocate separate memory for each member, while unions share the same memory location for all members. Bit fields allow defining structure members using bits to optimize memory usage.

Uploaded by

mirziauddin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

C Unions

A union is a user-defined type similar to structs in C except for one key


difference.
Structures allocate enough space to store all their members, whereas unions
can only hold one member value at a time.

How to define a union?

We use the union keyword to define unions.

union car
{
char name[50];
int price;
};

The above code defines a derived type union car.

Create union variables

When a union is defined, it creates a user-defined type. However, no memory


is allocated. To allocate memory for a given union type and work with it, we
need to create variables.

union car
{
char name[50];
int price;
};

int main()
{
union car car1, car2, *car3;
return 0;
}

Another way of creating union variables is:

union car
{
char name[50];
int price;
} car1, car2, *car3;

In both cases, union variables car1, car2, and a union pointer car3 of union
car type are created.

Access members of a union

We use the . operator to access members of a union. And to access pointer


variables, we use the -> operator.
In the above example,

• To access price for car1, car1.price is used.


• To access price using car3, either (*car3).price or car3->price can be
used.
Difference between unions and structures

Let's take an example to demonstrate the difference between unions and


structures:

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}

Output

size of union = 32
size of structure = 40

Why this difference in the size of union and structure variables?


Here, the size of sJob is 40 bytes because
• the size of name[32] is 32 bytes
• the size of salary is 4 bytes
• the size of workerNo is 4 bytes
However, the size of uJob is 32 bytes. It's because the size of a union variable
will always be the size of its largest element. In the above example, the size of
its largest element, (name[32]), is 32 bytes.
With a union, all members share the same memory.

Example: Accessing Union Members

#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;

int main() {
j.salary = 12.3;

// when j.workerNo is assigned a value,


// j.salary will no longer hold 12.3
j.workerNo = 100;

printf("Salary = %.1f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
return 0;
}

Output

Salary = 0.0
Number of workers = 100

typedef in C
typedef is a keyword used in C language to assign alternative names to
existing datatypes. Its mostly used with user defined datatypes, when names
of the datatypes become slightly complicated to use in programs.

Syntax:

Syntax: typedef <existing_name> <alias_name>

Eg: typedef unsigned long ulong;

Suppose we want to create a variable of type unsigned int, then it becomes a


tedious task if we want to declare multiple variables of this type. To overcome
the problem, we use a typedef keyword.

1. typedef unsigned int unit;

In the above statements, we have declared the unit variable of type unsigned
int by using a typedef keyword.

Now, we can create the variables of type unsigned int by writing the following
statement:

1. unit a, b;

instead of writing:

1. unsigned int a, b;

Using typedef with structures

Consider the below structure declaration:

struct student
{
char name[20];
int age;
};
struct student s1;
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;

The above typedef can be written as:

typedef struct student


{
char name[20];
int age;
} stud;
stud s1,s2;

bit field is a data structure that allows the programmer to allocate memory to
structures and unions in bits in order to utilize computer memory in an efficient
manner.
Since structures and unions are user-defined data types in C, the user has an
idea of how much memory will they occupy. Accordingly, by the
implementation of bit fields, memory management becomes easy and
efficient.

Need for Bit Fields in C


Bit fields are of great significance in C programming, because of the following
reasons:

• Used to reduce memory consumption.


• Easy to implement.
• Provides flexibility to the code.

Declaration of Bit Fields in C


struct
{
data_type variable_name : size_in_bits;
};
The formal name for size_in_bits is called the width of the bit field.

Working of bitfields:
In order to understand how bit fields work, let us consider a problem, in which
we are expected to define a structured time to display the time according to
24-hour clock entered by the user with unsigned int hours, minutes and
seconds.

Since an unsigned integer occupies 4 bytes of memory according to a 64-bit


compiler, the size of the structure would be 12 bytes.

Implementation of a structured time without the use of bit fields:

#include <stdio.h>
struct time
{
unsigned int hours;
unsigned int minutes;
unsigned int seconds;
};
int main()
{
struct time t = {11, 30, 10}; // Here t is an object of the structure time
printf("Welcome to DataFlair tutorials!\n\n");
printf("The time is %d : %d : %d\n", t.hours, t.minutes, t.seconds);
printf("The size of time is %ld bytes.\n", sizeof(struct time));
return 0;
}
Output:

/tmp/DkJfzCevha.o

Welcome to DataFlair tutorials!

The time is 11 : 30 : 10

The size of time is 12 bytes.


Implementation of a structured time with the use of bit fields:

#include <stdio.h>
struct time
{
unsigned int hours: 5; // Size restricted to 5 bits
unsigned int minutes:6; // Size restricted to 6 bits
unsigned int seconds:6; // Size restricted to 6 bits
};
int main()
{
struct time t = {11, 30, 10}; // Here t is an object of the structure time
printf("Welcome to DataFlair tutorials!\n\n");
printf("The time is %d : %d : %d\n", t.hours, t.minutes, t.seconds);
printf("The size of time is %ld bytes.\n", sizeof(struct time));
return 0;
}
Output:
/tmp/DkJfzCevha.o
Welcome to DataFlair tutorials!

The time is 11 : 30 : 10
The size of time is 4 bytes.

You might also like