Kernighan ritchie 37 sect 512 present a very helpful

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: .9.2 Unions Unions provide a way to circumvent the type system of C, allowing a single object to be referenced according to multiple types. The syntax of a union declaration is identical to that for structures, but its semantics are very different. Rather than having the different fields reference different blocks of memory, they all reference the same block. Consider the following declarations: struct S3 { char c; int i[2]; double v; }; union U3 { char c; int i[2]; double v; }; The offsets of the fields, as well as the total size of data types S3 and U3, are: 3.9. HETEROGENEOUS DATA STRUCTURES Type S3 U3 c 0 0 i 4 0 v 12 0 Size 20 8 157 (We will see shortly why i has offset 4 in S3 rather than 1). For pointer p of type union U3 *, references p->c, p->i[0], and p->v would all reference the beginning of the data structure. Observe also that the overall size of a union equals the maximum size of any of its fields. Unions can be useful in several contexts. However, they can also lead to nasty bugs, since they bypass...
View Full Document

Ask a homework question - tutors are online