Structure of Unions: Whenever you need different data types to be stored in the same memory. Saves memory space and provides flexibility in handling different data types. Ex: Used for HW configuration where each member in the union corresponds to a specific HW configuration, in protocol parsing, each member in the union can be used to perform specific operations such as parsed, processed etc… on the data.
Syntax:
Union uni_on1{ …};
Union uni_on2{…};
struct struct_of_union{
union uni_on1 mem1;
union uni_on2 mem2;
};
Struct struct_of_union a_struct;
A_struct.mem1.uni_on1 = some_val;
Ex:
struct pmop {
BASEOP
OP * op_first;
OP * op_last;
# ifdef USE_ITHREADS
PADOFFSET op_pmoffset;
#else
OP * op_pmregexp;
#endif
U32 op_pmflags;
union {
OP * op_pmreplroot;
PADOFFSET op_pmtargetoff;
GV * op_pmtargetgv;
} op_pmreplrootu;
union {
OP * op_pmreplstart;
#ifdef USE_ITHREADS
PADOFFSET op_pmstashoff;
#else
HV * op_pmstash;
#endif
} op_pmstashstartu;
OP * op_code_list;
}; // Used in Perl regular expression engine to represent a pattern match operation.
(/lib/x86_64-linux-gnu/perl/5.34.0/CORE/op.h)
Union of Structures: Used where we need to represent different data types in same memory location. EX: Used in file data strcutures where features such as file size, permission, timestamps are wrapped in a single data structures.
Ex:
union fw_cdev_event {
struct fw_cdev_event_common common;
struct fw_cdev_event_bus_reset bus_reset;
...
struct fw_cdev_event_iso_interrupt_mc iso_interrupt_mc;
struct fw_cdev_event_iso_resource iso_resource;
struct fw_cdev_event_phy_packet phy_packet;
}; // Used to represent different types of events or messages that can be received or transmitted within the FireWire communication context.
Structure of union of structure: Used to handle different data formats and interpretations on conditions or modes. Ex: Can be seen its usage in linux kernel sub system network.
struct __kernel_sockaddr_storage {
union {
struct {
__kernel_sa_family_t ss_family;
char __data[_K_SS_MAXSIZE - sizeof(unsigned short)];
};
void *__align; }; }; (//usr/include/linux/socket.h)
Array of pointers to functions: Used to store and manage collection of different function pointers.
Syntax:
char (*fun_ptr_arr[5])(int,char);
fun_ptr1[0] = some_fun1();
fun_ptr2[1] = some_fun2();

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An Article by: Yashwanth Naidu Tikkisetty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
