Programming in C

(Barry) #1
The #defineStatement 311

to be written.You can even use this macro in a subsequent macro definition to convert
an ASCII character from lowercase to uppercase, leaving any nonlowercase character
unchanged:
#define TO_UPPER(x) ( IS_LOWER_CASE (x)? (x) - 'a' + 'A' : (x) )
The program loop
while ( *string != '\0' )
{
*string = TO_UPPER (*string);
++string;
}
would sequence through the characters pointed to by string, converting any lowercase
characters in the string to uppercase.^5

Va riable Number of Arguments to Macros
A macro can be defined to take an indeterminate or variable number of arguments.This
is specified to the preprocessor by putting three dots at the end of the argument list.The
remaining arguments in the list are collectively referenced in the macro definition by the
special identifier __VA_ARGS_ _. As an example, the following defines a macro called
debugPrintfto take a variable number of arguments:
#define debugPrintf(...) printf ("DEBUG: " _ _VA_ARGS_ _);
Legitimate macro uses would include
debugPrintf ("Hello world!\n");
as well as
debugPrintf ("i = %i, j = %i\n", i, j);
In the first case, the output would be
DEBUG: Hello world!
And in the second case, if ihad the value 100 and jthe value 200 , the output would be
DEBUG: i = 100, j = 200
The printfcall in the first case gets expanded into
printf ("DEBUG: " "Hello world\n");
by the preprocessor, which also concatenates the adjacent character string constants
together. So the final printfcall looks like this:
printf ("DEBUG: Hello world\n");

5.There is a host of functions in the library for doing character tests and conversions. For example,
islowerand toupperserve the same purpose as the macros IS_LOWER_CASEand TO_UPPER.
For more details, consult Appendix B, β€œThe Standard C Library.”

TEAM FLY

Free download pdf