A union is a data type that can be considered special in D. It gives us the ability to have different data types in the same memory or storage location. The defined members of a union can be several, but only one of these members can have a value at any given time. Unions efficiently utilize a single memory location due to its multi-purpose ability.
The union statement creates a new user-defined data type, with more than one member base type for our program. Below is the general syntax used to define a union:
union union_name{
define member
}[one_or_more_union_variables]
union
: The keyword used to define a union.union_name
: An optional tag name given to a union. It is any legal D identifier.define member
: The part of the union statement block. We must declare more than one union member of any basic D inbuilt data type or a user-defined one.one_or_more_union_variables
: A single or multiple variable we want to be of the union data type we just defined. It is optional as well.union example {
int my_int;
float my_float;
char my_str[40];
} sample_variable;
It implies that a variable of data type example
can store an integer, a floating-point number, or a string of characters. It means one variable (a single memory location) can be used to store several types of data. Depending on our requirement, any built-in or user-defined data types can be used inside a union.
The sample_variable
variable can be of any member type that is defined above just by doing this inside the main method. That will allow the sample_variable
to hold an integer as implied by the my_int
member.
example sample_variable;
sample_variable.my_int =20;
Let’s look at the code below:
import std.stdio; //define a union union Example { int my_int; float my_float; char[40] my_str; }; void main( ) { // declare variable sample_var as type example Example sample_var; //assign value to the variables sample_var.my_int = 10; sample_var.my_float = 220.5; sample_var.my_str = "I am loving this"; //check size of the variables writeln( "size of : ", sample_var.sizeof); writeln( "data.my_int : ", sample_var.my_int); writeln( "data.my_float: ", sample_var.my_float); writeln( "data.my_str : ", sample_var.my_str); }
Example
, with allowable data types of int
, float
, and string
.main
function blocks, which return no value.sample_var
as the type of Example
inside function main
.sample_var
several values based on the basic types in the union.The value of sample_var.my_int
and sample_var.my_float
are output erroneously. This happened because in the case of several assignments to a particular union variable, in this case, sample_var
, the variable with the largest value, sample_var.my_str
is automatically displayed correctly while the rest are wrong.
Note: Unions have a size that is the size of the largest value of the union.
RELATED TAGS
CONTRIBUTOR
View all Courses