How do you declare a union in C:

C Union. Union is an user defined datatype in C programming language. It is a collection of variables of different datatypes in the same memory location. We can define a union with many members, but at a given point of time only one member can contain a value.

In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y. #include <stdio.h> // Declaration of union is same as structures.

For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.

#include <stdio.h>

// Declaration of union is same as structures
union test {
	int x, y;
};

int main()
{
	// A union variable t
	union test t;

	t.x = 2; // t.y also gets value 2
	printf("After making x = 2:\n x = %d, y = %d\n\n",
		t.x, t.y);

	t.y = 10; // t.x is also updated to 10
	printf("After making y = 10:\n x = %d, y = %d\n\n",
		t.x, t.y);
	return 0;
}

output:

After making x = 2:
 x = 2, y = 2

After making y = 10:
 x = 10, y = 10

Pointers to unions?
Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same.

c union
#include <stdio.h>

union test {
	int x;
	char y;
};

int main()
{
	union test p1;
	p1.x = 65;

	// p2 is a pointer to union p1
	union test* p2 = &p1;

	// Accessing union members using pointer
	printf("%d %c", p2->x, p2->y);
	return 0;
}

output:

65 A

Let’s have a look at the pictorial representation of the memory allocation.

The below figure shows the pictorial representation of the structure. The structure has two members; i.e., one is of integer type, and the another one is of character type. Since 1 block is equal to 1 byte; therefore, ‘a’ variable will be allocated 4 blocks of memory while ‘b’ variable will be allocated 1 block of memory.

The below figure shows the pictorial representation of union members. Both the variables are sharing the same memory location and having the same initial address.

Leave a Reply

For News Subscribe Us!

Can curiosity may end shameless explained. True high on said mr on come. An do mr design at little myself wholly entire though. Attended of on stronger or mr pleasure.

You have been successfully Subscribed! Ops! Something went wrong, please try again.

© 2022 Code With AM