Sams Teach Yourself C in 21 Days

(singke) #1
Implementing Structures, Unions, and TypeDefs 281

11


initialize it. print_function()will evaluate the typevariable in order to print a state-
ment with the appropriate variable type. This prevents getting erroneous data such as that
in Listing 11.7.

DOremember which union member is
being used. If you fill in a member of
one type and then try to use a different
type, you can get unexpected results.

DON’Ttry to initialize more than the
first union member.
DON’Tforget that the size of a union is
equal to its largest member.

DO DON’T


Creating Synonyms for Structures with

typedef
You can use the typedefkeyword to create a synonym for a structure or union type. For
example, the following statements define coordas a synonym for the indicated structure:
typedef struct {
int x;
int y;
} coord;
You can then declare instances of this structure using the coordidentifier:
coord topleft, bottomright;
Note that a typedefis different from a structure tag, as described earlier in today’s les-
son. If you write
struct coord {
int x;
int y;
};
the identifier coordis a tag for the structure. You can use the tag to declare instances of
the structure, but unlike using a typedef, you must include the structkeyword:
struct coord topleft, bottomright;
Whether you use typedefor a structure tag to declare structures makes little difference.
Usingtypedefresults in slightly more concise code because the structkeyword doesn’t
have to be used. On the other hand, using a tag and having the structkeyword explicit
makes it clear that it is a structure being declared.

18 448201x-CH11 8/13/02 11:17 AM Page 281

Free download pdf