7213709-C-Programming

Page 56

The important feature of macros is that they are not merely numerical constants which are referenced at compile time, but are strings which are physically replaced before compilation by the preprocessor! This means that almost anything can be defined: #define SUM

1 + 2 + 3 + 4

would allow SUM to be used instead of 1+2+3+4. Or #define STRING "Mary had a little lamb..."

would allow a commonly used string to be called by the identifier "string" instead of typing it out afresh each time. The idea of a define statement then is: #define macroname

definition on rest of line

Macros cannot define more than a single line to be substituted into a program but they can be used anywhere, except inside strings. (Anything enclosed in string quotes is assumed to be complete and untouchable by the compiler.) Some macros are defined already in the file stdio.h such as: EOF NULL

The end of file character (= -1 for instance) The null character (zero) = 0

• • • • • • •

Macro functions: Macros with parameters: Example 6: Note about include: Other Preprocessor commands: Example 7: Questions 12:

Macro Functions A more advanced use of macros is also permitted by the preprocessor. This involves macros which accept parameters and hand back values. This works by defining a macro with some dummy parameter, say x. For example: a macro which is usually defined in one of the standard libraries is abs() which means the absolute or unsigned value of a number. It is defined below: #define ABS(x) ((x) < 0) ? -(x) : (x)

The result of this is to give the positive (or unsigned) part of any number or variable. This would be no problem for a function which could accept parameters, and it is, in fact, no problem for macros. Macros can also be made to take parameters. Consider the ABS() example. If a programmer were to write ABS(4) then the preprocessor would substitute 4 for x. If a program read ABS(i) then the preprocessor would substitute i for x and so on.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.