Union is also like a Structure means Unions is also used for Storing data of different data types But the Difference b/w Structure and Union is that Structure Consume the Memory of addition of all elements of Different Data Types but a Union Consume the Memory that is Highest among all variables.
It Consume Memory of highest variables and it will share the data among all the other Variables Suppose that if a union Contains variables Like Int ,Float ,Char then the Memory Will be consumed of Float variable because float is highest among all variables of data types etc. We can declare a Union in a Structure and Vice-versa.
A union is defined in the same way as a structure by specifying the keyword union in place of keyword struct. The syntax for defining a union is
union union_name //union declaration
data_type member_name 1;
data_type member_name2 ;
To understand the concept of union definition, consider this example.
Example : A code segment to demonstrate union definition
In this example, a union stu having two members roll_no and grade is declared. After union definition, union variables can be declared either at the time of union definition or by using a separate declaration statement in the program. For example, variables of the union stu , can be declared as
//variable declaration along with union definition
//same as in Example above
}stu1,stu2; // union variables declaration
// variable declaration in the program
stu stu1,stu2; I I keyword union not required
In order to access an individual member of a union variable, the member selection operator (the dot operator) is used with the union name. For example, consider this statement.
In this statement, the member roll_no of union variable stu1 is assigned the value 101.
Anonymous Union: C++ supports a special type of union known as anonymous union. An anonymous union is defined without specifying the union name (or union tag), which implies, no variables of this union can be declared. However, an unnamed variable of anonymous union is created automatically, whose members can be accessed directly without using the dot operator.
To understand the concept of anonymous unions, consider this example.
Example : A code segment to demonstrate anonymous union
union // Anonymous Union definition
In this example, an anonymous union having two members namely, roll_no and grade is defined. Note that these members can be accessed directly using these statements.
Cout<< roll_no; //print value of roll_no
grade=’A’ ; / /assign value to grade
Note that a union defined without a union tag cannot be considered as an anonymous union if its variables are declared along with its definition. For example, consider these statements.
union / /Not an Anonymous Union
/ /same as in Example above