C Unions

1. What is a Union?

  • A union is similar to a structure (struct) in C, but all members share the same memory location.

  • Only one member can store a value at a time.

  • Useful for memory-efficient programs when you need alternative data types in the same location.

Syntax:

union UnionName {
data_type member1;
data_type member2;
...
};

2. Example: Basic Union

#include <stdio.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

data.i = 10;
printf(“data.i = %d\n”, data.i);

data.f = 220.5;
printf(“data.f = %.2f\n”, data.f);

// Only the last assigned value is stored
strcpy(data.str, “Hello”);
printf(“data.str = %s\n”, data.str);

// Previous values are overwritten
printf(“data.i = %d\n”, data.i); // may show garbage
printf(“data.f = %.2f\n”, data.f); // may show garbage

return 0;
}

Output:

data.i = 10
data.f = 220.50
data.str = Hello
data.i = <garbage>
data.f = <garbage>

Only one member’s value is valid at a time.


3. Size of a Union

  • The size of a union is equal to the size of its largest member.

#include <stdio.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
printf(“Size of union = %lu bytes\n”, sizeof(union Data));
return 0;
}

Output:

Size of union = 20 bytes
  • str is the largest member → union size = 20 bytes.


4. Union with Struct Example

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

struct Info {
char name[50];
union Data data;
};

int main() {
struct Info info;

strcpy(info.name, “Alice”);
info.data.i = 100;

printf(“Name: %s\n”, info.name);
printf(“Integer: %d\n”, info.data.i);

info.data.f = 220.5; // overwrites previous value
printf(“Float: %.2f\n”, info.data.f);

return 0;
}

Output:

Name: Alice
Integer: 100
Float: 220.50

5. Key Points About Unions

  1. All members share the same memory location.

  2. Only one member can hold a value at a time.

  3. Memory size = size of largest member.

  4. Useful for memory-efficient storage and type alternatives.

  5. Access union members with dot . (normal) or arrow -> (pointer).

  6. Often used in embedded systems, protocol implementations, and type conversion.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *