Sams Teach Yourself C in 21 Days

(singke) #1
A program can’t assume that the word alignment will be the same or that it will be on or
off. The members could be aligned on every two bytes, four bytes, or eight bytes. You
can’t assume that you know.

Reading and Writing Structures

When reading or writing structures, you must be cautious. It’s best to never use a literal
constant for the size of a structure or union. If you’re reading or writing structures to a
file, the file probably won’t be portable. This means you need to concentrate only on
making the program portable. The program then needs to read and write the data files
specific to the machine compiled on. The following is an example of a readstatement
that would be portable:
fread( &the_struct, sizeof( the_struct ), 1, filepointer );
As you can see, the sizeofcommand is used instead of a literal. Regardless of whether
byte alignment is on or off, the correct number of bytes should be read.

Structure Order
When you create a structure, you might assume that the members will be stored in the
order in which they are listed. There isn’t a standard stating that a certain order must be
followed. Because of this, you can’t make assumptions about the order of information
within a structure.

Preprocessor Directives
On Day 21, “Advanced Compiler Use,” you learned about several preprocessor directives
you can use. Several preprocessor directives have been defined in the ANSI standards.
You use two of these all the time:#includeand#define. Several other preprocessor
directives are in the ANSI standards. The additional preprocessor directives available
under the ANSI guidelines are listed in Table D.5.

TABLED.5 ANSI standard preprocessor directives
#define #if
#elif #ifdef
#else #ifndef
#endif #include
#error #pragma

816 Appendix D

47 448201x-APP D 8/13/02 11:17 AM Page 816

Free download pdf