[previous_group] [previous] [up] * [next_group]

Making the Program Readable with Macros

Macros are a way of making our programs more readable by defining symbolic names for constants and expressions to hide their details. For example, we could have written the data_ok() function as:
        int data_ok(int whole, int num, int denom)
        /*  Given: the stock price values
            Returns: TRUE if a valid stock price, FALSE otherwise
        */
        {
                if(denom == 0)  return 0;
                return 1;
        }

because in C, if the value of a condition expression is 0, it is considered false. If it is non-zero, it is considered true.

But the logic (meaning) of the return value from data_ok() is supposed to be TRUE or FALSE. We can understand the program better if we can just say that.

So we define macros for these two symbols using the define directive.

        #define FALSE 0
        #define TRUE  1

These directives are seen only by the compiler. TRUE and FALSE ARE NOT VARIABLES, they are macros. There are no cells allocated at run time for these names, instead, the compiler remembers the characters defined to be the value of the macro, and substitutes it in the code where ever the name occurs BEFORE even beginning translation. So when we write:
                if(denom == 0)  return FALSE;

the comiler sees:
                if(denom == 0)  return 0;

The first case is more readable to someone trying to understand the program; the second is more readable by the compiler. In general, we use macros to eliminate "magic number" in our code - numbers that have no meaning in themselves, but represent values that do have meaning. For example, in the recycle problem in homework 1, we had several constants that can be considered to be magic numbers. We can hide these magic numbers using macros and write code referring to the "CENTER_A_GLASS_RATE" instead of 0.02.

As an additional advantage to macros, if the "constant" occurs in more than one place in the code and could change, when we change the value, we must remember to change it in all places it is used. For example, in the text payroll program example, we have constants specifying the number of regular hours in a work week and the overtime factor used for computing pay. If we use macros for these constants, there is only one location we need to change the value, and the preprocessor will see to it that it is changed everywhere.


[up] to Overview.

[next_group]