typedef. McGraw-Hill The Complete Reference Fourth Edition
Реклама
Реклама
184
C + + : T h e C o m p l e t e R e f e r e n c e
Since sizeof is a compile-time operator, all the information necessary to compute the size of any variable is known at compile time. This is especially meaningful for
union
s, because the size of a union is always equal to the size of its largest member.
For example, consider union u { char ch; int i; double f;
} u_var;
Here, the sizeof(u_var) is 8. At run time, it does not matter what u_var is actually holding. All that matters is the size of its largest member, because any union must be as large as its largest element.
typedef
You can define new data type names by using the keyword typedef. You are not actually creating a new data type, but rather defining a new name for an existing type. This process can help make machine-dependent programs more portable. If you define your own type name for each machine-dependent data type used by your program, then only the typedef statements have to be changed when compiling for a new environment. typedef also can aid in self-documenting your code by allowing descriptive names for the standard data types. The general form of the typedef statement is typedef type newname; where type is any valid data type and newname is the new name for this type. The new name you define is in addition to, not a replacement for, the existing type name.
For example, you could create a new name for float by using typedef float balance;
This statement tells the compiler to recognize balance as another name for float.
Next, you could create a float variable using balance: balance over_due;
Here, over_due is a floating-point variable of type balance, which is another word for float.
C h a p t e r 7 : S t r u c t u r e s , U n i o n s , E n u m e r a t i o n s , a n d U s e r - D e f i n e d T y p e s
185
Now that balance has been defined, it can be used in another typedef. For example, typedef balance overdraft; tells the compiler to recognize overdraft as another name for balance, which is another name for float.
Using typedef can make your code easier to read and easier to port to a new machine, but you are not creating a new physical type.
This page intentionally left blank
Chapter 8
C-Style Console I/O
Copyright © 2003 by The McGraw-Hill Companies. Click here for terms of use.
187
Завантажити
Реклама