Monday, September 30, 2024

Union in C Language

Union in C 

union:- 

A union is a user-defined data type in the C programming language that allows for the storage of elements of various data types, similar to a structure. However, in contrast to structures, all members of a C union occupy the same memory location. Consequently, at any given moment, only one member can hold data.

when union is declared the compiler automatically allocates enough memory storage to hold largest number. to access union directly we use dot(.) operator.to access union through pointer we use (->) operator. union conserve memory space, useful for applications involving multiple elements.

In union the integer(i) and character (ch) share the same memory location.

program to store 

#include<stdio.h>
#include<string.h>
union student;
{
char name[20];
int age;
};

main()
{
union student *s;
//*s means s is an array of undefined elements.
int i;
clrscr();
for(i=0;i<=2;i++)
{
printf("\n Enter the name: ");
fflush(stdin);
scanf("%s"&s[i].name);
printf("\n Enter the age: ");
scanf("%d",&s[i].age);
}

printf("\n Name Age");
printf("\n ----------------");
for(i=0;i<=2;i++)
{
printf("\n %s\t\t%d",s[i].name, s[i].age);
printf("\n ----------------");
}

getch();
}

No comments:

Post a Comment

Autonomous Vehicles

Autonomous Vehicles Autonomous vehicles are cars or trucks that can drive themselves without needing a human to control them. They use advan...