How SHOULD these macros work?

Lee Crawford crawford at scri.fsu.edu
Sun Feb 17 06:01:28 AEST 1991


Well, its a simple consideration of the preprocessors replacement ordering.

You asked:

|  What behavior SHOULD be expected from the following:
|
|  #define one val1,val2
|  #define two(arg1,arg2) arg1+arg2
|
|   ....
|
|     two(one)

I guess I'll give answering your question a shot:

  I think what you have to understand is how the C/C++ preprocessor works, 
for it is the preprocessing phase of compilation that is causing the effects
that
you find strange.

  The initial actions of the preprocessor are to break up the text of any
source
code into a stream of tokens. As it breaks off these tokens it scans then for 
macro calls. (A macro constant just has not parrenthesization) Thus, for either
of
the following two code segments:

  #define one val1,val2
  #define two(arg1,arg2) arg1+arg2

or

  #define two(arg1,arg2) arg1+arg2
  #define on val1,val2.

You notice that the first recognized token of the program text:

  two(one)

would be the string "two". Thus regardless of the ordering of the definitions
or
whatnot, the preprocesser first turns its attentions to a replacement of the
macro "two". Thus:

  two(one)

becomes

   one+

and you will likely find yourself with an error message mentioning that the 
required number of arguments was not present. When macro replacement occurs
during preprocessing, after a single replacement the preprocessor resumes token
scanning at the beginning of the previous expansion. Thus the preprocessor is 
now trying to figure out what to do with:

  one+

It then finds the token "one" and replaces it with "val1,val2". And

  one+

becomes

  val1,val2+.  

I hope this has all made sense. If you wanted val1+val2 as the expansion of 
your macro invocation then you will have to sort out a different way of doing
so.

-------------------- Cut here ---------------------------------------

  Lee Crawford
  Florida State University 
  Department of Physics
  crawford at fsulcd.physics.fsu.edu (INTER/ARPA-NET)
  fsulcd::crawford (DECnet)
  (904) 644 2334 (LipNET)

-------------------------------------------------------------------



More information about the Comp.lang.c mailing list