3.2 Structures and Unions
Structures group members (data and functions) to create new data types. Structures encapsulate data members (usually different data types), much like functions encapsulate program statements. Unions are like structures, but data members overlay (share) memory, and unions may access members as different types. We use structures and unions in applications that need user-defined types, such as databases, windows, and graphics.
Structures
Structure definitions have several formats, all of which include data members and member functions. To show the formats for structure definitions, let's look at structure data members first. We'll examine structure member functions in the next section.
The first structure format appears frequently in header files.
struct struct_name { Type data_member1; Type data_member2; Type data_memberN; };
The word struct_name is a new data type. Data members may be any type, including pointers, references, arrays, and other structures whose types do not have the same name as struct_name. The compiler does not allocate memory with this format because we define only a type and not a variable.
NOTE
Structure data members cannot have the same type name as their enclosing structure, but we can define pointers to the same structure type.
struct node { // structure type int data; // data member node *fwd; // pointer to struct type node *back; // pointer to struct type };
Note how soon we drop the word struct from subsequent node definitions once we define it as a type.
The second structure format builds a structure from an existing structure type and includes an initialization list to initialize it.
struct struct_name name = { init_list };
The keyword struct is optional when you define struct_name elsewhere. This format allocates memory for structure name, which is type struct_name. The brace-enclosed initialization list is optional.
The third structure format combines the first and second formats.
struct struct_name { Type data_member1; Type data_member2; Type data_memberN; } name = { init_list };
This format allocates memory, and the keyword struct is necessary to define a structure type. You may omit struct_name in this format if you don't need to use it later on in another structure definition.
NOTE
Structure initializations require braces with init_list. Consider the following.
struct X { // structure definition int num; // data member }; X a = 12; // illegal - no conversion X a = { 12 }; // legal - initializes data member
The first initialization without braces generates a compilation error because the compiler attempts to convert an integer 12 to a structure X type. The second initialization with braces is correct. Always use pairs of braces to properly initialize your structures.
Member Functions
C++ also allows function declarations (called member functions) inside structures.
struct struct_name { Type member_function1(signature); Type member_function2(signature); };
Typically, member function names are distinct, but the name of a member function may be the same as another if their signatures differ. There is no size overhead for member functions inside structures (try sizeof() to convince yourself).
Member functions are essential in object-oriented programming because new data types combine functionality (member functions) with data (data members), all in a single unit. This concept lets you design objects with an implementation (how objects work) and an interface (how objects behave). We explore these important concepts in Chapter 4 with class definitions.
The dot (.) operator provides access to structure members.
struct X { int num; // data member int f(); // member function }; X a = { 12 }; // initialize data member cout << a.num << endl; // data member, displays 12 cout << a.f() << endl; // calls member function
Structure Pointers
Pointers may address structures. The formats are
struct struct_name { Type data_member; Type member_function(signature); } *pname = { init_list }; struct struct_name *pname = { init_list };
The brace-enclosed init_list is optional and must contain a pointer expression whose type matches or converts to struct_name. If you initialize structure pointers, the braces surrounding init_list are not necessary. The word struct_name is optional in the first format, and the keyword struct is optional in the second format when you define struct_name elsewhere.
Here are the two formats to access structure members.
struct_name_variable.member_name // structure struct_name_pointer->member_name // structure pointer
A structure variable name must appear to the left of the . (dot) operator and a structure pointer name must appear to the left of the -> (arrow) operator. Here are some examples of these operators with structure type block.
struct block { // structure type int buf[80]; // data member char *pheap; // data member void header(const char *); // member function }; block data = { {1,2,3}, "basic" }; // structure variable block *ps = &data; // structure pointer data.pheap++; // increment data member data.header("magic"); // call member function ps->pheap++; // increment data member ps->header("magic"); // call member function ps.pheap++; // illegal, ps is a pointer data->header("magic"); // illegal, data is a structure
The inner braces in the initialization list for data initialize only the first three integers of the buf data member array (the remaining elements are zero). The precedence of . and -> is high; hence, no parentheses are necessary to combine them with a ++ operator when we increment pheap.
Be aware that memory allocation for structures does maintain the order of its data members in structure definitions. Structures, therefore, may contain "holes" due to machine word alignment (buf[79] in place of buf[80], for example).
Arrays with Structures
Arrays of structures and arrays of structure pointers are also possible. Two groups of formats exist. Here is the first one.
struct struct_name name[size] = { init_list }; struct struct_name name[size1][size2][sizeN] = { init_list }; struct struct_name *pname[size] = { init_list }; struct struct_name *pname[size1][size2][sizeN] = { init_list };
The keyword struct is optional when you define struct_name elsewhere, and the rules for size are the same as the rules for arrays of built-in types (see "Arrays" on page 35). The optional brace-enclosed init_list initializes a data member in each array element. With arrays of structure pointers (pname), init_list must have pointer expressions that match or convert to struct_name. When you initialize arrays of structures or arrays of structure pointers, you must include braces with init_list.
The second group of formats define a structure type and follow the same rules as above. The keyword struct must appear in both formats, but struct_name is optional.
struct struct_name { Type data_member; Type member_function(signature); } name[size1][size2][sizeN] = { init_list }; struct struct_name { Type data_member; Type member_function(signature); } *pname[size1][size2][sizeN] = { init_list };
Here are several examples of structure arrays.
struct block { // structure type int buf[80]; // data member char *pheap; // data member void header(const char *); // member function }; block dbase[2] = { // array of 2 structures { {1,2,3}, "one" }, // initialize first element { {4,5,6}, "two" } // initialize second element }; block *pb[2]; // array of 2 pointers to block dbase[1].pheap++; // increment data member dbase[1].buf[0] = 'x'; // assign to data member dbase[1].header("magic"); // call member function pb[1] = &dbase[1]; // pb[1] points to dbase[1] pb[1]->pheap++; // increment data member pb[1]->buf[0] = 'x'; // assign to data member pb[1]->header("magic"); // call member function
NOTE
In the above example, we use an outer pair of braces on separate lines to initialize each member of the dbase structure array. Braces surrounding individual structure array elements make their initializations readable and easy to modify. Remember to use at least one pair of braces.
Nested Structures
Structure definitions that appear inside other structure definitions are nested structures. Here is an example.
struct team { struct address { // nested structure char location[80]; // team location int zipcode; // team zip code }; char name[20]; // name of team address sponsor; // sponsor's address address home_field; // home field address };
Nested structures encapsulate structure definitions and make them an integral part of an enclosing structure definition. Use the . or -> operators in succession to access the member you want from a nested structure.
team soccer = { "bears", {"123 Main", 30302}, {"8 Elm", 32240} }; team *ps = &soccer; // structure pointer cout << soccer.name << endl; // displays "bears" cout << soccer.sponsor.zipcode << endl; // displays 30302 cout << ps->home_field.zipcode << endl; // displays 32240
The first cout statement uses a . operator to display the team's name. Two . operators are necessary to display the zip code of the team's sponsor in the second cout statement. The third cout statement uses -> with structure pointer ps and . with structure data member home_field to display the team's home field zip code.
NOTE
Nested structures can use the same name as their enclosing structure names if they nest, too. Consider the following.
struct X { // outer X struct Y { // Y nested in outer X struct X { // inner X nested in Y int i; // member of inner X }; X mystuff; // member of Y int j; // member of Y }; Y stuff; // member of outer X int k; // member of outer X };
A structure Y nests inside outer structure X. Structure Y also nests an inner structure X, which is legal because its name is distinct from its immediately enclosing structure name (Y). Sometimes name collisions do occur when you piece together existing structures to form new ones, so be aware of this rule.
Typedefs with Structures
Chapter 2 introduces typedefs as synonyms for built-in types (see "Typedefs" on page 43). Typedefs also apply to structures and help make structure definitions more readable. Consider the structure definitions from the previous section.
struct node { int data; node *fwd; node *back; }; node element; node *p = &element;
Here's how we can simplify this code with the following typedef.
typedef struct node *Pnode; struct node { int data; Pnode fwd; Pnode back; } ; node element; Pnode p = &element;
Pnode is a synonym for struct node *. This typedef eliminates the pointer notation from our original code and makes it more readable.
NOTE
Create typdef names with uppercase first letters for better readability. Place typedef statements and structure definitions in header (.h) files and #include them where necessary. Remember that typedefs are not new types; they are just synonyms for existing ones. Typedefs, therefore, are not type safe.
Structure Copy and Assignment
Sometimes you want to save a structure temporarily or initialize a new structure from another one of the same type. The following statements attempt to copy the data members of one structure into another structure of the same type.
struct value { // structure definition double x; char name[10]; } a = { 5.6, "start" }; // initialize members of struct a value b; // structure b of same type b.x = a.x // legal - copy doubles b.name = a.name; // illegal - not lvalues
Separate data member assignments are not only tedious for structures with a large number of members, but assignments fail with array members (array names are not lvalues). Fortunately, there is an easier way.
value b = a; // structure copy value c; c = a; // structure assignment
With structures of the same type, you may copy an existing structure to a new one or assign one structure to another. The compiler copies each member of one structure into the other (even array members!).
Remember that references to structures do not perform structure copies.
value f; // structure value & e = f; // reference to a structure
The reference e is only an alias for structure f.
NOTE
Use structure copy and assignment statements. For built-in types (char, int, float, etc.), most compilers generate in assembly code block move instructions, which move data in memory without loops or counters. Thus, structure copy and assignment are efficient and convenient.
Unions
Unions have the same formats and operators as structures. Unlike structures, which reserve separate chunks of memory for each data member, unions allocate only enough memory to accommodate the largest data member. On 16-bit and 32-bit machines, for example, the definition
union jack { long number; char chbuf[4]; } chunk;
allocates only four bytes of memory. Variable chunk.number is a long, and chunk.chbuf[2] (for example) is a char, both within the same memory area. Figure 3.3 shows the memory layout for chunk.
Figure 3.3. Memory layout of a union
You may create pointers to unions and initialize unions with an lvalue of the same data type as the union's first data member. Member functions are legal inside union definitions, but data members with constructors are not (see "Constructors" on page 181). Union assignment works just like structure assignment. Maintaining data integrity for union members is the programmer's responsibility.
C++ also has anonymous unions. An anonymous union allocates memory for its largest data member but doesn't create a type name (hence the name "anonymous"). Here's the format.
union { Type data_member1; Type data_member2; Type data_memberN; };
A program that declares an anonymous union may access data members directly (without a . or ->). Member functions are illegal inside anonymous union definitions.
To demonstrate anonymous unions, Listing 3.7 employs another version of itoh(), which converts short variables to hexadecimal characters for display.
Listing 3.7 Integer-to-hexadecimal conversion, using anonymous union
void itoh(unsigned short n) { union { // anonymous union unsigned short num; unsigned char s[sizeof(short)]; }; const char *hex = "0123456789abcdef"; num = n; // store number as a short cout << hex[s[1] >> 4]; // first byte - high nibble cout << hex[s[1] & 15]; // first byte - low nibble cout << hex[s[0] >> 4]; // second byte - high nibble cout << hex[s[0] & 15]; // second byte - low nibble }
An anonymous union creates two bytes (16 bits) of memory for itoh() to access. The statement num = n stores the number we pass to itoh() into memory as a short, and the cout statements access the same bytes of memory as characters. We use a 4-bit right shift (>> 4) to access the high nibble (4 bits) and a 4-bit mask (& 15) to access the low nibble. Both operations yield a 4-bit result between 0 and 15, which we use as an index with pointer hex to convert the result to ASCII characters ('0' to 'f'). The memory that our anonymous union creates is available only inside itoh().
Why use this technique? First, this version of itoh() executes fast. Unlike other versions, there are no recursive calls, loops, or multiply or divide operators. Second, on some machines, the assembly code from this function may be smaller in size than other versions. In time-critical code or with programs that have memory constraints, this version of itoh() may be preferable to others.
NOTE
Unions are not always portable, due to the way different processors store bytes in memory. Our version of itoh(), for instance, runs correctly on IntelÆ processors, but displays the bytes in reverse order on SPARCÆ-based workstations. The following preprocessor statements declare and initialize a const integer that identifies the machine we are using.
#ifdef SPARC const int byte = 0; // SPARC-based #else const int byte = 1; // Intel #endif
Inside itoh(), we modify the cout statements as follows.
cout << hex[s[byte] >> 4]; // first byte - high nibble cout << hex[s[byte] & 15]; // first byte - low nibble cout << hex[s[!byte] >> 4]; // second byte - high nibble cout << hex[s[!byte] & 15]; // second byte - low nibble
You may extend these preprocessor statements to handle other machines as well. This approach lets you maintain one version of itoh() that's portable across different machines.
Bitfields
When hardware assigns special meanings to bits in memory, bitfields are often easier to work with than bit masks and shift operators. The following dbyte structure definition, for instance, defines four bitfield data members, all in the same integer word.
struct dbyte { unsigned int flag : 1; // one bit unsigned int mode : 2; // two bits unsigned int : 1; // unused bit unsigned int type : 4; // four bits };
A bitfield is any integral type (signed and unsigned char, short, int, long, or an enumerated type). The number following the colon separator must be a constant expression and specifies the number of bits for the bitfield. Member flag, for example, is one bit, whereas mode and type are two bits and four bits, respectively. An unnamed bitfield (the third member in dbyte) is useful for padding bits within other named bitfields. A zero following the colon separator aligns the following bitfield on a machine-specific addressable boundary. The address operator (&) and references and pointers are illegal with bitfields. The keyword static (page 125) is also illegal with bitfields.
Here's an example on a machine with 16-bit word sizes.
dbyte v = { 0 }; // create word with bitfields v.flag = 1; // 0000 0000 0000 0001 v.mode = 3; // 0000 0000 0000 0111 v.type = 9; // 0000 0000 1001 0111
Each assignment statement sets the appropriate bits within a bitfield, which we show with italics inside the comments. The following reinterpret cast converts the address of v to an integer pointer before we dereference and display the integer result. Here's the output.
int n = *reinterpret_cast<int *>(&v); cout << hex << n << endl; // displays 97 (hex)
NOTE
The compiler packs adjacent bits within the same integer in the order that the bitfield members appear inside a structure or class definition. Be aware that this ordering is machine dependent, however. On another 16-bit machine, for example, the above example displays a different result.
cout << hex << n << endl; // displays e900 (hex)
The hexadecimal output displays the bits in reverse order because this machine packs bits right-to-left. Use bitfields carefully within your designs and remember that bitfields do not always conserve memory. Extracting a 2-bit bitfield from an integer word, in fact, may take longer than accessing an 8-bit character on some machines.