60 likes | 77 Views
Learn about union data structure in C that allows for different components to vary depending on the value of another component. Understand how to define and manipulate unions to store data efficiently. Avoid common errors by utilizing contextual statements.
E N D
CSci 160Lecture 44 Martin van Bommel
Union Introduction • So far, all variables of a particular structure type have exactly the same components • Sometimes we need a structured type in which some components vary depending on the value of another component • e.g. data stored about a geometric figure depends on the type of figure
Union Type • C provides a union data structure typedef union { int num; char ch[2]; } int_ch_t; • Variables of this type represent either an integer or two characters • Need some other value to determine which
Union Storage • What if parts of union not same memory size? typedef union { int num1; double num2; } num_t; • When create a variable, how large in memory? • Size of largest part of union (e.g. 8 bytes)
Geometric Figures • For problem with geometric figures, first define structures for each type of figure • Then define a union type with a component for each figure type • Finally define structure containing both a component of the union type and a component whose value denotes which is the correct interpretation of union • See program geometry.c
Union Problems • Most common error with union types is referencing a component that is not currently valid • Helpful to place in another structure with component whose value indicates correct interpretation • Then all manipulation done within context of if or switch statement