Programming in C

(Barry) #1
The #includeStatement 313

The ##Operator


This operator is used in macro definitions to join two tokenstogether. It is preceded (or
followed) by the name of a parameter to the macro.The preprocessor takes the actual
argument to the macro that is supplied when the macro is invoked and creates a single
token out of that argument and whatever token follows (or precedes) the ##.
Suppose, for example, you have a list of variables x1through x100.You can write a
macro called printxthat simply takes as its argument an integer value 1 through 100
and that displays the corresponding xvariable as shown:


#define printx(n) printf ("%i\n", x ## n)


The portion of the define that reads


x ## n


says to take the tokens that occur before and after the ##(the letter xand the argument
n,respectively) and make a single token out of them. So the call


printx (20);


is expanded into


printf ("%i\n", x20);


The printxmacro can even use the previously defined printintmacro to get the vari-
able name as well as its value displayed:


#define printx(n) printint(x ## n)


The invocation


printx (10);


first expands into


printint (x10);


and then into


printf ("x10" " = %i\n", x10);


and finally into


printf ("x10 = %i\n", x10);


The #includeStatement


After you have programmed in C for a while, you will find yourself developing your
own set of macros that you will want to use in each of your programs. But instead of
having to type these macros into each new program you write, the preprocessor enables
you to collect all your definitions into a separate file and then includethem in your pro-
gram, using the #includestatement.These files normally end with the characters .hand
are referred to as headeror includefiles.

Free download pdf