Thursday, January 5, 2012

How does the preprocessor work with a define directive?

The form of a define directive is

#define symbolic_name replacement

or

#define DAYS_IN_YEAR 365

where symbolic_name is the name of the constant macro that we are creating and replacement is the value with which we want symbolic_name replaced. The word define must be completely in lower case. On being instructed by a define directive, the preprocessor replaces any symbolic_name (excluding those that appear in comments or in string literals) in the program with the given replacement. For example, the symbolic name DAYS_IN_YEAR in the statement

printf("Days in year=%5d\n",DAYS_IN_YEAR);

is replaced by 365 before the program is translated into machine language. In other words, the preceding statement will be "rewritten" by the preprocessor to be

printf("Days in year=%5d\n,365);

prior to the compiler translating the code into machine language. In this example, the constant macro (DAYS_IN_YEAR) is replaced with the value 365 throughout the program by the preprocessor before the program is compiled.

Note that only one constant macro can be defined per line. The constant macro cannot be placed on the left side of an assignment statement, meaning that we cannot try to assign a new value to the constant macro at a later point in the program. You can understand why this does not work if you think about the operation involved. For instance, if we wanted to write

DAYS_IN_YEAR = 365.25

as an assignment statement in our program, the preprocessor would convert this to be

365 = 365.25

before the source code is translated into object code. This statement clearly makes no sense and therefore illustrates why we cannot use a constant macro on the left side of an assignment statement. Therefore, it is said that a constant macro is not an lvalue (pronounced "ell value"), meaning it cannot go on the left side of an assignment statement. A constant macro is considered to be an rvalue (pronounced "are value"), meaning that it can go on the right side of an assignment statement bu not the left.

No comments:

Post a Comment