Unions
a union is a derived type (similar to structure) with members that share the same storage space. sometimes the same type of construct needs different types of data. used when its necessary to store different types of data in the same storage area.
unions have members. only one member can contain a value at any time so only one access of a member at a given time. a member can have any data type.
unions are useful in embedded programming, situations where direct access to the hardware/memory is needed
Defining a union
the declaration is like structure
the union tag is optional and each member definition is a normal variable definition
example:
the length of this is same as 'str' variable cause it hase the largest size in the union.
Creating union variables
example:
Anonymous unions
in c11 an unnamed memory union of structure.
example:
Accessing union members
exactly like accessing struct members and values
we have three ways:
ptrst->code
item.code
(*ptrst).code
example:
Last updated