Programming in C

(Barry) #1
The #defineStatement 305

And if the program is written to use MAXIMUM_DATAVALUESin all cases where the size of
the array was used, the preceding definition could be the only statement in the program
that would have to be changed.


Program Portability


Another nice use of the define is that it helps to make programs more portable from one
computer system to another. At times, it might be necessary to use constant values that
are related to the particular computer on which the program is running.This might have
to do with the use of a particular computer memory address, a filename, or the number
of bits contained in a computer word, for example.You will recall that your rotate
function from Program 12.4 used the knowledge that an intcontained 32 bits on the
machine on which the program was executed.
If you want to execute this program on a different machine, on which an intcon-
tained 64 bits, the rotatefunction would not work correctly.^4 Study the following
code. In situations in which the program mustbe written to make use of machine-
dependent values, it makes sense to isolate such dependencies from the program as much
as possible.The #definestatement can help significantly in this respect.The new version
of the rotatefunction would be easier to port to another machine, even though it is a
rather simple case in point. Here’s the new function:


#include <stdio.h>


#define kIntSize 32 // machine dependent !!!


// Function to rotate an unsigned int left or right


unsigned int rotate (unsigned int value, int n)
{
unsigned int result, bits;


/* scale down the shift count to a defined range */

if ( n > 0 )
n = n % kIntSize;
else
n = -(-n % kIntSize);

if ( n == 0 )
result = value;


  1. Of course, you can write the rotatefunction so that it determines the number of bits in an
    intby itself and, therefore, is completely machine independent. Refer back to exercises 3 and 4 at
    the end of Chapter 12, “Operations on Bits.”

Free download pdf