In computer science, a union is a value that may have any of several representations or formats; or it is a data structurethat consists of a variable that may hold such a value. Some programming languages support special data types, calledunion types, to describe such values and variables. In other words, a union type definition will specify which of a number of permitted primitive types may be stored in its instances, e.g., “float or long integer”. Contrast with a record (or structure), which could be defined to contain a float and an integer; in a union, there is only one value at any given time.
A union can be pictured as a chunk of memory that is used to store variables of different data types. Once a new value is assigned to a field, the existing data is overwritten with the new data. The memory area storing the value has no intrinsic type (other than just bytes or words of memory), but the value can be treated as one of several abstract data types, having the type of the value that was last written to the memory area.
In type theory, a union has a sum type; this corresponds to disjoint union in mathematics.
Depending on the language and type, a union value may be used in some operations, such as assignment and comparison for equality, without knowing its specific type. Other operations may require that knowledge, either by some external information, or by the use of a tagged union.
int main(int argc, char **argv)
union student st;
int n, i;
printf("Enter a number between 1 to 10: ");
for(i = 1; i <= n; i++)
printf("\nEnter details of student %d:", i);
printf("\nId of student %d: ", i);
printf("\nStudent %d Id: %d", i, st[i].id);
printf("\nName of student %d: ", i);
printf("\nStudent %d Name: ", i);
Input and output for the above program is as follows:
Enter a number between 1 to 10: 2
Enter details of student 1:
Id of student 1: 101
Student 1 Id: 101
Name of student 1: teja
Student 1 Name: teja
Enter details of student 2:
Id of student 2: 102
Student 2 Id: 102
Name of student 2: sruthi
Student 2 Name: sruthi
Take your time to comment on this article.