Purpose of using union within structure in c -
typedef struct { int k; union { int i; int j; }use; }std;
directly can use variable , j in structure why used within union.
in example, i.e.
typedef struct { int k; union { int i; int j; }use; }std;
it doesn't seem make sense i
, j
same type , names of variables isn't descriptive.
it can make sense have same type union elements if make code easier write, read, understand , maintain. example:
... union { int numberofcars; int numberofbicycles; }use; ...
when writing code handling cars
use numberofcars
, when writing code handling bicycles
use numberofbicycles
. in way code easier understand/maintain , 2 code blocks still share common structure.
in 1 code block have:
std cardealer; cardealer.use.numberofcars = 9;
and in code block (other file perhaps), have:
std bicyclesdealer; bicyclesdealer.use.numberofbicycles = 9;
a more typical case unions elements of different type.
Comments
Post a Comment